/** Copyright (c) Scott Gasch Module Name: eval.c Abstract: Position evaluation routines. Author: Scott Gasch (scott.gasch@gmail.com) 14 Jun 2004 Revision History: $Id: eval.c 357 2008-07-03 16:18:11Z scott $ **/ #include "chess.h" // // CountBits and the CoorFromBitBoard{Rank8ToRank1,Rank1ToRank8} // wrappers (bitboard.c) are real out-of-line asm calls on every one of // eval.c's ~20 production call sites (passed-pawn detection, bishop- // pair logic, etc.), hit on every real Eval() call. CountBits' asm // body (x64.asm) isn't even O(1) popcnt, it's a Kernighan bit-clearing // loop -- O(popcount) iterations plus call overhead. Redirected via // #define, the same mechanism chess.h already uses for the OTHER // direction (#ifdef CROUTINES routes CountBits/FirstBit/LastBit to the // slow C fallbacks) -- this routes them to the fast inline // FastCountBits/FastCoorFromBitBoardRank8ToRank1/ // FastCoorFromBitBoardRank1ToRank8 wrappers (chess.h) instead, for // every existing call site below with no further edits. Those used to // be duplicated here as file-local statics; promoted to chess.h so // every other translation unit's bitboard-scan loops (recogn.c, // board.c, generate.c, movesup.c, probe.c, testmove.c -- added during // the cNonPawns/cPawns/uPawnCount/uNonPawnCount retirement work) get // the fast path too, not just eval.c -- confirmed by disassembly that // those files were still emitting real callq+PLT relocations to the // slow extern versions before this. Gated on !CROUTINES so the // CROUTINES debug/comparison build still gets the real (slow, // cross-checked) implementations. // #ifndef CROUTINES #define CountBits FastCountBits #define CoorFromBitBoardRank8ToRank1 FastCoorFromBitBoardRank8ToRank1 #define CoorFromBitBoardRank1ToRank8 FastCoorFromBitBoardRank1ToRank8 #endif // !CROUTINES // Bishop/knight/rook mobility computed during their own eval pass only // knows about enemy PAWN attacks (bishop/knight) or enemy PAWN+MINOR // attacks (rook) -- the only attack tables fully populated that early // -- so a square right next to the enemy king, or (for bishop/knight) // covered by an enemy piece not yet evaluated, looks "safe" and counts // toward mobility even though it plainly isn't. Below this many // candidate squares, don't trust that partial-information count: defer // to _EvalTrappedPieces, which re-derives a final safe-escape count // once the full attack picture (both colors, both kings) is in. // Genuinely 0-mobility pieces are the one exception -- see // _EvalBishop's comment on why those are scored immediately instead. #define EVAL_MOBILITY_CAREFULLY_BELOW (3) // // To simplify code / maintenance I use the same loop for both colors // in some places. These globals coorespond to "ahead of the piece" // or "behind the piece" for each color. // const int g_iAhead[2] = { +1, -1 }; const int g_iBehind[2] = { -1, +1 }; // // General eval terms // --------------------------------------------------------------------------- // //static SCORE TRADE_PIECES[3][17] = //{// 0 1 2 3 4 5 6 7 8 | 9..15 -- down piece count // { -1, 90, 81, 73, 67, 62, 57, 52, 50, 50,50,50,50,50,50,50,-1}, // { -1, 125, 117, 109, 100, 91, 84, 78, 71, 66,66,66,66,66,66,66,-1}, // { -1, 150, 132, 124, 116, 109, 102, 94, 87, 77,77,77,77,77,77,77,-1}, //}; //static SCORE DONT_TRADE_PAWNS[3][9] = //{// 0 1 2 3 4 5 6 7 8 -- up pawn count // { -43, -15, 0, +3, +6, +10, +15, +21, +28 }, // // 0 // { -63, -25, 0, +4, +9, +14, +19, +25, +32 }, // // 1 // { -10, 0, 0, +7, +15, +20, +24, +29, +36 }, // // 2 //}; static ULONG REDUCED_MATERIAL_DOWN_SCALER[32] = { // none na na m na R 2m na 0, 0, 0, 0, 0, 0, 0, 0, // Rm 3m/Q 2R R2m 4m/Qm 2Rm R3m/QR Q2m 0, 1, 1, 1, 2, 2, 2, 3, // 2R2m R4m/QRm Q3m 2R3m/ QR2m Q4m 2R4m/ QR3m // Q2R Q2Rm 4, 5, 6, 6, 7, 7, 7, 7, // na Q2R2m QR4m na Q2R3m na na full 8, 8, 8, 8, 8, 8, 8, 8, }; // // Same shape as REDUCED_MATERIAL_DOWN_SCALER (0 with little material left, // ramping to 8 with a full army) but decays to 0 much sooner -- "haven't // castled yet" / "minors still at home" are opening-specific concerns that // stop mattering well before the point where real king danger fades, so // this table's zero region extends much further up the index range than // REDUCED_MATERIAL_DOWN_SCALER's does. // static ULONG CASTLE_AND_DEVELOPMENT_SCALER[32] = { // none na na m na R 2m na 0, 0, 0, 0, 0, 0, 0, 0, // Rm 3m/Q 2R R2m 4m/Qm 2Rm R3m/QR Q2m 0, 0, 0, 0, 0, 0, 0, 0, // 2R2m R4m/QRm Q3m 2R3m/ QR2m Q4m 2R4m/ QR3m // Q2R Q2Rm 0, 1, 2, 3, 4, 5, 6, 7, // na Q2R2m QR4m na Q2R3m na na full 7, 8, 8, 8, 8, 8, 8, 8, }; static ULONG REDUCED_MATERIAL_UP_SCALER[32] = { // none na na m na R 2m na 8, 8, 8, 8, 8, 8, 8, 8, // Rm 3m/Q 2R R2m 4m/Qm 2Rm R3m/QR Q2m 8, 7, 7, 7, 7, 6, 6, 5, // 2R2m R4m/QRm Q3m 2R3m/ QR2m Q4m 2R4m/ QR3m // Q2R Q2Rm 4, 3, 3, 3, 2, 2, 2, 1, // na Q2R2m QR4m na Q2R3m na na full 1, 1, 0, 0, 0, 0, 0, 0, }; static ULONG PASSER_MATERIAL_UP_SCALER[32] = { // none na na m na R 2m na 8, 8, 8, 8, 8, 8, 7, 7, // Rm 3m/Q 2R R2m 4m/Qm 2Rm R3m/QR Q2m 7, 6, 7, 5, 4, 5, 4, 3, // 2R2m R4m/QRm Q3m 2R3m/ QR2m Q4m 2R4m/ QR3m // Q2R Q2Rm 2, 2, 1, 1, 0, 0, 0, 0, // na Q2R2m QR4m na Q2R3m na na full 0, 0, 0, 0, 0, 0, 0, 0, }; static ULONG MULTIPLE_PASSER_SCALER[9] = { // 0 1 2 3 4 5 6 7 8 0, 32, 27, 22, 18, 11, 8, 4, 2 }; COOR QUEENING_RANK[2] = { 1, 8 }; COOR JUMPING_RANK[2] = { 7, 2 }; // // Pawn eval terms // --------------------------------------------------------------------------- // // "There is one case which can be treated as positional or material, // namely the rook's pawn, which differs from other pawns in that it // can only capture one way instead of two. Since this handicap cannot // be corrected without the opponent's help, I teach my students to // regard the rook's pawn as a different piece type, a crippled // pawn. Database statistics indicate that it is on average worth // about 15% less than a normal pawn. The difference is enough so that // it is usually advantageous to make a capture with a rook's pawn, // promoting it to a knights pawn, even if that produces doubled pawns // and even if there is no longer a rook on the newly opened rook's // file." // --Larry Kaufman, IM // "Evaluation of Material Imbalance" // static SCORE PAWN_CENTRALITY_BONUS[128] = { 0, 0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0, -5, 0, 0, 0, 0, 0, 0, -5, 0,0,0,0,0,0,0,0, -5, 0, 5, 5, 5, 5, 0, -5, 0,0,0,0,0,0,0,0, -5, 0, 5, 8, 8, 5, 0, -5, 0,0,0,0,0,0,0,0, // ------------------------------------------------------------------- -5, 0, 5, 8, 8, 5, 0, -5, 0,0,0,0,0,0,0,0, -5, 0, 5, 5, 5, 5, 0, -5, 0,0,0,0,0,0,0,0, -5, 0, 0, 0, 0, 0, 0, -5, 0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0 }; // Hand-restored 2026-08-30: the DNA-tuned values here had drifted to // mostly-positive across the board (a shielded backward pawn was scoring // as a +12..+17 bonus on most files, and several EXPOSED entries were // less negative than the corresponding SHIELDED ones on the same file -- // i.e. "more exposed" scored better than "less exposed"). Both the // ASSERT(BACKWARD_SHIELDED_BY_LOCATION[c] < 0) and the analogous EXPOSED // assert below had been silently commented out rather than investigated. // Replaced with a monotonic, strictly-negative, rank-mirrored shape: // backward pawns are always a defect, exposed is always worse than // shielded at the same rank, and the penalty grows as the pawn advances // toward the more contested center ranks (4/5) where a backward pawn is // most exploitable. Table is indexed by absolute square (not // color-relative), hence the rank2/rank7, rank3/rank6, rank4/rank5 // mirroring -- same as the original layout. static SCORE BACKWARD_SHIELDED_BY_LOCATION[128] = { +0, +0, +0, +0, +0, +0, +0, +0, 0,0,0,0,0,0,0,0, -7, -5, -5, -7, -7, -5, -5, -7, 0,0,0,0,0,0,0,0, -5, -4, -4, -5, -5, -4, -4, -5, 0,0,0,0,0,0,0,0, -4, -3, -3, -4, -4, -3, -3, -4, 0,0,0,0,0,0,0,0, // ------------------------------------------------------------------- -4, -3, -3, -4, -4, -3, -3, -4, 0,0,0,0,0,0,0,0, -5, -4, -4, -5, -5, -4, -4, -5, 0,0,0,0,0,0,0,0, -7, -5, -5, -7, -7, -5, -5, -7, 0,0,0,0,0,0,0,0, +0, +0, +0, +0, +0, +0, +0, +0, 0,0,0,0,0,0,0,0 }; static SCORE BACKWARD_EXPOSED_BY_LOCATION[128] = { +0, +0, +0, +0, +0, +0, +0, +0, 0,0,0,0,0,0,0,0, -12, -9, -9, -11, -11, -9, -9, -12, 0,0,0,0,0,0,0,0, -9, -7, -7, -9, -9, -7, -7, -9, 0,0,0,0,0,0,0,0, -7, -6, -6, -7, -7, -6, -6, -7, 0,0,0,0,0,0,0,0, // ------------------------------------------------------------------- -7, -6, -6, -7, -7, -6, -6, -7, 0,0,0,0,0,0,0,0, -9, -7, -7, -9, -9, -7, -7, -9, 0,0,0,0,0,0,0,0, -12, -9, -9, -11, -11, -9, -9, -12, 0,0,0,0,0,0,0,0, +0, +0, +0, +0, +0, +0, +0, +0, 0,0,0,0,0,0,0,0 }; // // "The first statement I can confirm is that doubled pawns are indeed // on average undesirable. However this statistic needs to be broken // down to be useful. Doubled pawns themselves are really more // serious than this generally, but when your pawns are doubled you // automatically get an extra half-open file for your rooks (or queen, // but the queen can also use diagonals). So it follows logically // that the net cost of doubled pawns is much greater in the absence // of major pieces. The database shows that with all rooks present, // doubled pawns "cost" only about 1/16th of a pawn on average. With // one rook each the cost rises to 1/4th of a pawn and with no rooks // present to 3/8ths of a pawn. With the queens present the cost is // again only 1/16th of a pawn; without them it's a quarter pawn. So // the lessons are clear; beware of doubled pawns when major pieces // have been exchanged, and beware of exchanging major pieces when you // are the one with the doubled pawns." // --Larry Kaufman, IM // "All About Doubled Pawns" // // Note: indexed by number of files with 1+ pawn on them. static SCORE DOUBLED_PAWN_PENALTY_BY_COUNT[4][9] = { // ------------ count of doubled+ pawns ------------ {// 0 1 2 3 4 5 6 7 8 : no majors alive +0, -32, -65, -99, -134, -170, -207, -222, -250 }, {// : 1 rook +0, -23, -47, -76, -108, -144, -184, -200, -216 }, {// : 2 rooks or 1 queen +0, -13, -23, -34, -46, -64, -86, -111, -138 }, {// : all majors alive +0, -7, -13, -25, -39, -55, -73, -95, -121 }, }; static SCORE ISOLATED_PAWN_BY_PAWNFILE[9] = { 0, -8, -9, -10, -10, -10, -10, -9, -8 }; static SCORE ISOLATED_EXPOSED_PAWN = -5; // Turned down (2026-08-30): a per-pawn modifier that stacks on top of //< DOUBLED_PAWN_PENALTY_BY_COUNT's whole-position doubled-pawn aggregate // for the specific case of a pawn that's both isolated and doubled -- // a different angle (single-worst-case flag vs. whole-position // severity), not the same fact counted twice, so scaled down rather // than removed. static SCORE ISOLATED_DOUBLED_PAWN = -7; // // Note: -25% to -33% if the enemy occupies or controls the next sq. // static SCORE PASSER_BY_RANK[2][9] = {// 0 1 2 3 4 5 6 7 8 { +0, +0,+162,+111, +62, +36, +18, +13, +0 }, // black { +0, +0, +13, +18, +36, +62,+111,+162, +0 } // white }; static SCORE CANDIDATE_PASSER_BY_RANK[2][9] = {// 0 1 2 3 4 5 6 7 8 { +0, +0, +0, +48, +34, +22, +13, +9, +0 }, // black { +0, +0, +9, +13, +22, +34, +48, +0, +0 } // white }; // Note: x2 // Scaled to 1/3 of the original hand-tuned magnitude (2026-08-30): these // three terms, plus PASSER_BY_RANK and OUTSIDE_PASSER_BY_DISTANCE, all // separately price "how good is this passer" from different angles // (connected to a partner passer, backed by an ordinary pawn, outside // the opposing pawn majority) and can stack for the same pawn -- a // rank-7 connected+outside passer could hit ~370cp in this pawn-hash- // cached family alone, ~9x Crafty's ~40cp ceiling for the equivalent // concept. Rather than remove any of these (they're each pricing a // genuinely distinct structural fact, not re-counting the same one -- // and pawn-hash caching makes the compute cost of keeping all of them // free), turned the magnitude down on the three secondary/modifier // terms so the stack lands in a saner range; PASSER_BY_RANK (the core // "how far advanced" signal) is left as the primary, least-reduced // term. static SCORE CONNECTED_PASSERS_BY_RANK[2][9] = {// 0 1 2 3 4 5 6 7 8 { +0, +0, +32, +25, +16, +7, +3, +2, +0 }, // black { +0, +0, +2, +3, +7, +16, +25, +32, +0 } // white }; static SCORE SUPPORTED_PASSER_BY_RANK[2][9] = {// 0 1 2 3 4 5 6 7 8 { +0, +0, +20, +13, +4, +2, +1, +1, +0 }, // black { +0, +0, +1, +1, +2, +4, +13, +20, +0 } // white }; // Split out 2026-08-30 from SUPPORTED_PASSER_BY_RANK, which _EvalKing's // "kings in front of passers" endgame bonus was silently reusing -- // pawn-support and king-escort are different concepts (this fires when // the KING stands next to its own passer, not when a pawn does), so // scaling one for its real purpose was silently also scaling the // other. Seeded with SUPPORTED_PASSER_BY_RANK's original (pre-scaling) // hand-tuned magnitude, since that's what this use case was actually // getting before today's pawn-hash pass touched the shared table for // an unrelated reason. static SCORE KING_SUPPORTING_OWN_PASSER_BY_RANK[2][9] = {// 0 1 2 3 4 5 6 7 8 { +0, +0, +60, +40, +13, +6, +3, +1, +0 }, // black { +0, +0, +1, +3, +6, +13, +40, +60, +0 } // white }; static SCORE OUTSIDE_PASSER_BY_DISTANCE[9] = {// 0 1 2 3 4 5 6 7 8 +0, +0, +2, +5, +7, +9, +11, +14, +18 }; static SCORE PASSER_BONUS_AS_MATERIAL_COMES_OFF[32] = { // none na na m na R 2m na +60, -1, -1, +37, -1, +43, +19, -1, // Rm 3m/Q 2R R2m 4m/Qm 2Rm R3m/QR Q2m +14, +9, +20, +4, +3, +3, 0, 0, // 2R2m R4m/QRm Q3m 2R3m/ QR2m Q4m 2R4m/ QR3m // Q2R Q2Rm 0, 0, 0, 0, 0, 0, 0, 0, // na Q2R2m QR4m na Q2R3m na na full 0, 0, 0, 0, 0, 0, 0, 0, }; // 2026-09-17: was +800 -- found via fuzzing that _RecognizeKPK stacks // material balance and a flat 2*VALUE_PAWN on top of this before // returning it as a hard recognizer bound (RECOGN_LOWER/UPPER), so a // "winning" race claim could reach ~988 total even before considering // whether the claim itself was right. Crafty's equivalent term // (pawn_can_promote, evaluate.h) is a flat 525 and -- critically -- // only ever an additive eval nudge feeding real alpha-beta search, // never a hard bound. Turned down to ~300/pawn regardless of that // separate soundness fix (see the losing-side-has-no-pawns guard in // _RecognizeKPK) since the two problems compound independently. SCORE RACER_WINS_RACE = +300; static SCORE UNDEVELOPED_MINORS_IN_OPENING[5] = {// 0 1 2 3 4 0, -14, -18, -24, -30 }; // // Bishop eval terms // --------------------------------------------------------------------------- // // // "The bishop pair has an average value of half a pawn (more when the // opponent has no minor pieces to exchange for one of the bishops), // enough to regard it as part of the material evaluation of the // position, and enough to overwhelm most positional considerations. // Moreover, this substantial bishop pair value holds up in all // situations tested, regardless of what else is on the board... // // ...One rule which I often teach to students is that if you have the // bishop pair, and your opponent's single bishop is a bad bishop // (hemmed in by his own pawns), you already have full compensation // for a pawn... Kasparov has said something similar... // // As noted before, the bishop pair is worth more with fewer pawns on // the board. Aside from this factor, the half pawn value of the // bishop pair is remarkably constant, applying even when there are no // pieces on the board except two minors each." // --Larry Kaufman, IM // "Evaluation of Material Imbalance" static SCORE BISHOP_PAIR_BONUS = 30; static SCORE STATIONARY_PAWN_ON_BISHOP_COLOR[128] = { +0, +0, +0, +0, +0, +0, +0, +0, 0,0,0,0,0,0,0,0, -4, -6, -7, -7, -7, -7, -6, -4, 0,0,0,0,0,0,0,0, -6, -7, -9, -8, -8, -9, -7, -6, 0,0,0,0,0,0,0,0, -7, -8, -10, -11, -11, -10, -8, -7, 0,0,0,0,0,0,0,0, // ------------------------------------------------------------------- -7, -8, -10, -11, -11, -10, -8, -7, 0,0,0,0,0,0,0,0, -6, -7, -9, -8, -8, -9, -7, -6, 0,0,0,0,0,0,0,0, -4, -6, -7, -7, -7, -7, -6, -4, 0,0,0,0,0,0,0,0, +0, +0, +0, +0, +0, +0, +0, +0, 0,0,0,0,0,0,0,0 }; static SCORE TRANSIENT_PAWN_ON_BISHOP_COLOR[128] = { +0, +0, +0, +0, +0, +0, +0, +0, 0,0,0,0,0,0,0,0, -1, -1, -2, -2, -2, -2, -1, -1, 0,0,0,0,0,0,0,0, -3, -4, -4, -4, -4, -4, -4, -3, 0,0,0,0,0,0,0,0, -4, -5, -7, -8, -8, -7, -5, -4, 0,0,0,0,0,0,0,0, // ------------------------------------------------------------------- -4, -5, -7, -8, -8, -7, -5, -4, 0,0,0,0,0,0,0,0, -3, -4, -4, -4, -4, -4, -4, -3, 0,0,0,0,0,0,0,0, -1, -1, -2, -2, -2, -2, -1, -1, 0,0,0,0,0,0,0,0, +0, +0, +0, +0, +0, +0, +0, +0, 0,0,0,0,0,0,0,0 }; // // A bishop can move to between 0..13 squares. // static SCORE BISHOP_MOBILITY_BY_SQUARES[14] = {// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 -22, -14, -10, -5, -1, 0, +1, +3, +4, +5, +6, +7, +8, +9 };// ^ | // // Pseudo-mobility: squares this bishop can "see" past a directly-attacked // higher-value enemy piece (rook/queen/king) -- real positional pressure // (the squares a capture or a moving-away enemy piece would open up), not // real mobility (the bishop cannot actually move there this ply). No // attempt to model whether the bishop itself is defended -- that's a // search-shaped question (SEE/exchange-accurate, whose-move-is-it), not // an eval one; see MOBILITY_BITBOARD_REWRITE.md. Deliberately smaller // than BISHOP_MOBILITY_BY_SQUARES throughout. // static SCORE BISHOP_XRAY_MOBILITY_BY_SQUARES[9] = {// 0 1 2 3 4 5 6 7 8 +0, +1, +1, +2, +2, +3, +3, +4, +4 }; static SCORE BISHOP_UNASSAILABLE_BY_DIST_FROM_EKING[9] = {// 0 1 2 3 4 5 6 7 8 +0, +33, +28, +18, +8, +4, +0, -10, -16 }; // // Knight eval terms // --------------------------------------------------------------------------- // static SCORE KNIGHT_CENTRALITY_BONUS[128] = { -12, -8, -8, -8, -8, -8, -8, -12, 0,0,0,0,0,0,0,0, -8, -2, -2, 0, 0, -2, -2, -8, 0,0,0,0,0,0,0,0, -8, -2, +4, +5, +5, +4, -2, -8, 0,0,0,0,0,0,0,0, -8, -2, +5, +8, +8, +5, -2, -8, 0,0,0,0,0,0,0,0, // ------------------------------------------------------------------- -8, -2, +5, +8, +8, +5, -2, -8, 0,0,0,0,0,0,0,0, -8, -2, +4, +5, +5, +4, -2, -8, 0,0,0,0,0,0,0,0, -8, -2, -2, 0, 0, -2, -2, -8, 0,0,0,0,0,0,0,0, -12, -8, -8, -8, -8, -8, -8, -12, 0,0,0,0,0,0,0,0 }; static SCORE KNIGHT_KING_TROPISM_BONUS[9] = {// 0 1 2 3 4 5 6 7 8 0, +15, +12, +9, +4, +0, +0, +0, +0 }; static SCORE KNIGHT_UNASSAILABLE_BY_DIST_FROM_EKING[9] = {// 0 1 2 3 4 5 6 7 8 +0, +25, +19, +14, +6, +0, +0, +0, +0 }; static SCORE KNIGHT_ON_INTERESTING_SQUARE_BY_RANK[2][9] = {// 0 1 2 3 4 5 6 7 8 { +0, +12, +11, +9, +6, +3, +0, +0, +0 }, // black { +0, +0, +0, +0, +3, +6, +9, +11, +12 } // white }; // // A knight can move to between 0..8 squares // ----------------------------------------- // 0 = supported enemy pawn // 1 = unsupported enemy pawn, friend pawn, enemy B/N // enemy controlled empty sq. // 2 = enemy >B, friend controlled empty sq, no one controlled empty sq // // Total: 16 mobility max // static SCORE KNIGHT_MOBILITY_BY_COUNT[9] = {// 0 1 2 3 4 5 6 7 8 -17, -10, -6, 0, +3, +5, +7, +8, +8 };// ^ | static SCORE KNIGHT_WITH_N_PAWNS_SUPPORTING[3] = { +0, +4, +8 }; static SCORE KNIGHT_IN_CLOSED_POSITION[33] = {// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 4, 6, 9, 11, 12, 13, 15, 17, 19, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 27 // 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 }; // // Rook eval terms // --------------------------------------------------------------------------- // // Simplified 2026-09-06 (board_representation/EVAL.md section 9): flat // average bonus, not scaled by distance from the enemy king -- by direct // instruction. Each was a [8]-by-distance table; these are that table's // simple mean, rounded. static SCORE ROOK_ON_FULL_OPEN = 18; static SCORE ROOK_ON_HALF_OPEN_WITH_ENEMY = 9; static SCORE ROOK_ON_HALF_OPEN_WITH_FRIEND = 10; // Cache of the three constants above, indexed [friend pawn on file?] // [enemy pawn on file?] so _EvalRook's hot path is a single array read // instead of rebuilding a local array every call. Not `static const` // -- the three source constants are DNA-tunable globals (plain mutable // SCORE, not compile-time constants), so this has to be a plain // mutable array, rebuilt by InitializeEval() whenever they change (startup, // and after every `evaldna read`), not frozen at compile time. static SCORE ROOK_FULL_HALF_OPEN_BONUS[2][2] = { { 16, 9 }, { 10, 0 } }; // Same treatment for the enemy/friend-passer-on-file bonuses -- was // PASSER_BY_RANK[xColor][rank]/4 (enemy case) and a rank-scaled // behind/leads-passer split (friend case, +1..+25 behind, -3..-22 in // front); flat means of the meaningful (non-padding) entries. static SCORE ROOK_WITH_ENEMY_PASSER = 17; static SCORE ROOK_WITH_FRIEND_PASSER = 10; // A rook on the 7th (White) or 2nd (Black) rank attacks along the // enemy's back-ranks-minus-one, hitting undeveloped/unmoved pawns and // cutting the enemy king off from that rank -- a small, classic bonus // independent of the file-openness/passer bonuses above. BBRANK22/ // BBRANK77 are compile-time constants (chess.h), so this table (unlike // ROOK_FULL_HALF_OPEN_BONUS above) can be a real `static const`: it // depends on the board geometry, not on any DNA-tunable value. static const BITBOARD BBROOK_7TH_RANK[2] = { BBRANK22, BBRANK77 }; // [BLACK], [WHITE] static SCORE ROOK_ON_SEVENTH_BONUS = 9; static SCORE ROOK_VALUE_AS_PAWNS_COME_OFF[17] = {// 0 1 2 3 4 5 6 7 8 +55, +51, +44, +38, +33, +27, +22, +16, +7, // 9 10 11 12 13 14 15 16 +1, -3, -6, -9, -12, -18, -22, -25 }; // // Note: these are multiplied by two (one per rook). // static SCORE ROOK_CONNECTED_VERT = +7; // x2 static SCORE ROOK_CONNECTED_HORIZ = +4; // x2 // // A rook can move to between 0..14 squares // ---------------------------------------- // 0 = supported enemy P/N/B, friend piece // 1 = unsupported enemy piece, enemy controlled empty sq, enemy R // 2 = enemy >R, friend controlled empty sq, no one controlled empty sq // // Total: 28 mobility max // static SCORE ROOK_MOBILITY_BY_SQUARES[15] = {// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -32, -26, -20, -14, -7, -2, +0, +4, +8, +12, +15, +17, +19, +21, +22 };// ^ | // // Pseudo-mobility: squares this rook can "see" past a directly-attacked // enemy queen or king -- same idea as BISHOP_XRAY_MOBILITY_BY_SQUARES // above, same caveats (no defended/undefended modeling -- that's // search's job). Deliberately smaller than ROOK_MOBILITY_BY_SQUARES // throughout. // static SCORE ROOK_XRAY_MOBILITY_BY_SQUARES[9] = {// 0 1 2 3 4 5 6 7 8 +0, +1, +1, +2, +2, +3, +3, +4, +4 }; // // Queen eval terms // --------------------------------------------------------------------------- // // // A queen can move to between 0..27 squares // ----------------------------------------- // 0 = supported enemy P/N/B/R, friend piece // 1 = unsupported enemy piece, enemy controlled empty sq, enemy Q // 2 = enemy K, no one controlled empty sq, friend controlled empty sq // // Total: 54 mobility max // static SCORE QUEEN_MOBILITY_BY_SQUARES[28] = {// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -30, -26, -22, -17, -11, -8, -4, -2, -1, +2, +4, +7, +10, +12, +14, // | //15 16 17 18 19 20 21 22 23 24 25 26 27 +15, +16, +17, +18, +19, +20, +20, +21, +21, +22, +22, +23, +23 }; // // In "Evaluation of Material Imbalance", IM Larry Kaufman makes the // point that queens are worth more then the standard nine "points". // Thus, this scale is biased upwards by about 0.15 pawn. // static SCORE QUEEN_KING_TROPISM[8] = {// 0 1 2 3 4 5 6 7 0, +34, +28, +22, +19, +17, +16, +15 }; // // King eval terms // --------------------------------------------------------------------------- // // 2026-09-15: this table is ONLY for CountKingSafetyDefects (the cheap // lazy-eval-proxy/search-extension-reduction-gate sibling of _EvalKing, // called directly from search.c/searchsup.c independent of Eval() ever // running) -- deliberately frozen/split off from _EvalKing's own real // computation (see KING_EVAL_INITIAL_LOCATION below), which used to // read this exact array. That coupling meant any future retune of // _EvalKing's king-location term would silently perturb search // extension/reduction gate frequency too, an unrelated and much // higher-blast-radius side effect than "retune an eval term" should // have. DO NOT repoint _EvalKing at this table again -- add to/reshape // KING_EVAL_INITIAL_LOCATION instead. See king_safety_data/HANDOFF.md's // 2026-09-15 addendum. static ULONG KING_INITIAL_COUNTER_BY_LOCATION[2][128] = { { 2, 0, 0, 0, 1, 0, 0, 2, 0,0,0,0,0,0,0,0, 1, 1, 1, 1, 1, 1, 1, 1, 0,0,0,0,0,0,0,0, 3, 3, 3, 3, 3, 3, 3, 3, 0,0,0,0,0,0,0,0, 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, // ------------------------------------------------------------------- 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0 }, { 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, // ------------------------------------------------------------------- 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, 3, 3, 3, 3, 3, 3, 3, 3, 0,0,0,0,0,0,0,0, 1, 1, 1, 1, 1, 1, 1, 1, 0,0,0,0,0,0,0,0, 2, 0, 0, 0, 1, 0, 0, 2, 0,0,0,0,0,0,0,0 } }; // 2026-09-15: _EvalKing's own copy -- same starting values as // KING_INITIAL_COUNTER_BY_LOCATION above (no retuning done yet, this // split is purely about ownership/decoupling), but SCORE-typed (this // function's real ring-scan is SCORE-native post-rewrite, no more // shared uCounter) and free to be reshaped independently -- e.g. the // offboard-ring-exposure idea from king_safety_data/HANDOFF.md's // session notes (a1-style corner exposure, distinct from this table's // current pure-rank shape) without touching CountKingSafetyDefects' // search-gate behavior at all. static SCORE KING_EVAL_INITIAL_LOCATION[2][128] = { { 2, 0, 0, 0, 1, 0, 0, 2, 0,0,0,0,0,0,0,0, 3, 1, 1, 1, 1, 1, 1, 3, 0,0,0,0,0,0,0,0, 4, 3, 3, 3, 3, 3, 3, 4, 0,0,0,0,0,0,0,0, 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, // ------------------------------------------------------------------- 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0 }, { 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, // ------------------------------------------------------------------- 4, 4, 4, 4, 4, 4, 4, 4, 0,0,0,0,0,0,0,0, 4, 3, 3, 3, 3, 3, 3, 4, 0,0,0,0,0,0,0,0, 3, 1, 1, 1, 1, 1, 1, 3, 0,0,0,0,0,0,0,0, 2, 0, 0, 0, 1, 0, 0, 2, 0,0,0,0,0,0,0,0 } }; static SCORE KING_TO_CENTER[128] = { +0, +0, +0, +0, +0, +0, +0, +0, 0,0,0,0,0,0,0,0, +1, +3, +5, +7, +7, +5, +3, +1, 0,0,0,0,0,0,0,0, +3, +5, +13, +15, +15, +13, +5, +3, 0,0,0,0,0,0,0,0, +5, +7, +17, +23, +23, +17, +7, +5, 0,0,0,0,0,0,0,0, // ------------------------------------------------------------------ +5, +7, +17, +23, +23, +17, +7, +5, 0,0,0,0,0,0,0,0, +3, +5, +13, +15, +15, +13, +5, +3, 0,0,0,0,0,0,0,0, +1, +3, +5, +7, +7, +5, +3, +1, 0,0,0,0,0,0,0,0, +0, +0, +0, +0, +0, +0, +0, +0, 0,0,0,0,0,0,0,0 }; // // If a side has less than this much material we don't bother scoring // the other side's king safety. Note: this doesn't incl pawn // material. // // 2026-10-06: also now the single dividing line for _EvalKing's whole // safety-vs-activity split (see that function's header comment) -- // below this, the king is actively encouraged out (KING_TO_CENTER) // instead of just not being penalized for leaving. The separate, // stricter KEEP_KING_AT_HOME_THRESHOLD used to gate the stay-home // bonus on its own, independently of this one, leaving a dead band // between the two thresholds where safety was scored but neither the // stay-home bonus nor any come-out encouragement applied. Retired -- // the stay-home bonus now uses this same threshold, so "safety scored" // and "stay-home bonus applies" are exactly the same condition. #define DO_KING_SAFETY_THRESHOLD \ (VALUE_ROOK + VALUE_BISHOP + VALUE_BISHOP + VALUE_KING) static ULONG KING_COUNTER_BY_ATTACK_PATTERN[32] = { //p 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 //m 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 //r 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 //q 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 //k 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0,0,2,2,1,1,3,3,1,1,3,3,2,2,4,4,2,2,3,3,2,2,4,4,2,2,4,4,3,4,5,5 }; static SCORE KING_SAFETY_BY_COUNTER[42] = { -0, -4, -8, -12, -16, -20, -25, -31, -38, -50, -63, -76, -90, -105,-120,-135,-150,-165,-180,-195,-210,-225,-240,-255,-270,-290, -310,-330,-350,-370,-390,-410,-440,-470,-500,-500,-500,-500,-500, -500,-500,-500 }; // Added 2026-08-30: penalty for the enemy queen directly attacking or // x-raying squares near this king, indexed by count (capped at 6). // Replaces the old per-queen "pointing near enemy K" bolt-on // (QUEEN_ATTACKS_SQ_NEXT_TO_KING, computed via the queen's own // mobility ray-cast, direct-attacks only) with a version computed from // data this loop already reads for king safety (no extra attack-table // work) and that also catches x-ray/latent queen threats the old // version missed. Calibrated against the removed term's own magnitude // (uNearKing * 8, capped at 6 -> max 48) rather than guessed, since // that's what was empirically shown to matter for real solve rate -- // see the 180-position king-safety-term distribution sampled // 2026-08-30 (median -27, p75 -16, only ~1% worse than -200) for the // scale this needs to slot into. // 2026-09-14: rescaled from the original -8/count step (see the // 2026-08-30 comment above -- that step was calibrated against a // *removed* legacy term's own magnitude, not against real mate data). // king_safety_data/HANDOFF.md's mate-mining logistic regression found // `queenproximity` (after folding in the collinear front/back/sq3/sq4 // atk_queen sub-features it was absorbing -- see // eval_tune/king_safety_data/HANDOFF.md's 2026-09-14 addendum) has a // per-unit raw coefficient of +1.00, calibrated against // `misscastleshort`'s own cleaned coefficient (+0.71) and this table's // sibling constant KING_MISSING_ONE_CASTLE_OPTION's already-live -23 // value (same direct-EVAL_TERM unit family, unlike the file-storm // tables below which feed the separate uCounter/KING_SAFETY_BY_COUNTER // lookup and need their own, different calibration) -- see // (misscastleshort_live / misscastleshort_raw_coef) = k, then // k * queenproximity_raw_coef =~ -32/count. // // -32/count self-play-tested net negative (2780 games, score 0.490, // llr -1.91 trending to H0) alongside the back-flight bonus below -- // consistent with this term's own weaker calibration confidence flagged // up front (anchored against misscastleshort's never-independently- // validated historical value, a bigger single-step jump than the // file-storm retune's already-large ~1.75-2x). Direction still looks // right (a real, non-collinear predictor), so trimmed 33% to -21/count // rather than reverted outright. Re-validate via sd10 + self-play // before trusting this magnitude either. // -21/count + material scaling (see above) pulled self-play from // clearly negative (score 0.490, llr -1.91 unscaled) to nearly flat // (770 games, score 0.494, llr -0.34, drifting slowly) -- scaling was // the bigger fix, but still trending slightly negative. Trimmed // another ~33% to -14/count. static SCORE KING_QUEEN_PROXIMITY_DANGER[7] = {// 0 1 2 3 4 5 6 +0, -10, -18, -25, -32, -39, -55 }; static SCORE KING_MISSING_ONE_CASTLE_OPTION = -23; // 2026-09-14: new term, not a retune of an existing one. // king_safety_data/HANDOFF.md's regression found `back_flight` (an // empty, unattacked ring square on the side of the king AWAY from the // attacker) is a real, non-collinear PROTECTIVE signal (negative raw // coefficient -0.035, i.e. more open escape squares behind the king // predicts LESS mate risk) -- unlike `front_flight`, which is a real // danger signal already captured by EmptyUnattackedSquare's front // weight. Calibrated the same way as KING_QUEEN_PROXIMITY_DANGER above // (misscastleshort-anchored k =~ -32.4, applied to back_flight's raw // coefficient) =~ +1.1/square, originally rounded to +1 -- but that // +1 was never independently self-play tested in isolation (the // "worth landing and validating" below didn't happen before other // king-safety changes piled on top of it), so it never carried the // weight of a validated constant, just a first guess like everything // else in this file. // // 2026-09-15: nudged +1 -> +3. Every regression refit run this session // (the original mate-mining regression, and 6,890-row and 92,468-row // ElasticNet/Ridge fits on curated mate/control data) puts // back_flight's magnitude at roughly half of front_flight's // (KING_RING_FRONT_FLIGHT_PENALTY, -6); the +1 baseline's ratio (1/6) // was much smaller than that. Small and deliberately so -- this is // the single most novel, least-collinear finding from the regression, // worth landing and validating in isolation before combining with // anything else. static SCORE KING_BACK_FLIGHT_BONUS = 3; // 2026-09-15: _EvalKing's linear-SCORE ring-scan terms, promoted here // from local statics inside that function so they're DNA-registered // (see g_EvalDNA below) and Texel-tunable -- see that promotion's // comment in _EvalKing for why (hand-translating mate-mining // regression coefficients into centipawns via a single assumed anchor // constant was the likely source of this rewrite's self-play // regression, not the underlying feature signal). Starting values are // unchanged from the original hand-translated guesses; only their // storage location/tunability changed here. // // 2026-09-15 (later same day): nudged, NOT re-derived from scratch -- // absolute-magnitude derivation (regression coefficient -> centipawns // via a single anchor constant, then Texel coordinate descent on top of // curated data) was tried and abandoned; every method produced huge, // untrustworthy magnitude swings (see eval_tune/ king-safety session // notes). What *did* replicate cleanly across the original mate-mining // regression, a small-scale (6,890-row) and full-scale (92,468-row) // ElasticNet/Ridge refit was the *relative ranking* between terms, so // only reordering/small nudges within the existing scale are applied: // - MINOR: data unanimously ranks side ~ front > back in danger; // baseline had back rated *most* dangerous (backwards) -- permuted // the same three magnitudes rather than resizing them. // - ROOK: baseline's front > back > side already matched the data's // ranking untouched. // - PAWN: data ranks pawn-ring-attacks mid-tier (stronger than // back-tier piece attacks), baseline had it tied for smallest -- // small bump. // - UNDEFENDED: baseline already had back as the largest magnitude, // matching the one sub-signal (back_undef) that was stable across // every fit -- left alone. front/side undefended-square counts were // the single most consistently weak/sign-unstable feature across // every regression run tried (zeroed by ElasticNet, near-zero and // sign-flipping under Ridge) -- softened slightly rather than left // implying confidence the data doesn't support. // - XRAY: consistently signed, non-trivial magnitude in every fit; // baseline had it smallest in the whole file -- small bump. // - FRONT_FLIGHT_PENALTY: already correctly signed/positioned once // PAWN moved above it -- untouched. // - BACK_FLIGHT_BONUS (see above): data puts this at roughly half of // FRONT_FLIGHT_PENALTY's magnitude; baseline's ratio was much // smaller than that -- small bump. // KING_QUEEN_PROXIMITY_DANGER and KING_MISSING_ONE_CASTLE_OPTION // deliberately NOT touched: the former is already self-play validated // and not cleanly re-derivable at this feature granularity (a 7-bucket // nonlinear table vs. one linear coefficient); the latter applies one // shared constant to both short- and long-castle loss even though the // regression finds those two nowhere near equally dangerous -- fixing // that is a structural change (splitting the constant), not a nudge, // and wasn't made without discussing it first. // // 2026-09-15 (later still): PAWN and XRAY nudged again after a THIRD, // independent calibration method (logistic regression against material // balance -- computed straight from the FEN via python-chess, not // anything derived from these same ring features, so it doesn't have // iSafety's circularity problem) confirmed the same finding as the // first pass: both terms are still ranked mid/low here while every // method tried puts them near the top tier, comparable to front-tier // piece attacks. Rank order elsewhere (9 of 13 comparable terms) // already matched this newest fit without further changes, including // UNDEFENDED[back] and both flight terms -- only these two still // disagreed, so only these two moved again. static SCORE KING_RING_ATTACK_MINOR[3] = { -15, -14, -17 }; static SCORE KING_RING_ATTACK_ROOK[3] = { -14, -11, -8 }; static SCORE KING_RING_ATTACK_PAWN = -12; static SCORE KING_RING_UNDEFENDED[3] = { -4, -12, -5 }; static SCORE KING_RING_XRAY_BONUS = -8; static SCORE KING_RING_FRONT_FLIGHT_PENALTY = -6; static SCORE KING_INITIAL_LOCATION_SCALE = -3; static SCORE KING_ATTACK_PATTERN_SCALE = -10; static SCORE KING_DANGER_ACCELERATOR[7] = {// 0-55 56-111 112-167 168-223 224-279 280-335 336+ 128, 175, 225, 200, 145, 128, 128 }; // Flat "this is bad" flags for _EvalTrappedPieces -- not an attempt to // price the material outcome (search resolves that), just a nudge away // from positions with a piece that looks stuck. ENPRISE_AND_TRAPPED is // larger because that case is opponent-to-move / imminently capturable; // TRAPPED_WITH_MOVE is our own move, so there's still a chance to // wriggle out. static SCORE ENPRISE_AND_TRAPPED_PENALTY = -50; static SCORE TRAPPED_WITH_MOVE_PENALTY = -10; typedef struct _DNA_BASE_SIZE { SCORE *pBase; ULONG uCount; } DNA_BASE_SIZE; #define DNA_VAR(x) {(SCORE *)&(x), 1} #define DNA_ARRAY(x) {(SCORE *)(x), ARRAY_LENGTH(x)} #define DNA_MATRIX(x) {(SCORE *)(x), ARRAY_LENGTH(x) * ARRAY_LENGTH((x)[0])} static DNA_BASE_SIZE g_EvalDNA[] = { DNA_ARRAY(REDUCED_MATERIAL_DOWN_SCALER), DNA_ARRAY(CASTLE_AND_DEVELOPMENT_SCALER), DNA_ARRAY(REDUCED_MATERIAL_UP_SCALER), DNA_ARRAY(PASSER_MATERIAL_UP_SCALER), DNA_ARRAY(PAWN_CENTRALITY_BONUS), DNA_ARRAY(BACKWARD_SHIELDED_BY_LOCATION), DNA_ARRAY(BACKWARD_EXPOSED_BY_LOCATION), DNA_MATRIX(DOUBLED_PAWN_PENALTY_BY_COUNT), DNA_ARRAY(ISOLATED_PAWN_BY_PAWNFILE), DNA_VAR(ISOLATED_EXPOSED_PAWN), DNA_VAR(ISOLATED_DOUBLED_PAWN), DNA_MATRIX(PASSER_BY_RANK), DNA_MATRIX(CANDIDATE_PASSER_BY_RANK), DNA_MATRIX(CONNECTED_PASSERS_BY_RANK), DNA_MATRIX(SUPPORTED_PASSER_BY_RANK), DNA_MATRIX(KING_SUPPORTING_OWN_PASSER_BY_RANK), DNA_ARRAY(OUTSIDE_PASSER_BY_DISTANCE), DNA_ARRAY(PASSER_BONUS_AS_MATERIAL_COMES_OFF), DNA_VAR(RACER_WINS_RACE), DNA_ARRAY(UNDEVELOPED_MINORS_IN_OPENING), DNA_VAR(BISHOP_PAIR_BONUS), DNA_ARRAY(STATIONARY_PAWN_ON_BISHOP_COLOR), DNA_ARRAY(TRANSIENT_PAWN_ON_BISHOP_COLOR), DNA_ARRAY(BISHOP_MOBILITY_BY_SQUARES), DNA_ARRAY(BISHOP_XRAY_MOBILITY_BY_SQUARES), DNA_ARRAY(BISHOP_UNASSAILABLE_BY_DIST_FROM_EKING), DNA_ARRAY(KNIGHT_CENTRALITY_BONUS), DNA_ARRAY(KNIGHT_KING_TROPISM_BONUS), DNA_ARRAY(KNIGHT_UNASSAILABLE_BY_DIST_FROM_EKING), DNA_MATRIX(KNIGHT_ON_INTERESTING_SQUARE_BY_RANK), DNA_ARRAY(KNIGHT_MOBILITY_BY_COUNT), DNA_ARRAY(KNIGHT_WITH_N_PAWNS_SUPPORTING), DNA_ARRAY(KNIGHT_IN_CLOSED_POSITION), DNA_VAR(ROOK_ON_FULL_OPEN), DNA_VAR(ROOK_ON_HALF_OPEN_WITH_ENEMY), DNA_VAR(ROOK_ON_HALF_OPEN_WITH_FRIEND), DNA_VAR(ROOK_WITH_ENEMY_PASSER), DNA_VAR(ROOK_WITH_FRIEND_PASSER), DNA_VAR(ROOK_ON_SEVENTH_BONUS), DNA_ARRAY(ROOK_VALUE_AS_PAWNS_COME_OFF), DNA_VAR(ROOK_CONNECTED_VERT), DNA_VAR(ROOK_CONNECTED_HORIZ), DNA_ARRAY(ROOK_MOBILITY_BY_SQUARES), DNA_ARRAY(ROOK_XRAY_MOBILITY_BY_SQUARES), DNA_ARRAY(QUEEN_MOBILITY_BY_SQUARES), DNA_ARRAY(QUEEN_KING_TROPISM), DNA_MATRIX(KING_INITIAL_COUNTER_BY_LOCATION), DNA_MATRIX(KING_EVAL_INITIAL_LOCATION), DNA_ARRAY(KING_TO_CENTER), DNA_ARRAY(KING_SAFETY_BY_COUNTER), DNA_ARRAY(KING_QUEEN_PROXIMITY_DANGER), DNA_VAR(KING_MISSING_ONE_CASTLE_OPTION), DNA_VAR(KING_BACK_FLIGHT_BONUS), DNA_ARRAY(KING_RING_ATTACK_MINOR), DNA_ARRAY(KING_RING_ATTACK_ROOK), DNA_VAR(KING_RING_ATTACK_PAWN), DNA_ARRAY(KING_RING_UNDEFENDED), DNA_VAR(KING_RING_XRAY_BONUS), DNA_VAR(KING_RING_FRONT_FLIGHT_PENALTY), DNA_VAR(KING_INITIAL_LOCATION_SCALE), DNA_VAR(KING_ATTACK_PATTERN_SCALE), DNA_ARRAY(KING_DANGER_ACCELERATOR) }; ULONG DNABufferSizeBytes() { ULONG u; ULONG uSize = 0; for (u = 0; u < ARRAY_LENGTH(g_EvalDNA); u++) { uSize += 10 * g_EvalDNA[u].uCount; } return uSize + 1; } char * ExportEvalDNA() { ULONG uSize = DNABufferSizeBytes(); char *p = malloc(uSize); char *pch; ULONG u, v; SCORE *q; FLAG fFirst = TRUE; memset(p, 0, uSize); pch = p; for (u = 0; u < ARRAY_LENGTH(g_EvalDNA); u++) { q = g_EvalDNA[u].pBase; for (v = 0; v < g_EvalDNA[u].uCount; v++) { size_t cbLeft = uSize - (size_t)(pch - p); if (!fFirst) { pch += snprintf(pch, cbLeft, ",%d", *q); } else { pch += snprintf(pch, cbLeft, "%d", *q); fFirst = FALSE; } q++; } *pch++ = '\n'; *pch = '\0'; fFirst = TRUE; } return p; // caller must free } FLAG WriteEvalDNA(char *szFilename) { FILE *p = NULL; char *q = NULL; FLAG fRet = FALSE; if (SystemDoesFileExist(szFilename)) goto end; p = fopen(szFilename, "a+b"); if (!p) goto end; q = ExportEvalDNA(); if (!q) goto end; fprintf(p, "%s", q); fRet = TRUE; end: if (p) fclose(p); if (q) free(q); return fRet; } FLAG ImportEvalDNA(char *p) { ULONG u, v; for (u = 0; u < ARRAY_LENGTH(g_EvalDNA); u++) { for (v = 0; v < g_EvalDNA[u].uCount; v++) { while(*p && (!isdigit(*p) && (*p != '-'))) p++; if (*p == '\0') return FALSE; *(g_EvalDNA[u].pBase + v) = atoi(p); while(*p && (isdigit(*p) || (*p == '-'))) p++; } } return TRUE; } FLAG ReadEvalDNA(char *szFilename) { FILE *p = NULL; ULONG uSize = DNABufferSizeBytes(); char *q = malloc(uSize); FLAG fRet = FALSE; static char line[1024]; char *c; if (!q) goto end; memset(q, 0, uSize); p = fopen(szFilename, "rb"); if (!p) { Trace("Failed to open file \"%s\"\n", szFilename); goto end; } while(fgets(line, 1024, p) != NULL) { c = strchr(line, '#'); if (c) *c = '\0'; c = line; strcat(q, c); } fRet = ImportEvalDNA(q); end: if (q) free(q); if (p) fclose(p); return fRet; } // // Misc stuff // --------------------------------------------------------------------------- // // // The three ranks "around" a rank (indexed by rank, used in eval.c) // BITBOARD BBADJACENT_RANKS[9] = { 0, BBRANK11 | BBRANK22, BBRANK11 | BBRANK22 | BBRANK33, BBRANK22 | BBRANK33 | BBRANK44, BBRANK33 | BBRANK44 | BBRANK55, BBRANK44 | BBRANK55 | BBRANK66, BBRANK55 | BBRANK66 | BBRANK77, BBRANK66 | BBRANK77 | BBRANK88, BBRANK77 | BBRANK88 }; // // The files "around" one, indexed by file (used in eval.c) // BITBOARD BBADJACENT_FILES[8] = { // A = 0 BBFILEB, // B = 1 BBFILEA | BBFILEC, // C = 2 BBFILEB | BBFILED, // D = 3 BBFILEC | BBFILEE, // E = 4 BBFILED | BBFILEF, // F = 5 BBFILEE | BBFILEG, // G = 6 BBFILEF | BBFILEH, // H = 7 BBFILEG }; // // Same as BBADJACENT_FILES, but including the file itself -- callers // that used to OR in BBFILE[file] separately at every call (only one // site, eval.c's _EvalKing) can index this instead and skip the extra // load + OR. // BITBOARD BBADJACENT_FILES_INCLUSIVE[8] = { // A = 0 BBFILEA | BBFILEB, // B = 1 BBFILEA | BBFILEB | BBFILEC, // C = 2 BBFILEB | BBFILEC | BBFILED, // D = 3 BBFILEC | BBFILED | BBFILEE, // E = 4 BBFILED | BBFILEE | BBFILEF, // F = 5 BBFILEE | BBFILEF | BBFILEG, // G = 6 BBFILEF | BBFILEG | BBFILEH, // H = 7 BBFILEG | BBFILEH }; // // The ranks preceeding one, indexed by rank/color of pawn (used in // eval.c) // BITBOARD BBPRECEEDING_RANKS[8][2] = { // BLACK WHITE // ----- ----- { // 0 == RANK8 BBRANK72, 0 }, { // 1 == RANK7 BBRANK62, 0 }, { // 2 == RANK6 BBRANK52, BBRANK77 }, { // 3 == RANK5 BBRANK42, BBRANK67 }, { // 4 == RANK4 BBRANK32, BBRANK57 }, { // 5 == RANK3 BBRANK22, BBRANK47 }, { // 6 == RANK2 0, BBRANK37 }, { // 7 == RANK1 0, BBRANK27 } }; static FLAG _IsSquareSafeFromEnemyPawn(IN POSITION *pos, IN COOR c, IN BITBOARD bb) /** Routine description: Determine if a piece in square c is "outposted". A piece is outposted if no enemy pawns can advance to attack it / drive it away. Parameters: POSITION *pos : the board COOR c : the square (must not be empty!) BITBOARD bb : the bitboard of pawns you want to consider Return value: FLAG : TRUE if the piece is safe/outposted, FALSE otherwise **/ { ULONG uColor = GET_COLOR(pos->rgSquare[c].pPiece); ULONG uFile, uRank; #ifdef DEBUG COOR cSquare; PIECE p = pos->rgSquare[c].pPiece; BITBOARD dbb = bb; ASSERT(IS_ON_BOARD(c)); ASSERT(p && (IS_BISHOP(p) || IS_KNIGHT(p) || IS_PAWN(p))); ASSERT(IS_VALID_COLOR(uColor)); #endif uFile = FILE(c); ASSERT(uFile < 8); bb &= BBADJACENT_FILES[uFile]; ASSERT(((c & 0x70) >> 4) == (c >> 4)); uRank = c >> 4; ASSERT(uRank < 8); bb &= BBPRECEEDING_RANKS[uRank][uColor]; #ifdef DEBUG if (bb != 0) { while(IS_ON_BOARD(cSquare = CoorFromBitBoardRank8ToRank1(&dbb))) { ASSERT(pos->rgSquare[cSquare].pPiece); ASSERT(IS_PAWN(pos->rgSquare[cSquare].pPiece)); if ((FILE(cSquare) == (FILE(c) - 1)) || (FILE(cSquare) == (FILE(c) + 1))) { switch(uColor) { case WHITE: if (RANK(cSquare) > RANK(c)) { return(FALSE); } break; case BLACK: if (RANK(cSquare) < RANK(c)) { return(FALSE); } break; } } } ASSERT(FALSE); } else { ASSERT(bb == 0); while(IS_ON_BOARD(cSquare = CoorFromBitBoardRank8ToRank1(&dbb))) { ASSERT(pos->rgSquare[cSquare].pPiece); ASSERT(IS_PAWN(pos->rgSquare[cSquare].pPiece)); if ((FILE(cSquare) == (FILE(c) - 1)) || (FILE(cSquare) == (FILE(c) + 1))) { switch(uColor) { case WHITE: if (RANK(cSquare) > RANK(c)) { ASSERT(FALSE); } break; case BLACK: if (RANK(cSquare) < RANK(c)) { ASSERT(FALSE); } break; } } } } #endif return(bb == 0); } static ULONG _WhoControlsSquareFast(IN POSITION *pos, IN COOR c) /** Routine description: Determine which side controls a board square. Parameters: POSITION *pos : the board COOR c : the square in question Return value: static ULONG : (ULONG)-1 if neither side controls it or the sides control it evenly, WHITE if white controls the square, or BLACK if black controls the square. **/ { // // board_representation/EVAL.md section 9: bvAttacks/ATTACK_BITV // retired entirely now that king (the last piece to write it) has // converted -- every side's presence at this square is read // straight off its own bbXAttacks accumulator instead. Bit // positions (PAWN_BIT/MINOR_BIT/ROOK_BIT/QUEEN_BIT/KING_BIT) are // unchanged so g_SwapTable's indexing below still sees the same // shape it always has; x-ray-only presence (bbMinorXrayAttacks/ // bbRookXrayAttacks/bbQueenXrayAttacks) ORs into the same // byte-scale bit as its direct-attack counterpart, matching the // old struct's .uSmall/.uXray sharing one bit position for // "attacks or x-rays" (see g_SwapTable's own construction). King // has no x-ray (can't move through a blocker). This function is // only ever called after *both* kings finish evaluating (the // passed-pawn re-check and trapped-piece/danger passes all run // after Eval()'s king-eval block), so pos->bbKingAttacks is always // fully populated for both colors here -- unlike _EvalKing's own, // deliberately asymmetric internal bvAttack (see that function's // comment), this is a plain, symmetric fact query. // BITBOARD sq = COOR_TO_BB(c); ULONG uWhite = ((pos->bbPawnAttacks[WHITE] & sq) ? PAWN_BIT : 0) | ((pos->bbMinorAttacks[WHITE] & sq) ? MINOR_BIT : 0) | ((pos->bbMinorXrayAttacks[WHITE] & sq) ? MINOR_BIT : 0) | ((pos->bbRookAttacks[WHITE] & sq) ? ROOK_BIT : 0) | ((pos->bbRookXrayAttacks[WHITE] & sq) ? ROOK_BIT : 0) | ((pos->bbQueenAttacks[WHITE] & sq) ? QUEEN_BIT : 0) | ((pos->bbQueenXrayAttacks[WHITE] & sq) ? QUEEN_BIT : 0) | ((pos->bbKingAttacks[WHITE] & sq) ? KING_BIT : 0); ULONG uBlack = ((pos->bbPawnAttacks[BLACK] & sq) ? PAWN_BIT : 0) | ((pos->bbMinorAttacks[BLACK] & sq) ? MINOR_BIT : 0) | ((pos->bbMinorXrayAttacks[BLACK] & sq) ? MINOR_BIT : 0) | ((pos->bbRookAttacks[BLACK] & sq) ? ROOK_BIT : 0) | ((pos->bbRookXrayAttacks[BLACK] & sq) ? ROOK_BIT : 0) | ((pos->bbQueenAttacks[BLACK] & sq) ? QUEEN_BIT : 0) | ((pos->bbQueenXrayAttacks[BLACK] & sq) ? QUEEN_BIT : 0) | ((pos->bbKingAttacks[BLACK] & sq) ? KING_BIT : 0); ULONG u; PIECE p; CHAR ch; // g_SwapTable is only [14][32][32] (data.c) -- this is the bound // that actually matters, not just "no garbage above bit 7" below. // PAWN_BIT..KING_BIT briefly didn't fit in bits 0-4 earlier this // session (when _WhoControlsSquareFast was converted to read them // directly instead of going through the old ATTACK_BITV struct) // and silently indexed out of bounds on every attacked square -- // the (& 0xFFFFFF00) checks below never caught it (board_ // representation/EVAL.md section 9). ASSERT(uWhite < 32); ASSERT(uBlack < 32); ASSERT((uWhite & 0xFFFFFF00) == 0); ASSERT((uBlack & 0xFFFFFF00) == 0); p = pos->rgSquare[c].pPiece; ch = g_SwapTable[p][uWhite][uBlack]; if (ch != 0) { u = ch; u >>= 7; u = u & 1; ASSERT(((u == 1) && (ch < 0)) || ((u == 0) && (ch > 0))); return(FLIP(u)); } return((ULONG)-1); } /** Routine description: Zero out the Eval()-scoped attack-bitboard accumulators before building them for this call. Used to clear the old per-square rgSquare[c|8].bvAttacks/ATTACK_BITV structure too (a full-board macro-unrolled loop, since every square's storage needed zeroing); retired along with that structure (2026-09-05, board_ representation/EVAL.md section 9) -- nothing left to clear but the bbXAttacks accumulators themselves. Parameters: POSITION *pos Return value: void **/ static void _ClearAttackTables(IN OUT POSITION *pos) { pos->bbMinorAttacks[WHITE] = pos->bbMinorAttacks[BLACK] = 0; pos->bbMinorXrayAttacks[WHITE] = pos->bbMinorXrayAttacks[BLACK] = 0; pos->bbRookAttacks[WHITE] = pos->bbRookAttacks[BLACK] = 0; pos->bbRookXrayAttacks[WHITE] = pos->bbRookXrayAttacks[BLACK] = 0; pos->bbQueenAttacks[WHITE] = pos->bbQueenAttacks[BLACK] = 0; pos->bbQueenXrayAttacks[WHITE] = pos->bbQueenXrayAttacks[BLACK] = 0; pos->bbKingAttacks[WHITE] = pos->bbKingAttacks[BLACK] = 0; } static INLINE void _InitializePawnHashEntry(IN OUT PAWN_HASH_ENTRY *pHash, IN POSITION *pos) /** Routine description: Parameters: PAWN_HASH_ENTRY *pHash, POSITION *pos Return value: static INLINE void **/ { memset(pHash, 0, sizeof(PAWN_HASH_ENTRY)); pHash->u64Key = pos->u64PawnSig; } static INLINE void _EvaluateCandidatePasser(IN POSITION *pos, IN OUT PAWN_HASH_ENTRY *pHash, IN COOR c) /** Routine description: Parameters: POSITION *pos, PAWN_HASH_ENTRY *pHash, COOR c Return value: static INLINE **/ { COOR c1, cSquare; PIECE pSentry, pHelper; ULONG ucFile = FILE(c); ULONG uPawnFile = ucFile + 1; BITBOARD bb; ULONG uSentries, uHelpers; ULONG uColor; ULONG xColor; int d1; #ifdef DEBUG COOR cVerifySquare; ULONG uVerifySentries; #endif ASSERT(IS_ON_BOARD(c)); ASSERT(RANK(c) >= 2); ASSERT(RANK(c) <= 7); pHelper = pos->rgSquare[c].pPiece; ASSERT(IS_PAWN(pHelper)); uColor = GET_COLOR(pHelper); ASSERT(IS_VALID_COLOR(uColor)); xColor = FLIP(uColor); // The only way a pawn can be a passer/candidate if the other // side has a pawn on its same file is if that enemy pawn is // behind it. This is a corner case but it is important to // detect all passers. if (pHash->uCountPerFile[xColor][uPawnFile] != 0) { ASSERT((pos->bbPawns[xColor] & BBFILE[ucFile]) != 0); switch(uColor) { case WHITE: bb = pos->bbPawns[BLACK] & BBFILE[ucFile]; ASSERT(bb); while(IS_ON_BOARD(c1 = CoorFromBitBoardRank8ToRank1(&bb))) { ASSERT(FILE(c1) == ucFile); if (c1 < c) return; } break; case BLACK: bb = pos->bbPawns[WHITE] & BBFILE[ucFile]; ASSERT(bb); while(IS_ON_BOARD(c1 = CoorFromBitBoardRank1ToRank8(&bb))) { ASSERT(FILE(c1) == ucFile); if (c1 > c) return; } break; } } // Count xColor's sentry pawns and determine the location of the // critical square for the pawn at c to become a passer. Note if // there are no sentries then this pawn (on square c) is a passer // already, not a candidate. bb = pos->bbPawns[xColor] & BBADJACENT_FILES[ucFile]; bb &= BBPRECEEDING_RANKS[(c & 0x70) >> 4][uColor]; if (!bb) { ASSERT(FastCountBits(bb) == 0); // There are no enemy sentries so this pawn is a passer. pHash->bbPasserLocations[uColor] |= COOR_TO_BB(c); ASSERT(FastCountBits(pHash->bbPasserLocations[uColor]) > 0); ASSERT(FastCountBits(pHash->bbPasserLocations[uColor]) <= 8); EVAL_TERM(uColor, PAWN, c, pHash->iScore[uColor], PASSER_BY_RANK[uColor][RANK(c)], "passed pawn"); // However, don't give doubled passers such a big bonus. if (IS_PAWN(pos->rgSquare[c - 16 * g_iAhead[uColor]].pPiece)) { EVAL_TERM(uColor, PAWN, c, pHash->iScore[uColor], -(PASSER_BY_RANK[uColor][RANK(c)] / 2), "doubled passer"); } return; } uSentries = FastCountBits(bb); // There's one or more sentry pawns so we'll look for friendly // helpers to decide if this pawn is a candidate passer. First // figure out the critical square we need to get the passer // through. // // Cheap short-circuit first: an advanced pawn (rank 6/7 for WHITE, // rank 2/3 for BLACK) with a friend pawn on either adjacent file // already qualifies as a candidate regardless of what the (far // more expensive) helper-square walk below would find -- the two // conditions are OR'd together at the bottom of this function, so // computing uHelpers when this is already true is pure wasted // work. Skip straight to the candidate-passer bonus in that case. // if ((pHash->uCountPerFile[uColor][uPawnFile + 1] + pHash->uCountPerFile[uColor][uPawnFile - 1]) && (((WHITE == uColor) && (RANK(c) > 5)) || ((BLACK == uColor) && (RANK(c) < 4)))) { goto give_candidate_bonus; } if (uColor == WHITE) { pSentry = BLACK_PAWN; cSquare = CoorFromBitBoardRank1ToRank8(&bb); cSquare += 0x10; } else { pSentry = WHITE_PAWN; cSquare = CoorFromBitBoardRank8ToRank1(&bb); cSquare -= 0x10; } cSquare &= 0xF0; cSquare |= ucFile; ASSERT(IS_ON_BOARD(cSquare)); ASSERT(FILE(cSquare) == ucFile); #ifdef DEBUG uVerifySentries = 0; cVerifySquare = 0; d1 = 16 * g_iAhead[uColor]; c1 = c + d1; do { if (IS_ON_BOARD(c1 - 1)) { if (pos->rgSquare[c1 - 1].pPiece == pSentry) { uVerifySentries++; if (0 == cVerifySquare) { cVerifySquare = c1 - d1; ASSERT(cVerifySquare == cSquare); } } } if (IS_ON_BOARD(c1 + 1)) { if (pos->rgSquare[c1 + 1].pPiece == pSentry) { uVerifySentries++; if (0 == cVerifySquare) { cVerifySquare = c1 - d1; ASSERT(cVerifySquare == cSquare); } } } c1 = c1 + d1; } while(!RANK8(c1) && !RANK1(c1)); ASSERT(uVerifySentries == uSentries); #endif // // Note: we don't do this with bitboards because we want to not // consider a pawn to be a potential passer if it can't safely // advance to get into helper position. // // IDEA: scale the candidate passer bonus based on rank AND on // the distance the helper(s) have to go to get into position. // // FIXED 2026-09-05 (found while removing rgSquare[c|8].bvAttacks // entirely, board_representation/EVAL.md section 9; landed as its // own change with its own before/after check, not bundled into // that mechanical cleanup commit). This function runs from // _EvalPawns, which is the *first* piece type evaluated each // Eval() call, so the only attack data that actually exists yet is // pos->bbPawnAttacks -- every non-pawn piece, and (since commit // 57502d6) pawns' own old bvAttacks write, happens later in the // same call. The original condition here read the old combined // bvAttacks word (all piece types), which had been silently // always-zero -- and this gate silently always-true -- since // 57502d6; narrowed to what's actually valid at this point: // pos->bbPawnAttacks only. This is narrower than the original // presumably intended (any piece type, not just pawns), but it's // a real, correct check instead of a fake one, and pawns are the // dominant real-world case for contesting a helper-pawn square // anyway. // uHelpers = 0; d1 = 16 * g_iAhead[uColor]; ASSERT(-d1 == 16 * g_iBehind[uColor]); c1 = cSquare + 1 - d1; if ((IS_ON_BOARD(c1)) && (pHash->uCountPerFile[uColor][FILE(c1) + 1])) { ASSERT(pos->bbPawns[uColor] & BBFILE[FILE(c1)]); if (!(pos->bbPawnAttacks[xColor] & COOR_TO_BB(c1)) || (pos->bbPawnAttacks[uColor] & COOR_TO_BB(c1))) { // Friend helper pawn there? if (pos->rgSquare[c1].pPiece == pHelper) { uHelpers = 1; goto do_left; } // There is no helper pawn in the support position yet. // See if one can get there. c1 = c1 - d1; while (IS_ON_BOARD(c1) && ((!(pos->bbPawnAttacks[xColor] & COOR_TO_BB(c1))) || (pos->bbPawnAttacks[uColor] & COOR_TO_BB(c1)))) { if (pos->rgSquare[c1].pPiece == pHelper) { uHelpers = 1; break; } else if (pos->rgSquare[c1].pPiece == pSentry) { break; } c1 = c1 - d1; } } } do_left: c1 = cSquare - 1 - d1; if ((IS_ON_BOARD(c1)) && (pHash->uCountPerFile[uColor][FILE(c1) + 1])) { ASSERT(pos->bbPawns[uColor] & BBFILE[FILE(c1)]); if (!(pos->bbPawnAttacks[xColor] & COOR_TO_BB(c1)) || (pos->bbPawnAttacks[uColor] & COOR_TO_BB(c1))) { // Already a helper there? if (pos->rgSquare[c1].pPiece == pHelper) { uHelpers++; goto done_helpers; } // There is no pawn in the left support position yet. See // if one can get there. c1 -= d1; while (IS_ON_BOARD(c1) && ((!(pos->bbPawnAttacks[xColor] & COOR_TO_BB(c1))) || (pos->bbPawnAttacks[uColor] & COOR_TO_BB(c1)))) { if (pos->rgSquare[c1].pPiece == pHelper) { uHelpers++; break; } else if (pos->rgSquare[c1].pPiece == pSentry) { break; } c1 -= d1; } } } done_helpers: if (uHelpers >= uSentries) { give_candidate_bonus: ASSERT(CANDIDATE_PASSER_BY_RANK[uColor][RANK(c)] > 0); EVAL_TERM(uColor, PAWN, c, pHash->iScore[uColor], CANDIDATE_PASSER_BY_RANK[uColor][RANK(c)], "candidate passer"); // If the other side has no pieces then give this candidate an // extra bonus -- used to be a second full copy of the same // CANDIDATE_PASSER_BY_RANK value (an exact duplicate of the // term just added above, not a different angle on it), now a // fractional modifier. if (TotalNonPawnCount(pos, xColor) == 1) { EVAL_TERM(uColor, PAWN, c, pHash->iScore[uColor], CANDIDATE_PASSER_BY_RANK[uColor][RANK(c)] / 2, "candidate passer in endgame"); } } } static void _EvaluateConnectedSupportedOutsidePassers(IN POSITION *pos, IN OUT PAWN_HASH_ENTRY *pHash) /** Routine description: Parameters: POSITION *pos, PAWN_HASH_ENTRY *pHash Return value: void **/ { ULONG uColor; ULONG xColor; ULONG u, v; COOR c; COOR cLeftmostPasser, cRightmostPasser; PIECE pFriend; COOR cSupport; BITBOARD bb; static const INT iDelta[5] = { -1, +1, +17, +15, 0 }; FOREACH_COLOR(uColor) { ASSERT(IS_VALID_COLOR(uColor)); xColor = FLIP(uColor); if (pHash->bbPasserLocations[uColor]) { ASSERT(FastCountBits(pos->bbPawns[uColor]) > 0); pFriend = BLACK_PAWN | uColor; cLeftmostPasser = cRightmostPasser = ILLEGAL_COOR; // Leftmost/rightmost is just a min/max over FILE(c) -- no // need to wrap the passer walk in an outer per-file loop // just to get a file-ordered traversal; a single flat walk // over the whole bbPasserLocations bitboard visits the same // squares (CoorFromBitBoardRank8ToRank1 pops in rank-major // order, so leftmost/rightmost has to be tracked by explicit // comparison either way, not by iteration order). bb = pHash->bbPasserLocations[uColor]; while(IS_ON_BOARD(c = CoorFromBitBoardRank8ToRank1(&bb))) { ASSERT(pHash->uCountPerFile[uColor][FILE(c)+1] != 0); ASSERT(RANK(c) > 1); ASSERT(RANK(c) < 8); if ((cLeftmostPasser == ILLEGAL_COOR) || (FILE(c) < FILE(cLeftmostPasser))) { cLeftmostPasser = c; } if ((cRightmostPasser == ILLEGAL_COOR) || (FILE(c) > FILE(cRightmostPasser))) { cRightmostPasser = c; } v = 0; while(iDelta[v] != 0) { cSupport = c + iDelta[v] * g_iBehind[uColor]; if (IS_ON_BOARD(cSupport)) { if (pHash->bbPasserLocations[uColor] & COOR_TO_BB(cSupport)) { ASSERT(CONNECTED_PASSERS_BY_RANK[uColor] [RANK(c)] > 0); EVAL_TERM(uColor, PAWN, c, pHash->iScore[uColor], CONNECTED_PASSERS_BY_RANK[uColor] [RANK(c)], "connected passers"); // // TODO: connected passers vs a R is // strong. // } else if (pos->rgSquare[cSupport].pPiece == pFriend) { ASSERT(SUPPORTED_PASSER_BY_RANK[uColor] [RANK(c)] > 0); EVAL_TERM(uColor, PAWN, c, pHash->iScore[uColor], SUPPORTED_PASSER_BY_RANK[uColor] [RANK(c)], "supported passer"); } } v++; } } #ifdef DEBUG ASSERT(IS_ON_BOARD(cLeftmostPasser)); ASSERT(IS_ON_BOARD(cRightmostPasser)); ASSERT(RANK(cLeftmostPasser) > 1); ASSERT(RANK(cRightmostPasser) > 1); ASSERT(RANK(cLeftmostPasser) < 8); ASSERT(RANK(cRightmostPasser) < 8); if (FastCountBits(pHash->bbPasserLocations[uColor]) == 1) { ASSERT(cLeftmostPasser == cRightmostPasser); } #endif for (u = A; u <= D; u++) { if (pHash->uCountPerFile[xColor][u + 1] != 0) { ASSERT(pos->bbPawns[xColor] & BBFILE[u]); if (!(pHash->bbPasserLocations[xColor] & BBFILE[u])) { break; } } } if (u > FILE(cLeftmostPasser)) { EVAL_TERM(uColor, PAWN, ILLEGAL_COOR, pHash->iScore[uColor], OUTSIDE_PASSER_BY_DISTANCE[u-FILE(cLeftmostPasser)], "left outside passer"); } for (u = H; u >= E; u--) { if (pHash->uCountPerFile[xColor][u + 1] != 0) { ASSERT(pos->bbPawns[xColor] & BBFILE[u]); if (!(pHash->bbPasserLocations[xColor] & BBFILE[u])) { break; } } } if (u < FILE(cRightmostPasser)) { EVAL_TERM(uColor, PAWN, ILLEGAL_COOR, pHash->iScore[uColor], OUTSIDE_PASSER_BY_DISTANCE[FILE(cRightmostPasser)-u], "right outside passer"); } } } } // board_representation/EVAL.md section 2/0d: bitboard replacement for // the old per-pawn mailbox delta+IS_ON_BOARD population this function // used to do. pos->bbPawns[2] already has every pawn location // (incrementally maintained, chess.h) with zero per-pawn iteration // needed to query it -- the exact shift-and-mask technique // generate.c's _GenerateAllPawnMovesBB already uses to bulk-generate a // whole side's pawn captures (its bbCapLeft/bbCapRight, before being // masked down to actual enemy-occupied squares) is exactly "every // square this side's pawns attack" -- reused here verbatim, minus the // enemy-occupancy mask, since attack-bit population doesn't care what // (if anything) sits on the attacked square. See that function's // header comment for the full square-numbering/shift-direction // derivation (WHITE forward = bb >> 8, BLACK forward = bb << 8, // diagonals need the *opposite* file excluded to prevent same-row // wraparound) -- not repeated here. // // Unlike the old version, this does NOT write PAWN_BIT into the old // rgSquare[c|8].bvAttacks/ATTACK_BITV mechanism (retired entirely as // of 2026-09-05, once king -- the last piece writing it -- converted // too) -- pos->bbPawnAttacks[2] (chess.h) is the single source of // truth for "does a pawn attack this square", read directly by every // consumer. _ClearAttackTables(pos) still needs to run here first, to // zero the other bbXAttacks accumulators knight/bishop/rook/queen/king // populate as they each evaluate. static void _PopulatePawnAttackBits(IN OUT POSITION *pos) /** Routine description: Populate the attack table with pawn bits. Parameters: POSITION *pos : the board Return value: void **/ { _ClearAttackTables(pos); pos->bbPawnAttacks[BLACK] = ((pos->bbPawns[BLACK] & ~BBFILE[0]) << 7) | ((pos->bbPawns[BLACK] & ~BBFILE[7]) << 9); pos->bbPawnAttacks[WHITE] = ((pos->bbPawns[WHITE] & ~BBFILE[0]) >> 9) | ((pos->bbPawns[WHITE] & ~BBFILE[7]) >> 7); } static INLINE FLAG _FileCanSupportPawn(IN POSITION *pos, IN PAWN_HASH_ENTRY *pHash, IN ULONG uColor, IN ULONG uPawnFile, IN COOR c, IN BITBOARD bbBlockingRanks) /** Routine description: Can a friendly pawn on uPawnFile ever defend the pawn on square c -- either right now (already within defending range) or later (nothing permanently blocks it from advancing into range)? NOTE: on a doubled adjacent file, this only looks at whether *a* helper pawn on uPawnFile can reach c -- if the nearest one's only route there is an unsafe one-step push, this returns FALSE even though a second, more distant pawn on the same file might still reach c safely later. Rare (requires doubled pawns on the adjacent file specifically) and consistent with the rest of this function's approximate, snapshot-in-time nature. Parameters: POSITION *pos PAWN_HASH_ENTRY *pHash ULONG uColor : color of the pawn on c (and of the potential helper) ULONG uPawnFile : the adjacent file to test (0-7) COOR c : the pawn being supported BITBOARD bbBlockingRanks : c's rank plus every rank behind it, from uColor's forward direction (see caller) Return value: FLAG **/ { ULONG xColor = FLIP(uColor); if (0 == pHash->uCountPerFile[uColor][uPawnFile + 1]) { return FALSE; // no friendly pawn on that file at all } if (pos->bbPawns[uColor] & BBFILE[uPawnFile] & BBADJACENT_RANKS[RANK(c)]) { return TRUE; // already defending } // A friendly pawn one step short of defending range would have to // push onto its destination square to get there. If a live enemy // pawn attacks that destination and no friendly pawn attack of // our own covers it too (pos->bbPawnAttacks[] is already // populated by _PopulatePawnAttackBits before either _EvalPawns // pass runs, so both are real, current facts, not a guess about // some future position), pushing there just loses the pawn for // nothing -- not a safe way to arrive as a defender. If we also // attack the destination, the push is at worst an even trade, so // it doesn't disqualify this file. WHITE pushes toward decreasing // bitboard index (see _PopulatePawnAttackBits), so a pawn one // push short of the defending band sits at (band << 8), and its // destination is (that square >> 8) -- i.e. the original band // itself; BLACK is mirrored. { BITBOARD bbOneStepShort = (uColor == WHITE) ? (BBADJACENT_RANKS[RANK(c)] << 8) : (BBADJACENT_RANKS[RANK(c)] >> 8); BITBOARD bbHelper = pos->bbPawns[uColor] & BBFILE[uPawnFile] & bbOneStepShort; if (bbHelper) { BITBOARD bbDestination = (uColor == WHITE) ? (bbHelper >> 8) : (bbHelper << 8); if ((bbDestination & pos->bbPawnAttacks[xColor]) && !(bbDestination & pos->bbPawnAttacks[uColor])) { return FALSE; } } } // A friendly pawn is on the file but not yet close enough to // defend -- it can still march up and defend later, unless an // enemy pawn on this same file already sits at c's rank or behind // it (from our own forward direction), permanently blocking the // way. return (0 == (pos->bbPawns[xColor] & BBFILE[uPawnFile] & bbBlockingRanks)); } static INLINE FLAG _IsBackwardPawn(IN POSITION *pos, IN ULONG uColor, IN COOR c, IN COOR cSquare) /** Routine description: Is the pawn on square c "backward"? See "Pawn Power in Chess" pp. 25-27. The caller has already established the one condition that needs pos->bbPawnAttacks[]: the enemy, not a friendly pawn, controls c's stop square (cSquare). This checks the three remaining, independently-necessary conditions: 1. cSquare isn't itself occupied by a pawn (either color) -- otherwise this is a blocked/rammed pawn, not a backward one. 2. c has advanced far enough for the classification to apply. 3. Neither neighbor on an adjacent file, one rank ahead of c, is a friendly pawn -- i.e. our neighbors have already advanced past c, so they can no longer shield it. (0x88 coordinates make cSquare +/- 1 safe to test directly: IS_ON_BOARD() catches the file-edge case for free, unlike a bitboard shift which would need explicit BBFILE[0]/BBFILE[7] masking.) Parameters: POSITION *pos ULONG uColor : color of the pawn on c COOR c : the pawn being tested COOR cSquare : c's stop square (one square ahead of c) Return value: FLAG **/ { PIECE p; if (IS_PAWN(pos->rgSquare[cSquare].pPiece)) { return FALSE; // stop square is blocked by a pawn } if (!(((WHITE == uColor) && (RANK(c) < 4)) || ((BLACK == uColor) && (RANK(c) > 5)))) { return FALSE; // not advanced enough yet } p = (BLACK_PAWN | uColor); // uColor's own pawn, regardless of color return ((IS_ON_BOARD(cSquare - 1) && (pos->rgSquare[cSquare - 1].pPiece == p)) || (IS_ON_BOARD(cSquare + 1) && (pos->rgSquare[cSquare + 1].pPiece == p))); } PAWN_HASH_ENTRY * EvalPawns(IN OUT SEARCHER_THREAD_CONTEXT *ctx, OUT FLAG *pfDeferred) /** Routine description: Evaluate pawn structures; return a ptr to a pawn hash entry. Exposed (non-static) so testrecogn.c can build a real, fully-populated PAWN_HASH_ENTRY (bbPasserLocations included) to drive an EGTB cross-check of _EvalPasserRacesAgainstLoneKings -- same rationale as SideHasWinningChances's own exposure above. Parameters: SEARCHER_THREAD_CONTEXT *ctx : the searcher thread context Return value: PAWN_HASH_ENTRY * **/ { static ULONG uUnmovedRank[2] = { 0x10, 0x60 }; POSITION *pos = &ctx->sPosition; PAWN_HASH_ENTRY *pHash; COOR c, cSquare; ULONG uIsolated[2]; ULONG uDoubled[2]; SCORE iDuos[2]; ULONG u, uPawnFile; ULONG uColor; BITBOARD bb; BITBOARD bbBlockingRanks; int d1; #ifdef DEBUG SCORE t; #endif // Look up the hash entry for this position. INC(ctx->sCounters.pawnhash.u64Probes); pHash = PawnHashLookup(ctx); ASSERT(NULL != pHash); if (pHash->u64Key == pos->u64PawnSig) { *pfDeferred = TRUE; INC(ctx->sCounters.pawnhash.u64Hits); return(pHash); } // We need the attack table to evaluate the pawns... and we missed // the hash table so we have to populate it now. Can't defer this // one. *pfDeferred = FALSE; _InitializePawnHashEntry(pHash, pos); _PopulatePawnAttackBits(pos); uIsolated[BLACK] = uIsolated[WHITE] = 0; uDoubled[BLACK] = uDoubled[WHITE] = 0; iDuos[BLACK] = iDuos[WHITE] = 0; // First pass -- everything here except the per-square centrality // bonus is a closed-form aggregate over pos->bbPawns[uColor] // (uCountPerFile, uNumUnmovedPawns, bbStationaryPawns/ // uNumRammedPawns), so none of it needs a per-pawn mailbox walk; // only the centrality lookup genuinely needs one (it's a per-square // table, not summable any other way). BITBOARD bbAllPawns = pos->bbPawns[WHITE] | pos->bbPawns[BLACK]; FOREACH_COLOR(uColor) { ASSERT(IS_VALID_COLOR(uColor)); // Pre-count number of pawns per file, unrolled. ASSERT(pHash->uCountPerFile[uColor][0] == 0); pHash->uCountPerFile[uColor][A + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[A]); pHash->uCountPerFile[uColor][B + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[B]); pHash->uCountPerFile[uColor][C + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[C]); pHash->uCountPerFile[uColor][D + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[D]); pHash->uCountPerFile[uColor][E + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[E]); pHash->uCountPerFile[uColor][F + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[F]); pHash->uCountPerFile[uColor][G + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[G]); pHash->uCountPerFile[uColor][H + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[H]); ASSERT(pHash->uCountPerFile[uColor][9] == 0); // Count number of unmoved pawns. pHash->uNumUnmovedPawns[uColor] = FastCountBits(pos->bbPawns[uColor] & BBRANK[RANK(uUnmovedRank[uColor])]); ASSERT(pHash->uNumUnmovedPawns[uColor] <= 8); // Detect rammed and other stationary pawns. A pawn is // "stationary" if *any* pawn (either color -- e.g. a doubled // own-pawn block counts too) sits on its "stop square". It's // specifically "rammed" only when that blocker is the // enemy's. WHITE's stop square is one rank toward rank8 (bit // index -8 in the linear 0-63 bitboard numbering -- see // _PopulatePawnAttackBits' >>8/<<8 shifts for the same // convention), BLACK's is +8. pHash->bbStationaryPawns[uColor] = (uColor == WHITE) ? (pos->bbPawns[WHITE] & (bbAllPawns << 8)) : (pos->bbPawns[BLACK] & (bbAllPawns >> 8)); ASSERT(FastCountBits(pHash->bbStationaryPawns[uColor]) <= 8); // Give central pawns a small bonus and rook pawns a small // penalty. bb = pos->bbPawns[uColor]; while(IS_ON_BOARD(c = CoorFromBitBoardRank8ToRank1(&bb))) { EVAL_TERM(uColor, PAWN, c, pHash->iScore[uColor], PAWN_CENTRALITY_BONUS[c], "location"); } } // Rammed pairs (an enemy pawn, not just any pawn, on the stop // square): each pair shows up as exactly one bit in each // side's own stationary-pawn count, so no double-counting // (and no /2 fixup) is needed the way the old per-pawn, // per-color loop required. pHash->uNumRammedPawns = FastCountBits(pos->bbPawns[WHITE] & (pos->bbPawns[BLACK] << 8)); ASSERT(pHash->uNumRammedPawns <= 8); pHash->uTotalPawnCount = (UCHAR)FastCountBits(bbAllPawns); ASSERT(pHash->uTotalPawnCount <= 16); // _EvalKnight's closed-position scaler, computed once per unique // pawn structure instead of once per Eval() call -- see this // field's comment in chess.h. pHash->uClosedScaler = (UCHAR)(pHash->uTotalPawnCount - (pHash->uNumUnmovedPawns[WHITE] + pHash->uNumUnmovedPawns[BLACK]) + pHash->uNumRammedPawns); ASSERT(pHash->uClosedScaler <= 32); // Good/bad bishop pawn-structure score, cached per (color, color- // complex) instead of rescanned by every bishop of that color/ // complex in _EvalBishop (board_representation/EVAL.md-style note: // every input here -- bbStationaryPawns, bbPawns, bbPawnAttacks -- // is pure pawn-structure data already keyed by this pawn-hash // entry's signature, and the bishop's own square only ever selects // *which* of these two precomputed totals to use, never feeds the // computation itself. Semantics (corrected from the old per-bishop // version, which silently ignored enemy stationary pawns on the // bishop's complex entirely): // - own stationary pawns on the complex: always count (full // weight) -- they're not moving, they wall the bishop in for // good. // - enemy stationary pawns on the complex: count (full weight) // only if defended by another enemy pawn -- an undefended // stationary pawn is still a static target, not a durable // obstruction, the same reasoning the transient case below // already applied to enemy pawns. // - own transient (non-stationary) pawns on the complex: always // count (full weight) -- might move off later, hence the // separate, lighter table. // - enemy transient pawns on the complex: count (half weight) // only if defended -- unsupported ones are likely to be traded // off soon, not a durable obstruction. { static const BITBOARD bbColorSq[2] = { 0x55aa55aa55aa55aaULL, 0xaa55aa55aa55aa55ULL }; ULONG uComplex; FOREACH_COLOR(uColor) { ULONG xColor = FLIP(uColor); BITBOARD bbNonStationary = ~(pHash->bbStationaryPawns[WHITE] | pHash->bbStationaryPawns[BLACK]); for (uComplex = 0; uComplex < 2; uComplex++) { BITBOARD bbMask = bbColorSq[uComplex]; SCORE i = 16; BITBOARD bb; COOR cSq; bb = pHash->bbStationaryPawns[uColor] & bbMask; while (IS_ON_BOARD(cSq = CoorFromBitBoardRank8ToRank1(&bb))) { i += STATIONARY_PAWN_ON_BISHOP_COLOR[cSq]; } bb = pHash->bbStationaryPawns[xColor] & bbMask; while (IS_ON_BOARD(cSq = CoorFromBitBoardRank8ToRank1(&bb))) { if (pos->bbPawnAttacks[xColor] & COOR_TO_BB(cSq)) { i += STATIONARY_PAWN_ON_BISHOP_COLOR[cSq]; } } bb = pos->bbPawns[uColor] & bbNonStationary & bbMask; while (IS_ON_BOARD(cSq = CoorFromBitBoardRank8ToRank1(&bb))) { i += TRANSIENT_PAWN_ON_BISHOP_COLOR[cSq]; } bb = pos->bbPawns[xColor] & bbNonStationary & bbMask; while (IS_ON_BOARD(cSq = CoorFromBitBoardRank8ToRank1(&bb))) { if (pos->bbPawnAttacks[xColor] & COOR_TO_BB(cSq)) { i += TRANSIENT_PAWN_ON_BISHOP_COLOR[cSq] / 2; } } pHash->iBishopColorScore[uColor][uComplex] = (SHORT)i; } } } // Second pass, requires pHash->uCountPerFile[] populated for both // colors. FOREACH_COLOR(uColor) { ASSERT(IS_VALID_COLOR(uColor)); ULONG xColor = FLIP(uColor); ASSERT(IS_VALID_COLOR(xColor)); ASSERT(FastCountBits(pos->bbPawns[uColor]) <= 8); d1 = 16 * g_iAhead[uColor]; BITBOARD bbPawnsToWalk = pos->bbPawns[uColor]; while (IS_ON_BOARD(c = CoorFromBitBoardRank8ToRank1(&bbPawnsToWalk))) { ASSERT(IS_PAWN(pos->rgSquare[c].pPiece)); ASSERT((1 < RANK(c)) && (RANK(c) < 8)); // Find weak pawns... pawns that are isolated are weak as // are pawns that have advanced beyond their support. // Both of these can tie up one or more pieces in order to // defend them. A pawn is a target unless a friendly pawn // on *either* adjacent file can defend it, now or later // (see _FileCanSupportPawn). bbBlockingRanks is c's rank // plus every rank behind it (from uColor's forward // direction) -- an enemy pawn there on an adjacent file // permanently blocks that file from ever producing a // defender. bbBlockingRanks = BBRANK[RANK(c)] | BBPRECEEDING_RANKS[c >> 4][uColor]; if (!_FileCanSupportPawn(pos, pHash, uColor, FILE(c) - 1, c, bbBlockingRanks) && !_FileCanSupportPawn(pos, pHash, uColor, FILE(c) + 1, c, bbBlockingRanks)) { // // Single consolidated isolated-pawn penalty: base // severity by file, plus modifiers if the pawn is also // exposed and/or doubled. These used to be three // separate additive EVAL_TERM calls that all fired for // the same pawn, plus a fourth, whole-position // "exponential isolated" aggregate below that // double-counted the same uIsolated[] count this loop // already prices in one pawn at a time -- that // aggregate is removed entirely below rather than just // consolidated (see the comment there). // uPawnFile = FILE(c) + 1; uIsolated[uColor] += 1; ASSERT(uIsolated[uColor] > 0); ASSERT(uIsolated[uColor] <= 8); EVAL_TERM(uColor, PAWN, c, pHash->iScore[uColor], (ISOLATED_PAWN_BY_PAWNFILE[uPawnFile] + ((pHash->uCountPerFile[xColor][uPawnFile]==0) * ISOLATED_EXPOSED_PAWN) + ((pHash->uCountPerFile[uColor][uPawnFile] > 1) * ISOLATED_DOUBLED_PAWN)), "isolated pawn"); } uPawnFile = FILE(c) + 1; ASSERT((1 <= uPawnFile) && (uPawnFile <= 8)); ASSERT(FastCountBits(pos->bbPawns[uColor] & BBFILE[FILE(c)]) == pHash->uCountPerFile[uColor][uPawnFile]); // // Keep count of doubled pawns // uDoubled[uColor] += (pHash->uCountPerFile[uColor][uPawnFile] > 1); ASSERT((0 <= uDoubled[uColor]) && (uDoubled[uColor] <= 8)); // // We can detect pawn duos (triads, etc...) and backward pawns // by considering the control of the pawn's stopsquare. // cSquare = c + d1; ASSERT(IS_ON_BOARD(cSquare)); // // At this point in Eval()'s sequence (inside _EvalPawns, // before any other piece type has run this call), pawns // are the only thing that could possibly have marked an // attack -- bvAttacks itself no longer carries the pawn // bit at all (see _PopulatePawnAttackBits), so this reads // pos->bbPawnAttacks directly instead of the (permanently // zero, at this point in execution) bvAttacks word. // if (pos->bbPawnAttacks[uColor] & COOR_TO_BB(cSquare)) { // // Count pawn duos. See "Pawn Power in Chess" pp 10-16 // #ifdef DEBUG t = ((uColor * RANK(cSquare)) + (xColor * (9 - RANK(cSquare)))); if (uColor == WHITE) { ASSERT(t == RANK(cSquare)); } else { ASSERT(uColor == BLACK); ASSERT(t == (9 - RANK(cSquare))); } #endif iDuos[uColor] += ((uColor * RANK(cSquare)) + (xColor * (9 - RANK(cSquare)))); ASSERT(iDuos[uColor] <= (7 * 8)); } else if (pos->bbPawnAttacks[xColor] & COOR_TO_BB(cSquare)) { // // Detect backwards pawns. See "Pawn Power in Chess" pp 25-27 // if (_IsBackwardPawn(pos, uColor, c, cSquare)) { // // The pawn at c is backward. Determine whether // it is shielded or exposed. // pHash->bbStationaryPawns[uColor] |= COOR_TO_BB(c); ASSERT(FastCountBits(pHash->bbStationaryPawns[uColor]) <= 8); if (pHash->uCountPerFile[xColor][uPawnFile]) { ASSERT(BACKWARD_SHIELDED_BY_LOCATION[c] < 0); EVAL_TERM(uColor, PAWN, c, pHash->iScore[uColor], BACKWARD_SHIELDED_BY_LOCATION[c], "shielded backward pawn"); } else { ASSERT(BACKWARD_EXPOSED_BY_LOCATION[c] < 0); EVAL_TERM(uColor, PAWN, c, pHash->iScore[uColor], BACKWARD_EXPOSED_BY_LOCATION[c], "exposed backward pawn"); } } // // TODO: Think about backward doubled pawns; read Kauffman's // paper "All About Doubled Pawns". // } // // Handle passers / candidate passers // _EvaluateCandidatePasser(pos, pHash, c); } } // // Reward pawn duos, see "Pawn Power in Chess" pp. 10-16 // ASSERT(iDuos[WHITE] >= 0); ASSERT(iDuos[WHITE] <= 56); ASSERT(iDuos[BLACK] >= 0); ASSERT(iDuos[BLACK] <= 56); EVAL_TERM(WHITE, PAWN, ILLEGAL_COOR, pHash->iScore[WHITE], iDuos[WHITE] / 2, "pawn duos"); EVAL_TERM(BLACK, PAWN, ILLEGAL_COOR, pHash->iScore[BLACK], iDuos[BLACK] / 2, "pawn duos"); // // The penalty for doubled pawns is scaled based on two primary // factors: the presence of major pieces for the side with doubled // pawns and the number of doubled pawns on the board. The // presence of major pieces makes the doubled pawns less severe // while the presence of many doubled pawns makes the penalty for // each more severe. // ASSERT((uDoubled[WHITE] >= 0) && (uDoubled[WHITE] <= 8)); ASSERT((uDoubled[BLACK] >= 0) && (uDoubled[BLACK] <= 8)); u = FastCountBits(pos->bbPieces[BLACK][ROOK]) + FastCountBits(pos->bbPieces[BLACK][QUEEN]) * 2; u = MINU(u, 3); EVAL_TERM(BLACK, PAWN, ILLEGAL_COOR, pHash->iScore[BLACK], DOUBLED_PAWN_PENALTY_BY_COUNT[u][uDoubled[BLACK]], "exponential doubled"); u = FastCountBits(pos->bbPieces[WHITE][ROOK]) + FastCountBits(pos->bbPieces[WHITE][QUEEN]) * 2; u = MINU(u, 3); EVAL_TERM(WHITE, PAWN, ILLEGAL_COOR, pHash->iScore[WHITE], DOUBLED_PAWN_PENALTY_BY_COUNT[u][uDoubled[WHITE]], "exponential doubled"); ASSERT(uIsolated[WHITE] >= 0); ASSERT(uIsolated[WHITE] <= 8); ASSERT(uIsolated[BLACK] >= 0); ASSERT(uIsolated[BLACK] <= 8); // // Look for connected, supported and outside passed pawns to give // extra bonuses. // _EvaluateConnectedSupportedOutsidePassers(pos, pHash); // // TODO: recognize quartgrips and stonewalls // return(pHash); } ULONG CountKingSafetyDefects(IN OUT POSITION *pos, IN ULONG uColor) /** Routine description: Determine how many defects uColor's king position has _quickly_. TODO: add more knowledge as cheaply as possible... Parameters: POSITION *pos, ULONG uColor Return value: ULONG **/ { ULONG uCounter = 0; ULONG xColor = FLIP(uColor); COOR cKing; BITBOARD bbKingZone; BITBOARD bbBlockers; BITBOARD bb; COOR c; // // Don't count king safety defects if the real eval code in // _EvalKing would not... // if (pos->uNonPawnMaterial[xColor] < DO_KING_SAFETY_THRESHOLD) { return 0; } cKing = KingPosition(pos, uColor); uCounter = KING_INITIAL_COUNTER_BY_LOCATION[uColor][cKing] >> 1; ASSERT(IS_KING(pos->rgSquare[cKing].pPiece)); ASSERT(IS_ON_BOARD(cKing)); ASSERT(GET_COLOR(pos->rgSquare[cKing].pPiece) == uColor); // // board_representation/EVAL.md section 9 follow-up (2026-09-05): // real, blocker-aware attack tests against the king's actual // 8-neighbor zone (the same zone _EvalKing's own KingSafetyDeltas // loop tests, now that its own bug -- testing 11 squares including // two bogus same-rank-2-away entries -- is fixed), replacing the // old CHECK_VECTOR_WITH_INDEX geometry-only lookup. That lookup // tested three hypothetical king positions (cKing-1, cKing, // cKing+1 -- always on the same rank, driven by CHECK_VECTOR's // one-dimensional index arithmetic) via a table with no board- // occupancy awareness at all -- it couldn't tell a rook on an open // file from one blocked by its own pawn, and never tested whether // a piece threatened a square one rank away from the king. This // version can't reuse pos->bbXAttacks (Eval()-scoped, and this // function is also called directly from search.c/searchsup.c as // an extension/reduction gate, independent of whether Eval() ran // on the current position at all) -- but pos->bbOccupied is a // real, always-current POSITION field regardless, so a fresh, // per-piece magic-bitboard lookup here is both cheap (same O(1) // shape as the old table lookups) and genuinely blocker-aware. // X-rays deliberately not considered via chain-following (that // would double the per-slider cost of a function called at every // lazy-eval check across the whole search tree, for what's already // a rough magnitude estimate, not an exact score) -- but the // occupancy fed to the slider lookups below is deliberately just // xColor's own pieces (_BuildFriendlySideBB(pos, xColor)), not the // whole board: a piece belonging to uColor (a defending pawn, the // king itself) is transparent to these rays, only xColor's own // pieces actually block. This gets latent-threat detection (a // rook aimed at the king zone but currently shielded by the // king's own pawn still counts) for free, at zero extra cost -- // still one magic lookup per slider, just against a different // occupancy bitboard -- by direct instruction: we don't count our // own pieces as blocking the enemy king. // bbKingZone = g_KingAttacksBB[cKing] | COOR_TO_BB(cKing); bbBlockers = _BuildFriendlySideBB(pos, xColor); bb = pos->bbPieces[xColor][KNIGHT]; while (bb) { c = CoorFromBitBoardRank8ToRank1(&bb); uCounter += (g_KnightAttacksBB[c] & bbKingZone) != 0; } bb = pos->bbPieces[xColor][BISHOP]; while (bb) { c = CoorFromBitBoardRank8ToRank1(&bb); uCounter += (_BishopAttacksBB(c, bbBlockers) & bbKingZone) != 0; } bb = pos->bbPieces[xColor][ROOK]; while (bb) { c = CoorFromBitBoardRank8ToRank1(&bb); uCounter += (_RookAttacksBB(c, bbBlockers) & bbKingZone) != 0; } // Queen hits count double -- by direct instruction: a queen near // the king is a real, distinct danger source _EvalKing's own // KING_QUEEN_PROXIMITY_DANGER term prices separately from generic // attack presence, and this counter had no way to reflect that // (a queen hitting the zone counted exactly the same as a lone // knight doing so). Raises the bound below accordingly (up to 8 // queens are legal via promotion, each now worth 2). bb = pos->bbPieces[xColor][QUEEN]; while (bb) { c = CoorFromBitBoardRank8ToRank1(&bb); uCounter += 2 * (((_RookAttacksBB(c, bbBlockers) | _BishopAttacksBB(c, bbBlockers)) & bbKingZone) != 0); } ASSERT(uCounter < 30); return uCounter; } static SCORE _ComputeFileStormDefects(IN POSITION *pos, IN const PAWN_HASH_ENTRY *pHash, IN ULONG uColor) /** Routine description: Real, exact open-file/storming-pawn defect count for uColor's king -- king's own file plus the two adjacent ones (2026-08-30: collapsed from three copy-pasted blocks that differed only in c-1/c/c+1). Extracted unchanged from _EvalKing (2026-09-05, board_representation/EVAL.md section 9's king-safety-hash prototype) so it can be called once per side from _GetFileStormDefects's cache-miss path instead of inline. 2026-09-15: converted from an unsigned "counter" (fed through the old shared uCounter/KING_SAFETY_BY_COUNTER lookup) to a direct signed SCORE (centipawns), part of _EvalKing's move away from that shared nonlinear counter entirely -- see king_safety_data/ HANDOFF.md's 2026-09-15 addendum. Table SHAPE below is the ORIGINAL, pre-2026-09-14 relative weighting (0,4,3,1,.../+2,+1,+0), not the already-1.75-2x-bumped one -- that's deliberate: the mate- mining regression's filestormopenfile/filestormpawn coefficients were fit against CSV data extracted using this original shape, so scaling *this* shape by the regression-derived conversion factor is the correct one-step translation (scaling the already-bumped shape again would double-apply the 2026-09-14 tuning). Magnitude derived the same way as KING_QUEEN_PROXIMITY_DANGER's self-play-validated -14/count: k = (validated queenproximity weight) / (queenproximity's own cleaned raw regression coefficient) =~ -14 per raw coefficient unit, applied to filestormpawn's raw coefficient (+0.374) and filestormopenfile's (+0.360) against the original table's own integer steps. Unvalidated by self-play as of this writing -- expect this exact magnitude to move once tested, same as every other freshly-converted term here. Parameters: POSITION *pos PAWN_HASH_ENTRY *pHash ULONG uColor Return value: SCORE **/ { static SCORE KingStormingPawnDefects[8] = { +0, -21, -16, -5, 0, 0, 0, 0 }; // 2026-10-04: NEW -- own-side shield-pawn bonus, the mirror image // of KingStormingPawnDefects above (same DISTANCE-indexed shape, // opposite color of pawn, opposite sign). Addresses a real gap: // nothing in _EvalKing previously rewarded keeping a shield pawn // (f2/g2/h2-shaped) on its home square, or penalized pushing it // away -- KingFileDefects only checks whether *a* pawn of either // color still exists somewhere on the file at all, which stays // satisfied even after an unforced push (g2-g3 doesn't change // uCountPerFile), and the front-flight-penalty below is a generic // "empty+unattacked gap" term with no notion that this square // specifically used to be a shield pawn's. Observed in practice: // the engine pushes its own king-shield pawns with no offsetting // cost from this function, then gets punished by the opponent // for the resulting weakened cover. Starting magnitude (+6 at // distance 1, i.e. still right in front of the king) is a guess, // not yet self-play validated -- same disclaimer as every other // freshly-added term in this function's history; expect it to // move once tested. static SCORE KingShieldPawnBonus[8] = { +0, +6, +3, +1, 0, 0, 0, 0 }; // Indexed by (fOwn << 1) | fEnemy: 0=open (neither side has a pawn // here), 1=half-open toward the enemy only (their pawn gone, ours // still there), 2=half-open toward us only (ours gone, theirs still // there), 3=closed (both present). Previously collapsed 1 and 2 // into a single "half-open" bucket (uCountPerFile[WHITE][u]>0) + // (uCountPerFile[BLACK][u]>0) summed to 1 either way) -- split // 2026-10-08 since the two cases aren't symmetric (an enemy pawn // left behind is a real storming threat already priced by // KingStormingPawnDefects below, whereas our own pawn being the // only one left is comparatively mild). static SCORE KingFileDefects[4] = { -18, -10, -5, 0 }; // Old code's edge-file (a/h) kicker was a flat +1 counter-unit; // scaled by the same filestormopenfile-derived factor. static SCORE KING_FILE_EDGE_KICKER = -5; ULONG ufColor = FLIP(uColor); COOR c = KingPosition(pos, uColor); SCORE iScore = 0; COOR cFileSq, cSquare; ULONG u, v; BITBOARD bb; int w; for (w = -1; w <= 1; w++) { cFileSq = c + w; if (!IS_ON_BOARD(cFileSq)) { continue; } u = FILE(cFileSq) + 1; v = ((pHash->uCountPerFile[uColor][u] > 0) << 1) | (pHash->uCountPerFile[ufColor][u] > 0); ASSERT(v <= 3); iScore += KingFileDefects[v]; iScore += ((v != 3) && ((u == 1) || (u == 8))) * KING_FILE_EDGE_KICKER; bb = pos->bbPawns[ufColor] & BBFILE[u - 1]; if (bb) { if (uColor == WHITE) { cSquare = CoorFromBitBoardRank1ToRank8(&bb); } else { cSquare = CoorFromBitBoardRank8ToRank1(&bb); } ASSERT(IS_ON_BOARD(cSquare)); iScore += KingStormingPawnDefects[DISTANCE(cSquare, c)]; } // Shield-pawn bonus -- same file, but OUR OWN pawn, nearest // one to the king if doubled (same directional scan as the // enemy-storming-pawn lookup above, just over bbPawns[uColor] // instead of bbPawns[ufColor]). bb = pos->bbPawns[uColor] & BBFILE[u - 1]; if (bb) { if (uColor == WHITE) { cSquare = CoorFromBitBoardRank1ToRank8(&bb); } else { cSquare = CoorFromBitBoardRank8ToRank1(&bb); } ASSERT(IS_ON_BOARD(cSquare)); iScore += KingShieldPawnBonus[DISTANCE(cSquare, c)]; } } return iScore; } static SCORE _GetFileStormDefects(IN SEARCHER_THREAD_CONTEXT *ctx, IN POSITION *pos, IN const PAWN_HASH_ENTRY *pHash, IN ULONG uColor) /** Routine description: EXPERIMENTAL, prototype-only (2026-09-05, board_representation/ EVAL.md section 9's king-safety-hash discussion). Cache front end for _ComputeFileStormDefects, keyed on (pos->u64PawnSig, both kings' squares) -- deliberately covers only the DO_KING_SAFETY_ THRESHOLD-gated "safety branch" term (measured ~96% hit rate in general/middlegame positions), not the u<8-gated "endgame branch" terms (king-supporting-own-passer, in/out-of-action), which measured a much worse ~75-85% hit rate in bare K+P endgames and are cheap enough there that caching them isn't expected to pay off -- those stay inline in _EvalKing, uncached. On a miss, computes *both* sides' defect counts and stores them together, so whichever king _EvalKing evaluates second within the same Eval() call (kings are always evaluated black-then-white) is a guaranteed hit -- only one real miss per position, not one per king. 2026-09-15: return type/cache field changed ULONG -> SCORE along with _ComputeFileStormDefects -- see that function's comment. This function's own cache/probe/hit-rate mechanics are unaffected, only the value being cached changed shape. NOTE: CALIBRATE_POSITIONAL's two call sites (_RecordPositionalCalibration and the DumpPositional Calibration-ish block near EstimatePositionalScore) still treat this return value as a small unsigned index component (MINU(10, CountKingSafetyDefects(...) + _GetFileStormDefects(...))) -- now wrong now that this returns signed centipawns, but left alone by direct instruction (that non-default build flag's own recalibration is deferred as separate follow-up work, not part of this rewrite). Parameters: SEARCHER_THREAD_CONTEXT *ctx POSITION *pos PAWN_HASH_ENTRY *pHash ULONG uColor Return value: SCORE **/ { UINT64 u64Key = pos->u64PawnSig ^ g_u64SigSeeds[KingPosition(pos, WHITE)][KING][WHITE] ^ g_u64SigSeeds[KingPosition(pos, BLACK)][KING][BLACK]; ULONG uSlot = (ULONG)u64Key & (KING_SAFETY_HASH_TABLE_SIZE - 1); KING_SAFETY_HASH_ENTRY *pEntry = &ctx->rgKingSafetyHash[uSlot]; #ifdef EVAL_TIME // 2026-10-03: moved from bare PERF_COUNTERS to EVAL_TIME, where the // other 32 cycle-counting sites in this file already live. These // three were the only rdtsc calls leaking into the standard build // profile -- two per king-safety hash probe, in one of the hottest // paths in the engine, and rdtsc is ~20-30 cycles and partially // serializing, so it defeats out-of-order execution exactly where // that hurts most. EVAL_TIME exists for precisely this measurement // ("make a version that counts cycles spent in eval", GNUmakefile), // so nothing is lost -- the capability just stops being paid for in // every match and every suite run. UINT64 u64Start = SystemReadTimeStampCounter(); #endif INC(ctx->sCounters.kingsafetyhash.u64Probes); if (pEntry->u64Key == u64Key) { INC(ctx->sCounters.kingsafetyhash.u64Hits); #ifdef EVAL_TIME ctx->sCounters.kingsafetyhash.u64CyclesHit += (SystemReadTimeStampCounter() - u64Start); #endif return pEntry->iFileStormDefects[uColor]; } pEntry->u64Key = u64Key; pEntry->iFileStormDefects[WHITE] = _ComputeFileStormDefects(pos, pHash, WHITE); pEntry->iFileStormDefects[BLACK] = _ComputeFileStormDefects(pos, pHash, BLACK); #ifdef EVAL_TIME ctx->sCounters.kingsafetyhash.u64CyclesMiss += (SystemReadTimeStampCounter() - u64Start); #endif return pEntry->iFileStormDefects[uColor]; } static SCORE _GetKingActivityBonus(IN SEARCHER_THREAD_CONTEXT *ctx, IN POSITION *pos, IN const PAWN_HASH_ENTRY *pHash, IN ULONG uColor, IN COOR cKing) /** Routine description: Cache front end for _EvalKing's activity half (2026-10-06 safety/ activity split): combines "supporting own passer" and "is this king out of the action" into one cached lookup, since both only ever apply together (same caller, same branch) and both depend on exactly the same inputs -- pawn structure plus uColor's own king square, nothing else. One key computation and one hash probe serve both instead of two. Only called when the ENEMY (xColor) is down to at most one non-king piece -- see _EvalKing. Per-king, not per-position: unlike _GetFileStormDefects (keyed on both kings' squares, since "is the king's position safe" depends on both), out-of-action's old formula subtracted the enemy king's own distance to make a symmetric "who's closer" value, but that only made sense paired with the old combined-both-sides gate (uTotalNonPawnsBothSides==2, true or false identically for both kings' calls). The new gate is per-call (keyed on xColor, each king's own enemy), so the two calls can legitimately disagree -- one king's own position might qualify while the other's doesn't -- and a shared symmetric value can no longer be "added once, during white's call" the way the old code assumed. Each call now computes and caches its own independent value instead. Narrower key (just this king's square, not both) than _GetFileStormDefects's as a direct consequence -- only this king's own moves can invalidate it, not the opponent's too, so this should measure a *better* hit rate than file-storm's own ~75-85% in this same low-material regime, not a worse one. PROVISIONAL, like the formulas it combines: neither weight has been through any self-play validation -- see the old out-of-action formula's own removed comment (git history) for the outlier bug that originally motivated shrinking its weight. Needs the same calibration discipline as every other king-safety magnitude in this file. Also trades away per-passer-square EVAL_TERM attribution (summed into one combined value instead) -- EVAL_DUMP tracing only, not used in release builds, by direct request for fewer instructions in this inner loop. Parameters: SEARCHER_THREAD_CONTEXT *ctx POSITION *pos PAWN_HASH_ENTRY *pHash ULONG uColor : whose king this bonus is for COOR cKing : uColor's own king square (caller already has it -- KingPosition(pos, uColor) redundantly) Return value: SCORE **/ { UINT64 u64Key = pos->u64PawnSig ^ g_u64SigSeeds[cKing][KING][uColor]; ULONG uSlot = (ULONG)u64Key & (KING_SAFETY_HASH_TABLE_SIZE - 1); KING_SAFETY_HASH_ENTRY *pEntry = &ctx->rgKingSafetyHash[uSlot]; SCORE i, iTotal; COOR cSquare; BITBOARD bb; INC(ctx->sCounters.kingactionhash.u64Probes); if (pEntry->u64ActionKey == u64Key) { INC(ctx->sCounters.kingactionhash.u64Hits); return pEntry->iActionBonus; } // Supporting own passer -- bb here is exactly the own-passer // squares at king-move distance 1 (g_KingAttacksBB is that mask // by construction), so every popped square counts; no separate // DISTANCE() filter or ASSERTs needed. The extra "leading the // pawn toward promotion" bonus applies iff the passer square is // in the king's own back ring (g_KingRingBackBB) -- side- and // front-ring passers still get the base rank-scaled support // bonus, just not this extra. iTotal = 0; bb = pHash->bbPasserLocations[uColor] & g_KingAttacksBB[cKing]; while (IS_ON_BOARD(cSquare = CoorFromBitBoardRank8ToRank1(&bb))) { i = 2; i += KING_SUPPORTING_OWN_PASSER_BY_RANK[uColor][RANK(cSquare)]; i += 8 * ((COOR_TO_BB(cSquare) & g_KingRingBackBB[uColor][cKing]) != 0); iTotal += i; } // Out of action in KP-ish endgames, e.g. // 8/8/1p6/p6k/P3K3/8/1P6/8 w - - 0 11 -- how close this king is // to the whole pawn mass. The *2 preserves the old formula's own // scale (it used to be a differential, this is now a plain sum, // but the per-pawn magnitude is unchanged). i = 0; bb = pos->bbPawns[WHITE] | pos->bbPawns[BLACK]; while (IS_ON_BOARD(cSquare = CoorFromBitBoardRank8ToRank1(&bb))) { i -= (SCORE)DISTANCE(cSquare, cKing); } iTotal += i * 2; pEntry->u64ActionKey = u64Key; pEntry->iActionBonus = iTotal; return iTotal; } #ifdef CALIBRATE_POSITIONAL // // board_representation/EVAL.md section 9 recalibration (2026-09-05): // histogram of (cheap defect index -> real king-safety magnitude), one // row per possible EstimatePositionalScore bucket, so a p90-per-row // read after a calibration run over a large sample (curated suites or // a slice of ecm.ep_, at real search depth so the distribution matches // what the search tree actually sees, not just root positions) gives a // fresh iKingSwingP90 table -- coarse cp bins, not raw samples, to keep // this cheap enough to leave compiled into a whole search run rather // than needing to buffer millions of individual values. // // 2026-09-15: bucket index fixed to MINU(10, CountKingSafetyDefects) // ONLY, dropping _GetFileStormDefects -- it had drifted out of sync // with EstimatePositionalScore's own real lookup index back on // 2026-09-06 (_GetFileStormDefects was pulled out of that hot path for // being too expensive to call on ~90% of Eval() calls regardless of // exit, but this histogram's bucketing was never updated to match, // silently refitting against an index EstimatePositionalScore was no // longer using). Also: this histogram used to bin the pre-scale // KING_SAFETY_BY_COUNTER magnitude, which was always <= 0 by // construction; the 2026-09-15 linear-SCORE rewrite's iSafety can be // mildly positive (a well-covered king with real back-rank escape // squares and no attacks), so this now bins ABS(iSafety) -- by direct // instruction, the rare positive case is small enough not to need its // own separate treatment. // #define CALIBRATE_NUM_BUCKETS 11 #define CALIBRATE_BIN_WIDTH 5 #define CALIBRATE_NUM_BINS 200 // covers |raw king-safety magnitude| 0..999 static UINT64 g_CalibrateHist[CALIBRATE_NUM_BUCKETS][CALIBRATE_NUM_BINS]; UINT64 g_uCalibrateGateChecked = 0; UINT64 g_uCalibrateGateTrue = 0; UINT64 g_uCalibrateEvalCalls = 0; static void _RecordPositionalCalibration(IN SEARCHER_THREAD_CONTEXT *ctx, IN POSITION *pos, IN const PAWN_HASH_ENTRY *pHash, IN ULONG uColor, IN ULONG uRawMagnitude) /** Routine description: Bucket one real _EvalKing sample (this side's raw, pre-material-scaled king-safety magnitude) by the same cheap defect index EstimatePositionalScore would have used to estimate it, so a later DumpPositionalCalibration can compute a fresh p90-per-bucket table. Parameters: SEARCHER_THREAD_CONTEXT *ctx POSITION *pos PAWN_HASH_ENTRY *pHash : unused as of 2026-09-15 (see the bucket- index fix in this file's #ifdef CALIBRATE_POSITIONAL comment above) -- kept in the signature for call-site stability. ULONG uColor ULONG uRawMagnitude : ABS(iSafety), before the REDUCED_MATERIAL_DOWN_SCALER scaling _EvalKing applies next -- EstimatePositionalScore's table is looked up then scaled the same way, so the table itself should be fit against the unscaled value. Return value: void **/ { ULONG uIndex; ULONG uBin; // Only sample nodes Eval()'s own base-margin ("super lazy") gate // would actually pass through to EstimatePositionalScore in a real // build -- see ctx->fCalibrateCandidate's comment in chess.h. if (FALSE == ctx->fCalibrateCandidate) { return; } uIndex = MINU(10, CountKingSafetyDefects(pos, uColor)); uBin = MINU(CALIBRATE_NUM_BINS - 1, uRawMagnitude / CALIBRATE_BIN_WIDTH); g_CalibrateHist[uIndex][uBin]++; } void DumpPositionalCalibration(void) /** Routine description: Print a fresh iKingSwingP90[] table (p90 of the real, unscaled KING_SAFETY_BY_COUNTER value observed at each cheap defect-index bucket) from the histogram _RecordPositionalCalibration has been filling for the duration of this run. Only meaningful in a CALIBRATE_POSITIONAL build, after running a representative workload (the curated suites, or an ecm.ep_ slice, at real search depth -- root-only positions won't exercise the distribution of positions the search tree actually evaluates). Parameters: void Return value: void **/ { ULONG uIndex; ULONG uBin; UINT64 u64Total; UINT64 u64Running; SCORE iP90; Trace("Positional calibration: Eval() called %" COMPILER_LONGLONG_UNSIGNED_FORMAT " times\n", g_uCalibrateEvalCalls); Trace("Positional calibration: gate checked %" COMPILER_LONGLONG_UNSIGNED_FORMAT " times, true %" COMPILER_LONGLONG_UNSIGNED_FORMAT " times\n", g_uCalibrateGateChecked, g_uCalibrateGateTrue); Trace("Positional calibration (p90 per bucket, sample counts):\n"); for (uIndex = 0; uIndex < CALIBRATE_NUM_BUCKETS; uIndex++) { u64Total = 0; for (uBin = 0; uBin < CALIBRATE_NUM_BINS; uBin++) { u64Total += g_CalibrateHist[uIndex][uBin]; } if (0 == u64Total) { Trace(" bucket %2u: no samples\n", uIndex); continue; } u64Running = 0; iP90 = (SCORE)((CALIBRATE_NUM_BINS - 1) * CALIBRATE_BIN_WIDTH); for (uBin = 0; uBin < CALIBRATE_NUM_BINS; uBin++) { u64Running += g_CalibrateHist[uIndex][uBin]; if (u64Running * 10 >= u64Total * 9) { iP90 = (SCORE)(uBin * CALIBRATE_BIN_WIDTH); break; } } Trace(" bucket %2u: p90=%d (n=%" COMPILER_LONGLONG_UNSIGNED_FORMAT ")\n", uIndex, iP90, u64Total); } } #endif // CALIBRATE_POSITIONAL // 2026-09-17: BASE_MARGIN_MAT_BUCKETS/WIDTH and _MaterialBucket() pulled // out of the CALIBRATE_BASE_MARGIN/CALIBRATE_MARGIN_SAFETY-only guard // below -- now also used unconditionally (see g_u64EvalExitByBucket in // Eval(), and root.c's per-bucket exit-rate report) so a normal build // can report exit rate by material bucket, not just the flat aggregate // "Eval exit breakdown" line -- needed to see whether the p98/p2 margin // redesign actually moved the exit rate in any given bucket, since the // aggregate rate can mask buckets moving in opposite directions. #define BASE_MARGIN_MAT_BUCKETS 8 #define BASE_MARGIN_MAT_WIDTH 8 static ULONG _MaterialBucket(IN POSITION *pos) /** Routine description: Coarse combined-material bucket, 0 (bare kings) to BASE_MARGIN_MAT_BUCKETS-1 (full army). Originally CALIBRATE_BASE_ MARGIN-only; now also used by the always-on per-bucket eval-exit- rate counters. Parameters: POSITION *pos Return value: ULONG : 0..BASE_MARGIN_MAT_BUCKETS-1 **/ { ULONG uCombined = pos->uArmyScaler[WHITE] + pos->uArmyScaler[BLACK]; return MINU(BASE_MARGIN_MAT_BUCKETS - 1, uCombined / BASE_MARGIN_MAT_WIDTH); } // Always-on per-material-bucket eval-exit counters -- separate from // (and simpler than) the CALIBRATE_MARGIN_SAFETY machinery below: just // "how many nodes exited via this tier, in this material bucket", // enough to compute exit RATE per bucket (this array divided by the // per-bucket sum across all three) without needing a special // calibration build. See the five INC-site call pairs in Eval() below // and root.c's report. static UINT64 g_u64SuperLazyEvalsByBucket[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_u64LazyEvalsByBucket[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_u64FullEvalsByBucket[BASE_MARGIN_MAT_BUCKETS]; // Same idea, for the two NNUE exits -- added 2026-10-16 alongside the // EVAL_POSITIONAL_SOURCE_NNUE_FULL/NNUE_LAZY tiers, specifically to // answer "what fraction of real NNUE eval calls does the lazy probe // gate actually resolve" with a real measurement instead of a guess. static UINT64 g_u64NnueLazyEvalsByBucket[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_u64NnueFullEvalsByBucket[BASE_MARGIN_MAT_BUCKETS]; void DumpEvalExitRateByBucket(void) /** Routine description: Print per-material-bucket eval exit rate (super lazy / lazy / full, as a percentage of that bucket's own total) -- command.c's "calibrate exitrate". Complements the flat aggregate "Eval exit breakdown" line (root.c, printed at the end of every search) by showing whether that aggregate is hiding buckets moving in opposite directions. Parameters: void Return value: void **/ { ULONG m; Trace("Eval exit rate by material bucket (combined army scaler):\n"); for (m = 0; m < BASE_MARGIN_MAT_BUCKETS; m++) { UINT64 u64SL = g_u64SuperLazyEvalsByBucket[m]; UINT64 u64L = g_u64LazyEvalsByBucket[m]; UINT64 u64F = g_u64FullEvalsByBucket[m]; UINT64 u64Total = u64SL + u64L + u64F; if (0 == u64Total) { Trace(" bucket %u (scaler %u-%u): no samples\n", m, m * BASE_MARGIN_MAT_WIDTH, (m * BASE_MARGIN_MAT_WIDTH) + BASE_MARGIN_MAT_WIDTH - 1); continue; } Trace(" bucket %u (scaler %2u-%2u): n=%12" COMPILER_LONGLONG_UNSIGNED_FORMAT " super=%5.2f%% lazy=%5.2f%% full=%5.2f%%\n", m, m * BASE_MARGIN_MAT_WIDTH, (m * BASE_MARGIN_MAT_WIDTH) + BASE_MARGIN_MAT_WIDTH - 1, u64Total, 100.0 * (double)u64SL / (double)u64Total, 100.0 * (double)u64L / (double)u64Total, 100.0 * (double)u64F / (double)u64Total); } Trace("NNUE eval exit rate by material bucket (lazy probe gate vs full " "forward pass):\n"); for (m = 0; m < BASE_MARGIN_MAT_BUCKETS; m++) { UINT64 u64NL = g_u64NnueLazyEvalsByBucket[m]; UINT64 u64NF = g_u64NnueFullEvalsByBucket[m]; UINT64 u64Total = u64NL + u64NF; if (0 == u64Total) { Trace(" bucket %u (scaler %u-%u): no samples\n", m, m * BASE_MARGIN_MAT_WIDTH, (m * BASE_MARGIN_MAT_WIDTH) + BASE_MARGIN_MAT_WIDTH - 1); continue; } Trace(" bucket %u (scaler %2u-%2u): n=%12" COMPILER_LONGLONG_UNSIGNED_FORMAT " nnue_lazy=%5.2f%% nnue_full=%5.2f%%\n", m, m * BASE_MARGIN_MAT_WIDTH, (m * BASE_MARGIN_MAT_WIDTH) + BASE_MARGIN_MAT_WIDTH - 1, u64Total, 100.0 * (double)u64NL / (double)u64Total, 100.0 * (double)u64NF / (double)u64Total); } } #ifdef CALIBRATE_BASE_MARGIN // // board_representation/EVAL.md section 9: is LAZY_EVAL_BASE_MARGIN (the // flat, un-widened margin Eval() screens with before ever calling // EstimatePositionalScore) well-sized? Tracks: once the gate passes and // EstimatePositionalScore has widened the margin, does a real exit // actually happen, broken out by the worse (max) of the two sides' // cheap defect-index buckets? This answers "does the 'very dangerous' // bucket (10) ever actually exit, or does its wide margin effectively // rule it out". Doesn't require the lazy-exit machinery to be disabled // (unlike the CALIBRATE_POSITIONAL king-safety work above) -- real // exits still happen normally here, so this runs at normal speed. // // 2026-09-17: this used to also track a false-negative rate (the gate // coming back false, then checking whether a real exit would've been // available anyway) -- that required a flat-gate-false branch, which // stopped existing once the flat pre-check itself was retired (see the // `if (TRUE)` removal in Eval() below); removed alongside it rather // than leaving permanently-zero counters. // // 2026-09-06: added a material dimension -- pos->uArmyScaler[WHITE] + // pos->uArmyScaler[BLACK] (0-62), bucketed into 8 coarse bands, since // the lazy/full cost ratio measured directly (opening/middlegame vs a // bare K+P endgame) varies ~7x by material, and LAZY_EVAL_BASE_MARGIN // is currently one flat constant across all of it. static UINT64 g_uBaseMarginExitAttempted[BASE_MARGIN_MAT_BUCKETS][11]; static UINT64 g_uBaseMarginExitTaken[BASE_MARGIN_MAT_BUCKETS][11]; static ULONG _MaxKingDangerBucket(IN SEARCHER_THREAD_CONTEXT *ctx, IN POSITION *pos, IN PAWN_HASH_ENTRY *pHash) /** Routine description: Cheap helper for CALIBRATE_BASE_MARGIN instrumentation only: the worse of the two sides' combined cheap defect-index buckets, same definition EstimatePositionalScore's iKingSwingP90 lookup uses. Re-reads CountKingSafetyDefects/_GetFileStormDefects rather than threading extra output params through EstimatePositionalScore -- both hit the king-safety hash on a repeat call within the same Eval(), so this is cheap (see rgKingSafetyHash's "guaranteed intra-call hit" comment). Parameters: SEARCHER_THREAD_CONTEXT *ctx POSITION *pos PAWN_HASH_ENTRY *pHash Return value: ULONG : 0-10 **/ { ULONG uWhite = MINU(10, CountKingSafetyDefects(pos, WHITE) + _GetFileStormDefects(ctx, pos, pHash, WHITE)); ULONG uBlack = MINU(10, CountKingSafetyDefects(pos, BLACK) + _GetFileStormDefects(ctx, pos, pHash, BLACK)); return MAXU(uWhite, uBlack); } void DumpBaseMarginCalibration(void) /** Routine description: Print LAZY_EVAL_BASE_MARGIN calibration stats gathered so far this run: per-(material bucket, king-danger bucket) exit-attempted/ exit-taken counts (command.c's "calibrate basemargin"). Parameters: void Return value: void **/ { ULONG m, u; for (m = 0; m < BASE_MARGIN_MAT_BUCKETS; m++) { Trace("Base margin calibration -- material bucket %u " "(combined army scaler %u-%u):\n", m, m * BASE_MARGIN_MAT_WIDTH, (m * BASE_MARGIN_MAT_WIDTH) + BASE_MARGIN_MAT_WIDTH - 1); for (u = 0; u <= 10; u++) { if (0 == g_uBaseMarginExitAttempted[m][u]) { continue; } Trace(" king-danger bucket %2u: %" COMPILER_LONGLONG_UNSIGNED_FORMAT " attempted, %" COMPILER_LONGLONG_UNSIGNED_FORMAT " exited (%.2f%%)\n", u, g_uBaseMarginExitAttempted[m][u], g_uBaseMarginExitTaken[m][u], (100.0 * (double)g_uBaseMarginExitTaken[m][u] / (double)g_uBaseMarginExitAttempted[m][u])); } } } #endif // CALIBRATE_BASE_MARGIN #ifdef CALIBRATE_MARGIN_SAFETY // // board_representation/EVAL.md section 9: for every node that actually // took a lazy exit, how far off was the real (full-eval) score from // the lazy-path score that got returned? The *maximum* observed swing, // not just its p90, is what answers "how large would LAZY_EVAL_BASE_ // MARGIN have had to be before some exit here would have been // unsound" -- unlike iKingSwingP90 (an estimate that's allowed to be // wrong ~10% of the time by design), a used margin being exceeded even // once is a genuine soundness question, so max is the right statistic // here, not a percentile. Bucketed by combined material (same bucketing // as CALIBRATE_BASE_MARGIN) since the earlier lazy/full cost-ratio // measurement showed the two regimes are very different. // static UINT64 g_uMarginSwingMax[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uMarginSwingCount[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uMarginSwingSum[BASE_MARGIN_MAT_BUCKETS]; // 2026-09-17: max/avg alone hide the shape of the swing distribution -- // a bucket could have a huge max from one outlier and a small avg from // a long thin tail of near-zero swings, or a genuinely fat middle. // Histogram (same fixed-width-bin technique as RESID_HIST_* above, // swings are always >= 0 so no negative-offset needed) plus a sum-of- // squares accumulator lets DumpMarginSafetyCalibration report p10/p50/ // p90 and stdev per bucket, not just max/avg. #define SWING_HIST_BIN_WIDTH 10 #define SWING_HIST_BINS 300 // covers [0, 3000) cp; observed max so far ~1300 static UINT64 g_uMarginSwingHist[BASE_MARGIN_MAT_BUCKETS][SWING_HIST_BINS]; static UINT64 g_uMarginSwingSumSq[BASE_MARGIN_MAT_BUCKETS]; // Genuine soundness check: did the swing ever exceed the *actual* // (already-widened) margin that was used to justify this specific // exit? Unlike the raw max above (which just says "how far things // moved"), this directly answers "was any real exit actually unsound". static UINT64 g_uMarginExceeded[BASE_MARGIN_MAT_BUCKETS]; // 2026-09-17: how many exceeded-margin FENs have already been printed // for this (tier, material bucket) -- capped at MARGIN_EXCEEDED_FEN_ // SAMPLE_CAP so a run with hundreds of thousands of exceeded events // (a real possibility while tuning loose margins) doesn't flood the // log; just enough examples per bucket to eyeball by hand. #define MARGIN_EXCEEDED_FEN_SAMPLE_CAP 5 static UINT64 g_uMarginExceededFenSamples[BASE_MARGIN_MAT_BUCKETS]; // Same four counters, kept in a fully separate set for the super-lazy // exit (eval.c's material-only check before the regular lazy gate). // Its own SUPER_LAZY_MARGIN was never run through this harness when // it was added -- a much cheaper, much-larger-required-gap check than // the regular lazy exit, so mixing its swings into the buckets above // would wash out both regimes' signal. static UINT64 g_uSuperLazyMarginSwingMax[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uSuperLazyMarginSwingCount[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uSuperLazyMarginSwingSum[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uSuperLazyMarginSwingHist[BASE_MARGIN_MAT_BUCKETS][SWING_HIST_BINS]; static UINT64 g_uSuperLazyMarginSwingSumSq[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uSuperLazyMarginExceeded[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uSuperLazyMarginExceededFenSamples[BASE_MARGIN_MAT_BUCKETS]; // Same again, for the experimental NNUE lazy probe (docs/NNUE.md's // "Lazy-evaluation tiering plan") -- |NnueForward() - NnueProbeScore()| // swing, same bucketing (_MaterialBucket), same harness, own counter // set so this doesn't mix with either HCE tier's numbers. No real // margin exists for this tier yet -- this is purely measurement, not // gating anything -- so RecordNnueLazyMarginSafetySwing is always // called with an effectively-infinite iActualMarginUsed (see its call // site in Eval()) until a real margin is derived from this data. static UINT64 g_uNnueLazyMarginSwingMax[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uNnueLazyMarginSwingCount[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uNnueLazyMarginSwingSum[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uNnueLazyMarginSwingHist[BASE_MARGIN_MAT_BUCKETS][SWING_HIST_BINS]; static UINT64 g_uNnueLazyMarginSwingSumSq[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uNnueLazyMarginExceeded[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uNnueLazyMarginExceededFenSamples[BASE_MARGIN_MAT_BUCKETS]; // Material-only "super lazy" tier -- |NnueForward() - // pos->iMaterialBalance[uToMove]|, no fit/regression at all (unlike // the accumulator probe above): VALUE_PAWN=100 means iMaterialBalance // is already in centipawns, the same units NnueForward returns, so // raw material balance is directly usable as the "center" estimate -- // exactly how classic Eval()'s own super-lazy exit already uses it. // Same bucketing/harness as the lazy tier above. static UINT64 g_uNnueSuperLazyMarginSwingMax[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uNnueSuperLazyMarginSwingCount[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uNnueSuperLazyMarginSwingSum[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uNnueSuperLazyMarginSwingHist[BASE_MARGIN_MAT_BUCKETS][SWING_HIST_BINS]; static UINT64 g_uNnueSuperLazyMarginSwingSumSq[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uNnueSuperLazyMarginExceeded[BASE_MARGIN_MAT_BUCKETS]; static UINT64 g_uNnueSuperLazyMarginExceededFenSamples[BASE_MARGIN_MAT_BUCKETS]; static void _RecordMarginSafetySwingInto(IN OUT UINT64 *puMax, IN OUT UINT64 *puCount, IN OUT UINT64 *puSum, IN OUT UINT64 *puSumSq, IN OUT UINT64 puHist[][SWING_HIST_BINS], IN OUT UINT64 *puExceeded, IN OUT UINT64 *puFenSamples, IN CHAR *szTierLabel, IN POSITION *pos, IN SCORE iSwing, IN SCORE iActualMarginUsed) { ULONG uMatBucket = _MaterialBucket(pos); ULONG uHistBin = MINU(SWING_HIST_BINS - 1, (ULONG)iSwing / SWING_HIST_BIN_WIDTH); if (iSwing > iActualMarginUsed) { puExceeded[uMatBucket]++; // 2026-09-17: capped FEN sampler, a few examples per (tier, // bucket) to eyeball by hand -- generalized from a 2026-09-16 // one-off (super-lazy bucket 0 alone) that first found a real // eval bug this way ("in/out of action"). Cheap: PositionToFen // only runs MARGIN_EXCEEDED_FEN_SAMPLE_CAP times per bucket for // the life of the process, not once per exceeded event. if (puFenSamples[uMatBucket] < MARGIN_EXCEEDED_FEN_SAMPLE_CAP) { CHAR *pszOutlierFen = PositionToFen(pos); if (NULL != pszOutlierFen) { puFenSamples[uMatBucket]++; Trace("MARGINSAFETY_EXCEEDED tier=%s bucket=%u swing=%d margin=%d fen=%s\n", szTierLabel, uMatBucket, (int)iSwing, (int)iActualMarginUsed, pszOutlierFen); SystemFreeMemory(pszOutlierFen); } } } ASSERT(iSwing >= 0); puCount[uMatBucket]++; puSum[uMatBucket] += (UINT64)iSwing; puSumSq[uMatBucket] += (UINT64)iSwing * (UINT64)iSwing; puHist[uMatBucket][uHistBin]++; if ((UINT64)iSwing > puMax[uMatBucket]) { puMax[uMatBucket] = (UINT64)iSwing; } } static void RecordMarginSafetySwing(IN POSITION *pos, IN SCORE iSwing, IN SCORE iActualMarginUsed) /** Routine description: Record one (material bucket, |real - lazy| swing) sample for DumpBaseMarginCalibration's margin-safety report, and check whether this specific exit's swing exceeded the actual margin that was used to justify it (a genuine unsoundness event, not just "large"). Parameters: POSITION *pos SCORE iSwing : >= 0 SCORE iActualMarginUsed : the real (post-EstimatePositionalScore) alpha or beta margin this exit was taken under Return value: void **/ { _RecordMarginSafetySwingInto(g_uMarginSwingMax, g_uMarginSwingCount, g_uMarginSwingSum, g_uMarginSwingSumSq, g_uMarginSwingHist, g_uMarginExceeded, g_uMarginExceededFenSamples, "lazy", pos, iSwing, iActualMarginUsed); } static void RecordSuperLazyMarginSafetySwing(IN POSITION *pos, IN SCORE iSwing, IN SCORE iActualMarginUsed) /** Routine description: Same as RecordMarginSafetySwing, but for the super-lazy exit's own separate bucket set -- see the comment on the g_uSuperLazyMargin* arrays above for why these are kept apart. Parameters: POSITION *pos SCORE iSwing : >= 0 SCORE iActualMarginUsed : SUPER_LAZY_MARGIN Return value: void **/ { _RecordMarginSafetySwingInto(g_uSuperLazyMarginSwingMax, g_uSuperLazyMarginSwingCount, g_uSuperLazyMarginSwingSum, g_uSuperLazyMarginSwingSumSq, g_uSuperLazyMarginSwingHist, g_uSuperLazyMarginExceeded, g_uSuperLazyMarginExceededFenSamples, "superlazy", pos, iSwing, iActualMarginUsed); } static void RecordNnueLazyMarginSafetySwing(IN POSITION *pos, IN SCORE iSwing, IN SCORE iActualMarginUsed) /** Routine description: Same shape as RecordSuperLazyMarginSafetySwing, but for the experimental NNUE accumulator-based lazy probe (docs/NNUE.md's "Lazy-evaluation tiering plan") -- |NnueForward() - NnueProbeScore()|, own counter set. No margin is actually gated on yet -- iActualMarginUsed is passed as an effectively-infinite sentinel from Eval() until a real margin is derived from this measurement, so puExceeded stays meaningless for now; only the histogram/sum/sumSq/max/count fields are real data at this stage. Parameters: POSITION *pos SCORE iSwing : >= 0 SCORE iActualMarginUsed : sentinel (no real margin chosen yet) Return value: void **/ { _RecordMarginSafetySwingInto(g_uNnueLazyMarginSwingMax, g_uNnueLazyMarginSwingCount, g_uNnueLazyMarginSwingSum, g_uNnueLazyMarginSwingSumSq, g_uNnueLazyMarginSwingHist, g_uNnueLazyMarginExceeded, g_uNnueLazyMarginExceededFenSamples, "nnue_lazy", pos, iSwing, iActualMarginUsed); } static void RecordNnueSuperLazyMarginSafetySwing(IN POSITION *pos, IN SCORE iSwing, IN SCORE iActualMarginUsed) /** Routine description: Same shape as RecordNnueLazyMarginSafetySwing, but for the material-only "super lazy" signal (|NnueForward() - pos->iMaterialBalance[uToMove]|) -- own counter set, same sentinel-until-a-real-margin-exists convention. Parameters: POSITION *pos SCORE iSwing : >= 0 SCORE iActualMarginUsed : sentinel (no real margin chosen yet) Return value: void **/ { _RecordMarginSafetySwingInto(g_uNnueSuperLazyMarginSwingMax, g_uNnueSuperLazyMarginSwingCount, g_uNnueSuperLazyMarginSwingSum, g_uNnueSuperLazyMarginSwingSumSq, g_uNnueSuperLazyMarginSwingHist, g_uNnueSuperLazyMarginExceeded, g_uNnueSuperLazyMarginExceededFenSamples, "nnue_superlazy", pos, iSwing, iActualMarginUsed); } // Plain Newton's-method sqrt, no -- chess.h's own VALUE_KING // #defines INFINITY_SCORE as a board-eval sentinel, which collides with // 's own INFINITY_SCORE macro, so libm's sqrt() isn't available // here without one shadowing the other. Variance is always small // (swings are bounded well under 2^31), so a fixed handful of Newton // iterations from a decent seed converges to full double precision. static double _Sqrt(IN double d) { double dGuess; int i; if (d <= 0.0) { return 0.0; } dGuess = d; for (i = 0; i < 40; i++) { dGuess = 0.5 * (dGuess + (d / dGuess)); } return dGuess; } // 2026-09-17: same idea as _PersistRawHistogramsToFile above, for the // swing histograms -- lets multiple sharded runs (e.g. N chunks of a // large position pool run in parallel on separate cores) be combined // after the fact into one true aggregate: sum count/exceeded/sum/ // sumSq/histogram bins bucket-by-bucket across shard files, then // recompute mean/stdev/percentiles from the combined totals. Doing // this from raw counts is required for correctness -- percentiles // (p10/p50/p90) can't be validly averaged across shards, only derived // fresh from the combined histogram. static void _PersistMarginSwingHistogramToFile(IN FILE *f, IN CHAR *szTierLabel, IN UINT64 *puCount, IN UINT64 *puExceeded, IN UINT64 *puSum, IN UINT64 *puSumSq, IN UINT64 *puMax, IN UINT64 puHist[][SWING_HIST_BINS]) { ULONG b, i; for (b = 0; b < BASE_MARGIN_MAT_BUCKETS; b++) { fprintf(f, "%s %u %" COMPILER_LONGLONG_UNSIGNED_FORMAT " %" COMPILER_LONGLONG_UNSIGNED_FORMAT " %" COMPILER_LONGLONG_UNSIGNED_FORMAT " %" COMPILER_LONGLONG_UNSIGNED_FORMAT " %" COMPILER_LONGLONG_UNSIGNED_FORMAT, szTierLabel, b, puCount[b], puExceeded[b], puSum[b], puSumSq[b], puMax[b]); for (i = 0; i < SWING_HIST_BINS; i++) { fprintf(f, " %llu", (unsigned long long)puHist[b][i]); } fprintf(f, "\n"); } } void PersistMarginSafetyHistogramsToFile(IN CHAR *szPathOverride) /** Routine description: Write both tiers' swing histograms (plus count/exceeded/sum/sumSq/ max per bucket) to a scratch file, in a format a small external script can sum bucket-by-bucket across multiple shard runs and recompute exact combined statistics from. See the comment on _PersistMarginSwingHistogramToFile above. Parameters: CHAR *szPathOverride : output path, or NULL to use the default (/var/tmp/typhoon/marginsafety_raw_histograms.txt) -- pass a distinct path per shard when running N copies of a large position pool in parallel, since they'd otherwise all clobber the same default file. Return value: void **/ { FILE *f; CHAR *szPath = (NULL != szPathOverride) ? szPathOverride : "/var/tmp/typhoon/marginsafety_raw_histograms.txt"; f = fopen(szPath, "w"); if (NULL == f) { Trace("PersistMarginSafetyHistogramsToFile: could not open output file %s.\n", szPath); return; } fprintf(f, "# SWING_HIST_BINS=%d SWING_HIST_BIN_WIDTH=%d SWING_HIST_MIN=0\n", SWING_HIST_BINS, SWING_HIST_BIN_WIDTH); fprintf(f, "# format: " " ... \n"); _PersistMarginSwingHistogramToFile(f, "lazy", g_uMarginSwingCount, g_uMarginExceeded, g_uMarginSwingSum, g_uMarginSwingSumSq, g_uMarginSwingMax, g_uMarginSwingHist); _PersistMarginSwingHistogramToFile(f, "superlazy", g_uSuperLazyMarginSwingCount, g_uSuperLazyMarginExceeded, g_uSuperLazyMarginSwingSum, g_uSuperLazyMarginSwingSumSq, g_uSuperLazyMarginSwingMax, g_uSuperLazyMarginSwingHist); _PersistMarginSwingHistogramToFile(f, "nnue_lazy", g_uNnueLazyMarginSwingCount, g_uNnueLazyMarginExceeded, g_uNnueLazyMarginSwingSum, g_uNnueLazyMarginSwingSumSq, g_uNnueLazyMarginSwingMax, g_uNnueLazyMarginSwingHist); _PersistMarginSwingHistogramToFile(f, "nnue_superlazy", g_uNnueSuperLazyMarginSwingCount, g_uNnueSuperLazyMarginExceeded, g_uNnueSuperLazyMarginSwingSum, g_uNnueSuperLazyMarginSwingSumSq, g_uNnueSuperLazyMarginSwingMax, g_uNnueSuperLazyMarginSwingHist); fclose(f); Trace("Raw margin-safety histograms written to %s\n", szPath); } static void _DumpMarginSafetyCalibrationInto(IN CHAR *szLabel, IN UINT64 *puMax, IN UINT64 *puCount, IN UINT64 *puSum, IN UINT64 *puSumSq, IN UINT64 *puExceeded) { ULONG m; Trace("%s -- |real - lazy| swing among exits taken, " "by material bucket:\n", szLabel); for (m = 0; m < BASE_MARGIN_MAT_BUCKETS; m++) { double dMean; double dVariance; double dStdev; if (0 == puCount[m]) { Trace(" material bucket %u (scaler %u-%u): no exits taken\n", m, m * BASE_MARGIN_MAT_WIDTH, (m * BASE_MARGIN_MAT_WIDTH) + BASE_MARGIN_MAT_WIDTH - 1); continue; } dMean = (double)puSum[m] / (double)puCount[m]; // E[X^2] - E[X]^2; clamp to 0 to guard against fp rounding // producing a tiny negative just under zero. dVariance = ((double)puSumSq[m] / (double)puCount[m]) - (dMean * dMean); if (dVariance < 0.0) { dVariance = 0.0; } dStdev = _Sqrt(dVariance); // 2026-09-17: no longer printing p10/p50/p90 here -- percentiles // don't combine validly across sharded runs (see // PersistMarginSafetyHistogramsToFile), so a single shard's // in-process percentile read stopped being the useful number // once the workflow moved to persisting raw histogram bins and // computing exact combined percentiles externally instead. Trace(" material bucket %u (scaler %u-%u): max=%" COMPILER_LONGLONG_UNSIGNED_FORMAT " avg=%.1f stdev=%.1f " "(n=%" COMPILER_LONGLONG_UNSIGNED_FORMAT ") exceeded=%" COMPILER_LONGLONG_UNSIGNED_FORMAT "\n", m, m * BASE_MARGIN_MAT_WIDTH, (m * BASE_MARGIN_MAT_WIDTH) + BASE_MARGIN_MAT_WIDTH - 1, puMax[m], dMean, dStdev, puCount[m], puExceeded[m]); } } void DumpMarginSafetyCalibration(IN CHAR *szHistogramPathOverride) /** Routine description: Print, per material bucket, the max/avg/stdev |real - lazy| swing observed among nodes that actually took a lazy exit this run (command.c's "calibrate marginsafety") -- once for the regular lazy exit (LAZY_EVAL_BASE_MARGIN / EstimatePositionalScore) and once for the super-lazy exit (SUPER_LAZY_MARGIN), which is a different-enough regime (cheaper check, much larger required gap) that lumping the two together would hide whichever one is actually unsound. Either section's max is the number that answers "how large would that margin need to be, at that material level, before an exit there could have been unsound." Also persists the raw swing histograms to file (see PersistMarginSafetyHistogramsToFile) so percentiles can be computed exactly, including across multiple sharded runs. Parameters: CHAR *szHistogramPathOverride : forwarded to PersistMarginSafetyHistogramsToFile -- NULL for the default path. Return value: void **/ { _DumpMarginSafetyCalibrationInto("Regular lazy margin safety", g_uMarginSwingMax, g_uMarginSwingCount, g_uMarginSwingSum, g_uMarginSwingSumSq, g_uMarginExceeded); _DumpMarginSafetyCalibrationInto("Super lazy margin safety", g_uSuperLazyMarginSwingMax, g_uSuperLazyMarginSwingCount, g_uSuperLazyMarginSwingSum, g_uSuperLazyMarginSwingSumSq, g_uSuperLazyMarginExceeded); _DumpMarginSafetyCalibrationInto("NNUE lazy probe margin safety", g_uNnueLazyMarginSwingMax, g_uNnueLazyMarginSwingCount, g_uNnueLazyMarginSwingSum, g_uNnueLazyMarginSwingSumSq, g_uNnueLazyMarginExceeded); _DumpMarginSafetyCalibrationInto("NNUE super lazy (material-only) margin safety", g_uNnueSuperLazyMarginSwingMax, g_uNnueSuperLazyMarginSwingCount, g_uNnueSuperLazyMarginSwingSum, g_uNnueSuperLazyMarginSwingSumSq, g_uNnueSuperLazyMarginExceeded); PersistMarginSafetyHistogramsToFile(szHistogramPathOverride); } #endif // CALIBRATE_MARGIN_SAFETY // 2026-09-16/17: shared, file-scope tables for the margin_a/margin_b // (super-lazy, in Eval() below) and margin_a'/margin_b' // (EstimatePositionalScore, regular lazy, right after this) margin // constructions. King safety is ARMY-ONLY for both tiers (no // CountKingSafetyDefects call from either -- a joint attacker-army x // defect-count table was considered for regular lazy specifically, but // dropped: CountKingSafetyDefects is slow despite being bitboard-based, // not worth paying for if the simpler table is already good enough; // it stays in the codebase for its existing, unrelated search // extension/reduction-gate use). Residual is NOT shared between tiers, // despite living together here -- iResidualP2/98ByOwnArmy is scoped // to regular lazy's own baseline (after bishop pairs: excludes pawns/ // passers/bad-trade/bishop-pairs, since regular lazy already has all // of that by the time it asks); iSuperLazyResidualP2/98ByOwnArmy is // scoped to super-lazy's own baseline (pure material: INCLUDES pawns/ // passers/bad-trade/bishop-pairs, since super-lazy has none of it yet). // Using the regular-lazy-scoped table for super-lazy was a real bug in // the first version of this redesign -- it silently excluded exactly // the terms super-lazy needed most and got quietly papered over with a // MAX() against the old flat floor, which defeated the whole point of // building a position-specific estimate. Fixed by measuring the right // thing instead of re-adding a workaround. // // Speed/accuracy knob: measured exceeded rate (fraction of lazy/ // super-lazy exits where the real full-eval score actually would have // landed back across alpha/beta -- i.e. this lazy exit was WRONG) by // percentile choice, both from the same 30k-position stratified pool, // same `sd 6` conditions, via CALIBRATE_MARGIN_SAFETY's `calibrate // marginsafety`. Bucket numbering here is the MATERIAL bucket // (_MaterialBucket: combined non-pawn army scaler for BOTH sides, // divided by 8 -- 0-7) -- NOT the same bucketing as the per-side // army-scaler/4 buckets the percentile tables below are keyed by. // Buckets 0-1 never take a regular-lazy exit at all (see // LAZY_EVAL_MIN_MATERIAL) so have no regular-lazy row. // // material bucket: 2 3 4 5 6 7 // (combined scaler) (16-23) (24-31) (32-39) (40-47) (48-55) (56-63) // ----------------------- ------- ------- ------- ------- ------- ------- // regular lazy, p90/p10: 0.97% 0.48% 0.72% 1.61% 1.54% 0.72% // regular lazy, p98/p2: 0.046% 0.013% 0.010% 0.029% 0.032% 0.041% // // material bucket: 1 2 3 4 5 6 7 // (combined scaler) (8-15) (16-23) (24-31) (32-39) (40-47) (48-55) (56-63) // ----------------------- ------- ------- ------- ------- ------- ------- ------- // super lazy, p90/p10: 9.43% 5.08% 3.73% 1.32% 1.14% 1.99% 0.54% // super lazy, p98/p2: 1.08% 0.349% 0.209% 0.045% 0.063% 0.069% 0.018% // // (Super-lazy has no material-bucket-0 row: excluded entirely, see the // bucket-0 comment at its exclusion gate below.) // // 2026-09-17 re-recalibration: switched from p90/p10 to p98/p2 given // the above -- p90/p10 exceeded on a non-trivial fraction of exits // (regular lazy: 0.5-1.6% across buckets; super-lazy: 0.5-9.4%, worst // in the low-material buckets), p98/p2 brings every bucket in both // tiers under 1.1%, an order of magnitude tighter. If p98/p2 still // isn't tight enough once self-play validates it, p99/p1 is the next // lever -- re-derive via `calibrate residual` against the same 30k // pool, no new position sample needed. // All four tables below are FINAL, derived from the same 30k-position // stratified pool (~104M-240M samples/bucket for residual/king, // buckets keyed by scaler/4). Full percentile spread recorded so a // future re-tightening (e.g. p99/p1) can read values straight off // these charts without re-running the 30k pool -- only the two // _P2By.../_P98By... lines actually feed the margin construction // below; min/p1/p5/p10/p50/p90/p95/p99/max are kept for reference. // // Residual by OWN army-scaler bucket (regular-lazy baseline: excludes // pawns/passers/bad-trade/bishop-pairs): // bucket 0 (scaler 0-3): n=104187433 min=-144 p1=-30 p2=-10 p5=-10 p10=-10 p50=10 p90=110 p95=130 p98=190 p99=230 max=767 // bucket 1 (scaler 4-7): n=125821895 min=-166 p1=-10 p2=-10 p5=-10 p10=10 p50=50 p90=150 p95=210 p98=250 p99=290 max=817 // bucket 2 (scaler 8-11): n=239860406 min=-174 p1=-30 p2=-30 p5=-10 p10=-10 p50=30 p90=130 p95=170 p98=230 p99=270 max=761 // bucket 3 (scaler 12-15): n=190456720 min=-209 p1=-50 p2=-30 p5=-30 p10=-10 p50=30 p90=110 p95=130 p98=190 p99=230 max=708 // bucket 4 (scaler 16-19): n=216350902 min=-220 p1=-70 p2=-70 p5=-50 p10=-30 p50=30 p90=90 p95=110 p98=150 p99=170 max=735 // bucket 5 (scaler 20-23): n=189558383 min=-225 p1=-70 p2=-50 p5=-30 p10=-30 p50=30 p90=70 p95=90 p98=130 p99=150 max=728 // bucket 6 (scaler 24-27): n=135722645 min=-231 p1=-90 p2=-70 p5=-50 p10=-30 p50=10 p90=70 p95=90 p98=110 p99=130 max=760 // bucket 7 (scaler 28-31): n=164358044 min=-256 p1=-110 p2=-110 p5=-90 p10=-90 p50=-30 p90=30 p95=50 p98=70 p99=90 max=796 // 2026-09-17 BEST-GUESS #2: guess #1 (p95/p5 uniformly) measured // 0.002-0.270% on a 500-position sample (buckets 2-7) -- still under // the ~0.4% target, especially buckets 4-5 (0.002% each). Per direct // instruction, loosened buckets 2-5 one more step to p90/p10 (values // read off the chart above, no new run); buckets 6-7 already looked // close to target at p95/p5 (0.270%/0.152%) and are left unchanged. // Buckets 0-1 never take a regular-lazy exit at all (LAZY_EVAL_MIN_ // MATERIAL) so their values are moot either way. Caveat: the 500- // position sample is noisy (small event counts in low buckets, and // not truly 500 independent draws -- a single game's tree can dominate // a material bucket's node population), so this is still a guess // pending the next full 30k-position `calibrate marginsafety` run. // 2026-09-17 BEST-GUESS #3: real 30k-pool re-check of guess #2 (not // the noisy 500-position sample) measured bucket2=0.385% (right on // target) but buckets 3-7 all 0.048-0.099%, still well under the // 0.4-0.5% target -- loosened further to p85/p15 (exact values from // the persisted raw histogram, /var/tmp/typhoon/residual_raw_ // histograms.txt -- see hist_percentile.py). Bucket 2 left unchanged // (already at target). // 2026-09-17 BEST-GUESS #4: buckets 0-2 left at guess #3 (0.06-0.39% // measured, buckets 0-1 take no lazy exits so moot). Buckets 3-7 // measured 0.048-0.099%, well under the ~0.4-0.5% target -- loosened // one more notch (values read off the persisted 30k histogram via // hist_percentile.py, no new sample needed): bucket 3 p85/p15 -> // p80/p20, bucket 4 p85/p15 -> p80(tie)/p20, bucket 5 p85/p15 -> // p85(tie)/p20, bucket 6 p85/p15 -> p75/p25, bucket 7 p90/p20-ish -> // p75/p25 (P98 only, P2 already at its floor). Re-verify with a full // `calibrate marginsafety` pass -- not expected to land exactly on // target given cross-bucket confounds (see guess #3 comment above). // 2026-09-17 BEST-GUESS #5: buckets 3-5 loosened one more notch // (p80/p20-ish -> p70/p30, values from the persisted 30k histogram). // Bucket 0-2, 6-7 unchanged pending their own re-check (guess #4's // 30k run showed bucket 2 already over target without being touched, // and buckets 6-7 already over target from guess #4's loosening -- // see command history). // 2026-09-17 BEST-GUESS #6: targeting ~0.66% in every bucket. Bucket 2 // was drifting up untouched (0.72% guess #4 -> 1.04% guess #5) -- // tightened p90/p10-ish -> p80/p20. Bucket 5 was under target (0.39%) // -- loosened a tad, p70/p30 -> p90/p30 (P98 side only). // 2026-09-17 BEST-GUESS #7: targeting ~0.66% in every bucket. // Bucket 2 (1.62%, way over) -- guess #6's "tighten" actually // narrowed the margin by mistake (tighten = lower exceeded rate = // WIDEN the percentile spread, not narrow it); corrected direction, // widened past guess #5's own (-10,130) to (-30,190) i.e. p97/p3. // Buckets 3/4/6 (0.71-0.74%, slightly over) widened a little (P98 // +20 each). Bucket 5 (0.30%, under) narrowed back (P98 70->50, // reverting guess #6's accidental widen). Bucket 7 (0.47%, under) // narrowed a little (P2 -70->-50). // 2026-09-17 BEST-GUESS #8: buckets 3-5 came in well under target // (0.27-0.39% vs ~0.66%) -- narrowed further for speed (guess #5's // bucket 5 narrow was too small a step, barely moved anything; // bigger step this time). Bucket 3: p75/p30 -> p60/p40. Bucket 4: // P98 only, p75/p40 -> p55/p40 (P2 unchanged, bin ties at that end). // Bucket 5: p65/p35-ish -> p55/p45, moved both sides this time. // Buckets 0-2/6-7 untouched pending their own re-check. // 2026-09-18: restored to the guess-#11 values (11 rounds of // calibration against the 30k-position pool and the 200k-position // cross-sectional run, see the guess #1-11 history above) after // briefly suspecting -- and ruling out, via the 16:15 ZFS snapshot // still showing a winning match_play series with guesses #9/#10 // already applied -- that this table's loosening was the source of // the 2026-09-17 self-play regression. The real cause was util.c's // WalkPV/MakeUserMove change (reverted separately). static const SCORE iResidualPessimisticByOwnArmy[8] = { -10, -10, -10, 10, -10, 30, -10, -50, }; static const SCORE iResidualOptimisticByOwnArmy[8] = { 130, 210, 170, 50, 70, 30, 50, -10, }; // Super-lazy-scoped residual by OWN army-scaler bucket (material-only // baseline: includes pawns/passers/bad-trade/bishop-pairs): // bucket 0 (scaler 0-3): n=104187433 min=-363 p1=-110 p2=-90 p5=-50 p10=-30 p50=30 p90=210 p95=290 p98=410 p99=530 max=2383 // bucket 1 (scaler 4-7): n=125821895 min=-356 p1=-70 p2=-50 p5=-30 p10=-10 p50=90 p90=290 p95=370 p98=490 p99=830 max=2456 // bucket 2 (scaler 8-11): n=239860406 min=-341 p1=-70 p2=-50 p5=-30 p10=-10 p50=70 p90=250 p95=330 p98=430 p99=530 max=2065 // bucket 3 (scaler 12-15): n=190456720 min=-324 p1=-70 p2=-50 p5=-30 p10=-10 p50=70 p90=230 p95=290 p98=390 p99=450 max=2183 // bucket 4 (scaler 16-19): n=216350902 min=-343 p1=-90 p2=-70 p5=-50 p10=-30 p50=50 p90=190 p95=250 p98=310 p99=370 max=1946 // bucket 5 (scaler 20-23): n=189558383 min=-299 p1=-70 p2=-50 p5=-30 p10=-10 p50=70 p90=170 p95=230 p98=290 p99=330 max=1959 // bucket 6 (scaler 24-27): n=135722645 min=-322 p1=-90 p2=-70 p5=-50 p10=-30 p50=50 p90=150 p95=190 p98=250 p99=290 max=1921 // bucket 7 (scaler 28-31): n=164358044 min=-304 p1=-90 p2=-90 p5=-70 p10=-50 p50=10 p90=90 p95=130 p98=170 p99=210 max=2039 // 2026-09-17 BEST-GUESS #3: real 30k-pool re-check of guess #2 revealed // the 500-position sample had misled guess #2 in the dangerous // direction on two buckets: material bucket 1 (reverted to p98/p2 // based on a 500-position reading of 0.035%) actually measured 1.13% // at full scale, and material bucket 3 (table never touched at all) // measured 0.94% -- a real cross-bucket confound (changing OTHER // buckets' margins shifts real search behavior/tree shape everywhere, // so even an untouched bucket's measured exceeded rate moves). Per- // side buckets 0-3 tightened to p99/p1 (exact values from the // persisted raw histogram) to address both -- material buckets 1 and 3 // are populated by a diffuse mix of per-side bucket combinations, not // a clean 1:1 mapping, so this can't precisely target either bucket // alone, only reduce risk broadly in the low-army region feeding both. // Buckets 4-6 measured 0.22-0.30%, still under target -- loosened // further to p85/p15. Bucket 7 (0.15%) and the king table (negligible // spread above p90 in every bucket, confirmed against the persisted // histogram) left unchanged. Real search-tree-shape changes are // expected from this (not just a measurement artifact) -- re-verify // with a full `calibrate marginsafety` pass, best-effort, not // expected to land exactly on target for every bucket given the // diffuse material-bucket-to-per-side-bucket mapping. // 2026-09-17 BEST-GUESS #4: bucket 1 was the worst outlier at 1.13% // measured (target ~0.4-0.5%) -- tightened one more notch past p99/p1, // to p99.5/p0.5 (values from the persisted 30k histogram). Buckets 0 // and 2-3 left at guess #3 (bucket 3 measured 0.94%, also over target, // but a diffuse material-bucket confound with bucket 1 -- see guess #3 // comment above -- so left alone pending its own re-check rather than // guessing a second simultaneous change). Buckets 4-7 measured // 0.15-0.30%, well under target -- loosened one more notch: buckets // 4-6 p85/p15 -> p80/p20, bucket 7 p90/p10 -> p85/p15. // 2026-09-17 BEST-GUESS #5: bucket 3 was over target (0.94% guess #3, // 1.23% guess #4, moving the wrong direction despite never being // touched -- a cross-bucket confound from bucket 1's changes) -- // tightened past p99/p1 to p99.5/p0.5, same lever used for bucket 1. // Bucket 7 was still under target (0.15%/0.29%) -- loosened one more // notch, p85/p15 -> p75/p25 (P98 side only; P2 already at p85's floor). // 2026-09-17 BEST-GUESS #6: targeting ~0.66% in every bucket. Bucket // 1 (0.458%, under target) was at p99.5/p0.5 -- backed off a tiny bit // to p99/p1. Bucket 3 (1.11%, worst outlier, already at p99.5/p0.5) // has no looser-percentile lever left in this histogram's resolution // -- padded a fixed +120/-20 beyond p99.5/p0.5 instead. Bucket 6 // (0.96%, over target, was p80/p20) tightened to p90/p10. Bucket 7 // (0.36%, under target, was p75/p25) loosened a tad, P2 side only // (p25 -> p30-ish). // 2026-09-17 BEST-GUESS #7: targeting ~0.66% in every bucket. // Bucket 1 (0.49%, slightly under) narrowed a little (P2 -70->-50). // Buckets 2/4/6 (0.68/0.61/0.71%) already close enough -- left // alone. Bucket 3 (1.09%, still worst, already past p99.5) widened // further via a bigger pad (-110,650) -> (-150,850). Buckets 5/7 // (0.54%/0.56%, slightly under) narrowed a little (P98 -20 each). // 2026-09-17 BEST-GUESS #9: same 200k/sd3 cross-sectional finding as // the regular-lazy table above, new target 1.5%. Bucket 2 (2.99%, // worst of all despite never being touched before -- already sitting // at p99/p0.5, percentile table exhausted) padded further, same lever // used for bucket 3 previously. Bucket 3 (1.95%, least-bad of these // three but still over, already heavily padded) padded a bit more. // Bucket 6 (2.19%) widened p90/p10 -> p96/p6. // 2026-09-17 BEST-GUESS #10: target ~1-1.5%. Bucket 1 (0.34%, well // under) loosened, p99/p2-ish -> ~p98/p4. Bucket 2 (3.45%, worst -- // got WORSE after widening in guess #9 despite already sitting past // p99.5) padded further again regardless; this bucket has resisted // two widening passes in a row, likely the same cross-bucket-combo // issue diagnosed for bucket 3 earlier (material bucket != per-side // bucket, diffuse mapping) rather than something this table alone can // fix -- flagging for a real root-cause dig rather than more blind // widening if this doesn't help either. Buckets 3-7 left alone. // 2026-09-17 BEST-GUESS #11: bucket 2 (2.97%, still worst after three // widening rounds in a row -- see guess #10's note, likely a // cross-bucket-combo issue this table alone can't fully fix) padded // further again. Rest left alone. // 2026-09-18: restored to the guess-#11 values (see the matching note // on iResidualPessimisticByOwnArmy above) after ruling out this // table's loosening as the cause of the 2026-09-17 self-play // regression -- the 16:15 ZFS snapshot already had guesses #9/#10 // applied and was still winning. The real cause was util.c's WalkPV/ // MakeUserMove change (reverted separately). static const SCORE iSuperLazyResidualPessimisticByOwnArmy[8] = { -110, -30, -190, -170, 10, 10, -50, -10, }; static const SCORE iSuperLazyResidualOptimisticByOwnArmy[8] = { 530, 490, 1050, 950, 150, 110, 190, 40, }; // King safety by ATTACKER army-scaler bucket: // bucket 0 (scaler 0-3): n=104187433 min=-68 p1=-10 p2=10 p5=10 p10=10 p50=10 p90=30 p95=30 p98=50 p99=50 max=165 // bucket 1 (scaler 4-7): n=125821895 min=0 p1=10 p2=10 p5=10 p10=10 p50=10 p90=30 p95=30 p98=50 p99=50 max=162 // bucket 2 (scaler 8-11): n=239860406 min=-89 p1=-30 p2=-30 p5=-30 p10=-10 p50=10 p90=10 p95=10 p98=30 p99=30 max=162 // bucket 3 (scaler 12-15): n=190456720 min=-176 p1=-70 p2=-70 p5=-50 p10=-50 p50=-10 p90=-10 p95=10 p98=10 p99=10 max=137 // bucket 4 (scaler 16-19): n=216350902 min=-307 p1=-190 p2=-170 p5=-130 p10=-110 p50=-30 p90=-10 p95=-10 p98=-10 p99=10 max=129 // bucket 5 (scaler 20-23): n=189558383 min=-354 p1=-250 p2=-230 p5=-190 p10=-130 p50=-50 p90=-30 p95=-10 p98=-10 p99=-10 max=45 // bucket 6 (scaler 24-27): n=135722645 min=-401 p1=-270 p2=-250 p5=-170 p10=-150 p50=-70 p90=-30 p95=-10 p98=-10 p99=-10 max=13 // bucket 7 (scaler 28-31): n=164358044 min=-394 p1=-190 p2=-170 p5=-130 p10=-90 p50=-50 p90=-10 p95=-10 p98=-10 p99=10 max=6 static const SCORE iKingP2ByAttackerArmy[8] = { 10, 10, -30, -70, -170, -230, -250, -170, }; static const SCORE iKingP98ByAttackerArmy[8] = { 50, 50, 30, 10, -10, -10, -10, -10, }; // 2026-09-17: p50 tables, same 30k-position pool, same bucketing as // their P2/P98 siblings above -- but used for a different purpose: // a signed, unbounded (well, table-bounded) *typical-value estimate* // of that side's own missing positional terms, fed to QSearch's // futility margin as iPositional[side] on a lazy/super-lazy exit // (matches full-eval's own iPositional convention exactly -- see // Eval()'s "Adjust dynamic positional component" block below, which // computes a side's *own* real positional score minus its material, // not a relative-to-opponent quantity). This is deliberately NOT the // p98/p2 pessimistic/optimistic pairing margin_a/margin_b use -- // p50 is the right statistic for a bias correction, p98/p2 is the // right statistic for a soundness bound. iPositional[color] = // iKingP50ByAttackerArmy[opponent's army bucket] (opponent is the // attacker of this side's own king) + iResidualP50ByOwnArmy[this // side's own army bucket] (or the super-lazy-scoped sibling, for the // super-lazy exit). // residual p50 (regular-lazy baseline), by OWN army bucket: // 10, 50, 30, 30, 30, 30, 10, -30 // super-lazy-scoped residual p50 (material-only baseline), by OWN army bucket: // 30, 90, 70, 70, 50, 70, 50, 10 // king safety p50, by ATTACKER army bucket: // 10, 10, 10, -10, -30, -50, -70, -50 static const SCORE iResidualP50ByOwnArmy[8] = { 10, 50, 30, 30, 30, 30, 10, -30, }; static const SCORE iSuperLazyResidualP50ByOwnArmy[8] = { 30, 90, 70, 70, 50, 70, 50, 10, }; static const SCORE iKingP50ByAttackerArmy[8] = { 10, 10, 10, -10, -30, -50, -70, -50, }; static void EstimatePositionalScore(IN SEARCHER_THREAD_CONTEXT *ctx, IN POSITION *pos, IN PAWN_HASH_ENTRY *pHash, IN OUT SCORE *piAlphaMargin, IN OUT SCORE *piBetaMargin) /** Routine description: Before doing an early lazy eval, look at the position and widen the alpha/beta margins to account for the positional terms that have not been computed yet at this point in Eval() -- king safety plus a flat residual covering mobility, passers, and everything else that genuinely requires full evaluation to find out. Both terms below are calibrated from measured data (CALIBRATE_ POSITIONAL instrumentation, 200M full-eval samples: for each value, p90 of the *actual* score swing between this point in Eval() and full-eval completion, so the resulting margin is wrong (too narrow) on at most ~10% of calls, in either bucket. See conversation history for the percentile tables -- if re-tuning, regenerate them, don't hand- edit these numbers. Note: king safety and "everything else" turned out to be close to independent of piece count and of each other, so summing their two p90s (rather than deriving one joint p90) is a deliberately conservative (wider than strictly necessary) combination. O(1) -- no attack bitboard generation -- so it's safe to call whenever the cheap material-only lazy check (the caller's first-pass margin) wasn't enough to resolve the cutoff on its own. Parameters: SEARCHER_THREAD_CONTEXT *ctx : unused as of 2026-09-06 (_GetFileStormDefects, the only user, was pulled out of this hot path -- see the iKingSwingP90 staleness comment below); kept in the signature for call-site stability. POSITION *pos PAWN_HASH_ENTRY *pHash : unused as of 2026-09-06, same reason as ctx above. pHash->iScore is already folded into pos->iScore by this point regardless, and the passer-specific estimate this used to compute turned out to be negligible next to the residual term below. SCORE *piAlphaMargin, *piBetaMargin : widened in place, identically (no measured basis for an asymmetric alpha/beta split) Return value: void **/ { // 2026-09-16 redesign: replaces the old symmetric "sum both sides' // unscaled p90 magnitude, rescale by attacker army at runtime" // construction entirely -- that mechanism pooled the p90 fit // across every material level for a given CountKingSafetyDefects // bucket, then linearly rescaled by attacker army at use time; that // rescale assumed a linear relationship between "how much raw // danger a defect-count implies" and "how much material the // attacker actually has" that the real terms (each individually // gated on specific attacking pieces existing) don't obey -- a // structural mismatch, not just a stale fit (see conversation // history for the full derivation). // // New approach: two direct, jointly-collected percentile tables -- // king safety bucketed by the ATTACKER's own army scaler (danger // to a king is a function of the attacker's material, not the // king-owner's), and residual (mobility/trapped/misc, with // material/pawns/passers/bad-trade/bishop-pairs/king safety already // excluded) bucketed by each side's OWN army scaler (residual is // relative/congestion-driven, not attacker-driven, unlike king // safety -- bucketing it by one side's own army alone, ignoring the // enemy, was tried and came back noisy/non-monotonic; the // differential does not, but this per-side percentile construction // sidesteps needing the differential directly by keying each side's // OWN contribution off its OWN army only, then combining per-side // via the asymmetric construction below). // // The margin construction itself mirrors this file's existing // QSearch futility precedent (iPositional is returned per-color, // not as a single "estimate minus full eval" blob, because a // combined delta lets the two sides' real swings partially cancel // and hides the structure that actually matters) -- and is the // same operation as futility pruning, one stack frame up: for the // fail-high check (score - margin_a > beta), soundness requires // assuming the most PESSIMISTIC-for-me, OPTIMISTIC-for-my-opponent // outcome for each term; the fail-low check (score + margin_b < // alpha) requires the mirror. For every term, uniformly (no sign- // flipping needed regardless of whether the raw term is usually // positive or negative): // // margin_a = [opponent's p90(term) - my p10(term)], summed over terms // margin_b = [my p90(term) - opponent's p10(term)], summed over terms // // King safety is cross-referenced (my king's term uses the // OPPONENT's army bucket, since they're the attacker; the // opponent's king term uses MY army bucket) -- residual is not // (each side's residual is keyed by that side's own army). // // PROVISIONAL tables below: from a 200-position stratified // (material-balanced) sample, ~8.76M full-eval samples -- adequate // for validating the construction and getting real numbers in // place, but due for a refresh from the much larger 30k-position // stratified histogram run once it lands (board_representation/ // EVAL.md section 9 / 2026-09-16 super-lazy speed investigation). // Re-derive via `calibrate residual` (DUMP_RESIDUAL_SAMPLES build). // Uses the file-scope army-only king table (iKingP2/98ByAttacker- // ArmyOnly) and residual table (iResidualP2/98ByOwnArmy), shared // with super-lazy's identical construction below in Eval(). A // joint (attacker-army x defect-count) king table was considered // (CountKingSafetyDefects would supersede the army-only estimate // once we're already committed to the more expensive lazy-eval // path) but deliberately dropped -- CountKingSafetyDefects is slow // despite being bitboard-based, not worth paying for here if the // simpler army-only table is already good enough. It stays in the // codebase for its existing, unrelated use as a search extension/ // reduction gate (search.c/searchsup.c) -- just no longer called // from eval's margin construction at all, either tier. ULONG uColor = pos->uToMove; ULONG xColor = FLIP(uColor); ULONG uMyBucket = MINU(7, pos->uArmyScaler[uColor] / 4); ULONG uOppBucket = MINU(7, pos->uArmyScaler[xColor] / 4); SCORE iSelfPessimisticEnemyOptimisticMargin, iSelfOptimisticEnemyPessimisticMargin; iSelfPessimisticEnemyOptimisticMargin = MAX0((iKingP98ByAttackerArmy[uMyBucket] - iKingP2ByAttackerArmy[uOppBucket]) + (iResidualOptimisticByOwnArmy[uOppBucket] - iResidualPessimisticByOwnArmy[uMyBucket])); iSelfOptimisticEnemyPessimisticMargin = MAX0((iKingP98ByAttackerArmy[uOppBucket] - iKingP2ByAttackerArmy[uMyBucket]) + (iResidualOptimisticByOwnArmy[uMyBucket] - iResidualPessimisticByOwnArmy[uOppBucket])); // Caller's iBetaMargin gates "score - margin > beta" (fail-high, // needs margin_a); iAlphaMargin gates "score + margin < alpha" // (fail-low, needs margin_b). // // 2026-09-17: the flat iSwingFloorByArmy MAX() floor that used to // sit here is GONE, for the same reason super-lazy's analogous // floor was already dropped (see Eval()'s super-lazy margin // construction, above) -- a MAX() against a much larger flat number // just silently overrides the position-specific estimate in most // cases, defeating the entire point of building it. margin_a/ // margin_b now stand alone. If CALIBRATE_MARGIN_SAFETY turns up a // real, non-trivial exceeded rate once this is validated against // the 30k pool, the fix is tightening the percentile choice (e.g. // p95/p5 or p99/p1), not resurrecting a flat backstop. *piAlphaMargin += iSelfOptimisticEnemyPessimisticMargin; *piBetaMargin += iSelfPessimisticEnemyOptimisticMargin; } // // ====================================================================== // static void _RecordTrappedCandidate(IN OUT POSITION *pos, IN ULONG uColor, IN COOR c, IN BITBOARD bbEscapes) /** Routine description: Record a trapped-piece candidate for uColor -- either a genuinely zero-mobility piece (bbEscapes passed as 0: nothing to re-derive, see _EvalBishop's comment), or a bishop/knight deferred because its own partial-information mobility count was low but nonzero (bbEscapes is that piece's own bbMobility snapshot at nomination time). Used by _EvalBishop/_EvalKnight/_EvalRook/_EvalQueen; the actual attacked-or-not check, and (for a deferred candidate) the final mobility re-derivation, happen later in _EvalTrappedPieces. Capped at ARRAY_LENGTH(pos->cTrapped[0]) candidates per side -- extras are just dropped, not a real concern in practice. Parameters: POSITION *pos, ULONG uColor, COOR c, BITBOARD bbEscapes Return value: void **/ { if (pos->uNumTrapped[uColor] < ARRAY_LENGTH(pos->cTrapped[uColor])) { pos->bbTrappedEscapes[uColor][pos->uNumTrapped[uColor]] = bbEscapes; pos->cTrapped[uColor][pos->uNumTrapped[uColor]++] = c; } } static void _EvalBishop(IN OUT POSITION *pos, IN COOR c, IN PAWN_HASH_ENTRY *pHash, IN BITBOARD bbEnemyRQK) /** Routine description: Parameters: POSITION *pos, COOR c, PAWN_HASH_ENTRY *pHash, BITBOARD bbEnemyRQK -- enemy rook|queen|king, precomputed once per color by Eval()'s driver instead of rebuilt by every bishop of that color (see MOBILITY_BITBOARD_REWRITE.md) -- depends only on static piece locations, no eval-ordering dependency. Return value: FLAG **/ { static const BITBOARD bbColorSq[2] = { 0x55aa55aa55aa55aaULL, 0xaa55aa55aa55aa55ULL }; static const COOR cBishopAtHome[2][2] = { { C8, F8 }, // BLACK { C1, F1 } // WHITE }; ULONG uColor; ULONG xColor; BITBOARD bb; BITBOARD bbMask; BITBOARD bbPc; SCORE i; ULONG u; ULONG uTotalMobility; PIECE p; ASSERT(IS_ON_BOARD(c)); p = pos->rgSquare[c].pPiece; ASSERT(p && IS_BISHOP(p)); uColor = GET_COLOR(p); xColor = FLIP(uColor); // Undeveloped minor piece; maybe penalized later in EvalKing. pos->uMinorsAtHome[uColor] += (c == cBishopAtHome[uColor][0]); pos->uMinorsAtHome[uColor] += (c == cBishopAtHome[uColor][1]); ASSERT(pos->uMinorsAtHome[uColor] <= 4); // Good and bad bishops given pawn structure (own and enemy, // stationary and transient) on this bishop's color complex -- // cached per (color, complex) in the pawn hash, since none of it // depends on which square of that complex the bishop actually // sits on. See the cache population in the pawn-hash-miss path // above (_EvalPawns's FOREACH_COLOR block) for the full semantics. bbMask = bbColorSq[IS_SQUARE_WHITE(c)]; i = pHash->iBishopColorScore[uColor][IS_SQUARE_WHITE(c)]; EVAL_TERM(uColor, BISHOP, c, pos->iScore[uColor], i, "good/bad bishop pawns"); // Still needed below: "non-stationary pawns of either color on // this color complex," used by the mobility walk's // BMOB_FRIEND_PAWN case (see its comment just below). bbPc = ~(pHash->bbStationaryPawns[WHITE] | pHash->bbStationaryPawns[BLACK]) & bbMask; // // Bishop mobility (and update attack tables) -- single magic-bitboard // probe, no chain walk (see MOBILITY_BITBOARD_REWRITE.md). The old // seven-case BMobCaseTable collapses to pure mask arithmetic over the // one-shot first-blocker attack set: // - terminal enemy non-pawn (minor/rook/queen/king): counts // unconditionally -- this is a capture, always "real" mobility. // - empty or terminal enemy pawn: counts unless pawn-unsafe -- both // terminal-square categories together are exactly "not // friend-occupied and not enemy-non-pawn-occupied," the same // partition knight's reduction uses. // - terminal friendly, non-stationary pawn on this bishop's own // color complex: still counts -- bbPc (already computed above for // the good/bad transient-pawn scoring) is exactly "non-stationary // pawns of either color on this color complex." // - any other friendly piece (knight/rook/king): blocks, no count. // // Deliberately NOT replicated: mobility/connectivity credit for // squares beyond a friendly bishop/queen or enemy rook/queen/king -- // a bishop cannot physically move past a piece it would capture in // one ply, so that was never "real mobility" to begin with (dropping // it is a correctness fix, not just a simplification). See // MOBILITY_BITBOARD_REWRITE.md for the king-ring x-ray replacement, // which is the one piece of information this loses that's worth // deliberately replacing below. // BITBOARD bbAttack = _BishopAttacksBB(c, pos->bbOccupied); BITBOARD bbEnemySame = pos->bbPieces[xColor][BISHOP] | pos->bbPieces[xColor][KNIGHT]; BITBOARD bbUnsafeForMinor = pos->bbPawnAttacks[xColor]; BITBOARD bbEnemyPawnHere = bbAttack & pos->bbPawns[xColor]; BITBOARD bbTransientHere = bbAttack & pos->bbPawns[uColor] & bbPc; BITBOARD bbEnemyGEHere = bbAttack & bbEnemyRQK; BITBOARD bbMobility; BITBOARD bbXray; pos->bbMinorAttacks[uColor] |= bbAttack; bbMobility = (bbAttack & ~pos->bbOccupied & ~bbUnsafeForMinor) | (bbAttack & bbEnemySame) | bbEnemyGEHere | (bbEnemyPawnHere & ~bbUnsafeForMinor) | bbTransientHere; // // King-ring x-ray, replacing the old chain's attack-bit population: // only pay for an extra magic probe when this bishop already // directly attacks an enemy rook/queen/king square (bbEnemyGEHere, // already computed above for mobility -- free to test). Every bit // in bbEnemyGEHere is, by construction, the terminal blocker of a // *different* diagonal ray, so masking all of them off at once and // re-probing in a single magic lookup gives the exact same union a // per-blocker loop would (removing one ray's blocker can't affect a // different ray's result) -- no need to isolate and remove them one // at a time. No deeper chaining needed either way, since the only // consumer (_EvalKingSafety) only ever ANDs this against the king's // ring, never walks further. // bbXray = bbEnemyGEHere ? _BishopAttacksBB(c, pos->bbOccupied & ~bbEnemyGEHere) : 0; pos->bbMinorXrayAttacks[uColor] |= bbXray; // Pseudo-mobility bonus for squares seen past the higher-value // blocker -- see BISHOP_XRAY_MOBILITY_BY_SQUARES's comment. bbXray // already includes the blocker's own square (redundant with // bbAttack, which already counts it as a capture), so subtracting // bbAttack leaves exactly the net-new squares revealed behind it. EVAL_TERM(uColor, BISHOP, c, pos->iScore[uColor], BISHOP_XRAY_MOBILITY_BY_SQUARES[ MINU(FastCountBits(bbXray & ~bbAttack), 8)], "xray pseudo-mobility"); uTotalMobility = FastCountBits(bbMobility); ASSERT(uTotalMobility <= 13); // // uTotalMobility here is necessarily pessimistic-as-an-upper-bound // (not pessimistic-as-a-lower-bound): at this point in Eval() only // enemy PAWN attacks are known, so a square next to the enemy king, // or covered by an enemy piece that hasn't run its own eval pass // yet, still looks safe and gets counted. More attack information // can only mark MORE squares unsafe later, never fewer -- so this // count can only ever be too high, never too low. // // That asymmetry is exactly why a genuinely 0-mobility bishop is // scored and recorded immediately rather than deferred: 0 is // already the floor, so a fuller attack picture later can't change // it (0 minus more unsafe squares is still 0) -- there is nothing // to gain by waiting. A LOW but nonzero count, however, could // easily still be an overcount (the classic case that motivated // this: a pawn push that cuts off the bishop's retreat leaves two // "safe" squares right next to the enemy king that are only safe // because the king's own attacks aren't in the table yet) -- defer // those to _EvalTrappedPieces, which re-derives the true count once // both kings and every piece type have contributed to the attack // tables, instead of locking in a score that a fuller picture might // revise downward. // if (uTotalMobility < EVAL_MOBILITY_CAREFULLY_BELOW) { if (uTotalMobility == 0) { EVAL_TERM(uColor, BISHOP, c, pos->iScore[uColor], BISHOP_MOBILITY_BY_SQUARES[0], "bishop mobility"); } _RecordTrappedCandidate(pos, uColor, c, bbMobility); } else // reasonable mobility { EVAL_TERM(uColor, BISHOP, c, pos->iScore[uColor], BISHOP_MOBILITY_BY_SQUARES[uTotalMobility], "bishop mobility"); } // // Bonus for a bishop that's securely placed -- safe from ever // being challenged by an enemy pawn, and (checked below) defended // by a friendly one -- near the enemy king. This is a // bishop-specific king-tropism/outpost bonus. // bb = pos->bbPawns[xColor] & (~pHash->bbStationaryPawns[xColor]); if (TRUE == _IsSquareSafeFromEnemyPawn(pos, c, bb)) { // Defended (and defending) a friendly pawn. if (pos->bbPawnAttacks[uColor] & COOR_TO_BB(c)) { #ifdef DEBUG p = BLACK_PAWN | uColor; ASSERT(((IS_ON_BOARD(c + 17 * g_iBehind[uColor]) && (pos->rgSquare[c + 17 * g_iBehind[uColor]].pPiece==p)) || ((IS_ON_BOARD(c + 15 * g_iBehind[uColor])) && (pos->rgSquare[c + 15 * g_iBehind[uColor]].pPiece==p)))); #endif u = DISTANCE(c, KingPosition(pos, xColor)); i = BISHOP_UNASSAILABLE_BY_DIST_FROM_EKING[u]; EVAL_TERM(uColor, BISHOP, c, pos->iReducedMaterialDownScaler[uColor], i, "[scaled] unassailable"); } } } static void _EvalKnight(IN OUT POSITION *pos, IN COOR c, IN PAWN_HASH_ENTRY *pHash) /** Routine description: Parameters: POSITION *pos, COOR c, PAWN_HASH_ENTRY *pHash, Return value: FLAG **/ { static const int iPawnStart[2] = { -17, +15 }; static const COOR cKnightAtHome[2][2] = { { B8, G8 }, // BLACK { B1, G1 } // WHITE }; PIECE p; COOR cSquare; BITBOARD bb; ULONG uColor; ULONG xColor; ULONG uPawnsSupporting; ULONG uMobilitySquares; BITBOARD bbMobility; SCORE i; ULONG uDist; p = pos->rgSquare[c].pPiece; ASSERT(p && IS_KNIGHT(p)); uColor = GET_COLOR(p); ASSERT(IS_VALID_COLOR(uColor)); xColor = FLIP(uColor); // Unmoved piece; potentially penalized in EvalKing. pos->uMinorsAtHome[uColor] += (c == cKnightAtHome[uColor][0]); pos->uMinorsAtHome[uColor] += (c == cKnightAtHome[uColor][1]); ASSERT(pos->uMinorsAtHome[uColor] <= 4); // Centrality bonus EVAL_TERM(uColor, KNIGHT, c, pos->iScore[uColor], KNIGHT_CENTRALITY_BONUS[c], "board centrality"); // Give a bonus to knights on a closed / busy board. ASSERT(pHash->uClosedScaler <= 32); EVAL_TERM(uColor, KNIGHT, c, pos->iScore[uColor], KNIGHT_IN_CLOSED_POSITION[pHash->uClosedScaler], "in closed/open position"); // Outposted knights. See if square c is safe from enemy pawns; // if so give bonus for outposted knight which increases the // closer it is to the enemy king and the more pawns it has // supporting it. uDist = DISTANCE(c, KingPosition(pos, xColor)); ASSERT((uDist > 0) && (uDist <= 8)); bb = pos->bbPawns[xColor] & (~pHash->bbStationaryPawns[xColor]); if (TRUE == _IsSquareSafeFromEnemyPawn(pos, c, bb)) { // Count the number of supporting pawns the knight has uPawnsSupporting = 0; p = BLACK_PAWN | uColor; cSquare = c + iPawnStart[uColor]; uPawnsSupporting = (IS_ON_BOARD(cSquare) && (pos->rgSquare[cSquare].pPiece == p)); cSquare += 2; uPawnsSupporting += (IS_ON_BOARD(cSquare) && (pos->rgSquare[cSquare].pPiece == p)); ASSERT(uPawnsSupporting <= 2); // Give a bonus based on distance from enemy king i = KNIGHT_UNASSAILABLE_BY_DIST_FROM_EKING[uDist] + KNIGHT_WITH_N_PAWNS_SUPPORTING[uPawnsSupporting]; EVAL_TERM(uColor, KNIGHT, c, pos->iReducedMaterialDownScaler[uColor], i, "[scaled] unassailable/support"); // Now, if there's zero or one supporter see if the enemy has a // bishop the color of the knight it could capture with. if (uPawnsSupporting != 2) { if (IS_SQUARE_WHITE(c)) { if (WhiteSqBishopCount(pos, xColor)) { EVAL_TERM(uColor, KNIGHT, c, pos->iScore[uColor], -(i / 2), "not safe from enemy B"); } } else { if (FastCountBits(pos->bbPieces[xColor][BISHOP]) - WhiteSqBishopCount(pos, xColor)) { EVAL_TERM(uColor, KNIGHT, c, pos->iScore[uColor], -(i / 2), "not safe from enemy B"); } } } } else // not outposted { // Still good to be close to the enemy king. i = KNIGHT_KING_TROPISM_BONUS[uDist]; EVAL_TERM(uColor, KNIGHT, c, pos->iReducedMaterialDownScaler[uColor], i, "[scaled] enemy king tropism"); } // Give a bonus for blockading an enemy backward pawn. cSquare = c + 16 * g_iAhead[uColor]; bb = pHash->bbStationaryPawns[xColor]; if (bb & COOR_TO_BB(cSquare)) { ASSERT(pos->rgSquare[cSquare].pPiece); ASSERT(IS_PAWN(pos->rgSquare[cSquare].pPiece)); EVAL_TERM(uColor, KNIGHT, c, pos->iScore[uColor], KNIGHT_ON_INTERESTING_SQUARE_BY_RANK[uColor][RANK(c)], "blockades enemy pawn"); } // // Removed 2026-08-30 ("A knight with an open file behind it is // good"): dubious chess reasoning on its own (open-file bonuses // are classically a rook concept -- knights don't use files the // way rooks do) compounded by reusing KNIGHT_ON_INTERESTING_SQUARE // _BY_RANK, the *same* table as the backward-pawn-blockade bonus // just above, for a completely unrelated condition. That reuse // muddied what the table means and made it untunable // independently for either concept. // // // Do mobility and piece relevance. Also update attack tables. // // board_representation/EVAL.md section 1b/2: g_KnightAttacksBB[c] // (generate.c's precomputed table, already used by move // generation) is exactly the old per-square g_iNDeltas walk's // destination set, IS_ON_BOARD baked in at table-build time -- no // per-square branch, no mailbox read, no switch. Knights never // x-ray or have a battery partner, so the old NMobCaseTable's four // cases collapse to two bitboard masks: NMOB_ENEMY_OTHER (any // enemy non-pawn -- count unconditionally) and NMOB_MOBILE_SQUARE // (empty or enemy pawn -- count unless pawn-unsafe). NMOB_FRIEND // needs no term at all, it's just "neither of the above." // { BITBOARD bbAttack = g_KnightAttacksBB[c]; BITBOARD bbFriendOcc = _BuildFriendlySideBB(pos, uColor); BITBOARD bbEnemyNonPawnOcc = _BuildFriendlySideBB(pos, xColor) & ~pos->bbPawns[xColor]; BITBOARD bbUnsafeForMinor = pos->bbPawnAttacks[xColor]; pos->bbMinorAttacks[uColor] |= bbAttack; bbMobility = (bbAttack & bbEnemyNonPawnOcc) | (bbAttack & ~bbFriendOcc & ~bbEnemyNonPawnOcc & ~bbUnsafeForMinor); uMobilitySquares = FastCountBits(bbMobility); } ASSERT(uMobilitySquares >= 0); ASSERT(uMobilitySquares <= 8); // See _EvalBishop's comment above its own identically-structured // mobility scoring for why 0-mobility is scored immediately while // a low-but-nonzero count is deferred to _EvalTrappedPieces instead. if (uMobilitySquares < EVAL_MOBILITY_CAREFULLY_BELOW) { if (uMobilitySquares == 0) { EVAL_TERM(uColor, KNIGHT, c, pos->iScore[uColor], KNIGHT_MOBILITY_BY_COUNT[0], "knight mobility"); } _RecordTrappedCandidate(pos, uColor, c, bbMobility); } else // reasonable mobility { EVAL_TERM(uColor, KNIGHT, c, pos->iScore[uColor], KNIGHT_MOBILITY_BY_COUNT[uMobilitySquares], "knight mobility"); } } static void _EvalRook(IN OUT POSITION *pos, IN COOR c, IN PAWN_HASH_ENTRY *pHash, IN BITBOARD bbEnemyQK, IN BITBOARD bbUnsafeForRook) /** Routine description: Parameters: IN POSITION *pos, IN COOR c, IN PAWN_HASH_ENTRY *pHash, IN BITBOARD bbEnemyQK -- enemy queen|king, precomputed once per color by Eval()'s driver (see MOBILITY_BITBOARD_REWRITE.md) -- depends only on static piece locations. IN BITBOARD bbUnsafeForRook -- enemy pawn|minor attacks, precomputed once per color right before the rook loops start, valid because both colors' knight+bishop passes are already complete by then. Return value: FLAG **/ { PIECE p; ULONG uColor; ULONG uTotalMobility; BITBOARD bbMobility; SCORE i; ASSERT(IS_ON_BOARD(c)); p = pos->rgSquare[c].pPiece; ASSERT(p && IS_ROOK(p)); uColor = GET_COLOR(p); ASSERT(IS_VALID_COLOR(uColor)); ULONG xColor = FLIP(uColor); ASSERT(IS_VALID_COLOR(xColor)); BITBOARD bbFile = BBFILE[FILE(c)]; BITBOARD bbFriendPawns = pos->bbPawns[uColor] & bbFile; BITBOARD bbEnemyPawns = pos->bbPawns[xColor] & bbFile; SCORE bonus = ROOK_FULL_HALF_OPEN_BONUS[bbFriendPawns != 0][bbEnemyPawns != 0]; bonus += (SCORE)((bbEnemyPawns & pHash->bbPasserLocations[xColor]) != 0) * ROOK_WITH_ENEMY_PASSER; bonus += (SCORE)((bbFriendPawns & pHash->bbPasserLocations[uColor]) != 0) * ROOK_WITH_FRIEND_PASSER; bonus += (SCORE)((COOR_TO_BB(c) & BBROOK_7TH_RANK[uColor]) != 0) * ROOK_ON_SEVENTH_BONUS; EVAL_TERM(uColor, ROOK, c, pos->iScore[uColor], bonus, "file/passer bonus"); // // Rooks increase in value as pawns come off: // // "A further refinement would be to raise the knight's value by // 1/16 and lower the rook's value by 1/8 for each pawn above five // of the side being valued, with the opposite adjustment for each // pawn short of five." // --Larry Kaufman, IM // "Evaluation of Material Imbalance" // EVAL_TERM(uColor, ROOK, c, pos->iScore[uColor], ROOK_VALUE_AS_PAWNS_COME_OFF[pHash->uTotalPawnCount], "increase in value/pawns"); ASSERT(pHash->uTotalPawnCount == (FastCountBits(pos->bbPawns[uColor]) + FastCountBits(pos->bbPawns[xColor]))); // // Rook mobility (and update attack tables) -- single magic-bitboard // probe, no chain walk (see MOBILITY_BITBOARD_REWRITE.md). The old // RMobCaseTable's six cases collapse to mask arithmetic over the // one-shot first-blocker attack set: // - terminal enemy rook/queen/king: counts unconditionally -- a // capture is always "real" mobility regardless of value. // - empty or terminal enemy pawn/knight/bishop: counts unless the // square is attacked by an enemy pawn or minor -- both // terminal-square categories together are exactly "not // friend-occupied and not enemy-rook/queen/king-occupied," the // same partition bishop/knight's reductions use. // - any friendly piece: blocks, no count. A friendly rook // specifically also earns the connected-rook bonus (direct // attack only now, not chained through a further blocker). // // Deliberately NOT replicated: mobility/connectivity credit for // squares beyond a friendly rook/queen or enemy queen/king -- a // rook cannot physically move past a piece it would capture in one // ply, so that was never "real mobility" to begin with (dropping it // is a correctness fix, not just a simplification). See // MOBILITY_BITBOARD_REWRITE.md for the king-ring x-ray replacement, // which is the one piece of information this loses that's worth // deliberately replacing below. // BITBOARD bbAttack = _RookAttacksBB(c, pos->bbOccupied); BITBOARD bbEnemyOcc = _BuildFriendlySideBB(pos, xColor); BITBOARD bbEnemySame = pos->bbPieces[xColor][ROOK]; BITBOARD bbEnemyGEHere = bbAttack & bbEnemyQK; BITBOARD bbEnemyLEHere = bbAttack & bbEnemyOcc & ~bbEnemySame & ~bbEnemyGEHere; BITBOARD bbFriendRookHere = bbAttack & pos->bbPieces[uColor][ROOK]; BITBOARD bbXray; pos->bbRookAttacks[uColor] |= bbAttack; bbMobility = (bbAttack & ~pos->bbOccupied & ~bbUnsafeForRook) | (bbAttack & bbEnemySame) | bbEnemyGEHere | (bbEnemyLEHere & ~bbUnsafeForRook); // Connected-rook bonus -- direct attack only now; see the comment // above. while (bbFriendRookHere) { COOR cBlocker = CoorFromBitBoardRank8ToRank1(&bbFriendRookHere); FLAG fHoriz = (RANK(cBlocker) == RANK(c)); EVAL_TERM(uColor, ROOK, cBlocker, pos->iScore[uColor], (ROOK_CONNECTED_HORIZ * fHoriz + ROOK_CONNECTED_VERT * FLIP(fHoriz)), "rooks connected"); } // // King-ring x-ray, replacing the old chain's attack-bit population: // only pay for an extra magic probe when this rook already directly // attacks the enemy queen or king square (bbEnemyGEHere, already // computed above for mobility -- free to test). bbEnemyGEHere has // at most two bits (queen, king), each the terminal blocker of a // *different* ray -- masking both off at once and re-probing in a // single magic lookup gives the same union a per-blocker loop would // (one ray's blocker removal can't affect the other ray's result). // No deeper chaining needed either way, since the only consumer // (_EvalKingSafety) only ever ANDs this against the king's ring, // never walks further. // bbXray = bbEnemyGEHere ? _RookAttacksBB(c, pos->bbOccupied & ~bbEnemyGEHere) : 0; pos->bbRookXrayAttacks[uColor] |= bbXray; // Pseudo-mobility bonus for squares seen past the queen/king blocker // -- see ROOK_XRAY_MOBILITY_BY_SQUARES's comment, same reasoning as // bishop's identical term. EVAL_TERM(uColor, ROOK, c, pos->iScore[uColor], ROOK_XRAY_MOBILITY_BY_SQUARES[ MINU(FastCountBits(bbXray & ~bbAttack), 8)], "xray pseudo-mobility"); uTotalMobility = FastCountBits(bbMobility); ASSERT(uTotalMobility <= 14); ASSERT(pos->uArmyScaler[xColor] <= 31); // Same partial-information reasoning, and same immediate-0/deferred- // low-nonzero split, as _EvalBishop's identically-structured // mobility scoring (see its comment) -- bbUnsafeForRook above only // knows about enemy pawn/minor attacks, not the enemy king's or (for // a rook specifically) a not-yet-evaluated enemy queen's, so a low // nonzero count here is still liable to be an overcount. if (uTotalMobility < EVAL_MOBILITY_CAREFULLY_BELOW) { _RecordTrappedCandidate(pos, uColor, c, bbMobility); } i = ROOK_MOBILITY_BY_SQUARES[uTotalMobility]; i *= (int)(REDUCED_MATERIAL_UP_SCALER[pos->uArmyScaler[xColor]] + 1); i /= 8; EVAL_TERM(uColor, ROOK, c, pos->iScore[uColor], i, "rook mobility"); } static void _EvalQueen(IN OUT POSITION *pos, IN COOR c, IN PAWN_HASH_ENTRY *pHash, IN BITBOARD bbEnemyQK, IN BITBOARD bbUnsafeForQueen) /** Parameters: POSITION *pos, COOR c, PAWN_HASH_ENTRY *pHash, BITBOARD bbEnemyQK -- enemy queen|king, precomputed once per color by Eval()'s driver -- identical formula to _EvalRook's bbEnemyQK, so the same precomputed value is reused for both (see MOBILITY_BITBOARD_REWRITE.md). BITBOARD bbUnsafeForQueen -- precomputed once per color right before the queen loops start, valid because both colors' pawn/minor/rook passes are already complete by then. Return value: FLAG **/ { PIECE p = pos->rgSquare[c].pPiece; ULONG uColor; ULONG xColor; ULONG uTotalMobility; ASSERT(IS_ON_BOARD(c)); ASSERT(p && IS_QUEEN(p)); uColor = GET_COLOR(p); ASSERT(IS_VALID_COLOR(uColor)); xColor = FLIP(uColor); ASSERT(IS_ON_BOARD(KingPosition(pos, xColor))); ASSERT(IS_KING(pos->rgSquare[KingPosition(pos, xColor)].pPiece)); // // Queen mobility (and update attack tables) -- two single magic // probes (rook-direction + bishop-direction), unioned, then one // shared mask pass. No chain walk (see MOBILITY_BITBOARD_REWRITE.md): // - terminal enemy queen/king: counts unconditionally -- a capture // is always "real" mobility. // - empty or terminal enemy pawn/minor/rook: counts unless the // square is attacked by an enemy pawn, minor, rook, or (modulo // our own defense) the enemy king -- same partition // bishop/knight/rook's reductions use, just with a bigger // "cheaper piece" set since the queen is the most valuable. // - any friendly piece: blocks, no count. // // Deliberately NOT replicated: mobility credit for squares beyond a // friendly rook/bishop/queen battery partner -- a queen cannot // physically move past a piece it shares a square with in one ply, // so (same as bishop/rook) that was never "real mobility" to begin // with. Also NOT replicated, and needing no replacement: the old // code's x-ray-attack population. Unlike bishop/rook, queen's old // chain only ever continued through a FRIENDLY blocker (it never // x-rayed through any enemy piece at all -- QMOB_ENEMY_GE always // stopped the ray in the original mailbox table). By the same // redundancy argument used to drop bishop/rook's friendly-blocker // x-ray case, that information was always a duplicate of the // blocking piece's own direct-attack pass -- there's no enemy-GE // case here to replace, so _EvalKingSafety's queen-x-ray reads // (pos->bbQueenXrayAttacks[xColor]) see nothing lost by simply never // populating it. // BITBOARD bbEnemyOcc = _BuildFriendlySideBB(pos, xColor); BITBOARD bbAttackTotal = _RookAttacksBB(c, pos->bbOccupied) | _BishopAttacksBB(c, pos->bbOccupied); BITBOARD bbEnemyGEHere = bbAttackTotal & bbEnemyQK; BITBOARD bbEnemyLEHere = bbAttackTotal & bbEnemyOcc & ~bbEnemyGEHere; BITBOARD bbMobility = (bbAttackTotal & ~pos->bbOccupied & ~bbUnsafeForQueen) | bbEnemyGEHere | (bbEnemyLEHere & ~bbUnsafeForQueen); pos->bbQueenAttacks[uColor] |= bbAttackTotal; uTotalMobility = FastCountBits(bbMobility); ASSERT(uTotalMobility <= 27); EVAL_TERM(uColor, QUEEN, c, pos->iScore[uColor], QUEEN_MOBILITY_BY_SQUARES[uTotalMobility], "queen mobility"); // Look for queens with no mobility who are under attack. These // pieces are trapped! if (uTotalMobility == 0) { _RecordTrappedCandidate(pos, uColor, c, 0); } } static SCORE FORCEINLINE _EvalKingSafety(IN POSITION *pos, IN const COOR c, IN const PAWN_HASH_ENTRY *pHash, IN SEARCHER_THREAD_CONTEXT *ctx, IN const ULONG uColor, IN const ULONG xColor, IN const BITBOARD bbRing) /** Routine description: Safety half of _EvalKing's 2026-10-06 safety-vs-activity split -- see that function's header comment. Full ring-attack/danger- pattern scoring, file-storm defects (cached), stay-on-initial- square bonus, castling/development. Only called when the enemy has enough material (DO_KING_SAFETY_THRESHOLD) to make an attack worth scoring. FORCEINLINE: this and _EvalKingActivity are split out of _EvalKing purely for readability -- _EvalKing calls exactly one of the two per invocation (never both), so forcing both inline reproduces the exact same generated code as the old single monolithic function, not a real call. Parameters: POSITION *pos, COOR c, PAWN_HASH_ENTRY *pHash, SEARCHER_THREAD_CONTEXT *ctx, ULONG uColor, ULONG xColor, BITBOARD bbRing : g_KingAttacksBB[c], already computed by the caller Return value: SCORE **/ { BITV bvPattern; ULONG uQueenNearKing; SCORE iKingScore = 0; // 2026-09-15: linear-SCORE rewrite -- see king_safety_data/ // HANDOFF.md's 2026-09-15 addendum for the full rationale. Replaces // the old shared uCounter -> KING_SAFETY_BY_COUNTER nonlinear-lookup // mechanism (EmptyAttackedSquare/EmptyUnattackedSquare/ // OccupiedAttackedSquare/KingFlightDefects/KingSafetyDeltas/ // KING_RING_IS_BACK all retired) with per-defect SCORE weights that // accumulate into one running total and get scaled by // REDUCED_MATERIAL_DOWN_SCALER exactly ONCE at the end -- by direct // instruction, since this is the hottest inner loop in eval.c and // scaler*(A+B+C+...) is one multiply instead of scaler*A + scaler*B // + ... Ring-square attack/defense/flight terms below are computed // via bitboard intersection + FastCountBits() against the whole front/ // back/side bucket at once (g_KingRingFrontBB/g_KingRingBackBB/ // g_KingRingSideBB, data.c), not a per-square branchy loop -- a // fixed handful of AND+popcount ops regardless of how many ring // squares are actually occupied/attacked. // // Magnitudes are the mate-mining logistic regression's cleaned, // collinearity-reduced coefficients (front_def/back_def/*_atk_queen // dropped -- collinear with the atk_* terms and queenproximity // respectively), unstandardized (divided by each raw feature's own // std-dev) and converted to centipawns via k =~ -14, the same // conversion constant KING_QUEEN_PROXIMITY_DANGER's self-play- // validated -14/count already established (anchor: validated weight // / that term's own cleaned raw coefficient). None of the NEW // per-piece-type/undefended/xray/flight terms below have been // through self-play yet as of this writing -- expect every one of // these starting magnitudes to move once tested, same discipline as // the file-storm and queenproximity retunes before them. // // 2026-09-15 (later): promoted from local statics to file scope // and DNA-registered (see g_EvalDNA below) so they can be Texel- // tuned directly against real game outcomes instead of hand- // translated from regression coefficients -- see king_safety_data/ // HANDOFF.md's addendum on why the log-odds-to-centipawn // translation step was the likely source of this rewrite's // self-play regression, not the underlying feature signal itself. const ULONG uKingDangerAcceleratorBucketWidth = 56; // Depending on whether we are assessing a black or white king, // the "front" and "back" directions swap. Front is "towards // the center of the board at game start time". BITBOARD bbFront = g_KingRingFrontBB[uColor][c]; BITBOARD bbBack = g_KingRingBackBB[uColor][c]; BITBOARD bbSide = g_KingRingSideBB[c]; ASSERT(bbRing == (bbFront | bbBack | bbSide)); BITBOARD bbEnemyAtkAny = pos->bbPawnAttacks[xColor] | pos->bbMinorAttacks[xColor] | pos->bbRookAttacks[xColor] | pos->bbQueenAttacks[xColor]; BITBOARD bbEnemyXrayAny = pos->bbMinorXrayAttacks[xColor] | pos->bbRookXrayAttacks[xColor] | pos->bbQueenXrayAttacks[xColor]; BITBOARD bbOwnDefendNoKing = pos->bbPawnAttacks[uColor] | pos->bbMinorAttacks[uColor] | pos->bbRookAttacks[uColor] | pos->bbQueenAttacks[uColor]; BITBOARD bbEmpty = ~pos->bbOccupied; BITBOARD bbUndefended = bbEnemyAtkAny & ~bbOwnDefendNoKing; SCORE iSafety = 0; // Pay attention to the types of pieces currently attacking. bvPattern = (((pos->bbPawnAttacks[xColor] & bbRing) != 0) ? PAWN_BIT : 0) | ((((pos->bbMinorAttacks[xColor] | pos->bbMinorXrayAttacks[xColor]) & bbRing) != 0) ? MINOR_BIT : 0) | ((((pos->bbRookAttacks[xColor] | pos->bbRookXrayAttacks[xColor]) & bbRing) != 0) ? ROOK_BIT : 0) | ((((pos->bbQueenAttacks[xColor] | pos->bbQueenXrayAttacks[xColor]) & bbRing) != 0) ? QUEEN_BIT : 0); ASSERT(bvPattern < 32); iSafety += KING_ATTACK_PATTERN_SCALE * (SCORE)KING_COUNTER_BY_ATTACK_PATTERN[bvPattern]; // Count how many ring squares are attacked by the enemy queen. // Note: we remove queen-king tropism bonus from EvalQueen in // favor of this. uQueenNearKing = FastCountBits( bbRing & (pos->bbQueenAttacks[xColor] | pos->bbQueenXrayAttacks[xColor]) ); ASSERT(uQueenNearKing <= 8); iSafety += KING_QUEEN_PROXIMITY_DANGER[MINU(uQueenNearKing, 6)]; // Minor attacks at front, side, back. iSafety += KING_RING_ATTACK_MINOR[0] * (SCORE)FastCountBits(bbFront & pos->bbMinorAttacks[xColor]); iSafety += KING_RING_ATTACK_MINOR[1] * (SCORE)FastCountBits(bbBack & pos->bbMinorAttacks[xColor]); iSafety += KING_RING_ATTACK_MINOR[2] * (SCORE)FastCountBits(bbSide & pos->bbMinorAttacks[xColor]); // Rook attacks at front, side, back. iSafety += KING_RING_ATTACK_ROOK[0] * (SCORE)FastCountBits(bbFront & pos->bbRookAttacks[xColor]); iSafety += KING_RING_ATTACK_ROOK[1] * (SCORE)FastCountBits(bbBack & pos->bbRookAttacks[xColor]); iSafety += KING_RING_ATTACK_ROOK[2] * (SCORE)FastCountBits(bbSide & pos->bbRookAttacks[xColor]); // Pawn attacks. iSafety += KING_RING_ATTACK_PAWN * (SCORE)FastCountBits(bbRing & pos->bbPawnAttacks[xColor]); // Undefended squares in front, side, back. iSafety += KING_RING_UNDEFENDED[0] * (SCORE)FastCountBits(bbFront & bbUndefended); iSafety += KING_RING_UNDEFENDED[1] * (SCORE)FastCountBits(bbBack & bbUndefended); iSafety += KING_RING_UNDEFENDED[2] * (SCORE)FastCountBits(bbSide & bbUndefended); // Only xray attack, no direct attack. iSafety += KING_RING_XRAY_BONUS * (SCORE)FastCountBits(bbRing & bbEnemyXrayAny & ~bbEnemyAtkAny); // Flight squares are empty, unattacked squares around the king. // In front of the king, though, these are gaps and a negative // whereas behind the king they are legitimately small bonuses. iSafety += KING_RING_FRONT_FLIGHT_PENALTY * (SCORE)FastCountBits(bbFront & bbEmpty & ~bbEnemyAtkAny); // Small bonus for empty squares behind the king to retreat into. iSafety += KING_BACK_FLIGHT_BONUS * (SCORE)FastCountBits(bbBack & bbEmpty & ~bbEnemyAtkAny); // _ComputeFileStormDefects's comment. iSafety += _GetFileStormDefects(ctx, pos, pHash, uColor); iSafety += KING_INITIAL_LOCATION_SCALE * KING_EVAL_INITIAL_LOCATION[uColor][c]; // Danger-magnitude acceleration -- see KING_DANGER_ACCELERATOR's // comment above. Applied here (as part of the real per-king // computation) rather than folded into the final material-scale // multiply below, since it's a function of the aggregate danger // itself, not of the attacker's material. if (iSafety < 0) { ULONG uMagBucket = MINU(6, (ULONG)(-iSafety) / uKingDangerAcceleratorBucketWidth); iSafety = (iSafety * KING_DANGER_ACCELERATOR[uMagBucket]) / 128; } #ifdef CALIBRATE_POSITIONAL // Restored 2026-09-15 (was dropped when the old uCounter/ // KING_SAFETY_BY_COUNTER-shaped call site disappeared in the // linear-SCORE rewrite) -- see _RecordPositionalCalibration's // comment for why this now bins ABS(iSafety) instead of the old // always-nonnegative -i. _RecordPositionalCalibration(ctx, pos, pHash, uColor, (ULONG)((iSafety < 0) ? -iSafety : iSafety)); #endif // Single multiply for the entire accumulated total -- the // whole point of this rewrite (see the function-header comment // above). Note: can't use pos->iReducedMaterialDownScaler here // because we are scaling based on the _other_ side's material. iSafety = (iSafety * (SCORE)REDUCED_MATERIAL_DOWN_SCALER[pos->uArmyScaler[xColor]]) / 8; EVAL_TERM(uColor, KING, c, iKingScore, iSafety, "king safety"); // Bonus for castling / penalty for loss of castle. Also, if // side has not yet castled AND castling is still a live // option, be concerned with undeveloped minor pieces. // // 2026-10-06: split the development penalty's gate from the // missing-castle-option penalty's -- they need different // conditions. Development should stop once the castling // decision is permanently settled, whether that's by // castling (the outer !fCastled check) or by losing both // rights without ever castling (not caught by that check // alone -- a side that never castles and never loses the // right would otherwise be flagged "undeveloped" forever). // The missing-castle-option penalty must do the opposite -- // persist *after* a right is lost, not stop then -- since // its whole purpose is discouraging throwing the right away // in the first place; gating it the same way development is // gated would silently disable it exactly when it's supposed // to fire. // // Color-indexed instead of a WHITE/BLACK branch over two // copy-pasted blocks -- one fewer per-piece branch for the // processor to mispredict (board_representation/EVAL.md // section 9). ULONG uDevelopmentScaler = CASTLE_AND_DEVELOPMENT_SCALER[pos->uArmyScaler[uColor]]; if (uDevelopmentScaler > 0) { static const BITV CASTLE_SHORT[2] = { CASTLE_BLACK_SHORT, CASTLE_WHITE_SHORT }; static const BITV CASTLE_LONG[2] = { CASTLE_BLACK_LONG, CASTLE_WHITE_LONG }; static const BITV bvBothRights[2] = { CASTLE_SHORT[BLACK] | CASTLE_LONG[BLACK], CASTLE_SHORT[WHITE] | CASTLE_LONG[WHITE] }; ASSERT(pos->uMinorsAtHome[uColor] <= 4); EVAL_TERM(uColor, 0, ILLEGAL_COOR, pos->iScore[uColor], (SCORE)((UNDEVELOPED_MINORS_IN_OPENING[pos->uMinorsAtHome[uColor]] * (SCORE)uDevelopmentScaler) / 8), "development"); // One popcount answers both "can this side still // castle at all" (>0, gates development below) and // "how many options are missing" (2-count, scales // the persistent penalty below) -- replaces two // separate (==0) branches/multiplies/EVAL_TERM calls // with one shared count. ULONG uRightsRemaining = FastCountBits(pos->bvCastleInfo & bvBothRights[uColor]); ASSERT(uRightsRemaining <= 2); // Deliberately NOT gated on uRightsRemaining > 0 -- // see this block's header comment. Fires at full // weight (both options gone) even long after the // rights were lost, for as long as uDevelopmentScaler // itself stays nonzero. EVAL_TERM(uColor, KING, c, iKingScore, (SCORE)( (FALSE == pos->fCastled[uColor]) * (KING_MISSING_ONE_CASTLE_OPTION * (SCORE)(2 - uRightsRemaining) * (SCORE)uDevelopmentScaler) / 8), "missing castle option(s)"); } return iKingScore; } static SCORE FORCEINLINE _EvalKingActivity(IN POSITION *pos, IN const COOR c, IN const PAWN_HASH_ENTRY *pHash, IN SEARCHER_THREAD_CONTEXT *ctx, IN const ULONG uColor, IN const ULONG xColor) /** Routine description: Activity half of _EvalKing's 2026-10-06 safety-vs-activity split -- see that function's header comment. KING_TO_CENTER unconditionally; once the enemy is down to at most one non-king piece, the sharper passer-support/in-the-action guidance too. Only called when the enemy lacks mating material (below DO_KING_SAFETY_THRESHOLD). FORCEINLINE -- see _EvalKingSafety's comment for why this costs nothing over the old monolithic function. Parameters: POSITION *pos, COOR c, PAWN_HASH_ENTRY *pHash, SEARCHER_THREAD_CONTEXT *ctx, ULONG uColor, ULONG xColor Return value: SCORE **/ { SCORE i; SCORE iKingScore = 0; // // Come out. KING_TO_CENTER applies unconditionally (no longer // gated by uTotalNonPawnsBothSides<8 -- that was a different, // combined-both-sides unit than this whole split now uses, and // left a gap between "safety stops mattering" and "centralizing // is actually encouraged"; see _EvalKing's header comment). // i = KING_TO_CENTER[c]; EVAL_TERM(uColor, KING, c, iKingScore, i, "centralize king"); // Sharper late-game guidance once the enemy is down to at most // one non-king piece (lone king, K+minor, K+rook, even K+queen // -- though a lone queen's own material value already exceeds // DO_KING_SAFETY_THRESHOLD on its own, VALUE_QUEEN=975 > // VALUE_ROOK+VALUE_BISHOP=800, so that specific case can never // actually reach this function at all; the count check below is // correct on its own terms regardless). Per-call/per-king // (xColor's own material), not the old combined-both-sides // uTotalNonPawnsBothSides==2 -- the two kings' own enemies can // legitimately disagree now. if (TotalNonPawnCount(pos, xColor) <= 2) { // Supporting-own-passer and out-of-action-in-KP-endgames, // combined into one cached lookup (_GetKingActivityBonus) // -- both depend only on (pawn structure + this king's own // square), both only ever apply in this same branch, so // one key computation/hash probe serves both instead of // two. Trades away per-passer-square EVAL_TERM attribution // (EVAL_DUMP tracing only, not used in release builds) for // fewer instructions in the inner loop, by direct request // -- see git history for the old separated version if // finer dump granularity is ever needed again. i = _GetKingActivityBonus(ctx, pos, pHash, uColor, c); EVAL_TERM(uColor, KING, c, iKingScore, i, "king activity (passer support + in/out of action)"); } return iKingScore; } static void _EvalKing(IN OUT POSITION *pos, IN const COOR c, IN const PAWN_HASH_ENTRY *pHash, IN SEARCHER_THREAD_CONTEXT *ctx) /** Routine description: 2026-10-06: restructured into an explicit safety-vs-activity split on pos->uNonPawnMaterial[xColor] (this king's own enemy's material) against DO_KING_SAFETY_THRESHOLD -- above it, stay hidden (_EvalKingSafety: full ring-attack/danger scoring, stay- on-initial-square bonus); below it, come out (_EvalKingActivity: KING_TO_CENTER unconditionally, plus, once the enemy is down to at most one non-king piece, the sharper passer-support/in-the- action guidance). Replaces the old `goto skip_safety` plus two *separate*, independently-thresholded gates (KEEP_KING_AT_HOME_ THRESHOLD for the stay-home bonus, uTotalNonPawnsBothSides<8/==2 -- a different, combined-both-sides unit -- for the endgame terms) that didn't line up with each other or with this one, leaving a dead band where safety was scored but neither a stay- home nor a come-out incentive applied. This single threshold now drives both halves, so the two outcomes are exact mirror images of one decision rather than three loosely related ones. Split into two FORCEINLINE helpers purely for readability -- see _EvalKingSafety's comment for why this costs nothing versus the old single monolithic function. No longer takes uTotalNonPawnsBothSides -- the old combined-both- sides gate it fed is gone, replaced by a per-call check (TotalNonPawnCount(pos, xColor), this king's own enemy only, not a hoisted both-sides sum), so there's no shared value left worth hoisting out to Eval(). Parameters: POSITION *pos, COOR c, PAWN_HASH_ENTRY *pHash, SEARCHER_THREAD_CONTEXT *ctx Return value: FLAG **/ { PIECE p; ULONG uColor, xColor; ULONG u; SCORE iKingScore; ASSERT(IS_ON_BOARD(c)); p = pos->rgSquare[c].pPiece; ASSERT(p && IS_KING(p)); uColor = GET_COLOR(p); xColor = FLIP(uColor); ASSERT(IS_VALID_COLOR(uColor) && IS_VALID_COLOR(xColor)); // Update attack bitvs for squares around the king. BITBOARD bbRing = g_KingAttacksBB[c]; pos->bbKingAttacks[uColor] |= bbRing; // Safety-vs-activity split -- see this function's header comment // (2026-10-06 restructuring). Don't bother with king safety when // the other side has low material; instead, actively encourage // this king out. u = pos->uNonPawnMaterial[xColor]; ASSERT(u >= VALUE_KING); if (u > DO_KING_SAFETY_THRESHOLD) { iKingScore = _EvalKingSafety(pos, c, pHash, ctx, uColor, xColor, bbRing); } else { iKingScore = _EvalKingActivity(pos, c, pHash, ctx, uColor, xColor); } pos->iScore[uColor] += iKingScore; ctx->sPlyInfo[ctx->uPly].iKingScore[uColor] = iKingScore; } static FLAG _EvalUnstoppablePasser(IN OUT POSITION *pos) /** Routine description: True-knowledge replacement for _EvalPasserRacesAgainstLoneKings (below), used ONLY when both sides are pure king-and-pawns (both TotalNonPawnCount == 1) -- the exact KPvKP shape this session's investigation exhaustively verified. Calls the SAME shared, exhaustively-verified routines recogn.c's hard-bound KPvKP recognizer uses (IsUnstoppableLoneKingPasser for a true-lone-king opponent's any-rank square-rule race, HasStaticUnstoppablePasser for the general "opponent also has pawns" 7th/2nd-rank case), so there is exactly one implementation of "is this pawn unstoppable," not two that can silently diverge the way this file's old passer-race heuristic and recogn.c's KPK recognizer once did (the whole reason this investigation started). _EvalPasserRacesAgainstLoneKings's own precondition is looser (fires whenever EITHER side is bare, even if the OTHER side still has real pieces, e.g. K+R+P vs K) -- that broader shape was never covered by this session's KPvKP work and is NOT provably safe for the shared routines here (their reasoning assumes no other pieces exist to interpose/defend/escape), so the call site below keeps routing that case to the old function unchanged. Returns whether it actually placed a credit for either side. This function is trustworthy but narrow -- it only ever fires for the true-lone-king sub-case of pure KPvKP, and stays silent (returns FALSE) for the "both sides still have pawns" sub-case rather than guess. The caller uses this to fall back to _EvalPasserRacesAgainstLoneKings (dodgy but broader-coverage) only when this function had nothing to say, instead of losing that coverage outright. Parameters: POSITION *pos Return value: FLAG -- TRUE if a credit was placed for either side **/ { ULONG uColor; FLAG fFired = FALSE; FOREACH_COLOR(uColor) { ULONG xColor = FLIP(uColor); COOR c; if (0 == FastCountBits(pos->bbPawns[uColor])) { continue; } if (0 == FastCountBits(pos->bbPawns[xColor])) { // True lone-king opponent: the general "rule of the // square + king escort" race, any rank, not just the // 7th/2nd -- see IsUnstoppableLoneKingPasser's own header // comment (0 wrong across all 165,676 EGTB-covered legal // single-pawn KPK positions). BITBOARD bb = pos->bbPawns[uColor]; while (IS_ON_BOARD(c = CoorFromBitBoardRank8ToRank1(&bb))) { if (TRUE == IsUnstoppableLoneKingPasser(pos, uColor, c)) { EVAL_TERM(uColor, PAWN, c, pos->iScore[uColor], RACER_WINS_RACE, "unstoppable passer (lone king)"); fFired = TRUE; // // break, not return: uColor is done (one credit is // enough for this side), but the OTHER color still // needs to be checked by this same FOREACH_COLOR // loop -- an earlier version of this function // returned here, which meant whichever color // happened to be checked first (by FOREACH_COLOR's // iteration order) silently suppressed any check of // the other side at all, even a far more urgent // threat. Found via a real regression: White's Ph7 // one push from queening // (8/7P/6p1/3k1p2/2p5/3pK3/8/8 w - -, this whole // investigation's original motivating position) // scored -6.09 (the exact ORIGINAL buggy value from // before this session) because Black's much weaker // d3 pawn got checked first and its credit's early // return meant White's real threat was never // evaluated at all. // break; } } } // // Deliberately nothing here for "opponent also has pawns." // A prior session (see the stashed 2026-09-2x eval.c/recogn.c // "passer-race + king-escort rework") tried exactly this // extension, measured it at only ~1% wrong-side rate against // EGTB, and STILL found it caused a real playing-strength // regression in overnight self-play -- a low measured // false-positive rate doesn't guarantee an eval nudge is // actually good for play; it can still systematically mislead // move choice/ordering in ways a raw error-rate number doesn't // capture. That session's own conclusion (matched here rather // than re-litigated): restrict this function to the exact same // true-lone-king precondition recogn.c's own hard bound // trusts, and leave the "both sides have pawns" case to // recogn.c's search-time recognizer (_RecognizeKPK) and plain // positional eval terms, not a duplicate heuristic here. An // eval.c attempt at this (HasRacingUnstoppablePasser) was // built and measured this session before finding this same // prior-session lesson -- removed rather than kept as unused // dead code; see git history if this is ever revisited with a // real self-play test to back it, not just an EGTB sample. // } return(fFired); } FLAG _EvalPasserRacesAgainstLoneKings(IN OUT SEARCHER_THREAD_CONTEXT *ctx, IN PAWN_HASH_ENTRY *pHash) /** Routine description: Determine if one side has a pawn that is unstoppable. This always works for KPK or KPKP but gets dodgy if a side has more than 1 pawn. Error rates on KPPKPP are ~5% and KPKPPP are ~1%. Parameters: SEARCHER_THREAD_CONTEXT *ctx, PAWN_HASH_ENTRY *pHash, Return value: void **/ { BITBOARD bb[2]; ULONG uColor, xColor; int d1; COOR cKing[2]; COOR c, cQueen; ULONG uEnemyKingDist, uPawnDist, uFriendKingDist; ULONG uMinRacerDist[2] = {99, 99}; ULONG uMovesSpent[2]; FLAG fDontCountMeOut[2]; POSITION *pos = &ctx->sPosition; // Don't recognize if stm is in check. PLY_INFO *pi = &ctx->sPlyInfo[ctx->uPly]; if (pi->fInCheck) { return(FALSE); } // Only deal with positions that have passers. bb[BLACK] = pHash->bbPasserLocations[BLACK]; bb[WHITE] = pHash->bbPasserLocations[WHITE]; if (!(bb[BLACK] | bb[WHITE])) { return(FALSE); } ASSERT((TotalNonPawnCount(pos, WHITE) == 1) || (TotalNonPawnCount(pos, BLACK) == 1)); // Don't make a call if the king is well placed and the side has // pawns left. fDontCountMeOut[BLACK] = ((RANK(KingPosition(pos, BLACK)) <= 3) && (pos->bbPawns[BLACK] != 0)); fDontCountMeOut[WHITE] = ((RANK(KingPosition(pos, WHITE)) >= 6) && (pos->bbPawns[WHITE] != 0)); cKing[WHITE] = KingPosition(pos, WHITE); ASSERT(IS_KING(pos->rgSquare[cKing[WHITE]].pPiece)); ASSERT(GET_COLOR(pos->rgSquare[cKing[WHITE]].pPiece) == WHITE); cKing[BLACK] = KingPosition(pos, BLACK); ASSERT(IS_KING(pos->rgSquare[cKing[BLACK]].pPiece)); ASSERT(GET_COLOR(pos->rgSquare[cKing[BLACK]].pPiece) == BLACK); FOREACH_COLOR(uColor) { // If uColor has no passers, skip it. if (!bb[uColor]) { continue; } // If xColor has any piece other than a king (and maybe some pawns), skip. xColor = FLIP(uColor); if (TotalNonPawnCount(pos, xColor) != 1) { continue; } d1 = 16 * g_iAhead[uColor]; uMovesSpent[uColor] = 1; uMovesSpent[xColor] = 0; while(IS_ON_BOARD(c = CoorFromBitBoardRank8ToRank1( &(bb[uColor])))) { // If this pawn is right next to the enemy king, don't // predict the number of moves it takes to queen. if (xColor == pos->uToMove && (DISTANCE(cKing[xColor], c) == 1) && (DISTANCE(cKing[uColor], c) != 1)) { uMovesSpent[xColor] += 1; continue; } fDontCountMeOut[uColor] = TRUE; cQueen = FILE_RANK_TO_COOR(FILE(c), QUEENING_RANK[uColor]); ASSERT(FILE(cQueen) == FILE(c)); // Don't call rook pawn races with the friendly king in a // dodgy position. if (((A == FILE(c)) || (H == FILE(c))) && (FILE(c) == FILE(cKing[uColor])) && (0 == DISTANCE(cKing[uColor], cQueen))) { continue; } uPawnDist = RANK_DISTANCE(cQueen, c); uPawnDist -= ((RANK(c) == JUMPING_RANK[uColor]) && (IS_EMPTY(pos->rgSquare[c + d1].pPiece) && IS_EMPTY(pos->rgSquare[c + d1 * 2].pPiece))); ASSERT((uPawnDist >= 1) && (uPawnDist <= 6)); uPawnDist += uMovesSpent[uColor]; // Rule of the square; can this passer make it to // the queening square before the enemy king? uEnemyKingDist = DISTANCE(cKing[xColor], cQueen); if (uEnemyKingDist > 0) { uEnemyKingDist -= (pos->uToMove == xColor); } ASSERT((uEnemyKingDist >= 0) && (uPawnDist <= 7)); if (uPawnDist < uEnemyKingDist) { uMinRacerDist[uColor] = MINU(uMinRacerDist[uColor], uPawnDist); } // See if the friend king can escort this passer in. Same- // file adjacency alone doesn't distinguish a king BEHIND // the pawn (genuine escort) from a king sitting on the // very next square in front of it, i.e. cKing[uColor] == // c + d1 (blocking its own pawn's path, not helping it) -- // found via an exhaustive KPvKP/EGTB cross-check // (8/8/8/8/8/6Pp/7k/5K2 b - -: Black king h2 sits directly // in front of its own h3 pawn, yet this branch credited an // escort bonus as if h2 were behind it). Exclude that // square explicitly rather than just checking direction, // since it's the one same-file square DISTANCE<=1 permits // that unambiguously blocks rather than escorts. uFriendKingDist = DISTANCE(cKing[uColor], cQueen); if ((uFriendKingDist <= 1) && (DISTANCE(cKing[uColor], c) <= 1)) { if (FILE(c) != FILE(cKing[uColor])) { uMinRacerDist[uColor] = MINU(uMinRacerDist[uColor], uPawnDist); } else if ((cKing[uColor] != (c + d1)) && (FILE(cKing[xColor]) != A) && (FILE(cKing[xColor]) != H)) { uMinRacerDist[uColor] = MINU(uMinRacerDist[uColor], (uPawnDist + 1)); } } } // uMovesSpent[xColor] counts how many of uColor's OWN passers // just got individually skipped above as "adjacent to xColor's // king, xColor to move -- assume it's captured for free." Fine // when it happens to exactly one pawn, but when it happens to // TWO OR MORE, xColor's king is adjacent to multiple of // uColor's passers at once and can only actually capture ONE // of them -- the classic king-overload fork (found via random // KPPKPP/KPKPPP sampling against EGTB: // 8/5P2/1k6/8/8/8/pKp2P2/8 w - -, White king b2 flanked by // Black's a2 and c2, each one square from queening -- White // captures one, Black queens the other, Black wins by force, // but the per-pawn skip above silently dropped BOTH of // Black's passers from consideration, crediting White's own // ordinary race instead). This function's per-pawn model has // no way to actually resolve a fork like this ("TODO: winning // connected passers" above already flags the general // connected-passer gap as out of scope) -- the safe, precision- // over-recall response is not to guess who really wins, but to // stop trusting THE OTHER side's credit here, the same way // fDontCountMeOut already protects a side with real drawing // chances elsewhere in this function. if (uMovesSpent[xColor] >= 2) { fDontCountMeOut[uColor] = TRUE; } } if ((uMinRacerDist[WHITE] < uMinRacerDist[BLACK]) && (FALSE == fDontCountMeOut[BLACK])) { EVAL_TERM(WHITE, PAWN, ILLEGAL_COOR, pos->iScore[WHITE], RACER_WINS_RACE - uMinRacerDist[WHITE] * 4, "winning racer pawn"); return(TRUE); } else if ((uMinRacerDist[BLACK] < uMinRacerDist[WHITE]) && (FALSE == fDontCountMeOut[WHITE])) { EVAL_TERM(BLACK, PAWN, ILLEGAL_COOR, pos->iScore[BLACK], RACER_WINS_RACE - uMinRacerDist[BLACK] * 4, "winning racer pawn"); return(TRUE); } return(FALSE); } static void _ReEvalPassers(IN OUT POSITION *pos, IN PAWN_HASH_ENTRY *pHash) /** Routine description: Parameters: POSITION *pos, PAWN_HASH_ENTRY *pHash, Return value: void **/ { ULONG u; ULONG uColor; ULONG xColor; COOR c; COOR cSquare; BITBOARD bb; PIECE p; SCORE i; ULONG uNumPassers[2] = { 0, 0 }; int d1; ASSERT(pHash->bbPasserLocations[WHITE] | pHash->bbPasserLocations[BLACK]); FOREACH_COLOR(uColor) { xColor = FLIP(uColor); bb = pHash->bbPasserLocations[uColor]; if (bb != 0) { uNumPassers[uColor] = FastCountBits(bb); ASSERT(uNumPassers[uColor] > 0); d1 = 16 * g_iAhead[uColor]; ASSERT((d1 * 2) == (32 * g_iAhead[uColor])); while(IS_ON_BOARD(c = CoorFromBitBoardRank8ToRank1(&bb))) { // // Consider the control of the square in front of the passer // cSquare = c + d1; ASSERT(IS_ON_BOARD(cSquare)); u = _WhoControlsSquareFast(pos, cSquare); if (u == xColor) { EVAL_TERM(uColor, PAWN, c, pos->iScore[uColor], -((PASSER_BY_RANK[uColor][RANK(c)] / 4) + (PASSER_BY_RANK[uColor][RANK(c)] / 16)), "enemy controls sq ahead"); } else if (u == (ULONG)-1) { p = pos->rgSquare[cSquare].pPiece; if (!IS_EMPTY(p) && (OPPOSITE_COLORS(p, uColor))) { ASSERT(GET_COLOR(p) != uColor); EVAL_TERM(uColor, PAWN, c, pos->iScore[uColor], -(PASSER_BY_RANK[uColor][RANK(c)] / 4), "enemy occupies sq ahead"); } } #ifdef DEBUG else { ASSERT(u == uColor); } #endif // // Consider distance from friend king / enemy king // i = (8 - DISTANCE(c, KingPosition(pos, uColor))); if (((uColor == WHITE) && ((KingPosition(pos, BLACK) >> 4) <= (c >> 4))) || ((uColor == BLACK) && ((KingPosition(pos, WHITE) >> 4) >= (c >> 4)))) { // // The enemy king is ahead of the passer // i += FILE_DISTANCE(c, KingPosition(pos, xColor)) * 4; } else { // // The enemy king is behind the passer // i += 10 + DISTANCE(c, KingPosition(pos, xColor)) * 4; } i *= PASSER_MATERIAL_UP_SCALER[pos->uArmyScaler[xColor]]; i /= 8; EVAL_TERM(uColor, PAWN, c, pos->iScore[uColor], i, "passer distance to kings"); // // If a side is a piece down then the other side's passers // are even more dangerous. // if (TotalNonPawnCount(pos, uColor) > TotalNonPawnCount(pos, xColor)) { i = (PASSER_BY_RANK[uColor][RANK(c)] / 2); EVAL_TERM(uColor, PAWN, c, pos->iScore[uColor], i, "passer and piece up"); } // // TODO: For connected passers vs KR, consult the oracle // } } } // // Game stage bonus // u = pos->uArmyScaler[BLACK]; EVAL_TERM(WHITE, PAWN, ILLEGAL_COOR, pos->iScore[WHITE], (uNumPassers[WHITE] * PASSER_BONUS_AS_MATERIAL_COMES_OFF[u] * MULTIPLE_PASSER_SCALER[uNumPassers[WHITE]]) >> 5, "passer value material"); ASSERT(PASSER_BONUS_AS_MATERIAL_COMES_OFF[u] >= 0); u = pos->uArmyScaler[WHITE]; EVAL_TERM(BLACK, PAWN, ILLEGAL_COOR, pos->iScore[BLACK], (uNumPassers[BLACK] * PASSER_BONUS_AS_MATERIAL_COMES_OFF[u] * MULTIPLE_PASSER_SCALER[uNumPassers[BLACK]]) >> 5, "passer value material"); ASSERT(PASSER_BONUS_AS_MATERIAL_COMES_OFF[u] >= 0); } static void _EvalBadTrades(IN OUT POSITION *pos) /** Routine description: Parameters: POSITION *pos, Return value: void **/ { ASSERT(pos->uNonPawnMaterial[WHITE] != pos->uNonPawnMaterial[BLACK]); ULONG uAhead = (pos->uNonPawnMaterial[WHITE] > pos->uNonPawnMaterial[BLACK]); ULONG uBehind = FLIP(uAhead); #ifdef DEBUG if (pos->uNonPawnMaterial[WHITE] > pos->uNonPawnMaterial[BLACK]) { ASSERT(uAhead == WHITE); ASSERT(uBehind == BLACK); } else { ASSERT(pos->uNonPawnMaterial[BLACK] > pos->uNonPawnMaterial[WHITE]); ASSERT(uAhead == BLACK); ASSERT(uBehind == WHITE); } #endif // // A material-VALUE imbalance (uNonPawnMaterial differing, the // caller's gate) is not the same fact as a piece-COUNT imbalance -- // e.g. 2R vs R+N is "up the exchange" with equal piece count on // both sides, not a side that has simplified/traded down to fewer // pieces. Ported from a stashed, previously-uncommitted eval.c // change (2026-09-2x eval audit session) -- mirrors Crafty's // EvaluateMaterial (~/crafty/evaluate.c), whose bad_trade bonus // explicitly requires Abs(occupied_count_diff) != 2 && // occupied_count_diff != 0, i.e. it never fires when piece counts // are equal, deliberately leaving pure up-the-exchange positions to // ordinary material valuation instead of this term. Without this // check, typhoon double-counts: real, up-the-exchange credit // already exists via material value, and this term used to stack // an unconditional extra "keep trading" bonus on top regardless of // whether uAhead had actually traded down to fewer pieces at all -- // found via the original eval audit // (8/2r4p/8/5p1R/8/1n4P1/1pk2PKP/4R3 b, 2R vs R+N, equal piece // count: typhoon +2.07 for White, Crafty -1.63 for White -- // opposite sign, traced to this exact double-count). // if (TotalNonPawnCount(pos, uAhead) == TotalNonPawnCount(pos, uBehind)) { return; } // // Encourage the side that is ahead in piece material to continue // trading pieces and not to trade pawns. This also has the // effect of making the side that is behind in material want to // trade pawns and not pieces. This also gives the side that is // ahead a bit of a "bad trade" bonus. Note that the bonus is not // given if the side "ahead" has no pawns AND no mating material of // its own; this is so that the engine will not like positions like // KNB vs KRP - the side with the pawn has the winning chances. // ULONG uAheadPawnCount = FastCountBits(pos->bbPawns[uAhead]); ULONG uInverseBehindPieceCount = 11 - MINU(9, TotalNonPawnCount(pos, uBehind)); // // "No mating material" here means the SAME lone-minor-piece test // SideHasWinningChances (above) already uses: king + exactly one // knight/bishop and nothing else -- a K+N or K+B can never force // mate alone, which is the actual KNB-vs-KRP failure mode this // whole guard exists for. Found via a real counterexample // (2k5/4r3/KP2P3/P7/7P/8/8/8 b - -): Black is ahead in non-pawn // material with a ROOK, not a lone minor -- a rook can genuinely // blockade/pick off multiple passed pawns on its own, nothing like // the KNB-vs-KRP case this guard was built for -- yet the old // "zero pawns -> zero bonus" version zeroed this out unconditionally // by piece count alone, silencing exactly the term that should // have been pushing back against White's four separately-scored // passed pawns. // FLAG fAheadLoneMinorNoMate = (2 == TotalNonPawnCount(pos, uAhead)) && (1 == (FastCountBits(pos->bbPieces[uAhead][KNIGHT]) + FastCountBits(pos->bbPieces[uAhead][BISHOP]))); EVAL_TERM(uAhead, 0, ILLEGAL_COOR, pos->iScore[uAhead], (uInverseBehindPieceCount * 16) * ((uAheadPawnCount != 0) || (FALSE == fAheadLoneMinorNoMate)), "trade pieces"); // Zero pawns AND no mating material for the ahead side is the // classic false-positive (KNB vs KRP, minor-up-no-pawns endings // that are often drawn or even lost) -- the old DONT_TRADE_PAWNS // table existed specifically to punish it (-43/-10 depending on // lead size) rather than just trailing off toward a small positive // number. Keep that guard as a cheap branch rather than a lookup // table; the positive slope for 1+ pawns doesn't need the same // care. Same mating-material exception as "trade pieces" above: // zero pawns with REAL mating material (a rook, say) isn't the // KNB-vs-KRP failure mode this -30 penalty exists for, so it gets // a neutral 0 instead of being punished. EVAL_TERM(uAhead, 0, ILLEGAL_COOR, pos->iScore[uAhead], (0 != uAheadPawnCount) ? (SCORE)(uAheadPawnCount * 2) : (TRUE == fAheadLoneMinorNoMate) ? -30 : 0, "don't trade pawns"); } #if 0 static void _EvalLookForDanger(IN OUT SEARCHER_THREAD_CONTEXT *ctx) /** Routine description: This routine looks for squares on the board where the side to move has a piece that is en prise. So far in eval we will have tagged pieces in situations where they are attacked by lesser-valued enemy pieces as "in danger". However, because of the order in which the attack table was generated, we will have missed situations where a piece is undefended (or underdefended) and attacked by an enemy piece that is the same (or greater) value. Note: This routine only considers side to move. Also Note: this routine does not find pawns that are en prise, only pieces. Parameters: SEARCHER_THREAD_CONTEXT *ctx Return value: void **/ { COOR c; BITBOARD bbNonKingPieces; POSITION *pos = &ctx->sPosition; ULONG uSide = pos->uToMove; #ifdef DEBUG PIECE p; #endif bbNonKingPieces = NON_KING_PIECES_BB(pos, uSide); while (IS_ON_BOARD(c = CoorFromBitBoardRank8ToRank1(&bbNonKingPieces))) { #ifdef DEBUG ASSERT(IS_ON_BOARD(c)); p = pos->rgSquare[c].pPiece; ASSERT(p); ASSERT(GET_COLOR(p) == uSide); ASSERT(!IS_PAWN(p)); #endif if (_WhoControlsSquareFast(pos, c) == FLIP(uSide)) { RecordEnprisePiece(ctx, c); } } } #endif static void _EvalTrappedPieces(IN OUT SEARCHER_THREAD_CONTEXT *ctx) /** Routine description: Parameters: SEARCHER_THREAD_CONTEXT *ctx Return value: static void **/ { COOR c; COOR cBestOwnTrapped; ULONG uBestOwnTrappedValue; ULONG uColor; ULONG xColor; ULONG u; ULONG uFinalMobility; BITBOARD bbOwnDefend; BITBOARD bbUnsafeNow; BITBOARD bbStillSafe; POSITION *pos = &ctx->sPosition; PIECE p; SCORE i; FOREACH_COLOR(uColor) { xColor = FLIP(uColor); cBestOwnTrapped = ILLEGAL_COOR; uBestOwnTrappedValue = 0; for (u = 0; u < pos->uNumTrapped[uColor]; u++) { c = pos->cTrapped[uColor][u]; ASSERT(IS_ON_BOARD(c)); p = pos->rgSquare[c].pPiece; #ifdef DEBUG ASSERT(p); ASSERT(!IS_PAWN(p)); ASSERT(GET_COLOR(p) == uColor); #endif // A nonzero bbTrappedEscapes snapshot means this candidate // was genuinely deferred (a bishop/knight/rook nominated at // low-but-nonzero partial-information mobility -- see // EVAL_MOBILITY_CAREFULLY_BELOW's comment) and is still // owed both its real mobility score (skipped at nomination // time) and a final trapped/not-trapped verdict, now that // every piece type -- including the enemy king -- has // contributed to the attack tables. A zero snapshot means // either a genuinely 0-mobility piece (already scored // inline, nothing left to re-derive -- see _EvalBishop's // comment on why those are never deferred) or a queen // (never deferred at all -- its own eval pass already runs // after every smaller piece type, so it doesn't have this // partial-information problem in the first place; see // _EvalQueen's bbUnsafeForQueen). if (pos->bbTrappedEscapes[uColor][u] != 0) { // bbOwnDefend excludes the candidate's own piece-type // bucket: bbMinorAttacks/bbRookAttacks already include // this very piece's own attack squares (populated // unconditionally before the nomination decision), // which are exactly its candidate escape squares -- // crediting that back as "defense" would be circular (a // piece can't defend the square it would occupy after // moving off its own square). Conservative side effect: // a genuinely different friendly minor/rook defending // the same square as a trapped minor/rook is also // excluded, since the merged bitboards can't // distinguish "this piece" from "another piece of the // same bucket" -- known limitation, not fixed here. bbOwnDefend = pos->bbPawnAttacks[uColor] | pos->bbQueenAttacks[uColor]; if (!IS_BISHOP(p) && !IS_KNIGHT(p)) { bbOwnDefend |= pos->bbMinorAttacks[uColor]; } if (!IS_ROOK(p)) { bbOwnDefend |= pos->bbRookAttacks[uColor]; } // The only thing nomination-time couldn't see: the // enemy king's own attacks (pos->bbKingAttacks[xColor] // -- both kings have finished evaluating well before // _EvalTrappedPieces runs, see Eval()'s call order). // Everything else a candidate square could be unsafe // for (a cheaper enemy piece attacking it) was already // known and excluded at nomination time -- see // EVAL_MOBILITY_CAREFULLY_BELOW's comment. bbUnsafeNow = pos->bbKingAttacks[xColor] & ~bbOwnDefend; bbStillSafe = pos->bbTrappedEscapes[uColor][u] & ~bbUnsafeNow; uFinalMobility = FastCountBits(bbStillSafe); if (IS_BISHOP(p)) { EVAL_TERM(uColor, BISHOP, c, pos->iScore[uColor], BISHOP_MOBILITY_BY_SQUARES[uFinalMobility], "bishop mobility (deferred)"); } else if (IS_KNIGHT(p)) { EVAL_TERM(uColor, KNIGHT, c, pos->iScore[uColor], KNIGHT_MOBILITY_BY_COUNT[uFinalMobility], "knight mobility (deferred)"); } else if (IS_ROOK(p)) { ASSERT(pos->uArmyScaler[xColor] <= 31); i = ROOK_MOBILITY_BY_SQUARES[uFinalMobility]; i *= (int)(REDUCED_MATERIAL_UP_SCALER[pos->uArmyScaler[xColor]] + 1); i /= 8; EVAL_TERM(uColor, ROOK, c, pos->iScore[uColor], i, "rook mobility (deferred)"); } if (bbStillSafe != 0) { // A real escape exists once full attack information // is in -- the loose, partial-information nomination // was a false alarm, not actually trapped. Its // (corrected, lower) mobility score was already // banked above; nothing more to do for it. continue; } } if (_WhoControlsSquareFast(pos, c) == xColor) { // See if the side who created the trap and controls // the square the trapped piece is sitting on has the // move too. If so, uColor moved at ply-1. if (OPPOSITE_COLORS(uColor, pos->uToMove)) { if (ctx->uPly > 0) { RecordEnprisePieceAtPly(ctx, ctx->uPly - 1, c); } EVAL_TERM(uColor, p, c, pos->iScore[uColor], ENPRISE_AND_TRAPPED_PENALTY, "en prise and trapped"); } // ctx->cTrapped[uPly] (RecordTrappedPiece's target) // is a single slot, not a list -- if more than one // of our own pieces is genuinely trapped this ply, // only report the most valuable one. else { if (PIECE_VALUE(pos->rgSquare[c].pPiece) > uBestOwnTrappedValue) { uBestOwnTrappedValue = PIECE_VALUE(pos->rgSquare[c].pPiece); cBestOwnTrapped = c; } } } } // uColor has the move but we found at least one piece that // seems to have no safe place to move and is actively under // attack now. It may not be lost, at least uColor has the // move. But this is still a bad thing. if (IS_ON_BOARD(cBestOwnTrapped)) { RecordTrappedPiece(ctx, cBestOwnTrapped); p = pos->rgSquare[cBestOwnTrapped].pPiece; EVAL_TERM(uColor, p, cBestOwnTrapped, pos->iScore[uColor], TRAPPED_WITH_MOVE_PENALTY, "trapped piece, our move"); } } } static void _EvalBishopPairs(IN POSITION *pos) /*++ Routine description: Give a flat bonus to sides that have a viable bishop pair (one light-squared, one dark-squared) -- not scaled by pawn count, by direct instruction (2026-09-06). Parameters: IN POSITION *pos - position Return value: static void --*/ { ULONG uColor; FOREACH_COLOR(uColor) { ULONG uBishopCount = FastCountBits(pos->bbPieces[uColor][BISHOP]); ASSERT(uBishopCount <= 10); ULONG uWhiteSqBishopCount = WhiteSqBishopCount(pos, uColor); ASSERT(uWhiteSqBishopCount <= 10); FLAG fPair = ((uBishopCount > 1) & (uWhiteSqBishopCount != 0) & (uWhiteSqBishopCount != uBishopCount)); EVAL_TERM(uColor, 0, ILLEGAL_COOR, pos->iScore[uColor], fPair * BISHOP_PAIR_BONUS, "bishop pair"); } } FLAG FORCEINLINE SideHasWinningChances(IN POSITION *pos, IN ULONG uColor) /** Routine description: Cheap, material-count-only classifier (the same idea as Crafty's EvaluateWinningChances): can uSide possibly force a win from this material alone, ignoring the actual position entirely? Used only to soften (scale toward drawscore) an otherwise-misleading raw material lead in Eval() below -- unlike recogn.c's interior-node recognizers (RECOGN_EXACT/UPPER/LOWER), this is never a hard claim fed into a search bound, so a wrong answer here just biases the eval a little; it can't corrupt alpha-beta the way a wrong hard recognizer bound can (see recogn.c's _RecognizeKNKP/_RecognizeKBNK incident). Deliberately conservative: mostly covers material shapes where "no, this can't be forced" is basic, textbook chess knowledge (insufficient mating material, up the exchange with nothing else changed, bare knights vs a bare king). One exception that DOES need real board information, not just material counts, is included below (wrong-bishop-pawn-with-king-in-time) precisely because it's common enough and cheap enough to be worth it; anything else needing real board geometry is recogn.c's hard-recognizer territory (already exact for tiny material there) or plain search's job, not this cheap pre-check's. Parameters: POSITION *pos, ULONG uSide Return value: static FLAG : TRUE if uSide has any winning chances at all, FALSE if this exact material can provably never be forced to a win regardless of position. **/ { ULONG xColor = FLIP(uColor); ASSERT(IS_VALID_COLOR(uColor) && IS_VALID_COLOR(xColor)); INT iMajorDiff; INT iMinorDiff; ULONG uColorKnights; ULONG uColorBishops = FastCountBits(pos->bbPieces[uColor][BISHOP]); // Wrong-bishop rook-pawn fortress: a lone bishop + rook-pawn(s) (all // on the A- or H-file), with the bishop unable to control the // promotion square, is a known draw once the defending bare king // can reach the corner in time -- regardless of how much raw pawn // material uSide has. Checked before the blanket "any pawn -> TRUE" // return below, which would otherwise hide this case entirely. // Mirrors Crafty's EvaluateWinningChances (~/crafty/evaluate.c) -- // "in time" uses the same tempo-adjusted Chebyshev distance Crafty // uses (one square of credit to the defender if it's their move). // Ported from a stashed, previously-uncommitted eval.c change // (2026-09-2x eval audit session); testing methodology for its // false-positive rate against this session's own KP+KP* EGTB // harness is still to be built (see testeval.c/testrecogn.c) before // trusting the ~2.12% figure the stash's own comment cited -- that // number was never independently re-verified in this session. Only // ever softens a score (via EvalLookForDrawishSituations' /16 // shrink), never used as a search-terminating bound the way // recogn.c's tighter dist<=1-only version is, so a wrong FALSE here // is tolerable in a way it would not be in recogn.c. if ((2 == TotalNonPawnCount(pos, uColor)) && (1 == uColorBishops) && (1 == TotalNonPawnCount(pos, xColor)) && (0 == FastCountBits(pos->bbPawns[xColor])) && (FastCountBits(pos->bbPawns[uColor]) > 0)) { BITBOARD bbPawns = pos->bbPawns[uColor]; COOR cPromote = ILLEGAL_COOR; ULONG uColorWhiteSquareBishopCount = WhiteSqBishopCount(pos, uColor); if (uColor == WHITE) { if (!(bbPawns & ~BBFILE[A]) && (uColorWhiteSquareBishopCount == 0)) { cPromote = A8; } else if (!(bbPawns & ~BBFILE[H]) && (uColorWhiteSquareBishopCount == 1)) { cPromote = H8; } } else { if (!(bbPawns & ~BBFILE[A]) && (uColorWhiteSquareBishopCount == 1)) { cPromote = A1; } else if (!(bbPawns & ~BBFILE[H]) && (uColorWhiteSquareBishopCount == 0)) { cPromote = H1; } } if (IS_ON_BOARD(cPromote)) { COOR cWeakKing = KingPosition(pos, xColor); int iTempo = (pos->uToMove == xColor) ? 1 : 0; if (((int)DISTANCE(cWeakKing, cPromote) - iTempo) < 1) { return(FALSE); } } } // // A pawn always gives some winning chances (it can always try to // queen with support) -- nothing below applies. // if (FastCountBits(pos->bbPawns[uColor]) > 0) { return(TRUE); } // uSide's knight count is read twice below (the lone-minor check // and the two-knights check); uSideBishops was already computed // above. uColorKnights = FastCountBits(pos->bbPieces[uColor][KNIGHT]); // // No pawns and the only piece besides the king is a single minor: // never enough material to force mate (K+N or K+B vs anything is // never a forced win on material alone). // if ((2 == TotalNonPawnCount(pos, uColor)) && (1 == (uColorKnights + uColorBishops))) { return(FALSE); } // // No pawns and up exactly the exchange (one extra rook/queen, // balanced by one extra enemy minor elsewhere): not enough to // force a win either -- e.g. KRB vs KR can be held by the // defender with correct play. // iMajorDiff = (INT)(FastCountBits(pos->bbPieces[uColor][ROOK]) + 2 * FastCountBits(pos->bbPieces[uColor][QUEEN])) - (INT)(FastCountBits(pos->bbPieces[xColor][ROOK]) + 2 * FastCountBits(pos->bbPieces[xColor][QUEEN])); if ((1 == iMajorDiff) || (-1 == iMajorDiff)) { iMinorDiff = (INT)(FastCountBits(pos->bbPieces[xColor][KNIGHT]) + FastCountBits(pos->bbPieces[xColor][BISHOP])) - (INT)(uColorKnights + uColorBishops); if (iMajorDiff == iMinorDiff) { return(FALSE); } } // // No pawns, exactly two bare knights (no bishops/rooks/queens) for // uSide, and the enemy has nothing left at all: two knights can't // force mate against a bare king. Two bishops CAN (excluded here // by requiring BISHOP count == 0) and knight+bishop CAN too (also // excluded, since that has one bishop, not zero) -- both are // genuine, if sometimes technique-heavy, forced wins. // if ((2 == uColorKnights) && (0 == uColorBishops) && (0 == FastCountBits(pos->bbPieces[uColor][ROOK])) && (0 == FastCountBits(pos->bbPieces[uColor][QUEEN])) && (1 == TotalNonPawnCount(pos, xColor)) && (0 == FastCountBits(pos->bbPawns[xColor]))) { return(FALSE); } return(TRUE); } void InitializeEval(void) { ROOK_FULL_HALF_OPEN_BONUS[0][0] = ROOK_ON_FULL_OPEN; ROOK_FULL_HALF_OPEN_BONUS[0][1] = ROOK_ON_HALF_OPEN_WITH_ENEMY; ROOK_FULL_HALF_OPEN_BONUS[1][0] = ROOK_ON_HALF_OPEN_WITH_FRIEND; ROOK_FULL_HALF_OPEN_BONUS[1][1] = 0; } // 2026-09-17: DRAWISH_FACTS holds the three position-only inputs // EvalLookForDrawishSituations needs (_SideHasWinningChances for // both sides, and the BOOC opposite-bishop check) -- none of these // depend on the score at all, only on pos, which doesn't change // between Eval()'s two call sites (the regular-lazy pre-exit check // and the end of full eval). A node that attempts the lazy exit and // then falls through to full eval anyway used to pay for // _SideHasWinningChances (two calls) and the BOOC check twice, once // per site, for identical answers both times -- only the score-vs- // drawscore/50-move comparisons genuinely need to be re-run per call // site, since the score itself legitimately differs between the // early lazy-preview value and the final full-eval value. // _EnsureDrawishFactsComputed is a cheap (single-branch) fetch-or- // compute -- called at both sites so either call order (lazy-then- // full, or full alone when the lazy attempt is skipped entirely for // bare-king/low-material positions) computes the facts exactly once. typedef struct _DRAWISH_FACTS { FLAG fComputed; FLAG fSideToMoveHasWinningChances; FLAG fOpponentHasWinningChances; FLAG fBOOC; } DRAWISH_FACTS; static void _EnsureDrawishFactsComputed(IN POSITION *pos, IN ULONG uColor, IN OUT DRAWISH_FACTS *pFacts) { if (pFacts->fComputed) { return; } pFacts->fSideToMoveHasWinningChances = SideHasWinningChances(pos, uColor); pFacts->fOpponentHasWinningChances = SideHasWinningChances(pos, FLIP(uColor)); pFacts->fBOOC = (TotalNonPawnCount(pos, WHITE) == 2) && (TotalNonPawnCount(pos, BLACK) == 2) && (FastCountBits(pos->bbPieces[WHITE][BISHOP]) == 1) && (FastCountBits(pos->bbPieces[BLACK][BISHOP]) == 1) && (WhiteSqBishopCount(pos, WHITE) != WhiteSqBishopCount(pos, BLACK)); pFacts->fComputed = TRUE; } static void EvalLookForDrawishSituations(POSITION *pos, SCORE *piScoreForSideToMove, IN DRAWISH_FACTS *pFacts) { ULONG uColor = pos->uToMove; ASSERT(pFacts->fComputed); // If the side who's ahead by raw material/positional score can't // actually force a win with what it has left on the board (see // _SideHasWinningChances), squash the score hard towards draw -- // same idiom as the 50-move dampening just below (and the same // signed-arithmetic care: g_iDrawScore is currently always 0, but // write this relative to it rather than assuming that, matching // the 50-move code's own convention). /16 (not a full collapse to // drawscore) deliberately mirrors Crafty's EvaluateDraws -- e.g. // KRB vs KR is still theoretically losable by the run-of-the-mill // defender with the checks _SideHasWinningChances gates on, so // some residual signal survives. if ((*piScoreForSideToMove > g_iDrawScore[uColor]) && (FALSE == pFacts->fSideToMoveHasWinningChances)) { *piScoreForSideToMove = g_iDrawScore[uColor] + ((*piScoreForSideToMove - g_iDrawScore[uColor]) / 16); } else if ((*piScoreForSideToMove < g_iDrawScore[uColor]) && (FALSE == pFacts->fOpponentHasWinningChances)) { *piScoreForSideToMove = g_iDrawScore[uColor] + ((*piScoreForSideToMove - g_iDrawScore[uColor]) / 16); } // If this is a BOOC endgame, push towards draw score too. if (pFacts->fBOOC) { *piScoreForSideToMove = g_iDrawScore[uColor] + ((*piScoreForSideToMove - g_iDrawScore[uColor]) / 4); } // Drive the score towards draw as we approach a 50 move w/o // progress draw. if (pos->uFifty > 84) { ULONG uDrawDist = 101 - pos->uFifty; ASSERT(uDrawDist > 0); // uDrawDist is ULONG -- multiplying a negative SCORE by it // directly promotes the SCORE to unsigned first (usual // arithmetic conversions, same rank), wrapping a negative // *piScoreForSideToMove into a huge positive garbage value // instead of scaling it down. Cast uDrawDist to SCORE so the // multiply happens in signed arithmetic; its range (1-16) is // always representable. *piScoreForSideToMove = g_iDrawScore[uColor] + (*piScoreForSideToMove * (SCORE)uDrawDist / 16); } } #ifdef DUMP_RESIDUAL_SAMPLES // // Histogram-based percentile capture for residual (bucketed by OWN // army scaler) and king safety (bucketed by ATTACKER's army scaler) -- // see the two call sites inside Eval() below. Deliberately a histogram // (same idea as CALIBRATE_POSITIONAL's g_CalibrateHist), not a raw // per-sample Trace: a raw dump against the 30k-position calibration // pool would run into the billions of lines (a 200-position sample // alone already produced 8.76M), while this stays a fixed, tiny amount // of memory regardless of sample count and prints one summary via // `calibrate residual`. // #define RESID_HIST_BUCKETS 8 #define RESID_HIST_BINS 90 #define RESID_HIST_BIN_WIDTH 20 #define RESID_HIST_MIN (-900) static UINT64 g_ResidualHist[RESID_HIST_BUCKETS][RESID_HIST_BINS]; static UINT64 g_SuperLazyResidualHist[RESID_HIST_BUCKETS][RESID_HIST_BINS]; static UINT64 g_KingSafetyHist[RESID_HIST_BUCKETS][RESID_HIST_BINS]; static INT g_ResidualMin[RESID_HIST_BUCKETS]; static INT g_ResidualMax[RESID_HIST_BUCKETS]; static INT g_SuperLazyResidualMin[RESID_HIST_BUCKETS]; static INT g_SuperLazyResidualMax[RESID_HIST_BUCKETS]; static INT g_KingSafetyMin[RESID_HIST_BUCKETS]; static INT g_KingSafetyMax[RESID_HIST_BUCKETS]; static FLAG g_fResidHistInit = FALSE; static ULONG g_uResidualOutliersPrinted = 0; static ULONG g_uKingSafetyOutliersPrinted = 0; static void _ResidHistInitIfNeeded(void) { ULONG b; if (TRUE == g_fResidHistInit) return; for (b = 0; b < RESID_HIST_BUCKETS; b++) { g_ResidualMin[b] = 999999; g_ResidualMax[b] = -999999; g_SuperLazyResidualMin[b] = 999999; g_SuperLazyResidualMax[b] = -999999; g_KingSafetyMin[b] = 999999; g_KingSafetyMax[b] = -999999; } g_fResidHistInit = TRUE; } static void _RecordResidualSample(ULONG uOwnArmyBucket, INT iValue) { INT idx; _ResidHistInitIfNeeded(); idx = (iValue - RESID_HIST_MIN) / RESID_HIST_BIN_WIDTH; if (idx < 0) idx = 0; if (idx >= RESID_HIST_BINS) idx = RESID_HIST_BINS - 1; g_ResidualHist[uOwnArmyBucket][idx]++; if (iValue < g_ResidualMin[uOwnArmyBucket]) g_ResidualMin[uOwnArmyBucket] = iValue; if (iValue > g_ResidualMax[uOwnArmyBucket]) g_ResidualMax[uOwnArmyBucket] = iValue; } static void _RecordSuperLazyResidualSample(ULONG uOwnArmyBucket, INT iValue) { INT idx; _ResidHistInitIfNeeded(); idx = (iValue - RESID_HIST_MIN) / RESID_HIST_BIN_WIDTH; if (idx < 0) idx = 0; if (idx >= RESID_HIST_BINS) idx = RESID_HIST_BINS - 1; g_SuperLazyResidualHist[uOwnArmyBucket][idx]++; if (iValue < g_SuperLazyResidualMin[uOwnArmyBucket]) g_SuperLazyResidualMin[uOwnArmyBucket] = iValue; if (iValue > g_SuperLazyResidualMax[uOwnArmyBucket]) g_SuperLazyResidualMax[uOwnArmyBucket] = iValue; } static void _RecordKingSafetySample(ULONG uAttackerArmyBucket, INT iValue) { INT idx; _ResidHistInitIfNeeded(); idx = (iValue - RESID_HIST_MIN) / RESID_HIST_BIN_WIDTH; if (idx < 0) idx = 0; if (idx >= RESID_HIST_BINS) idx = RESID_HIST_BINS - 1; g_KingSafetyHist[uAttackerArmyBucket][idx]++; if (iValue < g_KingSafetyMin[uAttackerArmyBucket]) g_KingSafetyMin[uAttackerArmyBucket] = iValue; if (iValue > g_KingSafetyMax[uAttackerArmyBucket]) g_KingSafetyMax[uAttackerArmyBucket] = iValue; } static INT _HistPercentile(UINT64 *puHist, UINT64 uTotal, double dP) { UINT64 uTarget = (UINT64)(dP * (double)uTotal); UINT64 uRunning = 0; ULONG i; for (i = 0; i < RESID_HIST_BINS; i++) { uRunning += puHist[i]; if (uRunning >= uTarget) { return RESID_HIST_MIN + (INT)(i * RESID_HIST_BIN_WIDTH) + (RESID_HIST_BIN_WIDTH / 2); } } return RESID_HIST_MIN + (RESID_HIST_BINS * RESID_HIST_BIN_WIDTH); } static void _PersistRawHistogramsToFile(void) /** Routine description: 2026-09-17: write every raw bin of all three histograms to a fixed scratch file, so any future percentile (not just the ones DumpResidualAndKingSafetyHistograms happens to print) can be read off after the fact -- no need to re-run the 30k pool just to try a different percentile choice. Plain text, one line per (histogram, bucket): the bucket's min, max, then all RESID_HIST_BINS raw counts space-separated. A future script can reconstruct any percentile via the same cumulative-sum logic _HistPercentile uses. Parameters: void Return value: void **/ { FILE *f; ULONG b, i; f = fopen("/var/tmp/typhoon/residual_raw_histograms.txt", "w"); if (NULL == f) { Trace("_PersistRawHistogramsToFile: could not open output file.\n"); return; } fprintf(f, "# RESID_HIST_BINS=%d RESID_HIST_BIN_WIDTH=%d RESID_HIST_MIN=%d\n", RESID_HIST_BINS, RESID_HIST_BIN_WIDTH, RESID_HIST_MIN); fprintf(f, "# format: ... \n"); for (b = 0; b < RESID_HIST_BUCKETS; b++) { fprintf(f, "residual %u %d %d", b, g_ResidualMin[b], g_ResidualMax[b]); for (i = 0; i < RESID_HIST_BINS; i++) { fprintf(f, " %llu", (unsigned long long)g_ResidualHist[b][i]); } fprintf(f, "\n"); } for (b = 0; b < RESID_HIST_BUCKETS; b++) { fprintf(f, "sl_residual %u %d %d", b, g_SuperLazyResidualMin[b], g_SuperLazyResidualMax[b]); for (i = 0; i < RESID_HIST_BINS; i++) { fprintf(f, " %llu", (unsigned long long)g_SuperLazyResidualHist[b][i]); } fprintf(f, "\n"); } for (b = 0; b < RESID_HIST_BUCKETS; b++) { fprintf(f, "king %u %d %d", b, g_KingSafetyMin[b], g_KingSafetyMax[b]); for (i = 0; i < RESID_HIST_BINS; i++) { fprintf(f, " %llu", (unsigned long long)g_KingSafetyHist[b][i]); } fprintf(f, "\n"); } fclose(f); Trace("Raw histograms written to /var/tmp/typhoon/residual_raw_histograms.txt\n"); } void DumpResidualAndKingSafetyHistograms(void) { ULONG b, i; UINT64 uTotal; _PersistRawHistogramsToFile(); #define TRACE_HIST_ROW(hist, min, max) \ Trace(" bucket %u (scaler %u-%u): n=%llu min=%d p1=%d p2=%d " \ "p5=%d p10=%d p50=%d p90=%d p95=%d p98=%d p99=%d max=%d\n", \ b, b * 4, b * 4 + 3, (unsigned long long)uTotal, (min), \ _HistPercentile((hist), uTotal, 0.01), \ _HistPercentile((hist), uTotal, 0.02), \ _HistPercentile((hist), uTotal, 0.05), \ _HistPercentile((hist), uTotal, 0.10), \ _HistPercentile((hist), uTotal, 0.50), \ _HistPercentile((hist), uTotal, 0.90), \ _HistPercentile((hist), uTotal, 0.95), \ _HistPercentile((hist), uTotal, 0.98), \ _HistPercentile((hist), uTotal, 0.99), \ (max)) Trace("Residual by OWN army-scaler bucket:\n"); for (b = 0; b < RESID_HIST_BUCKETS; b++) { uTotal = 0; for (i = 0; i < RESID_HIST_BINS; i++) uTotal += g_ResidualHist[b][i]; if (0 == uTotal) { Trace(" bucket %u: no samples\n", b); continue; } TRACE_HIST_ROW(g_ResidualHist[b], g_ResidualMin[b], g_ResidualMax[b]); } Trace("Super-lazy-scoped residual (material baseline, includes " "pawns/passers/bad-trade/bishop-pairs) by OWN army-scaler " "bucket:\n"); for (b = 0; b < RESID_HIST_BUCKETS; b++) { uTotal = 0; for (i = 0; i < RESID_HIST_BINS; i++) uTotal += g_SuperLazyResidualHist[b][i]; if (0 == uTotal) { Trace(" bucket %u: no samples\n", b); continue; } TRACE_HIST_ROW(g_SuperLazyResidualHist[b], g_SuperLazyResidualMin[b], g_SuperLazyResidualMax[b]); } Trace("King safety by ATTACKER army-scaler bucket:\n"); for (b = 0; b < RESID_HIST_BUCKETS; b++) { uTotal = 0; for (i = 0; i < RESID_HIST_BINS; i++) uTotal += g_KingSafetyHist[b][i]; if (0 == uTotal) { Trace(" bucket %u: no samples\n", b); continue; } TRACE_HIST_ROW(g_KingSafetyHist[b], g_KingSafetyMin[b], g_KingSafetyMax[b]); } #undef TRACE_HIST_ROW } #endif SCORE Eval(IN SEARCHER_THREAD_CONTEXT *ctx, IN SCORE iAlpha, IN SCORE iBeta, OUT SCORE (*piPositional)[2]) /** Routine description: Parameters: SEARCHER_THREAD_CONTEXT *ctx, SCORE iAlpha, SCORE iBeta, SCORE (*piPositional)[2] : if non-NULL, filled in with an estimate of the non-material component of the score for each side, indexed by absolute color (WHITE/BLACK) -- exact if a full eval ran, a cheap estimate otherwise. On a lazy exit this is always >= 0 (an optimistic margin); on a full eval it can be negative (a side whose positional terms net worse than its raw material), floored at -FUTILITY_BASE_MARGIN_FULL/2 so it can only shrink a caller's margin so far. Callers must treat it as an estimate either way; it's only ever used to size a pruning margin, never as a hard fact. Return value: SCORE **/ { POSITION *pos = &(ctx->sPosition); ULONG uColor = pos->uToMove; ULONG xColor = FLIP(uColor); SCORE iScoreForSideToMove; SCORE iAlphaMargin, iBetaMargin; PAWN_HASH_ENTRY *pHash; COOR c; ULONG u; BITBOARD bb; FLAG fDeferred; // Computed at most once per Eval() call, on first need, by // whichever of the two EvalLookForDrawishSituations call sites // runs first -- see DRAWISH_FACTS's comment above. DRAWISH_FACTS sDrawishFacts = {0}; #ifdef EVAL_TIME UINT64 uTimer = SystemReadTimeStampCounter(); #endif #ifdef CALIBRATE_POSITIONAL g_uCalibrateEvalCalls++; #endif #ifdef CALIBRATE_MARGIN_SAFETY // Set when a real exit would have been taken; the rest of Eval() // still runs (for measurement), but the saved values get restored // just before returning so real search behavior is bit-for-bit // unaffected -- see the swing recorded near `end:` below. FLAG fWouldHaveExited = FALSE; SCORE iSavedLazyScore = 0; SCORE iSavedLazyPositional = 0; // 2026-09-17: iPositional is no longer flat/symmetric across colors // (p50-based, keyed by each side's own army bucket) -- iSavedLazy- // Positional above stays the margin-safety accounting value (still // symmetric, unrelated to iPositional), these two are what actually // gets restored into (*piPositional)[WHITE]/[BLACK] below. SCORE iSavedLazyPositionalWhite = 0; SCORE iSavedLazyPositionalBlack = 0; // Same idea, kept separate from the pair above: the super-lazy // exit (added 2026-09-07) is a much cheaper, much-larger-gap check // than the regular lazy exit and was never hooked into this // harness -- see RecordSuperLazyMarginSafetySwing below. FLAG fWouldHaveExitedSuperLazy = FALSE; SCORE iSavedSuperLazyScore = 0; SCORE iSavedSuperLazyMarginUsed = 0; #endif ASSERT(IS_VALID_SCORE(iAlpha)); ASSERT(IS_VALID_SCORE(iBeta)); ASSERT(iAlpha < iBeta); ASSERT((pos->iMaterialBalance[WHITE] * -1) == pos->iMaterialBalance[BLACK]); #ifdef EVAL_TIME UINT64 u64MaterialSetupTimer = SystemReadTimeStampCounter(); #endif #ifdef EVAL_DUMP EvalTraceClear(); #endif // NNUE short-circuit (docs/NNUE.md's rollout plan: keep both // evaluators coexisting behind a toggle, full bypass not partial // mixing). ctx->sNnueAccum is assumed correct here -- maintained // incrementally by every MakeMove/UnmakeMove since the last fresh // NnueAccumRecompute (root.c's ReInitializeSearcherContext, run // on every new root position). piPositional's contract ("always // >= 0 on anything but a full eval") is satisfied with a neutral // 0 -- none of the lazy/super-lazy margin-sizing machinery below // has been recalibrated against NNUE's score distribution yet // (a separate, not-yet-done project per NNUE.md), so this is // intentionally the least-specific answer that's still safe, not // an attempt to approximate what a real positional estimate would // say. // Initialize army scalers here -- moved ahead of BOTH the NNUE // short-circuit above and the super-lazy exit point below, // 2026-10-15 (was already ahead of super-lazy only, since // 2026-09-08; moved further to also cover the NNUE path). Their // only inputs, uNonPawnMaterial, are already available this early. // Side effect of this move: pos->uArmyScaler is now always fresh // after Eval() returns, including on the NNUE path -- previously // it was left stale (whatever a prior call last set) whenever // Eval() took the NNUE short-circuit, since that return happened // before this block ran at all. Nothing on the NNUE path // previously depended on uArmyScaler being stale vs fresh, so this // is strictly safer, not a behavior change worth gating. pos->uArmyScaler[BLACK] = pos->uNonPawnMaterial[BLACK] - VALUE_KING; pos->uArmyScaler[WHITE] = pos->uNonPawnMaterial[WHITE] - VALUE_KING; pos->uArmyScaler[BLACK] /= VALUE_PAWN; pos->uArmyScaler[WHITE] /= VALUE_PAWN; ASSERT(!(pos->uArmyScaler[BLACK] & 0x80000000)); ASSERT(!(pos->uArmyScaler[WHITE] & 0x80000000)); pos->uArmyScaler[BLACK] = MINU(31, pos->uArmyScaler[BLACK]); pos->uArmyScaler[WHITE] = MINU(31, pos->uArmyScaler[WHITE]); ASSERT(pos->uArmyScaler[BLACK] >= 0); ASSERT(pos->uArmyScaler[BLACK] <= 31); ASSERT(pos->uArmyScaler[WHITE] >= 0); ASSERT(pos->uArmyScaler[WHITE] <= 31); #ifdef EVAL_TIME ctx->sCounters.tree.u64CyclesEvalMaterialSetup += (SystemReadTimeStampCounter() - u64MaterialSetupTimer); #endif if ((TRUE == g_fUseNnueEval) && (TRUE == g_fNnueWeightsLoaded)) { // p98 of |NnueForward() - NnueProbeScore()| per material // bucket. Superseded 2026-10-15: originally derived from a // 91M-sample population over three curated tactical suites // (sd 10) -- replaced same day by a far larger and more // representative 3.09-BILLION-sample population, 16 parallel // shards of 12,500 positions each (200,000 total) from // tests/cross_sectional_200k.ep_ at sd 6. Per-suite tactical // positions are a narrow, biased slice (selected for sharp // tactics); the cross-sectional pool's much broader position // variety surfaced real outlier swings the narrower sample // never saw (max up to 534cp here vs ~472cp before) while // landing close to the same per-bucket numbers overall (mostly // 0-10cp different) -- see docs/NNUE.md's "Lazy-evaluation // tiering plan". Same bucketing as _MaterialBucket (combined // army scaler, width BASE_MARGIN_MAT_WIDTH). static const SCORE iNnueLazyMarginByMatBucket[BASE_MARGIN_MAT_BUCKETS] = { 180, 200, 190, 180, 170, 160, 150, 150, }; #ifdef CALIBRATE_MARGIN_SAFETY // Calibration build: ALWAYS run the real forward pass, never // skip it -- so any candidate gate decision can keep being // measured against ground truth before it's trusted live. // When the gate is enabled, measure against the real chosen // margin (making "exceeded" a meaningful, ongoing validation // signal); when disabled, still measure against an // effectively-infinite sentinel (pure observation, matches // this harness's original pre-gate behavior). SCORE iNnueScore = NnueForward(ctx); if (TRUE == g_fNnueProbeLoaded) { SCORE iProbeScore = NnueProbeScore(ctx); SCORE iSwing = (SCORE)abs((int)iNnueScore - (int)iProbeScore); SCORE iMarginUsed = (TRUE == g_fUseNnueLazyProbe) ? iNnueLazyMarginByMatBucket[_MaterialBucket(pos)] : INFINITY_SCORE; RecordNnueLazyMarginSafetySwing(pos, iSwing, iMarginUsed); } { // Material-only "super lazy" measurement -- no fit, no // probe, just the already-maintained material balance // (same cp units as NnueForward's output, see // RecordNnueSuperLazyMarginSafetySwing). No real margin // chosen yet, so always the infinite sentinel for now. SCORE iSuperLazyScore = pos->iMaterialBalance[pos->uToMove]; SCORE iSuperLazySwing = (SCORE)abs((int)iNnueScore - (int)iSuperLazyScore); RecordNnueSuperLazyMarginSafetySwing(pos, iSuperLazySwing, INFINITY_SCORE); } // This branch always returns the real forward pass (never // skips, by design -- see the big comment above), so it's // unconditionally the NNUE_FULL tier for futility-margin // selection purposes. ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_NNUE_FULL; g_u64NnueFullEvalsByBucket[_MaterialBucket(pos)]++; if (NULL != piPositional) { (*piPositional)[WHITE] = 0; (*piPositional)[BLACK] = 0; } return iNnueScore; #else // Production build: if the lazy probe gate is enabled and // confidently resolves the fail-high/fail-low question // relative to [iAlpha, iBeta], skip the real forward pass // entirely -- this is the actual speed win. Otherwise (gate // disabled, probe not loaded, or inconclusive), fall through // to the full pass exactly as before this feature existed. // Super-lazy pre-filter, experimental -- 2026-10-16: cheapest // possible check, pure material balance, no net evaluation at // all. Previously measurement-only (CALIBRATE_MARGIN_SAFETY // above records the real swing but always used an infinite // sentinel margin, i.e. never actually gated). Deliberately // loose/uncalibrated here per the "safety doesn't win games" // experiment -- g_iNnueSuperLazyMargin is a flat runtime // override (see nnueeval.c), not a per-bucket fit. if (TRUE == g_fUseNnueSuperLazy) { SCORE iSuperLazyScore = pos->iMaterialBalance[pos->uToMove]; if (((iSuperLazyScore - g_iNnueSuperLazyMargin) > iBeta) || ((iSuperLazyScore + g_iNnueSuperLazyMargin) < iAlpha)) { // Feed the same aggregate counters root.c's "Eval exit // breakdown" line reads -- otherwise that line stays // 0/0/0 under NNUE eval since it was only ever wired // to the HCE's own super-lazy/lazy/full exit sites. INC(ctx->sCounters.tree.u64SuperLazyEvals); ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_NNUE_LAZY; g_u64NnueLazyEvalsByBucket[_MaterialBucket(pos)]++; if (NULL != piPositional) { (*piPositional)[WHITE] = 0; (*piPositional)[BLACK] = 0; } return iSuperLazyScore; } } if ((TRUE == g_fUseNnueLazyProbe) && (TRUE == g_fNnueProbeLoaded)) { SCORE iProbeScore = NnueProbeScore(ctx); SCORE iMargin = (g_iNnueLazyMarginOverride >= 0) ? (SCORE)g_iNnueLazyMarginOverride : iNnueLazyMarginByMatBucket[_MaterialBucket(pos)]; if (((iProbeScore - iMargin) > iBeta) || ((iProbeScore + iMargin) < iAlpha)) { INC(ctx->sCounters.tree.u64LazyEvals); ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_NNUE_LAZY; g_u64NnueLazyEvalsByBucket[_MaterialBucket(pos)]++; if (NULL != piPositional) { (*piPositional)[WHITE] = 0; (*piPositional)[BLACK] = 0; } return iProbeScore; } } { SCORE iNnueScore = NnueForward(ctx); INC(ctx->sCounters.tree.u64FullEvals); ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_NNUE_FULL; g_u64NnueFullEvalsByBucket[_MaterialBucket(pos)]++; if (NULL != piPositional) { (*piPositional)[WHITE] = 0; (*piPositional)[BLACK] = 0; } return iNnueScore; } #endif } #ifdef DUMP_RESIDUAL_SAMPLES // Super-lazy's OWN baseline -- material only, before _EvalPawns // even runs. Separate from iResidualBaselineWhite/Black below // (captured after bishop pairs, i.e. regular-lazy's baseline): // that measurement deliberately excludes pawns/passers/bad-trade/ // bishop-pairs, which is correct for regular lazy (which already // has all of that by the time it asks) but wrong for super-lazy, // which has NONE of it yet. This is what a super-lazy-scoped // residual needs to be measured against instead. SCORE iSuperLazyResidualBaselineWhite = pos->iScore[WHITE]; SCORE iSuperLazyResidualBaselineBlack = pos->iScore[BLACK]; #endif // 2026-09-16: shared "too dangerous to shortcut" gate for both lazy // tiers -- exactly the condition search.c's own passer-race code // (_EvalPasserRacesAgainstLoneKings' caller) uses to decide whether // the volatile won-passer-race verdict can fire: one side down to // literally just a king (TotalNonPawnCount counts the king itself // as 1, so ==1 means no other non-pawn material at all). Regular // lazy already had a blunter, broader guard for this material // region (LAZY_EVAL_MIN_MATERIAL, a combined-army-scaler band) -- // but that band doesn't actually imply either side is bare-king // (e.g. a heavy attacker vs. a bare king can have a large combined // scaler despite one side having zero other material), so it // wasn't sufficient on its own. Super-lazy had no such guard at // all. Folding EvalLookForDrawishSituations into both tiers (above/ // below) closes the "insufficient winning chances"/BOOC/50-move // gap; this closes the remaining one -- the passer-race verdict // needs pHash->bbPasserLocations, which isn't available yet at // super-lazy's point in Eval() (it runs before _EvalPawns), so // that correction can't cheaply be folded in the same way and the // honest answer here is to just not shortcut in this regime. FLAG fBareKingEitherSide = (1 == TotalNonPawnCount(pos, WHITE)) || (1 == TotalNonPawnCount(pos, BLACK)); // Super-lazy exit point. #ifdef LAZY_EVAL // Combined-army bucket, still needed by the bucket-0 exclusion // below (a structural exclusion of pawn-dominated near-bare-army // positions, unrelated to the margin construction itself). ULONG uSuperLazyMatBucket = MINU( 7, (pos->uArmyScaler[WHITE] + pos->uArmyScaler[BLACK]) / 8); // 2026-09-16: exclude material bucket 0 (combined non-pawn army // scaler 0-7) from super-lazy entirely -- CALIBRATE_MARGIN_SAFETY // against 30k stratified positions found a 6.8% exceeded rate // there even after the bare-king exclusion above and the // EvalLookForDrawishSituations fix, traced by hand to real, // externally-corroborated (cross-checked against Crafty's own eval // breakdown on the same position, within 7%) swings of 650-750+ // centipawns from knight-vs-bishop-with-several-pawns-per-side // endgames. Root cause: this bucket is defined purely by non-pawn // material, so it says nothing about how many pawns are on the // board, and super-lazy runs before _EvalPawns entirely -- meaning // it's not just imprecise about pawn structure here, it's totally // blind to it, in exactly the material regime where pawns (passed- // pawn recognition, king-supports-own-passer, _ReEvalPassers) can // be nearly the entire evaluation. Not a bug to fix with a bigger // constant -- a structural mismatch between what this bucket // measures (piece count) and what actually drives the score // (pawn count) in this exact material range. Bucket 1+ (scaler // >=8) doesn't have this problem to nearly the same degree since // there's enough non-pawn material for pieces to matter alongside // pawns, not be dwarfed by them. if ((FALSE == fBareKingEitherSide) && (uSuperLazyMatBucket > 0)) { #ifdef EVAL_TIME UINT64 uSuperLazyTimer = SystemReadTimeStampCounter(); #endif iScoreForSideToMove = pos->iMaterialBalance[uColor]; ASSERT(IS_VALID_SCORE(iScoreForSideToMove)); // We have a super-rough eval -- material only at this point. // Compute two margins to check whether things look so good or // bad that we need not refine our eval because we are sure to // FH/FL anyway. ULONG uSuperLazyMyBucket = MINU(7, pos->uArmyScaler[uColor] / 4); ULONG uSuperLazyOppBucket = MINU(7, pos->uArmyScaler[xColor] / 4); SCORE iSuperLazySelfPessEnemyOptMargin = MAX0( (iKingP98ByAttackerArmy[uSuperLazyMyBucket] - iKingP2ByAttackerArmy[uSuperLazyOppBucket]) + (iSuperLazyResidualOptimisticByOwnArmy[uSuperLazyOppBucket] - iSuperLazyResidualPessimisticByOwnArmy[uSuperLazyMyBucket])); SCORE iSuperLazySelfOptEnemyPessMargin = MAX0( (iKingP98ByAttackerArmy[uSuperLazyOppBucket] - iKingP2ByAttackerArmy[uSuperLazyMyBucket]) + (iSuperLazyResidualOptimisticByOwnArmy[uSuperLazyMyBucket] - iSuperLazyResidualPessimisticByOwnArmy[uSuperLazyOppBucket])); if (iScoreForSideToMove + iSuperLazySelfOptEnemyPessMargin < iAlpha) { ASSERT(iScoreForSideToMove < iAlpha); #ifdef CALIBRATE_MARGIN_SAFETY iSavedSuperLazyMarginUsed = iSuperLazySelfOptEnemyPessMargin; #endif INC(ctx->sCounters.tree.u64SuperLazyEvals); g_u64SuperLazyEvalsByBucket[_MaterialBucket(pos)]++; if (NULL != piPositional) { // 2026-09-17: no longer flat 0 -- same p50-based typical- // value estimate as regular lazy, using the super-lazy- // scoped residual table (material-only baseline). See // iKingP50ByAttackerArmy/iSuperLazyResidualP50By- // OwnArmy (file-scope, above). ULONG uWhiteBucket = MINU(7, pos->uArmyScaler[WHITE] / 4); ULONG uBlackBucket = MINU(7, pos->uArmyScaler[BLACK] / 4); (*piPositional)[WHITE] = iKingP50ByAttackerArmy[uBlackBucket] + iSuperLazyResidualP50ByOwnArmy[uWhiteBucket]; (*piPositional)[BLACK] = iKingP50ByAttackerArmy[uWhiteBucket] + iSuperLazyResidualP50ByOwnArmy[uBlackBucket]; ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_SUPERLAZY; } #ifdef EVAL_TIME ctx->sCounters.tree.u64CyclesEvalSuperLazy += (SystemReadTimeStampCounter() - uSuperLazyTimer); #endif #ifdef CALIBRATE_MARGIN_SAFETY // Don't exit yet -- let the real full eval run below so we // can measure the true swing against SUPER_LAZY_MARGIN, // then restore this exact (zeroed) piPositional right // before `end:` so the caller sees what a normal build // would have returned. fWouldHaveExitedSuperLazy = TRUE; iSavedSuperLazyScore = iScoreForSideToMove; #else #ifdef EVAL_TIME ctx->sCounters.tree.u64CyclesEvalPreLazy += (SystemReadTimeStampCounter() - uTimer); ctx->sCounters.tree.u64CyclesSuperLazyExit += (SystemReadTimeStampCounter() - uTimer); ctx->sCounters.tree.u64CyclesInEval += (SystemReadTimeStampCounter() - uTimer); #endif goto end; #endif } if (iScoreForSideToMove - iSuperLazySelfPessEnemyOptMargin > iBeta) { ASSERT(iScoreForSideToMove > iBeta); #ifdef CALIBRATE_MARGIN_SAFETY iSavedSuperLazyMarginUsed = iSuperLazySelfPessEnemyOptMargin; #endif INC(ctx->sCounters.tree.u64SuperLazyEvals); g_u64SuperLazyEvalsByBucket[_MaterialBucket(pos)]++; if (NULL != piPositional) { // See the analogous alpha-side branch above -- same p50 // typical-value estimate. ULONG uWhiteBucket = MINU(7, pos->uArmyScaler[WHITE] / 4); ULONG uBlackBucket = MINU(7, pos->uArmyScaler[BLACK] / 4); (*piPositional)[WHITE] = iKingP50ByAttackerArmy[uBlackBucket] + iSuperLazyResidualP50ByOwnArmy[uWhiteBucket]; (*piPositional)[BLACK] = iKingP50ByAttackerArmy[uWhiteBucket] + iSuperLazyResidualP50ByOwnArmy[uBlackBucket]; ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_SUPERLAZY; } #ifdef EVAL_TIME ctx->sCounters.tree.u64CyclesEvalSuperLazy += (SystemReadTimeStampCounter() - uSuperLazyTimer); #endif #ifdef CALIBRATE_MARGIN_SAFETY fWouldHaveExitedSuperLazy = TRUE; iSavedSuperLazyScore = iScoreForSideToMove; #else #ifdef EVAL_TIME ctx->sCounters.tree.u64CyclesEvalPreLazy += (SystemReadTimeStampCounter() - uTimer); ctx->sCounters.tree.u64CyclesSuperLazyExit += (SystemReadTimeStampCounter() - uTimer); ctx->sCounters.tree.u64CyclesInEval += (SystemReadTimeStampCounter() - uTimer); #endif goto end; #endif } #ifdef EVAL_TIME ctx->sCounters.tree.u64CyclesEvalSuperLazy += (SystemReadTimeStampCounter() - uSuperLazyTimer); #endif } #endif // If we get here, we did not take the super lazy exit. This is // either a lazy exit node or a full eval node. // Pawn eval. Note: if fDeferred comes back as TRUE then we have // neither cleared nor initialized the attack tables. This is // because we hope that we can still get a lazy eval exit here and // save some time. BEFORE ANY CODE BELOW TOUCHES THE ATTACK // TABLES IT NEEDS TO CLEAR/POPULATE THEM THOUGH!!! #ifdef EVAL_TIME UINT64 u64PawnTimer = SystemReadTimeStampCounter(); pHash = EvalPawns(ctx, &fDeferred); { UINT64 u64Elapsed = SystemReadTimeStampCounter() - u64PawnTimer; ctx->sCounters.tree.u64CyclesEvalPawns += u64Elapsed; if (fDeferred) { ctx->sCounters.tree.u64CyclesEvalPawnsHit += u64Elapsed; ctx->sCounters.tree.u64CountEvalPawnsHit++; } else { ctx->sCounters.tree.u64CyclesEvalPawnsMiss += u64Elapsed; ctx->sCounters.tree.u64CountEvalPawnsMiss++; } } #else pHash = EvalPawns(ctx, &fDeferred); #endif ASSERT(NULL != pHash); ASSERT(IS_VALID_FLAG(fDeferred)); pos->iScore[uColor] = (PawnMaterial(pos, uColor) + pos->uNonPawnMaterial[uColor] + pHash->iScore[uColor]); pos->iScore[xColor] = (PawnMaterial(pos, xColor) + pos->uNonPawnMaterial[xColor] + pHash->iScore[xColor]); ASSERT(IS_VALID_SCORE(pos->iScore[WHITE] - pos->iScore[BLACK])); #ifdef EVAL_DUMP Trace("After pawns + material:\n%d\t\t%d\t\t(%d for %s)\n", pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif // Look for won passers races. Note: This code cannot trust the // state of the attack tables yet! #ifdef EVAL_TIME UINT64 u64PasserBadtradeBishopTimer = SystemReadTimeStampCounter(); #endif if (fBareKingEitherSide) { // // Pure king-and-pawns on BOTH sides: try the new, // exhaustively-verified shared logic first (see // _EvalUnstoppablePasser's header comment) -- it's trustworthy // whenever it has something to say. But it only ever fires for // the true-lone-king sub-case and stays silent (FALSE) for the // "both sides still have pawns" sub-case, which the old, // broader-but-dodgier heuristic used to cover -- fall back to // that old heuristic rather than simply losing that coverage. // Anything broader than pure KPvKP (one bare side, but the // OTHER side still has real pieces -- e.g. K+R+P vs K) always // uses the old heuristic unchanged; that shape was never // covered by this session's KPvKP investigation. // if ((1 == TotalNonPawnCount(pos, WHITE)) && (1 == TotalNonPawnCount(pos, BLACK))) { if (FALSE == _EvalUnstoppablePasser(pos)) { (void)_EvalPasserRacesAgainstLoneKings(ctx, pHash); } } else { (void)_EvalPasserRacesAgainstLoneKings(ctx, pHash); } #ifdef EVAL_DUMP Trace("After passer races:\n%d\t\t%d\t\t(%d for %s)\n", pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif } // Bad trade code. Note: this code cannot trust the state of the // attack tables... if (pos->uNonPawnMaterial[WHITE] != pos->uNonPawnMaterial[BLACK]) { _EvalBadTrades(pos); #ifdef EVAL_DUMP Trace("After bad trades:\n%d\t\t%d\t\t(%d for %s)\n", pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif } // Bishop pairs. Again... Note: this code cannot trust the state // of the attack tables. _EvalBishopPairs(pos); #ifdef EVAL_DUMP Trace("After bishop pair bonus:\n%d\t\t%d\t\t(%d for %s)\n", pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif #ifdef EVAL_TIME ctx->sCounters.tree.u64CyclesEvalPasserBadtradeBishop += (SystemReadTimeStampCounter() - u64PasserBadtradeBishopTimer); #endif #ifdef DUMP_RESIDUAL_SAMPLES // Snapshot right here: material + pawns/passers + bad-trade + // bishop pairs, before king safety or mobility/misc positional // terms run. Subtracting this (the same baseline regular lazy // itself reads its score from) plus the real per-side king score // (ctx->sPlyInfo[ctx->uPly].iKingScore[color], stored once // _EvalKing runs for that side) from the final full-eval score // isolates exactly what iResidualP98 is trying to estimate: // mobility + trapped pieces + everything else, with passers // already excluded. See the dump site below, near "Almost done". SCORE iResidualBaselineWhite = pos->iScore[WHITE]; SCORE iResidualBaselineBlack = pos->iScore[BLACK]; #endif #ifdef LAZY_EVAL // Below LAZY_EVAL_MIN_MATERIAL combined army scaler, skip lazy eval // entirely (see its chess.h comment) -- measured directly via // CALIBRATE_MARGIN_SAFETY, the regular lazy exit's real swing // exceeded its own assumed margin 20.6% of the time in near-bare- // king endgames, far above the ~0.01-0.36% rate everywhere else. // fBareKingEitherSide (set above, before the super-lazy exit point) // is a separate, more precise guard for the specific passer-race // mechanism -- kept in addition to this band, not instead of it, // since a heavy attacker vs. a bare king can still clear this // combined-scaler threshold despite one side being bare-king. if ((pos->uArmyScaler[WHITE] + pos->uArmyScaler[BLACK] >= LAZY_EVAL_MIN_MATERIAL) && (FALSE == fBareKingEitherSide)) { #ifdef EVAL_TIME UINT64 uLazyDecisionTimer = SystemReadTimeStampCounter(); #endif // // Compute an estimate of the score for the side to move based on the // eval terms we have already considered: // // 1. Material balance // 2. Pawn structure bonuses/penalties (incl passers/candidates) // 3. Passer races are detected already // 4. "Bad trade" code has already run // 5. Bishop pairs // iScoreForSideToMove = (pos->iScore[uColor] - pos->iScore[xColor]); ASSERT(IS_VALID_SCORE(iScoreForSideToMove)); // 2026-09-16: item 5 used to claim "we've already detected // unwinnable endgames" here, but nothing before this point // actually did -- EvalLookForDrawishSituations (insufficient- // winning-chances squash, BOOC, 50-move dampening) was only // ever called once, at the very end of the FULL eval path // (see its call site below), so a regular-lazy exit could // return a raw material-ahead score (e.g. "+300, bishop up") // in a position full eval would have squashed hard toward a // draw (BOOC: /4; no forcing material: /16) -- a large swing // with nothing to do with king safety or mobility. Call it // here too so regular lazy sees the same correction full eval // would apply. Cheap and safe to do this early: unlike // king safety/mobility, none of EvalLookForDrawishSituations' // three checks touch attack bitboards, only piece bitboards/ // counts and pos->uFifty, all already valid by this point. // _EnsureDrawishFactsComputed is a no-op if the call site // below (full eval, if this node falls through to it) already // populated sDrawishFacts -- can't happen in this order since // this is the first potential call site, but written this way // so either call order is correct. TIMED_EVAL_CALL(ctx, u64CyclesEvalDrawish, (_EnsureDrawishFactsComputed(pos, uColor, &sDrawishFacts), EvalLookForDrawishSituations(pos, &iScoreForSideToMove, &sDrawishFacts))); // // Eval has not considered several potentially large terms: // // 1. Piece positional components (such as mobility, trapped) // 2. King safety penalties (which can be large!) // 3. Other miscellaneous bonuses/penalties // // We build two "margins" to account for these components of the // score. // // 2026-09-17: no flat base margin, no floor -- matches super- // lazy's convention. margin_a'/margin_b' (built entirely by // EstimatePositionalScore below) stand alone. If CALIBRATE_ // MARGIN_SAFETY turns up a real, non-trivial exceeded rate once // this is validated against the 30k pool, the fix is tightening // the percentile choice there (e.g. p95/p5 or p99/p1), not // resurrecting a flat backstop that would just override the // position-specific estimate again. iAlphaMargin = iBetaMargin = 0; #ifdef CALIBRATE_POSITIONAL ctx->fCalibrateCandidate = FALSE; g_uCalibrateGateChecked++; #endif #ifdef CALIBRATE_POSITIONAL g_uCalibrateGateTrue++; #endif // // Ok, we can't say for sure that we won't take a lazy exit // yet. So do the expensive part of lazy eval estimation and // widen the margin further for king safety issues and passed // pawns. // #ifdef CALIBRATE_POSITIONAL // This node is one where a real (uninstrumented) build would // actually call EstimatePositionalScore and consider a lazy // exit -- the population _RecordPositionalCalibration should // be sampling from, per _EvalKing's calls below. ctx->fCalibrateCandidate = TRUE; #endif EstimatePositionalScore(ctx, pos, pHash, &iAlphaMargin, &iBetaMargin); #ifdef CALIBRATE_BASE_MARGIN ULONG uBucket = _MaxKingDangerBucket(ctx, pos, pHash); ULONG uMatBucket = _MaterialBucket(pos); g_uBaseMarginExitAttempted[uMatBucket][uBucket]++; if ((iScoreForSideToMove + iAlphaMargin <= iAlpha) || (iScoreForSideToMove - iBetaMargin >= iBeta)) { g_uBaseMarginExitTaken[uMatBucket][uBucket]++; } #endif // CALIBRATE_POSITIONAL builds never take the lazy exit here -- // the whole point of a calibration run is to compute the cheap // defect-count estimate *and* let Eval() continue on to // _EvalKing's real computation on every node, so the two can be // logged and compared. See _RecordPositionalCalibration below // (called from _EvalKing) and DumpPositionalCalibration // (command.c's "calibrate dump"). #ifndef CALIBRATE_POSITIONAL if (iScoreForSideToMove + iAlphaMargin <= iAlpha) { INC(ctx->sCounters.tree.u64LazyEvals); g_u64LazyEvalsByBucket[_MaterialBucket(pos)]++; if (NULL != piPositional) { // 2026-09-17: no longer flat 0 -- a p50-based typical- // value estimate of this side's own missing positional // terms (king safety + residual), matching full-eval's // own iPositional convention (that side's own real // positional score, not a relative-to-opponent // quantity). See iKingP50ByAttackerArmy/ // iResidualP50ByOwnArmy (file-scope, above) for the // full percentile charts this was derived from. ULONG uWhiteBucket = MINU(7, pos->uArmyScaler[WHITE] / 4); ULONG uBlackBucket = MINU(7, pos->uArmyScaler[BLACK] / 4); (*piPositional)[WHITE] = iKingP50ByAttackerArmy[uBlackBucket] + iResidualP50ByOwnArmy[uWhiteBucket]; (*piPositional)[BLACK] = iKingP50ByAttackerArmy[uWhiteBucket] + iResidualP50ByOwnArmy[uBlackBucket]; ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_LAZY; } #ifdef EVAL_TIME ctx->sCounters.tree.u64CyclesEvalPreLazy += (SystemReadTimeStampCounter() - uTimer); #endif #ifdef CALIBRATE_MARGIN_SAFETY // Don't exit yet -- let the real full eval run below so we // can measure the true swing, then restore these values // right before `end:` so the caller sees exactly what a // normal build would have returned. fWouldHaveExited = TRUE; iSavedLazyScore = iScoreForSideToMove; iSavedLazyPositional = iAlphaMargin; iSavedLazyPositionalWhite = iKingP50ByAttackerArmy[MINU(7, pos->uArmyScaler[BLACK] / 4)] + iResidualP50ByOwnArmy[MINU(7, pos->uArmyScaler[WHITE] / 4)]; iSavedLazyPositionalBlack = iKingP50ByAttackerArmy[MINU(7, pos->uArmyScaler[WHITE] / 4)] + iResidualP50ByOwnArmy[MINU(7, pos->uArmyScaler[BLACK] / 4)]; #else #ifdef EVAL_TIME ctx->sCounters.tree.u64CyclesEvalLazyDecision += (SystemReadTimeStampCounter() - uLazyDecisionTimer); ctx->sCounters.tree.u64CyclesLazyExit += (SystemReadTimeStampCounter() - uTimer); ctx->sCounters.tree.u64CyclesInEval += (SystemReadTimeStampCounter() - uTimer); #endif goto end; #endif } else if (iScoreForSideToMove - iBetaMargin >= iBeta) { INC(ctx->sCounters.tree.u64LazyEvals); g_u64LazyEvalsByBucket[_MaterialBucket(pos)]++; if (NULL != piPositional) { // See the analogous fail-low branch above -- same p50 // typical-value estimate, not a flat 0 or the margin // itself. ULONG uWhiteBucket = MINU(7, pos->uArmyScaler[WHITE] / 4); ULONG uBlackBucket = MINU(7, pos->uArmyScaler[BLACK] / 4); (*piPositional)[WHITE] = iKingP50ByAttackerArmy[uBlackBucket] + iResidualP50ByOwnArmy[uWhiteBucket]; (*piPositional)[BLACK] = iKingP50ByAttackerArmy[uWhiteBucket] + iResidualP50ByOwnArmy[uBlackBucket]; ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_LAZY; } #ifdef EVAL_TIME ctx->sCounters.tree.u64CyclesEvalPreLazy += (SystemReadTimeStampCounter() - uTimer); #endif #ifdef CALIBRATE_MARGIN_SAFETY fWouldHaveExited = TRUE; iSavedLazyScore = iScoreForSideToMove; iSavedLazyPositional = iBetaMargin; iSavedLazyPositionalWhite = iKingP50ByAttackerArmy[MINU(7, pos->uArmyScaler[BLACK] / 4)] + iResidualP50ByOwnArmy[MINU(7, pos->uArmyScaler[WHITE] / 4)]; iSavedLazyPositionalBlack = iKingP50ByAttackerArmy[MINU(7, pos->uArmyScaler[WHITE] / 4)] + iResidualP50ByOwnArmy[MINU(7, pos->uArmyScaler[BLACK] / 4)]; #else #ifdef EVAL_TIME ctx->sCounters.tree.u64CyclesEvalLazyDecision += (SystemReadTimeStampCounter() - uLazyDecisionTimer); ctx->sCounters.tree.u64CyclesLazyExit += (SystemReadTimeStampCounter() - uTimer); ctx->sCounters.tree.u64CyclesInEval += (SystemReadTimeStampCounter() - uTimer); #endif goto end; #endif } #endif // !CALIBRATE_POSITIONAL #ifdef EVAL_TIME ctx->sCounters.tree.u64CyclesEvalLazyDecision += (SystemReadTimeStampCounter() - uLazyDecisionTimer); #endif } // lazy eval #endif #ifdef EVAL_TIME ctx->sCounters.tree.u64CyclesEvalPreLazy += (SystemReadTimeStampCounter() - uTimer); #endif // If we get here we are doing a full eval. ctx->sPlyInfo[ctx->uPly].u64FullEvalSig = (pos->u64NonPawnSig ^ pos->u64PawnSig); // See if we have to clear/populate the pawn attack table. if (TRUE == fDeferred) { TIMED_EVAL_CALL(ctx, u64CyclesEvalAttackTablePop, _PopulatePawnAttackBits(pos)); } // Pre-compute some common terms used in per-piece evals: pos->uNumTrapped[BLACK] = pos->uNumTrapped[WHITE] = 0; pos->iReducedMaterialDownScaler[BLACK] = pos->iReducedMaterialDownScaler[WHITE] = 0; pos->uMinorsAtHome[BLACK] = pos->uMinorsAtHome[WHITE] = 0; // // Evaluate individual pieces. // // Precomputed once per color instead of rebuilt by every bishop/ // rook/queen of that color (see MOBILITY_BITBOARD_REWRITE.md's // "squeeze it" follow-up). bbEnemyRQK/bbEnemyQK depend only on // static piece locations -- no ordering dependency, safe to build // right here before any piece loop runs. bbUnsafeForRook/ // bbUnsafeForQueen are filled in below, at the loop boundary where // their inputs are guaranteed complete (both colors' knight+bishop // passes before rook; both colors' pawn/minor/rook passes before // queen) -- NOT incrementally mutated during a loop, which would // let one piece's own attack leak into its same-color sibling's // "unsafe" mask. BITBOARD bbEnemyRQK[2]; BITBOARD bbEnemyQK[2]; BITBOARD bbUnsafeForRook[2]; BITBOARD bbUnsafeForQueen[2]; bbEnemyQK[WHITE] = pos->bbPieces[WHITE][QUEEN] | COOR_TO_BB(pos->cKingSq[WHITE]); bbEnemyQK[BLACK] = pos->bbPieces[BLACK][QUEEN] | COOR_TO_BB(pos->cKingSq[BLACK]); bbEnemyRQK[WHITE] = bbEnemyQK[WHITE] | pos->bbPieces[WHITE][ROOK]; bbEnemyRQK[BLACK] = bbEnemyQK[BLACK] | pos->bbPieces[BLACK][ROOK]; // Knights. bb = pos->bbPieces[uColor][KNIGHT]; while (bb) { u = FastFirstBit(bb) - 1; bb &= (bb - 1); c = BIT_NUMBER_TO_COOR(u); TIMED_EVAL_CALL(ctx, u64CyclesEvalKnight, _EvalKnight(pos, c, pHash)); #ifdef EVAL_DUMP Trace("After our N at %s:\n%d\t\t%d\t\t(%d for %s)\n", CoorToString(c), pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif } // Enemy knights. ASSERT(xColor != pos->uToMove); bb = pos->bbPieces[xColor][KNIGHT]; while (bb) { u = FastFirstBit(bb) - 1; bb &= (bb - 1); c = BIT_NUMBER_TO_COOR(u); TIMED_EVAL_CALL(ctx, u64CyclesEvalKnight, _EvalKnight(pos, c, pHash)); #ifdef EVAL_DUMP Trace("After enemy N at %s:\n%d\t\t%d\t\t(%d for %s)\n", CoorToString(c), pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif } // Bishops. bb = pos->bbPieces[uColor][BISHOP]; while (bb) { u = FastFirstBit(bb) - 1; bb &= (bb - 1); c = BIT_NUMBER_TO_COOR(u); TIMED_EVAL_CALL(ctx, u64CyclesEvalBishop, _EvalBishop(pos, c, pHash, bbEnemyRQK[xColor])); #ifdef EVAL_DUMP Trace("After our B at %s:\n%d\t\t%d\t\t(%d for %s)\n", CoorToString(c), pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif } // Enemy bishops. bb = pos->bbPieces[xColor][BISHOP]; while (bb) { u = FastFirstBit(bb) - 1; bb &= (bb - 1); c = BIT_NUMBER_TO_COOR(u); TIMED_EVAL_CALL(ctx, u64CyclesEvalBishop, _EvalBishop(pos, c, pHash, bbEnemyRQK[uColor])); #ifdef EVAL_DUMP Trace("After enemy B at %s:\n%d\t\t%d\t\t(%d for %s)\n", CoorToString(c), pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif } // Both colors' knight+bishop passes are complete now -- safe to // build both colors' "unsafe for rook" masks once, here, instead of // every rook rebuilding its own color's mask from scratch. bbUnsafeForRook[WHITE] = pos->bbPawnAttacks[BLACK] | pos->bbMinorAttacks[BLACK]; bbUnsafeForRook[BLACK] = pos->bbPawnAttacks[WHITE] | pos->bbMinorAttacks[WHITE]; // Rooks. bb = pos->bbPieces[uColor][ROOK]; while (bb) { u = FastFirstBit(bb) - 1; bb &= (bb - 1); c = BIT_NUMBER_TO_COOR(u); TIMED_EVAL_CALL(ctx, u64CyclesEvalRook, _EvalRook(pos, c, pHash, bbEnemyQK[xColor], bbUnsafeForRook[uColor])); #ifdef EVAL_DUMP Trace("After our R at %s:\n%d\t\t%d\t\t(%d for %s)\n", CoorToString(c), pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif } // Enemy rooks. bb = pos->bbPieces[xColor][ROOK]; while (bb) { u = FastFirstBit(bb) - 1; bb &= (bb - 1); c = BIT_NUMBER_TO_COOR(u); TIMED_EVAL_CALL(ctx, u64CyclesEvalRook, _EvalRook(pos, c, pHash, bbEnemyQK[uColor], bbUnsafeForRook[xColor])); #ifdef EVAL_DUMP Trace("After enemy R at %s:\n%d\t\t%d\t\t(%d for %s)\n", CoorToString(c), pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif } // Both colors' pawn/minor/rook passes are complete now -- safe to // build both colors' "unsafe for queen" masks once, here, instead // of every queen rebuilding its own color's mask from scratch (most // positions only have one queen per side anyway, so this mainly // pays off on promoted-extra-queen positions, but it's free either // way). bbUnsafeForQueen[WHITE] = pos->bbPawnAttacks[BLACK] | pos->bbMinorAttacks[BLACK] | pos->bbRookAttacks[BLACK] | (g_KingAttacksBB[pos->cKingSq[BLACK]] & ~(pos->bbPawnAttacks[WHITE] | pos->bbMinorAttacks[WHITE] | pos->bbRookAttacks[WHITE])); bbUnsafeForQueen[BLACK] = pos->bbPawnAttacks[WHITE] | pos->bbMinorAttacks[WHITE] | pos->bbRookAttacks[WHITE] | (g_KingAttacksBB[pos->cKingSq[WHITE]] & ~(pos->bbPawnAttacks[BLACK] | pos->bbMinorAttacks[BLACK] | pos->bbRookAttacks[BLACK])); // Our queen(s). bb = pos->bbPieces[uColor][QUEEN]; while (bb) { u = FastFirstBit(bb) - 1; bb &= (bb - 1); c = BIT_NUMBER_TO_COOR(u); TIMED_EVAL_CALL(ctx, u64CyclesEvalQueen, _EvalQueen(pos, c, pHash, bbEnemyQK[xColor], bbUnsafeForQueen[uColor])); #ifdef EVAL_DUMP Trace("After our Q at %s:\n%d\t\t%d\t\t(%d for %s)\n", CoorToString(c), pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif } // Enemy queen(s). bb = pos->bbPieces[xColor][QUEEN]; while (bb) { u = FastFirstBit(bb) - 1; bb &= (bb - 1); c = BIT_NUMBER_TO_COOR(u); TIMED_EVAL_CALL(ctx, u64CyclesEvalQueen, _EvalQueen(pos, c, pHash, bbEnemyQK[uColor], bbUnsafeForQueen[xColor])); #ifdef EVAL_DUMP Trace("After enemy Q at %s:\n%d\t\t%d\t\t(%d for %s)\n", CoorToString(c), pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif } // Evaluate the two kings last. c = KingPosition(pos, uColor); #ifdef DEBUG ASSERT(IS_ON_BOARD(c)); { PIECE pDebugKing = pos->rgSquare[c].pPiece; ASSERT(IS_VALID_PIECE(pDebugKing)); ASSERT(GET_COLOR(pDebugKing) == uColor); ASSERT(IS_KING(pDebugKing)); } #endif TIMED_EVAL_CALL(ctx, u64CyclesEvalKing, _EvalKing(pos, c, pHash, ctx)); #ifdef EVAL_DUMP Trace("After our K at %s:\n%d\t\t%d\t\t(%d for %s)\n", CoorToString(c), pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif c = KingPosition(pos, xColor); #ifdef DEBUG ASSERT(IS_ON_BOARD(c)); { PIECE pDebugKing = pos->rgSquare[c].pPiece; ASSERT(IS_VALID_PIECE(pDebugKing)); ASSERT(GET_COLOR(pDebugKing) == xColor); ASSERT(IS_KING(pDebugKing)); } #endif TIMED_EVAL_CALL(ctx, u64CyclesEvalKing, _EvalKing(pos, c, pHash, ctx)); #ifdef EVAL_DUMP Trace("After enemy K at %s:\n%d\t\t%d\t\t(%d for %s)\n", CoorToString(c), pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif // Now that we have the whole attack table generated, think about // passed pawns identified by the pawn eval routine again. Also // see if the side not on move has a trapped piece. #ifdef EVAL_TIME UINT64 u64PostLazyMiscTimer = SystemReadTimeStampCounter(); #endif bb = (pHash->bbPasserLocations[WHITE] | pHash->bbPasserLocations[BLACK]); if (0 != bb) { _ReEvalPassers(pos, pHash); #ifdef EVAL_DUMP Trace("After re-eval passers:\n%d\t\t%d\t\t(%d for %s)\n", pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif } // _EvalLookForDanger/_EvalTrappedPieces only ever *add* a hint // when they find one; a full eval that finds nothing this time // would otherwise leave a stale, unrelated hint from an earlier // visit to this ply sitting here. Clear this ply's self-danger // slots first so a clean full eval reliably means a clean slate. ctx->cEnprise[ctx->uPly][0] = ctx->cEnprise[ctx->uPly][1] = ILLEGAL_COOR; ctx->cTrapped[ctx->uPly] = ILLEGAL_COOR; //_EvalLookForDanger(ctx); _EvalTrappedPieces(ctx); // TODO: endgame-specific knowledge? e.g. B over N in an endgame // with 2 pawn wings? // Roll in the reduced material down scaler terms (aggregate). ASSERT(pos->iReducedMaterialDownScaler[BLACK] > -200); ASSERT(pos->iReducedMaterialDownScaler[BLACK] < +200); pos->iScore[BLACK] += ( pos->iReducedMaterialDownScaler[BLACK] * (SCORE)REDUCED_MATERIAL_DOWN_SCALER[pos->uArmyScaler[BLACK]] ) / 8; ASSERT(pos->iReducedMaterialDownScaler[WHITE] > -200); ASSERT(pos->iReducedMaterialDownScaler[WHITE] < +200); pos->iScore[WHITE] += ( pos->iReducedMaterialDownScaler[WHITE] * (SCORE)REDUCED_MATERIAL_DOWN_SCALER[pos->uArmyScaler[WHITE]] ) / 8; #ifdef EVAL_TIME ctx->sCounters.tree.u64CyclesEvalPostLazyMisc += (SystemReadTimeStampCounter() - u64PostLazyMiscTimer); #endif #ifdef EVAL_DUMP Trace("After all pieces:\n%d\t\t%d\t\t(%d for %s)\n", pos->iScore[WHITE], pos->iScore[BLACK], (pos->iScore[uColor] - pos->iScore[xColor]), COLOR_NAME(uColor) ); #endif // Almost done iScoreForSideToMove = (pos->iScore[uColor] - pos->iScore[xColor]); #ifdef DUMP_RESIDUAL_SAMPLES // One CSV-ish line per full Eval() call: combined army scaler // (total pieces proxy), signed army-scaler diff (piece-balance // proxy), and each side's isolated residual (mobility/trapped/ // misc, with material/pawns/passers/bad-trade/bishop-pairs/king // safety already subtracted out via the baseline captured after // bishop pairs, above, and the real per-side king score). Sampled // before EvalLookForDrawishSituations' squash below, since that // squash is a separate, already-handled mechanism, not part of // what iResidualP98 is meant to estimate. { SCORE iResidualWhite = pos->iScore[WHITE] - iResidualBaselineWhite - ctx->sPlyInfo[ctx->uPly].iKingScore[WHITE]; SCORE iResidualBlack = pos->iScore[BLACK] - iResidualBaselineBlack - ctx->sPlyInfo[ctx->uPly].iKingScore[BLACK]; // Histogram, not a raw per-sample Trace -- at 30k-position // scale a raw dump would run into the billions of lines (a // 200-position sample alone produced 8.76M). Bucketed by OWN // army scaler (color-blind: each side contributes its own // row), same convention as the earlier ad hoc Python analysis. _RecordResidualSample(MINU(7, pos->uArmyScaler[WHITE] / 4), (INT)iResidualWhite); _RecordResidualSample(MINU(7, pos->uArmyScaler[BLACK] / 4), (INT)iResidualBlack); // Super-lazy-scoped residual: same idea, but relative to // super-lazy's own (material-only) baseline, so pawns/passers/ // bad-trade/bishop-pairs are included instead of excluded -- // this is what super-lazy's own margin_a/margin_b construction // actually needs (2026-09-17). { SCORE iSLResidualWhite = pos->iScore[WHITE] - iSuperLazyResidualBaselineWhite - ctx->sPlyInfo[ctx->uPly].iKingScore[WHITE]; SCORE iSLResidualBlack = pos->iScore[BLACK] - iSuperLazyResidualBaselineBlack - ctx->sPlyInfo[ctx->uPly].iKingScore[BLACK]; _RecordSuperLazyResidualSample(MINU(7, pos->uArmyScaler[WHITE] / 4), (INT)iSLResidualWhite); _RecordSuperLazyResidualSample(MINU(7, pos->uArmyScaler[BLACK] / 4), (INT)iSLResidualBlack); } // Outlier FEN capture -- thresholds picked comfortably beyond // the p10/p90 range seen in every bucket of the 200-position // smoke sample (worst bucket's p90/p10 topped out around // +/-230), so this only fires for genuine tail events worth // going back and looking at by hand, not routine variance. // 2026-09-17: capped -- the 200-position sample this threshold // was tuned against never came close to needing a cap, but the // far larger/more-varied 30k stratified pool hits this on a // real fraction of nodes and produced 2GB+ of Trace output // before filling /tmp on the first attempt. The histogram data // above is unaffected by this cap; only the (nice-to-have, // not essential) worked-example FEN capture is limited. if (((abs((int)iResidualWhite) > 250) || (abs((int)iResidualBlack) > 250)) && (g_uResidualOutliersPrinted < 200)) { CHAR *pszOutlierFen = PositionToFen(pos); if (NULL != pszOutlierFen) { Trace("RESIDUAL_OUTLIER_FEN resW=%d resB=%d fen=%s\n", (int)iResidualWhite, (int)iResidualBlack, pszOutlierFen); SystemFreeMemory(pszOutlierFen); g_uResidualOutliersPrinted++; } } // Same color-blind, per-side idea for king safety: each side's // REAL, already-scaled king contribution (ctx->sPlyInfo[...] // .iKingScore[color] -- scaled by REDUCED_MATERIAL_DOWN_SCALER // inside _EvalKing already, so this is the true realized // magnitude, not the pre-scale raw value the old iKingSwingP90 // table was fit against), paired with the ATTACKER's own army // (the side actually threatening that king), not the king // owner's. Bucketing directly by attacker army this way means // no runtime rescale step is needed at all in the redesign -- // the bucketing itself carries the army dependence. _RecordKingSafetySample(MINU(7, pos->uArmyScaler[BLACK] / 4), (INT)ctx->sPlyInfo[ctx->uPly].iKingScore[WHITE]); _RecordKingSafetySample(MINU(7, pos->uArmyScaler[WHITE] / 4), (INT)ctx->sPlyInfo[ctx->uPly].iKingScore[BLACK]); // Same idea as the residual outlier capture above -- threshold // picked beyond the p10/p90 range seen in every king-safety // bucket (worst bucket topped out around +/-160). if (((abs((int)ctx->sPlyInfo[ctx->uPly].iKingScore[WHITE]) > 200) || (abs((int)ctx->sPlyInfo[ctx->uPly].iKingScore[BLACK]) > 200)) && (g_uKingSafetyOutliersPrinted < 200)) { CHAR *pszOutlierFen = PositionToFen(pos); if (NULL != pszOutlierFen) { Trace("KINGSAFETY_OUTLIER_FEN kingW=%d kingB=%d fen=%s\n", (int)ctx->sPlyInfo[ctx->uPly].iKingScore[WHITE], (int)ctx->sPlyInfo[ctx->uPly].iKingScore[BLACK], pszOutlierFen); SystemFreeMemory(pszOutlierFen); g_uKingSafetyOutliersPrinted++; } } } #endif // Drive drawish situations towards the draw score. Usually a // no-op fetch here (sDrawishFacts already computed by the // regular-lazy attempt above) -- only does real work when that // attempt was skipped entirely (bare-king/low-material nodes, // see LAZY_EVAL_MIN_MATERIAL/fBareKingEitherSide above), in which // case this is that node's only call site. TIMED_EVAL_CALL(ctx, u64CyclesEvalDrawish, (_EnsureDrawishFactsComputed(pos, uColor, &sDrawishFacts), EvalLookForDrawishSituations(pos, &iScoreForSideToMove, &sDrawishFacts))); // Adjust dynamic positional component. Unlike the lazy-exit // margins above (always >= 0 by construction), this can go // negative -- a side whose positional terms (king safety, pawn // structure, hanging pieces, ...) net worse than its raw material // gets a genuinely negative value here. search.c's futility // margin (FUTILITY_BASE_MARGIN_BY_SOURCE[side's tier] + // piPositional[side]) deliberately lets that shrink the margin -- // a positionally-bad side is less likely to be saved by an // unexamined quiet move -- but floor it so one bad eval term // can't collapse the margin arbitrarily far; this only ever runs // on the full-eval exit, so -FUTILITY_BASE_MARGIN_FULL/2 (not the // lazy/super-lazy tiers) caps the damage at half of that tier's // base. if (NULL != piPositional) { (*piPositional)[WHITE] = MAX(pos->iScore[WHITE] - (SCORE)(PawnMaterial(pos, WHITE) + pos->uNonPawnMaterial[WHITE]), -(FUTILITY_BASE_MARGIN_FULL / 2)); (*piPositional)[BLACK] = MAX(pos->iScore[BLACK] - (SCORE)(PawnMaterial(pos, BLACK) + pos->uNonPawnMaterial[BLACK]), -(FUTILITY_BASE_MARGIN_FULL / 2)); ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_FULL; } g_Options.iLastEvalScore = iScoreForSideToMove; #ifdef CALIBRATE_MARGIN_SAFETY if (TRUE == fWouldHaveExitedSuperLazy) { // // Real (non-calibration) code checks super-lazy first and // returns immediately on a hit -- so if this call would *also* // have satisfied the regular lazy condition below, super-lazy // is still what a normal build actually returns. Record/ // restore this one, not the regular-lazy save in the other // branch. // // Direction matters: for an alpha-side exit (saved score below // alpha), only an *upward* real swing is dangerous -- it's the // one that could pull the score back over alpha. A downward // swing just makes the verdict even more clearly correct. Same // in reverse for a beta-side exit. abs() was conflating both // directions, so "exceeded" was really an upper bound on real // unsoundness, not a measurement of it. RecordSuperLazyMarginSafetySwing( pos, (iSavedSuperLazyScore < iAlpha) ? MAX0(iScoreForSideToMove - iSavedSuperLazyScore) : MAX0(iSavedSuperLazyScore - iScoreForSideToMove), iSavedSuperLazyMarginUsed); iScoreForSideToMove = iSavedSuperLazyScore; if (NULL != piPositional) { ULONG uWhiteBucket = MINU(7, pos->uArmyScaler[WHITE] / 4); ULONG uBlackBucket = MINU(7, pos->uArmyScaler[BLACK] / 4); (*piPositional)[WHITE] = iKingP50ByAttackerArmy[uBlackBucket] + iSuperLazyResidualP50ByOwnArmy[uWhiteBucket]; (*piPositional)[BLACK] = iKingP50ByAttackerArmy[uWhiteBucket] + iSuperLazyResidualP50ByOwnArmy[uBlackBucket]; // CALIBRATE_MARGIN_SAFETY builds: the FULL tag set above // reflects the fallthrough that just ran for measurement // purposes, not what a normal build actually returns here // -- fix it back up to match the restored (super-lazy) // values. ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_SUPERLAZY; } } else if (TRUE == fWouldHaveExited) { // // The real swing: how far the true, full-eval score actually // ended up from the lazy-exit score this node would have // returned. RecordMarginSafetySwing buckets this by material; // its max (not just p90) is the number that answers "how // large would LAZY_EVAL_BASE_MARGIN have had to be before an // exit here would have been unsound." // // Same directional fix as the super-lazy branch above. RecordMarginSafetySwing( pos, (iSavedLazyScore < iAlpha) ? MAX0(iScoreForSideToMove - iSavedLazyScore) : MAX0(iSavedLazyScore - iScoreForSideToMove), iSavedLazyPositional); // // Restore exactly what a normal build would have returned -- // this measurement must not change real search behavior. // iScoreForSideToMove = iSavedLazyScore; if (NULL != piPositional) { (*piPositional)[WHITE] = iSavedLazyPositionalWhite; (*piPositional)[BLACK] = iSavedLazyPositionalBlack; ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_LAZY; } } #endif #ifdef EVAL_TIME ctx->sCounters.tree.u64CyclesFullEvalExit += (SystemReadTimeStampCounter() - uTimer); ctx->sCounters.tree.u64CyclesInEval += (SystemReadTimeStampCounter() - uTimer); #endif INC(ctx->sCounters.tree.u64FullEvals); g_u64FullEvalsByBucket[_MaterialBucket(pos)]++; end: ASSERT(IS_VALID_SCORE(iScoreForSideToMove)); ASSERT((iScoreForSideToMove > -NMATE) && (iScoreForSideToMove < +NMATE)); ASSERT(abs(ctx->sPlyInfo[ctx->uPly].iKingScore[BLACK]) < 700); ASSERT(abs(ctx->sPlyInfo[ctx->uPly].iKingScore[WHITE]) < 700); return(iScoreForSideToMove); }