Chess engine

pawnstar

C++

The original: bitboards, a Lazy SMP alpha-beta search and an NNUE evaluation.

Strength
about 2900 Elo* for the early nets; the shipped net has not been rated
Licence
GPLv3
Source
GitHub

* Measured by us in June 2026 against engines on the CCRL lists, with the earlier v4 to v7 nets. It is not an official CCRL rating.

README.md · on GitHub

Pawnstar is a UCI chess engine written in C++23. It uses a bitboard board representation, a parallel alpha-beta search (Lazy SMP), a lockless transposition table, and a perspective NNUE evaluation. The engine is header-only — every class lives entirely in its src/*.h header as inline definitions, so only main.cpp is compiled and linked (each test/tool is a single self-contained translation unit), and the build needs no LTO.

Legal move generation (perft) ran at roughly 600 million moves per second on one thread of an Intel i9-13900HX laptop (June 2026), and at about 437 million on an Apple M1 Pro.

Features

Usage

Run as a UCI engine (connect via Arena, Cute Chess, or any UCI-compatible GUI):

./build/pawnstar

In addition to the standard UCI commands, a few engine-specific commands are available at the prompt:

eval        print the full evaluation the search uses for the current position
nnue        print the raw NNUE network output for the current position
getboard    print the FEN of the current position
bookmoves   list opening-book moves for the current position
dbg         dump internal diagnostic counters
bench       search a fixed position set to a fixed depth; print "<nodes> nodes <nps> nps"
help        list all commands

eval and nnue are not duplicates. eval is the value the search actually uses: the draw short-circuit (0 for a material/fifty-move/repetition draw), then the NNUE forward pass (memoised in the eval cache), then fifty-move scaling (ScaleByRule50, which fades the score toward 0 as the fifty-move clock climbs past 20 plies). nnue is the bare network output with none of that wrapping. They agree in a plain position but diverge on a draw or once the fifty-move clock is high.

UCI options

Pawnstar advertises these setoption options in its uci response:

The NNUE net

NNUE is Pawnstar's only evaluator, so a net is required. At startup the engine loads the shipped net nnue/pawnstar-v20.bin (~12.6 MB; resolved relative to the working directory, like pawnstar.book). If that file is not there (wrong cwd, missing/renamed file), the engine falls back to a copy of the net embedded in the binary at build time, so it always has a working evaluator; it errors out if that copy is refused too. A net file that is there and is read and refused — wrong architecture, wrong bucket map, corrupt payload — is fatal and does not fall back: the engine prints the reason and exits non-zero, because an engine that cannot play the net it was given must not play at all. To use a different net:

setoption name EvalFile value /path/to/net.bin      # load a different net at runtime

or via an environment variable at launch:

PAWNSTAR_EVALFILE=/path/to/net.bin ./build/pawnstar   # use a different net

See NNUE evaluation below for how it works and how to train a net.

Architecture

Board representation

Position (src/position.h) is the central immutable state class. It stores per-piece-type bitboards in pieces_ and per-colour bitboards in colors_ (public members), a 64-entry square→piece array for O(1) lookup, the incrementally-maintained Zobrist hash, castling rights, the en passant square, the half-move clock, and a checkers_ bitboard. MakeMove and MakeNullMove return a brand new Position by value (copy-make); there is no unmake. The half-move clock is the fifty-move rule's (FIDE 9.3) and FEN's: plies since the last pawn move or capture, so castling counts like any other piece move and does not reset it.

pieces_ is a std::array<Bitboard, 7> indexed by piece type, but pieces_[0] (the kNone slot) holds the occupied-squares set — the union of all pieces of both colours — rather than a piece bitboard; the six real piece types occupy indices 1–6. This lets occupancy queries and the magic-bitboard attack lookups read it directly without recomputing a union.

Bitboard (src/bitboard.h) wraps a uint64_t with the usual set operations plus a range-based iterator that yields the Square of each set bit, enabling for (Square s : bb).

Move encoding

Move (src/move.h) packs everything into a single 64-bit word:

Bits Field
0–5 to square
6–11 from square
12–14 moving piece
15–17 captured piece
18–21 move type (capture, promotion, castling, en passant, double push, …)
22 gives-check flag
23–24 transposition node type (CUT / ALL / PV)
25–32 transposition depth (int8)
33–40 transposition age / generation (uint8)
41–63 score (signed 23-bit) — move-ordering score, and the stored TT score

The upper bits (23–63) are scratch ordering space during search and carry the transposition metadata once a move is stored in the table. Because all of that lives in the move, a transposition entry is just a {hash, move} pair. MoveList is a StackList — a fixed-capacity, stack-allocated container — so move generation does no heap allocation. (The search's principal variation and per-thread position stack are std::vectors, the position stack reserved once up front; see the design notes.)

Attack generation

Sliding-piece attacks (bishop, rook, queen) use magic bitboards: the occupancy bits relevant to a square are masked, multiplied by a precomputed magic and shifted down to a hash slot (hash = (occupancy & mask) * magic >> shift). This is a plain 64-bit multiply — portable and fast on every x86-64 CPU (the previous pext-based lookup is microcoded/slow on AMD Zen 1/2). The hash indexes a 1-byte-per-slot index array that in turn selects a de-duplicated attack set, which (since most occupancies share an attack set) shrinks the tables ~5× to ~155 KB. The magic multipliers are baked-in constants found offline by tools/dump_magics; only the index/attack tables are filled at startup. Knight, king and pawn attacks are plain 64-entry lookup tables. All tables are computed once at program startup in src/generated_data.h.

Pins (src/pins.h) computes absolute pins and the squares each pinned piece may still move to, before move generation.

The search is a fail-soft negamax with alpha-beta pruning, driven by iterative deepening and parallelised with Lazy SMP: several threads each run an independent whole-tree search, sharing a single lockless transposition table rather than splitting the tree between them.

Iterative deepening and time management

Game::SearchRootNode (declared in class Game and defined at the bottom of src/game.h, after the search_state.h hub is included so SearchState is complete) runs on a dedicated worker thread — started by Game::StartThinking — so the UCI stop command, which sets an atomic cancellation flag polled throughout the tree, can interrupt it at any time. It searches the root move list at increasing depths starting from kStartDepth (3) up to kMaxPly − 1 (63), emitting an info depth … score … time … nodes … nps … hashfull … pv … line each time the best move improves (score mate <±moves> once a forced mate is found, otherwise score cp <centipawns>). After every iteration the root moves are re-sorted by their scores from the previous iteration, so the prior best move is tried first next time. The root searches a full [kAlpha, kBeta] window (no aspiration windows); alpha is raised in place as root moves beat it.

Root ordering passes. Before iterative deepening, SearchRootNode searches every root move to kStartDepth (3) with the full window and sorts the list by those scores, so deepening starts at depth 4. Under a hard limit — a positive hard deadline (the time left to the move, less Move Overhead) or a go nodes limit — that depth-3 pass can outlast the whole budget (on 67 positions from 8+0.08 games, 2.2.0 had no search result at all when the deadline fell inside it), so since 2.3.1 a depth-1 pass runs first: it orders the list, prints an info depth 1 line and, if the depth-3 pass is then cut, its order is kept and the move is chosen from it. In that depth-1 pass only, a transposition-table hit on a PV entry does not add a ply (see the PV extension below), which keeps it to about 2% of the depth-3 pass. If a pass is cut anyway, a cancel never decides the move by itself: the root's table move is played if its entry is deeper than kStartDepth, else the best move of the completed depth-1 pass, else the best move the cut pass completed. With no hard limit (fixed depth, go infinite, bench) the depth-3 pass runs alone and prints nothing, exactly as before, so the bench signature (5,617,906) is unchanged. Measured for the C++ engine on one of the project's Linux match machines (lin-0), 2026-11-08, 2.3.1's change against 2.3.0, with the Elo as measured match scores and 95% intervals: +3.65 (−8.24..+15.53) Elo at 1+0.01, with 0 against 24 moves played with no search that were not forced; +1.74 (−11.65..+15.13) at 8+0.08, 0 against 22 — a fix for unsearched moves, not a measured strength gain.

Under a standard (time-budgeted) clock the engine can stop before the allotted time is spent, using the stability of the result across iterations:

This avoids burning the whole clock on positions whose answer is already settled. Fixed-depth and fixed-time clocks bypass the heuristic.

The per-move soft budget is remaining_time / moves_to_go, and the configured Move Overhead is subtracted from the hard deadline to leave headroom for GUI/network lag. (Folding the per-move increment into the soft budget was SPRT-tested at 8+0.08 and 10+0.1 and proved neutral-to-slightly-negative in equal-clock self-play, so winc/binc are parsed but not currently used in budgeting.)

ChessClock (src/chess_clock.h) is implemented with std::chrono on the monotonic steady_clock: the soft/hard budgets are std::chrono::milliseconds durations and the hard stop is an absolute time_point deadline, polled (every ~2k nodes) via HasReachedHardDeadline. On ponderhit the clock restarts the budget from that instant (the deadline and search-start instant are std::atomic so the UCI thread can retarget the running search). It is covered by the test_chess_clock unit suite.

SearchState::Search (src/search_state.h) applies, at each node. (The SPRT figures below are development-time results from 2026-06-16 to 2026-06-20, fastchess at the time control named, each against the engine as it stood that day with the net of that day; they were not re-measured on later releases.)

Quiescence search (SearchState::SearchQuiescent, src/search_state.h) extends the leaves with captures only, so the static evaluation is never called on a position with a hanging capture available. It does not use a transposition table (no probe, no store). It applies SEE pruning — the captures are SEE-sorted, so the loop reads each move's precomputed ordering score and exits on the first losing capture (move.score() < 0); every remaining move loses material too, so none are searched (and no SEE is recomputed in the loop). Dropping the quiescence transposition table and switching to this sorted early-exit was SPRT-tested +38.65 ± 13.78 Elo at 8+0.08 (1318 games, LLR-accepted against [-5, 0]).

Move ordering and history heuristics

Alpha-beta prunes far more when the best move is searched first, so SearchState::ScoreAndSortMoves (src/search_state.h) assigns every move a 23-bit sort score (stored in the Move itself) in strict descending bands. The TT move is searched before the list is even generated; the remaining moves sort as:

Band Score Moves
Winning captures kWinningCaptureBase (1 << 20) + SEE captures / promotions with SEE ≥ 0
Killers kKillerBase (1 << 19) +1 / +0 the two killer moves for this ply
Countermove kKillerBase − 1 the best quiet refutation to the previous move
Quiet moves min(main history + continuation history, kKillerBase − 2) everything else
Losing captures negative SEE captures with SEE < 0, below the quiet moves

The killer and main-history tables answer "which quiet moves are good at this ply / in general?". The countermove and continuation-history tables refine that by conditioning on the previous move — the one move the opponent played to reach this node. That move is threaded down the tree as Search's prev_move parameter (Move::None() at the root and after a null move).

Both previous-move tables share a key that abstracts a move down to (piece, to-square) — the Move::piece_to() method:

int Move::piece_to() const;   // (piece() << 6) | to()  →  7 × 64 = kContKeys (448) keys

This is the standard "a piece lands on a square" abstraction — it generalises across positions (a knight reaching f5 is the same follow-up however it got there), and Move::None collapses to a harmless slot 0.

Captures are excluded from both tables (every record site guards on Move::IsQuiet()) because captures are already ordered by SEE — history signals only matter for quiets, which have no static score to sort on. Both tables are per-thread (owned by SearchState), so there is no cross-thread contention; the continuation_history_ buffer is heap-allocated once in the constructor, so the per-node hot path allocates nothing.

Parallel search (Lazy SMP)

Parallelism is provided by Lazy SMP: Game::SearchRootNode launches Game::thread_count_ threads (clamped to kMaxSearchThreads), each running its own complete iterative-deepening search of the root position via SearchState::IterativeDeepen. There is no tree splitting and no work queue — the threads cooperate purely through the shared lockless transposition table, where one thread's deeper or earlier results prefill the entries another thread will probe. Each thread owns its own SearchState (position stack, hash history, killers, node count) and its own ordering tables (history, countermove and continuation history), so the only cross-thread sharing is the transposition tables and the cancellation flag; there is no per-(ply, move) counter contention.

The thread count is set by the UCI Threads option (stored in Game::thread_count_); its default is computed once at construction from the PAWNSTAR_THREADS environment variable if set (>0), else hardware_concurrency(), clamped to [1, kMaxSearchThreads] (e.g. PAWNSTAR_THREADS=1 forces a deterministic single-threaded search, used to regenerate Bratko-Kopec reference data).

To keep the helper threads from recomputing the same tree in lockstep, the main thread (thread 0) searches every depth while each helper follows a Stockfish-style iteration-skip schedule (kSkipSize / kSkipPhase tables in search_state.h) that makes it skip selected depths. The threads therefore desynchronise and seed the shared table with a diverse mix of depths. Only the main thread prints info lines, applies time management and produces the authoritative best move; helpers run silently and stop as soon as the shared cancellation flag is set.

Because the helpers race ahead through the table, a search run to a nominal depth is non-deterministic and the returned best move (and its exact score) can vary slightly between runs — a known and accepted property of Lazy SMP. PAWNSTAR_THREADS=1 recovers determinism when that matters.

Tuning constants

The knobs above live in src/constants.h:

Constant Value Meaning
kStartDepth 3 First (full-width) iterative-deepening depth
kMaxPly 64 Hard ceiling on search depth / ply
kHashtableMegabytes 64 Main transposition table size
kScoreInstabilityThreshold 50 Centipawn window for the "score stable" time-management test
kMaxSearchThreads 256 Upper bound on Lazy SMP search threads

Transposition table

A 64 MB TT is used for the main search. Each entry is exactly 128 bits — a 64-bit Zobrist hash and a 64-bit move whose spare bits carry the score, depth, node type and age.

The table is lockless (Hyatt's XOR trick): each cell stores key = hash ^ data alongside data (the packed move), as two std::atomic<uint64_t> accessed with relaxed ordering.

A reader accepts a cell only if key ^ data equals the probe hash, so a torn pair written by two concurrent stores is detected and treated as a miss.

Concurrent writers race benignly (last writer wins). Aging is O(1): Age() bumps a generation counter and an entry is stale when its stamped age differs from it.

The probe is a random memory access, so once a child move has been made (its Zobrist hash known) the search Prefetches the cell the recursive node will read, hiding the cache-miss latency behind the intervening work. This is purely a latency optimization and does not change results.

Evaluation

EvaluatePosition (declared in src/evaluation.h, defined in the src/search_state.h hub) is NNUE-only: after a draw short-circuit it returns the network's score for the (lazily-maintained) accumulator, clamped to ±30000 so a pathological max-material eval can't overflow the int16 eval cache, memoised by Zobrist hash in that eval cache. See NNUE evaluation below. Earlier versions also had a tapered hand-crafted evaluation (material, piece-square tables, pawn structure, king safety, mobility); it was removed once NNUE became the sole evaluator.

Static exchange evaluation (EvaluateStaticExchange, src/static_exchange_evaluation.h) is independent of the NNUE eval: it resolves a capture sequence on a square, is used to order captures and promotions during search (see above) and to prune losing captures in quiescence, and is covered by test_see.

NNUE evaluation

Pawnstar evaluates exclusively with an NNUE (Efficiently Updatable Neural Network), and has no hand-crafted evaluation to fall back on. EvaluatePosition consults the net directly, after a draw short-circuit. The shipped net is loaded at startup, with a copy embedded in the binary in case the file is not there, and another can be loaded at run time — see The NNUE net above.

The shape. nnue/pawnstar-v20.bin is the shared Reckless NNUE shape, the same one trebuchet and the two ports carry:

768 inputs per (perspective, king bucket)  ->  1024 feature transformer  (x2 perspectives)
SCReLU,  concat[side to move | opponent] = 2048  ->  8 material output heads  ->  1 centipawn score

The 768 base inputs are (piece colour × piece type × square), replicated across 8 king buckets chosen by the perspective's own king square — its file × board-half, with files e–h mirrored onto a–d so the whole perspective flips horizontally and every bucket sees both wings. The score comes from one of 8 output heads selected by the number of pieces on the board, so the same hidden features are weighed differently as material comes off. kKingBucketMap in src/nnue.h is the one place the bucketing is written down; kNumKingBuckets is derived from it, and the trainer reads the same map.

Everything is integer: the feature weights and biases are int16 at scale QA, the output weights int16 at QB and the output biases int32 at QA·QB. That is what makes a search's node count a property of the position and the depth alone, so the three ports are bit-exact with each other at a fixed depth. The weights are heap-allocated — at 8 king buckets the array is about 12.6 MB and would overflow a default thread stack — owned by the Game, read-only after load and shared by every search thread.

The accumulator is maintained incrementally and lazily. Each SearchState holds a per-ply stack of accumulators, a copy-make scheme: playing a move pushes the child and marks its accumulator stale, and undoing one is free, because every ancestor's accumulator is still valid for the next sibling. The work happens only when an evaluation actually reads an accumulator and the eval cache misses: it walks back to the deepest valid ancestor and, for each ply forward, copies the parent and applies that move's feature delta — adding the arriving pieces' columns and subtracting the departing ones. A king crossing a bucket boundary rebuilds that one perspective from scratch. So a node that cuts off before evaluating pays nothing, and returning to a sibling after a deep sub-search costs one copy and one delta rather than a replay. The stack is reserved once at construction, so the search performs no heap allocation.

Training data, and the notice it obliges. The shipped net is trained entirely on Leela Chess Zero self-play data, published under the Open Database License 1.0. A trained net is a Produced Work under that licence, so distributing one obliges a notice naming the source — it does not make the net ODbL-licensed, and does not make it GPL merely because this project's code trained it. The notice is in THIRD-PARTY-NOTICES.md, and the engine prints it itself: send license over UCI.

Where the rest lives. nnue/README.md is the net's own record: the RNNUE1 container and its checks, how a net is trained, verified and stamped, what each net measured, and the attribution for the retired nets. The trainers and the data pipeline are shared across the engines and live in nnue-training.

Opening book

OpeningBook (src/opening_book.h) lets the engine play known opening lines instantly instead of searching. At startup the engine loads pawnstar.book from the working directory; the shipped book (pawnstar.book) was built by tools/make_book.cpp from the Lichess open database, which is released under the Creative Commons CC0 1.0 public-domain dedication - so the book carries no third party's restriction. The book file's own # header records the monthly export it came from, every filter used, the counts and the SHA-256 of exactly the bytes read. As with the NNUE net, if the file can't be loaded (wrong cwd, missing/renamed file) the engine falls back to a copy of the book embedded in the binary, so a relocated executable still has its book; the book is optional, so failing both is only a warning. The built-in book can be disabled with the OwnBook UCI option.

The file is plain text, one opening line per row, with each move in coordinate notation (from-square then to-square, e.g. e2e4 e7e5 g1f3). Tokens that begin with a digit are treated as move numbers and ignored, and a # begins a comment to end of line, so PGN-style numbered lines are also accepted. Each line is replayed from the standard start position and every move it visits is recorded. A move may carry a trailing ?, marking it questionable: it is replayed so the rest of its line still parses and the engine keeps its prepared reply to it, but it is never selected.

The shipped book was screened against the engine's own judgement at depth 12 with a 100 cp margin, which is where those marks come from: 555 of its 8,923 (position, move) pairs were marked, and 84 positions whose every move was marked were given the engine's own move, unmarked, so no position the book reaches is left with nothing to play. The screener lives in the public amphitheater-chess repository, drives any engine over UCI, and is run as:

amphitheater-cli screenbook -engine cmd=<engine> -book <book> [-out <book>] [-depth 12] [-margin 100] [-marks <file>]

-out defaults to the book that was read. src/match/BookScreener.h there records why a weak move is marked rather than deleted and what makes one move's score comparable with another's.

Internally the book is a std::map from position Zobrist hash to a vector of legal Moves, with repeats: a move that appears in many lines is stored many times, so picking uniformly at random (GetMove) naturally weights selection by how often the move occurs. SearchRootNode consults the book before searching and, on a hit, returns the chosen move immediately. The bookmoves UCI command prints the available book moves and their frequencies for the current position.

Design notes

A few deliberate choices shape the codebase:

Benchmarks

Pawnstar has no official CCRL rating. The figures currently tracked are:

make check is the regression baseline; the perft suite verifies move-generation correctness against the published node counts for the standard positions.

Limitations and known issues

License

Pawnstar is free software, licensed under the GNU General Public License, version 3 (GPLv3). You may redistribute and/or modify it under the terms of that license; it comes with no warranty. See the LICENSE file for the full text, or https://www.gnu.org/licenses/gpl-3.0.html.

The shipped network carries a notice of its own. nnue/pawnstar-v20.bin was trained entirely on the Leela Chess Zero self-play training data (https://storage.lczero.org/files/training_data/), a database published under the Open Database License 1.0 with its contents under the Database Contents License 1.0. A trained net is an ODbL Produced Work, and distributing one obliges a notice naming that source: the notice is in THIRD-PARTY-NOTICES.md, and the engine prints it in answer to the license command. The obligation is the notice alone — the net is neither ODbL-licensed nor GPL-licensed by having been trained with GPLv3 tooling.

The bundled opening book (pawnstar.book) was built from the Lichess open database, which is released under the Creative Commons CC0 1.0 public-domain dedication. CC0 waives attribution, so the credit in THIRD-PARTY-NOTICES.md is a courtesy and not an obligation Pawnstar carries - and nothing downstream inherits one either. The NNUE trainer sources under tools/bullet/ are written for the bullet trainer and adapted from it: pawnstar.rs from its simple example, and pawnstar_eval.rs from that example and from its Chess768 and ChessBucketsMirrored input code. bullet is MIT-licensed, Copyright (c) 2023 Jamie Whiting, so those two files are redistributed here with that attribution in their headers and bullet's licence text in THIRD-PARTY-NOTICES.md. bullet itself is not redistributed: tools/setup_bullet.sh fetches it at a pinned commit.

← All five engines