pawnstar-rs
Rust
A mechanical port to Rust, bit-exact with the C++: every node count, move and score identical.
- Strength
- same search as pawnstar
- Licence
- GPLv3
- Source
- GitHub
README.md · on GitHub
A UCI chess engine written in Rust: a mechanical port of the C++ Pawnstar engine. It has a bitboard board representation with magic bitboards, fully legal move generation, a Lazy SMP alpha-beta search, and an NNUE evaluation (1024 wide, 8 king buckets). A sibling Go port exists too, and all three engines are bit-exact with one another.
Bit-exact with the C++ original. At a fixed depth, single-threaded, this port runs exactly the same search as
the C++ engine: bench = 5,617,906 nodes at depth 13 (net v20; it was 6,601,454 on v12). The per-position node counts, best moves, PVs, scores and
every DEBUGX diagnostic counter are byte-identical to the C++ reference. This was checked by diffing transcripts at
depths 8 to 13, and tests/bench_golden_test.rs locks it in.
Usage
Run as a UCI engine (connect via Arena, Cute Chess, or any UCI-compatible GUI):
./target/release/pawnstar # interactive UCI sessionPoint any UCI GUI at the binary; it needs no configuration and nothing has to be installed beside it. The engine
prints its banner and version, loads the opening book and the net, and then reads UCI commands from stdin, one per
line, until end of input or quit.
In addition to the standard UCI commands, these engine-specific commands are available at the prompt. help lists
every command, and UCI protocol below is the full table, standard commands included.
eval the full evaluation the search uses for the current position
nnue the raw NNUE network output for the current position
getboard the FEN of the current position
bookmoves the opening-book moves for the current position, with their weights
freebook release the opening book from memory
dbg print the DEBUGX diagnostic counters
dbgclear reset them
bench search the fixed position set to a fixed depth; print the node total and nps
license the engine's licence and the third-party notices the shipped net and book oblige
help list every command
eval and nnue are not duplicates. eval is the value the search actually uses: the draw short-circuit (0
for a material, fifty-move or repetition draw), then the eval cache, then the network, then fifty-move scaling,
which fades the score towards 0 as the fifty-move clock climbs past 20 plies (Evaluation below).
nnue is the bare network output with none of that wrapping. They agree in a plain position and diverge on a
draw or once the fifty-move clock is high.
UCI options
Pawnstar advertises these setoption options in its uci response. Being a mechanical port, it advertises the
same names, types, ranges and defaults as the C++ and Go engines; tests/uci_binary_test.rs pins the advertised
Hash line verbatim, and tests/uci_commands_test.rs exercises every option's effect, its clamping and a
malformed value. UCI protocol below repeats this table beside the commands.
-
Hash(spin, default 64, 1–4096 MB) — transposition-table size, reallocated and cleared at runtime (setoption name Hash value <MB>). The default must stay equal to the other two ports': table size changes the collision pattern and so the node count at a fixed depth, so an unequal default breaks the three ports' bit-exactness at everygo— and invisibly, sincebenchpins 64 in all three. -
Clear Hash(button) — empties the transposition table without resizing it. -
Threads(spin, default =PAWNSTAR_THREADSor all cores, 1–256) — number of Lazy SMP search threads.1gives the deterministic single-threaded search the parity gate compares. -
Move Overhead(spin, default 30, 0–5000 ms) — time held back from every hard deadline to cover GUI and network lag, so the engine doesn't forfeit on time. -
OwnBook(check, default true) — whether to play from the opening book; set false to let the GUI's book drive the opening. The book is consulted only when this is on andgo searchmovesis not restricting the root. -
EvalFile(string, default empty — the shipped net) — path to anRNNUE1net to load at runtime (setoption name EvalFile value /path/to/net.bin), which clears the eval cache since the cached scores belong to the previous net. A net this refuses is not substituted for the one already playing: the net loaded before the command stays in play, and which net that is goes out on stdout and stderr, naming it — a harness that setEvalFile, sawreadyokand ran a thousand games would otherwise credit the result to a net that never played a move, andinfolines are exactly what a harness drops. -
Ponder(check, default false) — advertised so GUIs know the engine can ponder. Its value is declarative only; pondering itself is driven bygo ponderandponderhit.
A numeric option given a value that is not an integer is left as it was, rather than clamped or zeroed.
Environment variables, the same as the C++ engine's:
| Variable | Effect |
|---|---|
PAWNSTAR_THREADS |
The default Lazy SMP thread count. 1 gives a deterministic single-threaded search. |
PAWNSTAR_EVALFILE |
Overrides the path of the net. |
PAWNSTAR_BENCH_DEBUG=1 |
Makes bench print each position's best move, node count and DEBUGX counters, for cross-engine comparison. |
PAWNSTAR_PERFT_DEPTH |
Test only: caps the perft depth for quick iteration. |
PAWNSTAR_BK_DEPTH |
Test only: overrides the Bratko-Kopec search depth. |
The NNUE net and the opening book
NNUE is the only evaluator — there is no hand-written fallback evaluation — so a net is always needed. The
engine looks for nnue/pawnstar-v20.bin and pawnstar.book relative to the working directory first, then
relative to the executable's own directory and that directory's parent, so it finds both whichever of the three a
GUI launches it from. If a file is not found at all it falls back to the copy compiled into the binary
(include_bytes!, the C++ .incbin), so the executable is self-contained: a lone pawnstar plays with the
shipped net and book and no files beside it.
The two failures are not treated alike. A net that is simply missing falls back to the embedded copy and says
so on an info string. A net that is there and is refused by one of the container's integrity checks is
fatal at startup — the loader has already named the field that disagreed, and the engine exits non-zero rather
than quietly substitute different weights and play a whole match on a net nobody asked for. The book is optional,
so losing both the file and the embedded copy is only a warning.
To use a different net:
setoption name EvalFile value /path/to/net.bin # load a different net at runtime
or at launch:
PAWNSTAR_EVALFILE=/path/to/net.bin ./target/release/pawnstarEither way the net must be an RNNUE1 container of this build's NNUE shape — see
NNUE below and nnue/README.md.
Architecture
Each src/*.rs module ports the C++ header of the same name, one to one (see Structure). The C++
../pawnstar/CLAUDE.md is the authoritative deep-dive on the design and on the experiments behind it. This section
describes the engine as this port implements it.
Board representation
Position (src/position.rs) is a 160-byte Copy value. It is #[repr(C)] in the C++ field
order, with a const assertion that its size is 160, as the C++ static_asserts. It is immutable once built:
make_move and make_null_move return a new Position, and the search keeps a stack of them (copy-make), so undoing
a move is a pop and there is no unmake logic.
| Field | Type | Holds |
|---|---|---|
pieces |
[Bitboard; 7] |
One bitboard per piece type, indexed by Piece (Pawn = 1 … King = 6). Index 0 is the occupied squares, kept up to date as pieces move, so occupancy is a plain load. |
colors |
[Bitboard; 2] |
One bitboard per colour. |
squares |
[Piece; 64] |
The piece on each square, for O(1) lookup. |
checkers |
Bitboard |
The pieces giving check to the side to move, recomputed by make_move. |
hash |
u64 |
The Zobrist hash, updated incrementally (computed from scratch only when a FEN is read). |
king_location |
[Square; 2] |
Each king's square. |
en_passant_square |
Square |
The en passant target, or 0 for none. |
reversible_move_count |
u8 |
The fifty-move clock, in plies. |
full_move_count |
u8 |
The full-move number, zero-based. |
castling_rights |
CastlingRights |
Four bits. A 64-entry mask table clears the right a move gives up, so moving the king or a rook, or capturing a rook on its square, is one AND. |
is_null_move |
bool |
Whether the last move was a pass, so that null moves never follow one another. |
color_to_move |
Color |
The side to move. It is the last field, so it sits in what would otherwise be padding. |
Bitboard (src/bitboard.rs) wraps a u64. It has the set operators, pop_count, lsb, msb,
shifts in all eight compass directions (masking the files that would wrap), and an iterator over its set squares that
for s in bitboard loops use. The rank, file and square-colour masks are const.
Move encoding
Move (src/moves.rs) is one i64:
bits 0– 5 to square
bits 6–11 from square
bits 12–14 moving piece
bits 15–17 captured piece (None for a non-capture)
bits 18–21 move type (NonCapture, Capture, Promotion{Knight,Bishop,Rook,Queen}, PawnDoublePush, EpCapture, Castling)
bit 22 gives-check flag
bits 23–24 TT node type (Cut, All, Pv)
bits 25–32 TT depth searched (i8)
bits 33–40 TT age / generation (u8)
bits 41–63 score (signed 23-bit)
Equality and hashing look only at the identity, bits 0–21, so the score and TT metadata never make two moves differ.
Move::none() is zero. The score is read with an arithmetic right shift, which sign-extends the 23-bit field as the
C++ does.
Bits 23–63 do two jobs. While a move is being ordered they hold its sort score. While it is stored in the transposition table they hold the search score, depth, node type and age. A move is never both at once, so the bits are shared, and a table cell is just two 64-bit words.
A MoveList is a StackList<Move, 256> (src/stack_list.rs): a fixed array on the stack and a
length. Its storage is deliberately left uninitialised (MaybeUninit), so making one does not clear 2 KB at every
node, and only the live prefix is ever read. Move generation allocates nothing.
sort_moves sorts a list by descending score with a stable insertion sort: a move shifts left only past strictly
smaller scores, so moves with equal scores keep their generation order. The C++ replaced std::sort with this sort
because unstable tie-breaks made the bench node count differ between standard libraries. Replacing it with
sort_unstable would break parity.
Attack generation
Sliding attacks use magic bitboards (src/attacks.rs,
src/generated_data.rs). For each square, the relevant occupancy is masked, multiplied by a
precomputed magic number and shifted down to a slot: slot = ((occupied & mask) * magic) >> shift. That is one
64-bit multiply, portable to every CPU, with no reliance on BMI2's pext.
The slot does not index the attack sets directly. It indexes a one-byte indices table, which in turn indexes a
de-duplicated attacks table. Many occupancies share an attack set: a rook square has 4096 occupancies but only
about 100 distinct attack sets, and every square has fewer than 256, so a u8 index is enough. The indirection
shrinks the tables about five-fold, to about 155 KB.
The 128 magic multipliers are baked-in constants, found offline by a fixed-seed randomised search (dump_magics,
which ports the C++ std::mt19937_64 exactly and reproduces them bit for bit). The attacks and indices tables are
filled from them on first use (LazyLock). The builder asserts that no two occupancies with different attack sets
share a slot, so a changed mask generator cannot pass silently.
Everything else is a compile-time const, computed by const fns that run the C++ startup algorithms:
- the knight, king and pawn attack tables;
- the empty-board bishop and rook rays, which pin detection uses;
- the rank masks, which the en passant discovered-check test uses;
-
INTERVENING_SQUARES[from][to], the squares strictly between two squares on a shared line; - the Zobrist keys.
The Zobrist keys come from a fixed-seed xorshift* generator (seed 0xAA55AA55AA55AA55, the C++ engine's), drawn in a
fixed order: the piece-square keys, then the 16 castling-rights keys, then en passant keys for ranks 3 and 6 only.
Reordering the draws would change every key and every node count. The generated_data_test suite holds them to the
C++ values.
Move generation
Position::gen_moves::<IS_WHITE, DO_ALL_MOVES> (src/position.rs) generates fully legal moves.
It is the C++ GenMoves<Color, bool> template as const generics. generate_legal_moves calls it with
DO_ALL_MOVES = true, and generate_legal_captures (for quiescence) with captures and promotions only.
Pins. Pins::new (src/pins.rs) finds the absolutely pinned pieces before any piece moves are
made:
- Find the candidate pinners: enemy bishops, rooks and queens on an empty-board diagonal or line from the king.
- For each one, take the intervening squares between it and the king.
- If exactly one piece stands there and it is ours, it is pinned. Its allowed destinations are those squares plus the pinner's own square, so it may move along the pin or capture the pinner.
allowed_squares(from) gives a pinned piece its ray and every other piece all squares.
Generation order:
-
The king's forbidden squares. These are every square an enemy piece attacks, computed with our king removed from the occupancy, so a slider's attack runs on through the king's square (the king cannot step back along the check). Pawn attacks are two bulk shifts; every other piece is looked up.
-
King moves to the squares that are not forbidden: captures, then quiet moves.
-
Double check returns at once, since only the king can move.
-
Single check narrows the targets. Captures must take the checker, and quiet moves must land on the squares between the king and the checker.
-
Knight, bishop, rook and queen moves. Each piece's attack set is masked by its pin ray and then split into captures and quiet moves.
-
Castling, only when not in check, with the squares between king and rook empty and the squares the king crosses not attacked.
-
Pawn moves, all by bulk shifts of the pawn bitboard:
- single and double pushes;
- captures to the west and east;
- promotions, both by push and by capture, each to queen, rook, bishop and knight.
Each target is mapped back to its source by a fixed square delta and checked against that pawn's pin.
-
En passant. The capturing pawns are found with a reverse pawn-attack lookup from the target square. A capture is legal only if the captured pawn is a permitted capture, which also handles en passant out of check.
There is one rare extra test. When the king shares the rank, both pawns leave that rank at once, and that can uncover a rook or queen. The test removes both pawns from the occupancy and looks for a horizontal rook ray from the king to an enemy rook or queen.
Perft confirms the generator against the 131-record standard EPD at depth 6. Perft runs at about 255 Mnps on an M1 Pro; see Performance.
Search
Game (src/game.rs) holds what every search thread shares:
- the lockless transposition table and eval cache;
- the NNUE network, read-only during a search;
- the opening book;
- the chess clock;
- the options;
- the cancel, stop and ponder flags;
- the game history.
Everything a search thread writes is an atomic. Every other field is written only through Engine::game_mut(), which
joins the search worker first (see Deviations).
Everything else is per thread. It lives on each thread's SearchState (src/search_state.rs),
so the threads never contend:
SearchState
├── game &Game shared: TT, eval cache, net, clock, flags
├── positions Vec<Position> copy-make stack, seeded with the current position, reserved MAX_PLY + 4
├── hash_stack Vec<HashEntry> (hash, fifty-move clock) of every earlier position, for repetitions
├── acc_stack, acc_valid Vec<Accumulator>, Vec<bool> one NNUE accumulator per ply, brought up to date lazily
├── history HistoryTable butterfly history [side][from·to], i32, depth-weighted with gravity
├── killers [[Move; 2]; MAX_PLY] two quiet killer moves per ply
├── countermoves [Move; 7·64] best quiet reply to the previous move's (piece, to)
├── continuation_history Box<[i16]> (prev piece, to) × (piece, to): quiet follow-up scores
├── node_count u64 nodes searched by this thread
└── seldepth i32 deepest ply reached, for `info seldepth`
The stacks are reserved when the state is built, so no push during the search reallocates, and the per-node path
allocates nothing. hash_stack holds the whole game's history, so repetitions are found across the game as well as
the search.
Lazy SMP
Game::search_root_node runs thread_count threads (1 to 256). Each runs a complete, independent
iterative-deepening search of the root, and they share only the transposition table and eval cache: one thread's
entries prefill another's probes. There is no splitting of nodes and no work queue. The helpers are scoped threads
(std::thread::scope), joined when the main thread finishes and sets the cancel flag.
Thread 0 is authoritative: it prints info, manages time and returns the move. The helpers follow an iteration-skip
schedule (SKIP_SIZE / SKIP_PHASE), skipping selected depths so they don't recompute the main thread's tree in
lockstep.
The default thread count is PAWNSTAR_THREADS if set, else the machine's available parallelism. The UCI Threads
option changes it. With more than one thread the result is not deterministic; with one it is exactly the C++
engine's.
Iterative deepening and time
search_root_node:
- Returns a book move at once if
OwnBookis on and the book knows the position. - Applies
go searchmoves, then returns a forced move (the only legal one) without searching. - Plans the time (below), ages the transposition table, and orders the root moves by searching every one with the
full window. With no hard limit (fixed depth,
infinite,bench) that is one pass atSTART_DEPTH(3). Under a hard limit - a hard deadline (afterMove Overhead) orgo nodes- a depth-1 pass runs first (LIMITED_ORDERING_DEPTH), with the PV extension switched off (is_pv_extension_suppressed) so that a warm table cannot make it unbounded, and prints aninfo depth 1line; then the depth-3 pass. If a cancel cuts the depth-3 pass, the depth-1 order is kept (the cut pass is set aside whole), and a deeper transposition-table move for the root is preferred over either. If even the depth-1 pass is cut, the best move that finished is played, never the one whose search was interrupted. (Before 2.3.1 the depth-3 pass ran alone, and a deadline inside it could leave no search result at all.) - Launches the threads. Each one's
iterative_deepenruns from depth 4 upwards. At each depth it re-sorts the root moves by the previous iteration's scores and searches them all in one full-window pass. Alpha rises as moves improve, so every move after the first is a null-window scout.
There is no aspiration window: the C++ tested one and found no gain. The search stops early on a forced mate.
With a standard clock:
- The soft budget is
remaining / moves_to_go, wheremoves_to_goismovestogoormax(40 − move, 5). - The hard budget is
max(100 ms, min(2 × soft, remaining − 1 s)), lessMove Overhead. - Between iterations the main thread stops:
- once the soft budget is spent;
- after half of it, if the best move has been the same at every depth, or the score has stayed within 50 cp;
- after a quarter of it, if both are true.
- The hard deadline, and any
go nodeslimit, is polled every 2048 nodes.
movetime is a hard budget. depth, infinite and pondering have none. The increment is parsed but deliberately
not added to the budget: the C++ tested adding it and found it neutral to slightly negative.
Alpha-beta
SearchState::search is a fail-soft negamax. At each node, in order:
- Poll the deadline and node limit.
- Return a draw for insufficient material, the fifty-move rule or a threefold repetition.
- Extend by a ply when in check.
- Probe the transposition table.
- Apply internal iterative reduction.
- Drop into quiescence at depth 0, unless in check.
- At a non-PV node not in check, compute the static eval once and use it for both reverse futility pruning and the null-move gate.
- Search the TT move, then generate, score and sort the rest.
Whether a node is null-window (beta == alpha + 1) is checked again for each move against the current alpha. Once
an earlier move raises alpha at a PV node, the remaining moves are null-window too, and LMP and LMR must apply to them;
parity depends on it.
| Technique | Rule |
|---|---|
| Check extension | A node in check searches one ply deeper. Quiescence hands a position in check back to search. |
| Promotion and en passant extensions | The child of a promotion or an en passant capture searches one ply deeper. |
| Transposition table | A Cut entry at sufficient depth returns its score if it is ≥ beta. An All entry returns its score if it is ≤ alpha. A PV entry extends the depth by one (not in the depth-1 root ordering pass). That extension is not bounded: on a warm table it can repeat down a line, so seldepth reaches 62, the most MAX_PLY (64) allows (measured in the Go port, which searches identically: 18.4% of warm depth-4 lines reached seldepth 40 or more, against 3.2% cold). |
| Internal iterative reduction | At depth ≥ 4 with no TT move, search one ply shallower. |
| Reverse futility pruning | At a non-PV node not in check, at depth ≤ 7 and outside the mate band, return the eval if eval − 80·depth ≥ beta. |
| Null-move pruning | At a non-PV node not in check, after a real move, with more than three pieces of our own and eval ≥ beta: pass and search at depth − 4. A fail-high returns beta. |
| Late move pruning | At a null-window node not in check, at depth ≤ 8, skip quiet non-checking moves once move_index ≥ 3 + depth². Captures, promotions and checks are never pruned. |
| Principal variation search | The first move gets the full window and later moves a null window, re-searched with the full window on a fail-high. There is no scout when the node is in check or the move gives check. |
| Late move reduction | At a null-window node not in check, at depth > 2: −1 ply from the 5th move, −2 from the 8th (at depth > 3), −3 from the 14th. A fail-high is re-searched at full depth. |
| Mate scores | A mated node returns −31900 + ply, so a shorter mate scores higher. info reports score mate N beyond ±31000. |
The fifty-move clock counts plies since the last capture or pawn move (FIDE 9.3, and FEN's halfmove clock): every
other move advances it, castling included, and the position is a draw once it reaches 100. Draws by repetition look
back through hash_stack two plies at a time, starting four plies back, and stop at a clock of zero. A castling does
not zero the clock, so the walk carries on past it, but the castling rights it gives up are in the hash, so no
position before it matches. Two earlier matches make a threefold repetition. Insufficient material covers K v K,
K+minor v K, and K+B v K+B with the bishops on the same colour.
Quiescence
search_quiescent searches captures and promotions only. It stands pat on the static eval, and it neither probes nor
stores the transposition table. When in check it calls search instead, which searches every evasion.
The captures are sorted by SEE (below), so the loop stops at the first losing capture. Every move after it loses material too, so none is searched and no SEE is computed again. In the C++, dropping the quiescence table for this sorted early exit was worth +38.65 ± 13.78 Elo at 8+0.08 (a figure from the C++ repository, not re-measured here).
Move ordering
The TT move is searched before any list is generated, so a cutoff on it saves generating and scoring the rest.
score_and_sort_moves then stores a 23-bit score in each move and sorts the list by it, in disjoint bands:
| Band | Score |
|---|---|
| Winning or equal captures and promotions | 2^20 + SEE |
| First killer | 2^19 + 1 |
| Second killer | 2^19 |
| Countermove to the previous move | 2^19 − 1 |
| Other quiet moves | butterfly history + continuation history, clamped below the countermove |
| Losing captures | their (negative) SEE, below every quiet move |
Quiescence keys on the sign of that last band. A capture's SEE also says whether it gives check, which is recorded in the move's check flag.
History (src/history_table.rs) is a butterfly table, [side to move][from·to], pooling
statistics across every ply. When a move raises alpha or causes a cutoff, it is credited with a depth-weighted bonus,
min(depth², 400). On a cutoff, every quiet move searched before it at that node is debited by the same amount (the
malus).
Each update uses a gravity term, entry += bonus − entry·|bonus| / 16384. That keeps an entry within ±16384, where
recent evidence outweighs stale. The 1-ply continuation history (keyed by the previous move's (piece, to) and this
move's (piece, to), stored as i16) gets the same bonus and malus.
A quiet cutoff also becomes this ply's first killer (the old first killer moves to second), and the countermove to the previous move. Quiescence keeps a plain increment on the same table. The history is signed, so only its high side is clamped: an unsigned clamp would turn the malus into a top score.
Transposition table
src/transposition_table.rs is one table, 64 MB by default, resized and cleared by the
UCI Hash option. The number of cells is a power of two, so a cell is found by hash & mask.
The table is lockless (Hyatt's XOR trick). Each cell is two AtomicU64s, key = hash ^ data and data (the
packed move with its score, depth, node type and age). A reader loads both with relaxed ordering and accepts the cell
only if key ^ data == hash. That one check does two jobs:
-
It detects a torn pair. If two threads write a cell at once and a reader sees one thread's
keyand the other'sdata, the XOR matches no real hash, and the read is a miss: never a wrong entry. Racing writers resolve to a harmless last-writer-wins. - It guards against collisions. The full 64-bit hash is reconstructed, so an entry for another position that indexes the same cell is rejected.
Replacement: a cell is overwritten when it is empty, from an older search, no deeper than the new entry, or when the new entry is a PV node.
Aging is O(1). An 8-bit generation is incremented before each search and stamped on every entry written, and an
entry whose age differs is stale. Nothing is cleared between searches; ucinewgame, Clear Hash and bench clear the table.
search_single_move prefetches the child's cell straight after making the move, so the cache line is resident by the
time the child probes it. info hashfull samples the first 1000 cells.
Evaluation
evaluate_position (src/search_state.rs) is the search's evaluation, in centipawns for the
side to move:
- Draws (insufficient material, the fifty-move rule, repetition) return 0.
-
The eval cache (src/eval_cache.rs) is checked next. It is a lockless 8 MB table of single
AtomicU64s, each the top 48 bits of the hash beside a 16-bit score, so it needs no lock and cannot tear. A hit skips the network. - The network runs on a miss, on the accumulator brought up to date for this ply, and the result is stored in the cache.
- Fifty-move scaling is applied on the way out, never stored. Above 20 plies on the fifty-move clock, the eval ramps linearly towards zero as the clock nears 100. NNUE sees only piece placement, so without the ramp a winning eval would be the same at clock 0 and 99, and the search would have no reason to prefer progress over shuffling.
The raw eval is clamped to ±30000, which keeps it below the mate band (±31000) and within the cache's 16 bits.
Static exchange evaluation (src/static_exchange_evaluation.rs) resolves the sequence of captures on a square, least valuable attacker first: P = 100, N = B = 300, R = 500, Q = 900. It plays out the captures, then unwinds them, letting either side stop rather than make a losing recapture. A recapturing pawn reaching the last rank becomes a queen.
evaluate_static_exchange makes no move. It applies the capture to a lightweight SeeBoard of bitboards and works
out whether the move gives check from the attackers to the enemy king. That covers direct, discovered, promotion and
en passant checks alike. The see_test suite holds it to the make-move reference, evaluate_static_exchange_reference.
NNUE
src/nnue.rs is the engine's only evaluator, a port of the C++ network. It is a perspective net with
bullet's ChessBucketsMirrored features (ChessBuckets at the retired v12 shape, mirroring being the difference):
768 inputs per (perspective, king bucket) → 1024 feature transformer, shared by both perspectives
SCReLU, concat[side to move | other side] = 2048 → 8 output heads (centipawns, side to move)
QA = 255, QB = 64, SCALE = 400
King buckets. Each perspective picks one of 8 weight banks by its own king's square (KING_BUCKET_MAP). On
the shipped shape the bank is the king's mirrored file, min(file, 7 − file), plus 4 when the king has advanced
into the far half of the board: the perspective itself is mirrored first, so a and h are one bucket. The rank split
separates a sheltered king from an active one. (The retired v12 shape used unmirrored file pairs — a–b, c–d, e–f,
g–h — which is why turning mirroring on changes what a bucket means and not merely how many there are.)
Two shapes, one tree. The shared architecture every reckless-technology chess engine is moving onto adds
horizontal king mirroring (a perspective whose own king stands on files e–h is mirrored, square ^ 7, before
indexing, and the map becomes half·4 + min(file, 7 − file) — per file rather than per file pair) and 8 material
output heads ((piece_count − 2) / 4). Both are compile-time: the Cargo features nnue-king-mirroring and
nnue-output-buckets-8, together nnue-shared-shape, both in default since release 2.0.0 because the shipped
net needs them; the retired v12 shape is --no-default-features --features debugx. They are stamped into every
net's header, so a net only ever loads into a build of its own shape. A shape change is an evaluation change, so it
lands in pawnstar, pawnstar-rs and pawnstar-go together or not at all — as this flip did, with one net and
one new bench signature in all three. See
nnue/README.md, "The two network shapes".
Feature index. A piece's row is bank + (colour ^ colour_flip)·384 + (type − 1)·64 + (square ^ square_flip),
where the bank, the square flip (^ 0x38 for the black perspective, plus ^ 0x07 when mirrored) and the colour flip
are one nnue::Perspective value. They are gathered into one value because the incremental update is valid only
while all three stay put, and comparing just the bank is silently wrong once mirroring is on: a king stepping
d1 → e1 keeps its bucket while every row it reads moves. The feature-transformer weights are 6144 × 1024 i16,
12.6 MB, held in one 64-byte-aligned heap allocation.
The accumulator is two 1024-wide i16 arrays, one per perspective, maintained incrementally and lazily.
play_move and make_null_move only mark the new ply stale, and undo_move does nothing. current_accumulator
catches up only when an evaluation actually needs it, which is on an eval-cache miss: it walks back to the nearest
up-to-date ancestor, then copies and updates one ply at a time. A node that cuts off before evaluating (a TT cutoff,
RFP, null move or LMP) pays nothing.
Network::update finds the changed squares straight from the parent's and child's colour bitboards. A move changes
two to four of them, and captures, en passant, castling and promotion all fall out the same way. Only those columns
are added or subtracted, in both perspectives. A king move that changes its perspective's bank or its mirroring
moves every row that perspective reads, so that side is rebuilt from scratch and the other is diffed — one comparison
of the whole Perspective, which cannot miss either case. The i16 arithmetic wraps (wrapping_add /
wrapping_sub), as the C++ does.
The output layer runs in int8 on the search's path (evaluate):
- each SCReLU activation,
clamp(x, 0, 255)², is shifted right by 9 intou8(0–127); - it is multiplied by the output weights, requantised to
i8at load; - the products are summed in
i32, which provably cannot overflow and lets LLVM vectorise the loop.
The result is bit-identical to the C++ scalar, AVX2 and AVX-VNNI kernels, and within a bounded 40 cp (which is
exactly what v20's 250 reference positions measure, 2026-10-30; it was 26 on v12, and the rise is the one int8 scale
shared across eight output heads, not drift) of the exact int16 forward pass, evaluate_exact. The exact pass is
kept as the reference that nnue_test holds to the trainer's evals.
The net file is in the shared Reckless NNUE container, RNNUE1: the 64-byte self-describing header every
reckless-technology chess engine reads, then the weight payload. The header records the architecture - the features
per bucket, the king bucket count, the hidden size, the output bucket count, the architecture flags, the activation,
QA, QB and the eval scale - plus a CRC-64/XZ of the king-bucket map's 64 entries, the exact payload size, a CRC-64/XZ
over the payload and one over the header's own first 56 bytes.
The loader makes the container's two checks, in order: the header (the magic, its own checksum, every architecture
field against this engine's compile-time constants, then the map's checksum against the checksum of this engine's own
KING_BUCKET_MAP), then the payload (its declared size against what remains of the file, then its checksum). A net
that fails any of them is refused, loudly and on both streams: the engine names the field and both values as
an info string on stdout, which a GUI reads, and as the bare line on stderr, which a match harness keeps - a
harness routinely drops info lines, and a refusal only a GUI can see is a refusal nobody reads during an
unattended match. Nothing is written into the network until every check has passed, so a refused net leaves the net
already playing untouched rather than half-overwritten or unloaded. A setoption name EvalFile that is turned down
says so on both streams too, naming the net still playing: NNUE: keeping the net already loaded ('<origin>'); '<path>' was refused and is not in play. Keeping the old net is right; being quiet about it was the defect - a
harness that set EvalFile, saw readyok and ran a thousand games would otherwise credit the result to a net that
never played a move. And a refused net is never papered over with the embedded one - an engine that substituted a net
would play a whole match on weights nobody asked for, and the match would report a plausible Elo for a net that never
played a move. Only a net file that is missing falls back to the embedded copy. A net that loads says so the same
way (info string NNUE: loaded net '<origin>' on stdout, the bare NNUE: loaded net '<origin>' on stderr), so the
GUI and the harness are told which net is playing as surely as they are told which was refused.
The map's contents are part of the architecture, which is what the map checksum closes: the same eight king buckets
meaning other squares would load cleanly and read the wrong weight bank. stamp_net writes the header from its own
build's constants, so a net stamped by a tool built at another architecture carries that architecture's header and is
then refused - the header, never the file name, says what a net is.
The shipped net, v20 (release 2.0.0), is trained entirely on Leela Chess Zero self-play data. Against v12, the net it replaces, it measured +9.99 Elo (95% +2.42 to +17.57) at 8+0.08 over 8,000 games on reckless-ci-lin-0 and +1.13 (95% -5.63 to +7.89) at 12+0.12 over 12,000 games on reckless-ci-lin-0 and reckless-ci-lin-2, all played on 2026-10-30. The intervals are corrected for the openings being replayed (intra-class correlation 0.0746, design effect 2.47, the C++ repository's method; the 12+0.12 nominal interval is -3.17 to +5.43). The 8+0.08 interval is an estimate, because that arm's game files were never written, and the figure is biased upward, since the run was extended because its first stage looked good. So v20 is non-inferior to v12, not shown stronger: the 12+0.12 result cannot separate "nothing" from "a few Elo". v12 was itself trained on PlentyChess data and v20 on Leela data alone, so non-inferiority is what let the dependency go.
That training data is the Leela Chess Zero self-play training data
(https://storage.lczero.org/files/training_data/), runs test91 (62.83% of the pool) and test60 (37.17%),
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, so distributing this one obliges a notice naming the source: it is in
THIRD-PARTY-NOTICES.md, and the engine prints a condensed form on the license
command. The obligation is the notice - ODbL does not require the net itself to be ODbL-licensed, and the net is
not GPL merely because GPLv3 code trained it.
Pawnstar networks up to and including v12 were trained on self-play data generated by PlentyChess, by Yoshie2000 — approximately 6 billion positions. That data is no longer used. The attribution is kept deliberately, in nnue/README.md: those networks were measurably stronger for having been trained on that data, and the record should show where they came from. The nets' full lineage and the experiments behind them are in the C++ repository.
Opening book
src/opening_book.rs reads pawnstar.book: 3,328 lines in coordinate notation, 3,244 of them
built from the Lichess open database and so carrying no third party's restriction
(THIRD-PARTY-NOTICES.md); the other 84 end in a move this engine chose itself, as the
file says of them. 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. Each line is replayed from the start
position, and the book maps each position's Zobrist hash to the moves played from it, repeats included, so a uniform
random pick is weighted by frequency. No line is a prefix of another and each appears exactly once, so a move's
weight is the number of book lines passing through it, not a game count.
A move written with a trailing ? is questionable. It is replayed so the rest of its line still parses, but it is
never chosen. The shipped book has been through tools/filter_book in the C++ repository, which marks every move
scoring more than 100 cp below its position's best as that engine's own NNUE measures it at depth 12, so the engine
answers a move it would not play itself and never offers it. Where every move a position had is marked, that pass
added the engine's own choice there unmarked - the 84 lines above - so no position the book continues from is left
with nothing to play. bookmoves lists a position's moves and their counts. The book is consulted only when
OwnBook is on and go searchmoves is not restricting the root.
UCI protocol
src/input_handling.rs reads stdin line by line. It dispatches each command to its handler,
and runs searches on a worker thread so stop and ponderhit are heard during a search.
| Command | Notes |
|---|---|
uci, isready
|
The handshake: id, the options, uciok; readyok. |
ucinewgame |
Stops any search, clears the transposition table and eval cache, and resets the position. |
position startpos | fen <fen> [moves …] |
A malformed FEN never panics: missing fields take sane defaults, and anything unplayable falls back to the start position. |
go wtime/btime [winc/binc] [movestogo] |
A standard clock (see time). |
go movetime <ms>, depth <n>, nodes <n>, infinite
|
A fixed time, depth or node count, or until stop. The node limit is checked per thread, so it is exact at Threads=1. |
go searchmoves <m…> |
Restricts the root search to these moves. |
go … ponder, ponderhit
|
Searches on the opponent's time. No bestmove is sent until ponderhit (which starts the clock from that moment) or stop. |
stop, quit
|
Ends the search and sends bestmove, with ponder <reply> when the PV has a reply; quit also exits. A position with no legal move (mate or stalemate) is answered bestmove 0000, as the Go port does. |
bench [depth] |
The 16 Bratko-Kopec bench positions at depth 13, single-threaded, book off, with the table and eval cache cleared, printing nodes and nps. The node total is the parity signature. |
eval |
The search's full evaluation: draw short-circuit, cache, fifty-move scaling. |
nnue |
The raw network output, unscaled. |
getboard, bookmoves, freebook, dbg, dbgclear, help
|
Diagnostics: the FEN, the book's moves, freeing the book, the DEBUGX counters and their reset, and the command list. |
license |
The engine's licence and its third-party notices, condensed from THIRD-PARTY-NOTICES.md. The shipped net is an ODbL "Produced Work" of the Leela Chess Zero training data, and ODbL asks the attribution accompany it: a release binary downloaded on its own carries the notice this way. Printing only - it touches no engine state. |
| Option | Type | Default | Effect |
|---|---|---|---|
Hash |
spin 1–4096 | 64 | Transposition table size in MB (reallocated and cleared). The default must stay equal to the C++ and Go ports' (HASHTABLE_MEGABYTES): table size changes the collision pattern and so the node count at a fixed depth, so an unequal default breaks the three ports' bit-exactness at every go — and invisibly, since bench pins 64 in all three. tests/uci_binary_test.rs pins the advertised line. |
Threads |
spin 1–256 | cores | Lazy SMP thread count. |
Move Overhead |
spin 0–5000 | 30 | Milliseconds held back from every hard deadline for GUI and network lag. |
OwnBook |
check | true | Consult the opening book. |
EvalFile |
string | empty: the shipped net | Load another RNNUE1 net; clears the eval cache. A refused net is not loaded and the net already playing stays in use. |
Clear Hash |
button | Empty the transposition table. | |
Ponder |
check | false | Advertised for GUIs; pondering itself follows go ponder. |
info lines carry depth, seldepth, score cp or score mate N, time, nodes, nps, hashfull and pv.
Once a search has run for 3 s, they also carry currmove and currmovenumber.
Search diagnostics
src/debug_hashtable.rs keeps named DEBUGX counters. The increment! and increment_if!
macros count events through the search:
- beta cutoffs, and TT hits and cutoffs by node type;
- null-move, PVS and LMR attempts and failures;
- reverse futility prunes, late move prunes and quiescence SEE prunes;
- check, promotion and en passant extensions, and internal iterative reductions;
- draws, checkmates and stalemates, and eval-cache hits.
Each call site caches its counter's slot in a OnceLock. The counters are relaxed atomics, which single-threaded (the
mode the parity gate compares) are exactly the C++ plain integers. dbg prints them, and bench with
PAWNSTAR_BENCH_DEBUG=1 prints them per position. The debugx feature compiles them in; without it the macros are
empty.
Deviations from the C++
Every deviation preserves the C++'s behaviour. The fifty-move rules are the C++'s and Go's too: castling advances
the clock as any other piece move does (FIDE 9.3 and FEN's halfmove clock restart it on a capture or a pawn move
alone), and a checkmate on the hundredth ply is mate, not the fifty-move draw (FIDE 5.1.1); fifty_move_clock_test
holds both.
-
Threading is type-encoded. The C++ shares
Game&mutably across threads by convention. Here:- everything a search thread writes is an atomic: the TT cells, the eval cache, the stop and ponder flags, the
ponder move, the node count, and the clock instants as nanoseconds since a base, in
AtomicU64s; - the game history is a
Mutex<Vec<Position>>, which is never on the per-node hot path; - every other field is written only through
Engine::game_mut(), which joins the worker first; - Lazy SMP helpers are scoped threads.
- everything a search thread writes is an atomic: the TT cells, the eval cache, the stop and ponder flags, the
ponder move, the node count, and the clock instants as nanoseconds since a base, in
-
SearchState's C++mutablelazy-accumulator stacks become&mut selfmethods (current_accumulator,evaluate_position). - The book's random pick uses a wall-clock-seeded xorshift* instead of
std::mt19937. The randomness affects no test or gate, since the book is off inbenchand Bratko-Kopec.dump_magics, by contrast, portsstd::mt19937_64exactly, so it reproduces the baked magic constants bit for bit. - Numeric UCI values -
govalues,setoptionnumbers andbench <depth>- must be whole integers (parse_integer, the rule the C++ParseIntegerand Go'sstrconv.Atoishare). Agokeyword whose value is missing or malformed is ignored with it (go depth abcis a plaingo), an option is left as it was, andbenchkeeps its default depth. ThePAWNSTAR_THREADSenvironment variable is still read with C++atoisemantics (the leading digits, or 0 if there are none), as the C++ reads it. - On a malformed FEN this engine is defined and safe, where the C++ has istream and indexing quirks. Missing fields take sane defaults, and the stream-poisoning on a bad halfmove field is reproduced.
- The int8 eval dot accumulates in
i32, which is provably in range and gives identical results, so LLVM vectorises the scalar kernel. The C++ scalar kernel usesint64and its AVX2 kernelint32. -
quitstops the search and then returns frommain(process_inputreturns false), where the C++ callsexit(0). The exit code and the output are the same; returning runs the C runtime's exit handlers on every platform, where Rust'sprocess::exitisExitProcesson Windows and skips them - and with them an instrumented build's coverage profile.
Performance
The NNUE kernels are scalar only. They are bit-identical to the C++ SIMD kernels by construction, and the C++ also runs scalar on arm64, where this port was verified. Measured single-threaded on an Apple M1 Pro in July 2026, on the v12 net and before 2.0.0 (medians over alternating runs, with the history of the time; not re-measured since, and the v20 net costs more per node):
| Metric | C++ | Rust | ratio |
|---|---|---|---|
bench depth 13 (search nps) |
~1.15M | ~1.04M | 0.91× |
| Bratko-Kopec depth 12 (suite time) | ~5.2s | ~5.6s | 0.92× |
| perft suite (raw movegen Mnps) | 436 | 255 | 0.58× |
Real search speed is within about 10 % of the C++, since the search is bound by the evaluation and the eval kernels vectorise.
On 2026-07-03 (release 1.x, on the v12 net, before 2.0.0; the machine was not recorded), head to head at 10+0.1, the Rust port tied the C++ exactly at 150–150 over 300 games (UHO openings, single-threaded): 81 wins each and 138 draws, 0.0 ± 25.1 Elo. A three-way round robin with the Go port put all three engines within the error bars of one another (least squares, with C++ = 0: Go +13, Rust −7).
The perft gap is confined to raw move generation (gen_moves): per-element bounds checks and indirect attack-function
calls, which clang folds harder. Move generation is only about 1–2 % of a search node's cost, so it barely registers
in play.
Release 2.3.1 (2026-11-09) changed how a search under a hard limit starts (see Iterative deepening and
time). Measured on reckless-ci-lin-2 on 2026-11-09, at 1+0.01 over 2,000 games
against 2.3.0: -3.82 Elo (corrected 95% interval -17.86 to +10.22), so no strength change is detectable, with 0
against 110 unforced no-search moves. Time losses were 72 against 59, within chance. In a sweep of 1,072 node-limited
cases the Rust and C++ ports agreed in every one. With no hard limit nothing changes, and bench stays 5,617,906.
Future work is x86-64 AVX2/VNNI output-dot kernels, using std::arch and the ported cpuid gate in platform.rs. They
are untested here for lack of x86 hardware, and any such change must reproduce the bench golden signature exactly.
License
pawnstar-rs 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 NNUE network (nnue/pawnstar-v20.bin) and the opening book (pawnstar.book) are the ones Pawnstar ships, under the same license; the 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 this engine carries - and nothing downstream inherits one either.
THIRD-PARTY-NOTICES.md carries every third-party notice this engine owes - chiefly the
ODbL 1.0 / DbCL 1.0 attribution for the Leela Chess Zero self-play training data the shipped net was trained on,
which ODbL obliges whenever the net (an ODbL Produced Work) is distributed. The engine prints a condensed form on
the license command, so a release binary carries the attribution with it. The crate has no third-party code
dependencies.