Skip to content

Dev v1.8 - #40

Draft
frankkopp wants to merge 57 commits into
masterfrom
dev_v1.8
Draft

frankkopp wants to merge 57 commits into
masterfrom
dev_v1.8

Conversation

@frankkopp

Copy link
Copy Markdown
Owner

No description provided.

frankkopp added 13 commits April 1, 2026 00:47
- CMakeLists.txt: VERSION 1.7.0 -> 1.8.0
- Updated all docs (Build_Guide, Architecture, Sanitizer_Guide, arena README, tuning README, CLAUDE.md) with new executable names
- Updated scripts/run_vtune_analysis.ps1
- Replaced Release/FrankyCPP_v1.7_phase7.zip with Release/FrankyCPP_v1.8.zip
Remove permanently-disabled USE_SINGULAR_TT_BOUND config option (always false).
Semantically no-op: the conditional was always true, so behavior is unchanged.
Changes:
- Remove CONFIG_CONST member from SearchConfigData.h
- Remove registry entry from ConfigRegistry.cpp
- Remove 'if (isLowerBound || !USE_SINGULAR_TT_BOUND)' wrapper in Search.cpp
  (flatten singular extension code by one indent level)
- Remove orphaned ttBound variable and assignment (no longer used)
- Remove singularFilteredByBound stat field, merge, and display
- Remove references in TacticalTests.cpp and SearchTreeSizeTest.cpp
- Remove commented-out YAML reference in search.yaml
- Remove stale TODO comment for RFP improving margin
- Update PLAN_v1.8.md: mark QW1/T2/T7 complete, add A9 investigation
  item for Stockfish-style bound check (revisit later)
IID (Internal Iterative Deepening) was permanently disabled (false)
and fully replaced by IIR (Internal Iterative Reduction).
Removed:
- SearchConfigData: USE_IID, IID_DEPTH, IID_REDUCTION fields
- ConfigRegistry: 3 IID registry entries, mutual-exclusion assert sizes
- Search.cpp: IID/IIR mutual-exclusion check, IID code block (~35 lines),
  IID stats output section, stale IID comments
- SearchStats: iidSearches, iidMoves fields and their operator<</+= refs
- SearchTreeSizeTest: USE_IID references in baseline reset and test groups
- search.yaml: IID config comments
Updated static_assert sizes for all platform/build-type combinations.
- Wrap Position construction in try-catch for std::invalid_argument
- Report invalid FEN via uciError() (info string), preserve previous position
- Add positionFenErrorTest with 4 cases: invalid FEN, empty FEN, valid FEN,
  invalid FEN with trailing moves
- Add FRIEND_TEST declarations for new test in UciHandler.h
- Update PLAN_v1.8.md: mark QW3 and T4 as complete
- Add plan-qw3FenErrorHandling.prompt.md spec document
Replace random book move selection with frequency-weighted selection.
Moves leading to positions seen more often in the book source are
preferred over rare ones. The new BOOK_VARIETY UCI option (0-100,
default 30) controls randomness:
  0   = pick randomly among the highest-frequency moves only
  1-99 = blend frequency weights with uniform (higher = more random)
  100  = pure uniform random (original behavior)
Implementation:
- Add getBookMove(ZobristKey, int variety) to OpeningBook
- Uses destination position counter as frequency proxy (works for all
  book formats: SIMPLE, SAN, PGN — no scores/metadata needed)
- No changes to BookEntry struct — existing cache files stay valid
- Keep getRandomMove() for backward compatibility
- Add BOOK_VARIETY to SearchConfigData + ConfigRegistry (UCI exposed)
- Search.cpp uses getBookMove() with configured variety
- Remove resolved TODO comment from Search.cpp
Tests:
- getBookMoveValid: valid move from start position
- getBookMoveVarietyZero: only top-frequency moves returned
- getBookMoveUnknownPosition: MOVE_NONE for unknown position
- Search::newGame() now also clears lastSearchResult, resultReady flag,
  and measuredPostStopOverheadMs (reset to MOVE_OVERHEAD_MS)
- UciHandler::uciNewGameCommand() resets position to startpos
- Removed const from uciNewGameCommand() (needs to mutate pPosition)
- Removed TODO comment, replaced with doc listing all cleared state
- Updated help text for ucinewgame command
- Added UCI-level test (uciNewGameResetsState): verifies position reset,
  result cleared, and engine still functional after ucinewgame
- Updated PLAN_v1.8.md: QW5 and T3 marked complete
Replace print-only evasion test with 6 position blocks containing:
- Move count assertions (pseudo-legal, evasion, legal) for each position
- Structural invariants (evasion <= pseudo-legal, legal <= evasion)
- Legal-subset-of-evasion containment check via helper lambda
- Deep-copy of MoveList results to avoid internal buffer aliasing
- En passant evasion verification (position 4: f4e3 captures checker)
- No-castling-in-check assertion (position 1)
- Double-check king-only moves assertion (position 6)
- Evasion-vs-legal delta check (position 5: exactly 1 illegal evasion)
- sortValueTest: Replace TODO with 5 assertion groups (PV first,
  monotonic order, killer ordering, value-zone check, VALUE_MAX cap)
- sortValueWithHistoryTest: New test verifying history boost (+500)
  and counter-move boost (+600) against no-history baseline
- Use ranges::sort (unstable) to match production moveSort
- Define PV/killer moves as constexpr constants, reuse throughout
- Add FRIEND_TEST for sortValueWithHistoryTest in MoveGenerator.h
- Remove stale TODO comment (T9) in MoveGenerator.cpp:789
- Update PLAN_v1.8.md: QW7, QW8, T9, T10, T11, X2 marked complete
Removed commented-out resetToDefaults() call and FIXME comment. Caller owns config state; added clarifying comment. Updated PLAN_v1.8.md to mark QW9/F1 complete.
- Add 'signature' field to BenchResult (== totalNodes)
- Print 'Bench: <number>' line in printResults() for script parsing
- Add bench_signature.txt with per-compiler signatures (msvc/gcc/clang)
- Unit tests: signature==totalNodes, determinism, depth sensitivity,
  output parsing, and full bench vs committed signature file
- Signature test detects compiler via preprocessor, reads matching line
- Fix: main.cpp bench output interleave (logger init mid-cout-chain)
- Strengthen commit/push rules in CLAUDE.md and copilot-instructions.md
- Update arena.yaml config
- Mark QW10 and E3 complete in PLAN_v1.8.md
frankkopp added 16 commits April 2, 2026 13:03
- New docs/specs/PLAN_PGO.md: detailed plan for Profile-Guided Optimization
  covering CMake options, MSVC linker flags, presets, pgo-bench custom target,
  build_windows.ps1 production mode, and IDE workflow
- Updated PLAN_v1.8.md: cross-reference to PLAN_PGO.md in D2 entry and references
Implement the UCI 'debug on/off' command (previously stub) with full
diagnostic info string output when debug mode is enabled:
- debug on/off toggle with confirmation info string
- PV-leaf eval breakdown per iteration: material, positional, pawn,
  pieces, threats, coordination, king safety, tempo, game phase
- Iteration stats: TT hit-rate, beta-cut-1st-move percentage
- Book move announcement when opening book move is selected
Implementation:
- UciHandler: debugMode field, isDebugMode() getter, debugCommand()
  parses 'on'/'off' argument, help text updated
- Evaluator: EvalTrace struct with per-component Score breakdown,
  evaluateTrace() mirrors evaluate() capturing component deltas
- Search: isDebugMode() convenience, sendDebugEvalInfo() applies PV
  moves to position copy and evaluates leaf for meaningful breakdown
- Tests: debugDefault, debugOnOff, debugBadArg, debugInfoDuringSearch,
  debugBookMove
Plan updated: C2 marked complete in PLAN_v1.8.md.
Use std::format without L specifier for the 'Bench: <nodes>' line so it
is always locale-independent, even when another test imbues a locale with
thousands separators on std::cout.
Add UCI `Contempt` option (spin, -100..100, default 0) that biases
draw scores to avoid or seek draws. Positive contempt returns +cp
when the root side faces a draw, negative seeks draws.
- SearchConfigData: CONFIG_ESSENTIAL int CONTEMPT = 0
- ConfigRegistry: registered with UCI/YAML/display exposure
- Search: drawScore(p) replaces VALUE_DRAW in 6 non-TB draw paths
  (iterativeDeepening, rootSearch, search, qsearch)
- TB draw paths intentionally left as VALUE_DRAW (proven draws)
- 4 unit tests: zero/positive/negative contempt + stalemate integration
- PLAN_v1.8.md: A8/C4 marked complete
Add UCI option MultiPV (default=1, max=128) for reporting the top N
best moves with scores and PV lines per iteration depth.
Search changes:
- MultiPV loop in iterativeDeepening() wraps root search
- pvIdx=0 uses aspiration search; secondary PVs use full window
- Stockfish-style batched output: collect all PV results, sort by
  score (descending), report in batch with consistent node counts
- rootMoves[0..N] re-sorted to match, ensuring post-iteration code
  sees the true best move (handles search instability)
- Helper threads always use MultiPV=1 for efficiency
- effectiveMultiPV clamped to min(MULTI_PV, rootMoves.size())
- Aspiration lowerbound/upperbound UCI output suppressed when
  MultiPV>1 to prevent GUI display artifacts
- sendFinalUciInfo suppressed when MultiPV>1 to prevent best-thread
  selection from overwriting the multi-PV display on stop
UCI changes:
- Dynamic multipv field in sendIterationEndInfo/sendAspirationResearchInfo
- MultiPvResult struct holds collected PV line, score, seldepth
- sendMultiPvResultsToUci sends all PV lines in a single batch
Config:
- CONFIG_ESSENTIAL int MULTI_PV = 1 in SearchConfigData.h
- Registered as UCI spin option (1-128) in ConfigRegistry.cpp
Tests:
- multiPV1NoRegression, multiPV3ProducesValidResult
- multiPVClampedToLegalMoves, multiPVWithSMP, multiPVTimedSearch
Docs:
- PLAN_MultiPV.md updated to COMPLETE status
- Architecture.md, CLAUDE.md, copilot-instructions.md updated
Two thread-safety bugs caused ACCESS_VIOLATION crashes when running
with more than 4 threads (e.g. --bench --threads 6):
1. Shared pvMoveGenerator: Search::pvMoveGenerator was a single
   MoveGenerator shared across all threads. Multiple helpers calling
   extractPvWithTT() concurrently wrote to the same internal buffers,
   corrupting StaticMoveList::size_ (observed as 0x32c407fb).
   Fix: moved pvMoveGenerator to SearchThreadData (per-thread).
2. Shared Search::position read from helpers: line 848 copied
   Search::position (shared member) while the main thread was
   mid-search doing doMove/undoMove, producing corrupted Position
   copies with garbage kingSquare values.
   Fix: changed to copy from thread-local position parameter 'p'.
Run fewer games in the last batch instead of requiring exact divisibility.
Uses ceiling division for total batches and std::min for the last batch size.
frankkopp and others added 28 commits April 10, 2026 10:52
Add TT_STATS_ENABLED toggle in ConfigMode.h with TT_STAT_INC macro,
following the existing STAT_INC/ESSENTIAL_STAT_INC pattern.
Replace all raw counter increments in TT::probe()/put() and
PawnTT::probe()/put() with TT_STAT_INC() calls. When disabled
(TT_STATS_ENABLED=0), all diagnostic counters compile to no-ops,
enabling A/B measurement of false sharing impact under SMP.
Move all TT and PawnTT diagnostic counters (puts, probes, hits, misses,
collisions, overwrites, updates, entries) from shared mutable fields to
per-thread cache-line-aligned slots (statsSlots[threadIdx]).  Each search
thread now writes exclusively to its own Stats cache line, eliminating
false sharing that was the primary cause of poor SMP scaling.
Aggregation across thread slots happens only on cold paths (str(),
hashFull(), getters).  probe()/put() signatures gain a threadIdx
parameter (default 0 for backward compat).
Key changes:
- TT.h/cpp: Stats struct alignas(CacheLineSize), per-thread statsSlots
- PawnTT.h/cpp: Same per-thread stats pattern
- Search.cpp: Pass thread().id to tt->probe(), tt->put(), storeTt()
- Evaluator.h/cpp: Pass threadIdx through setPawnTT() to pawnCache calls
- globals.h: Add MAX_SEARCH_THREADS = 256 constant
- ConfigRegistry.cpp: Use MAX_SEARCH_THREADS for Threads option maxValue
NPS scaling improvement (bench, i9-13900KF, depth 12, 256 MB hash):
  1T:  2.52M (baseline)     8T:  19.3M (7.67x, was 3.25x)
  4T:  9.57M (3.79x)       12T:  27.4M (10.87x, was 3.24x)
  16T: 34.0M (13.48x, was 3.50x)  — efficiency >84% at 16T
ELO gain from SMP (vs SF18@2700, 5+0.05, 100 games/thread count):
  ~100-140 ELO at 8-16T (was ~35 ELO max pre-fix)
Also includes: arena thread-scaling config (1-16T vs SF2700),
SMP plan document with research findings and measurement data,
VTune profiling results (8T hotspots, memory-access, threading).
R2 code review found that both getTotalNodes() and aggregateStats()
iterated the entire searchThreadData vector, which grows but never
shrinks. When thread count decreased between searches (e.g. 8T->4T
without ucinewgame), stale nodesVisited and statistics from inactive
threads were included, inflating UCI node counts and search stats.
Fixed both functions to iterate only [0..numHelperThreads] active
threads instead of the full vector.
Updated PLAN_SMP_Thread_Scaling.md: R2 marked complete with findings.
The pre-fix NPS anomalies R3 was designed to investigate no longer
exist. R1 confirmed stable bench, R5 confirmed false sharing as root
cause, R2 found no race conditions. Per-position variance under Lazy
SMP is expected and not actionable. Updated gate note accordingly.
Memory wall hypothesis disproven — NPS ceiling was false sharing (R5),
not bandwidth. Post-fix scaling is 84% efficient at 16T with no plateau.
Phase 2 (TT replacement) and Phase 4 (thread divergence) are algorithmic
and don't need memory bandwidth data. R4 only relevant for Phase 3 (eval
architecture) or if scaling degrades at very high thread counts.
All blocking research (R1, R2, R5) is now complete. Implementation of
Phase 2+ can proceed.
…ds (Phase 4a)

Add per-thread iteration depth skipping using interleaved skip-size/skip-phase
tables (20 entries, max skip size 4). Each helper thread searches a different
subset of iteration depths based on its thread ID, ensuring threads are spread
across different depth levels at any moment for maximum TT entry diversity.
Main thread always searches every depth.
Config: USE_SMP_DEPTH_SKIP (default true, yaml-exposed). When false, reverts
to the original simple starting depth offset (1 + id % 3).
Bench results (8T, depth 12, 32 MB hash):
  - 38% fewer nodes (184M -> 113M) for same search depth
  - QSearch TT hit ratio: 71.5% -> 60.6% (less redundant shallow work)
  - Main search TT hit share: 28.5% -> 39.4% (more useful deep entries)
ELO validation (v1.8 vs v1.7, STC 10+0.1, 500 rounds):
  - 4T: +114 ELO (329-171, 65.8%)
  - 8T: +200 ELO (380-120, 76.0%)
Updated: Architecture.md, CLAUDE.md, PLAN_SMP_Thread_Scaling.md,
V1_ENGINE_STRENGTH_ROADMAP.md, arena results and test suite data.
Replace the legacy age increment/decrement system with a TT-level generation
counter (3 bits, 0-7). Entries are stamped with the current generation in put();
replacement score uses staleness = (generation - entry.gen) & 7 to prefer
evicting stale entries from old searches.
Key changes:
- newGeneration(): O(1) per search, replaces expensive full-table ageEntries() scan
- probe() is now fully read-only (no writes to entries) — eliminates the age--
  data race that was already disabled under SMP
- Entry field renamed: age -> gen (generation tag)
- Replacement formula: depth*16 - staleness*2 + hasMove
- TT::clear() resets generation=0 to match zeroed entries
ELO validation (v1.8 vs v1.7, STC 10+0.1, 500 rounds):
  - 4T: +84 ELO (309-191, 61.8%) — cumulative with Phase 1+4a
  - 8T: +217 ELO (388.5-111.5, 77.7%) — cumulative with Phase 1+4a
  - Phase 2b isolated: ELO-neutral (within ±30 noise margin)
  - Test suites: +31 positions (+1.0%) vs v1.7
Updated: Architecture.md, PLAN_SMP_Thread_Scaling.md, V1_ENGINE_STRENGTH_ROADMAP.md,
bench signature, arena results, match PGNs, and test suite data.
…ator

Replace popLSB() loop over individual pawns with Bitboard::shifted()
for bulk pawn attack computation in both evaluate() and evaluateTrace().
Uses wp.shifted(NORTH_EAST) | wp.shifted(NORTH_WEST) for white and
bp.shifted(SOUTH_EAST) | bp.shifted(SOUTH_WEST) for black, matching
the existing MoveGenerator style.
Two shift+OR ops per color replace up to 8 loop iterations of
popLSB() + table lookup + OR per side.
…l calls

S1: Merge evaluate() and evaluateTrace() into template<bool Trace> evaluateCore()
- std::conditional_t return type: <false> returns Value, <true> returns EvalTrace
- No pointer, no null, no lambda — direct if constexpr blocks
- [[maybe_unused]] const Score before pattern for delta capture
- Explicit template instantiations in .cpp (no header bloat)
- Also resolves S20 (passedPawns fallback duplication)
S2: Replace 8 explicit pieceEval calls with nested loop
- for (pt = KNIGHT..QUEEN) x Color::all()
- Iteration order preserved (piece-type outer, color inner)
Bench signature unchanged. NPS verified equivalent to baseline.
Replaced 4 duplicated king-safety blocks in knightEval, bishopEval,
rookEval, queenEval with a single-line condition reusing the already-
precomputed attackedByPT[KING][them] as king zone. Eliminates up to
8 redundant Bitboards::nonSliderAttacks lookups per evaluateCore() call.
~16 lines saved. Bench signature unchanged (38314796).
NPS verified: avg 2516 kNPS (5 runs, within expected 2500-2540 range).
S13: Remove unnecessary intermediate variable in qsearch drop-through
     (return qsearch() directly instead of const auto value = ...; return value).
S14: Move do_null computation before the move loop — matethreat is
     constant after the NMP block, no need to recompute per iteration.
Both are mechanical, behavior-preserving changes.
…reset()

S23: Replace default:break with __assume(false)/__builtin_unreachable()
     in pieceEval() switch - branch is unreachable (only KNIGHT..QUEEN).
S24: Add constexpr relativeRank(Color, Square) free function in square.h.
     Replace 5 identical inline rank-mirroring patterns in Evaluator.cpp
     (pawnEval x2, knightEval, rookEval, kingEval).
S25: Remove empty Evaluator::reset() method - zero call sites, pure dead code.
Bench: 38314796 (unchanged), NPS ~2497 kNPS (within range).
S6: Added constexpr addSigned(Score&, int, int, int) in score.h.
Replaced all 11 occurrences of the 2-line signed accumulation pattern
across 7 eval functions (pawnEval, knightEval, bishopEval, rookEval,
queenEval, kingEval, threatEval, coordinationEval).
S7: Removed 4 'if (mid || end)' guards in rookEval, queenEval,
threatEval, coordinationEval. The branch was almost always taken
(mobility/tropism ensure non-zero), making the guard pure overhead.
Removing it yielded ~+1% NPS (2,561 avg vs 2,540 reference).
Bench signature: 38314796 (unchanged)
…tatus

Architecture.md: Replace vague "legality check" with precise description
of what isLegalMove() actually does -- validates a pseudo-legal move by
checking the king is not left in check, or does not cross an attacked
square during castling.

Position.h: Expand isLegalMove() Doxygen comment with @note explaining
the pseudo-legal precondition and UB risk for arbitrary moves. Also
fix wasLegalMove() Note: -> @note tag.

PLAN_Code_Simplifications.md: Mark S8/S9/S10 as REJECTED with full
rationale; update summary table and phase lists accordingly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant