Chess engine

pawnstar-go

Go

pawnstar ported to Go, with hand-written AVX2 and NEON kernels for the network; on Apple Silicon it runs level with the C++.

Strength
same search as pawnstar
Licence
GPLv3
Source
GitHub

README.md · on GitHub

A UCI chess engine written in Go. This is a port of the original C++ Pawnstar engine.

The evaluation network

The engine evaluates with an embedded NNUE network, engine/nnue/pawnstar-v20.bin — v20, the net of release 2.0.0, trained entirely on Leela Chess Zero self-play data. It is the same blob, byte for byte, as pawnstar and pawnstar-rs ship.

Measured against the previous net, v12, in single-threaded self-play (both run on 2026-10-30, on the project's Linux match machines reckless-ci-lin-0 and reckless-ci-lin-2): +9.99 Elo at 8+0.08 over 8,000 games on lin-0 (95% interval +2.42 to +17.57; an estimate, because that arm's PGNs were never written, so the interval is bracketed from the opening-replay ICC of 0.061 measured on the same machine at the same openings; biased upward, because the run was extended after a good first stage) and +1.13 at 12+0.12 over 12,000 games (4,000 on lin-0 and 8,000 on lin-2; 95% interval -5.63 to +7.89, measured). Both intervals are widened for the replay of the 306-opening book; the 12+0.12 one uses ICC 0.0746 and design effect 2.473 from tools/opening_icc.py in pawnstar (the nominal interval was -3.17 to +5.43). That is a gain at the faster time control and no measurable difference at the slower one: v20 is non-inferior to v12, not shown stronger, and it was shipped to remove the PlentyChess-trained data.

Attribution for the training data

The Leela Chess Zero self-play training data is published under the Open Database License 1.0 (http://opendatacommons.org/licenses/odbl/1.0/), with its contents under the Database Contents License 1.0 (http://opendatacommons.org/licenses/dbcl/1.0/), from https://storage.lczero.org/files/training_data/. v20 was trained on the runs test91 (62.83% of the pool) and test60 (37.17%).

A trained network is an ODbL Produced Work, and distributing one obliges a notice naming the source. That notice, in full and with both run lines verbatim, is THIRD-PARTY-NOTICES.md - read it there. Two things it states plainly: the obligation is the notice, and ODbL does not require the network itself to be ODbL-licensed; and the engine's GPLv3 licence does not make the network GPLv3 merely because GPLv3 code trained it.

Because the net is embedded in the binary, the notice travels with the executable too: the license UCI command prints a condensed form of it, as does pawnstar-go --license on the command line, and every release's documentation bundle contains the file. That matters because no release publishes a source tarball - someone who downloads only the binary gets no file from this repository at all.

Provenance of earlier networks

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: networks from v20 (release 2.0.0) onward are trained entirely on Leela Chess Zero self-play data.

The attribution is kept here deliberately. Those networks were measurably stronger for having been trained on that data, and the record should show where they came from.

No network in the current release was trained on any PlentyChess data, and every network that was has been withdrawn. pawnstar-v12.bin and every net before it are removed from the source tree, and every release that shipped them has been deleted - so no binary distributed from this repository contains an evaluator trained on that data.

For the network's architecture, its container format and the gates on it, see NNUE evaluation under Architecture.

Usage

Run as a UCI engine — point any UCI-compatible GUI (Arena, Cute Chess, and the rest) at the binary, which needs no configuration:

./pawnstar-go             # interactive UCI session (pawnstar-go.exe on Windows)

No files need to sit beside it: both the NNUE network and the opening book are compiled into the binary (go:embed), so the single executable is the whole engine. It prints one banner line, Pawnstar (Go) — UCI compatible chess engine, before the handshake; a GUI ignores it. The only command-line argument it recognises is --license (--licence, -license, -licence), which prints the licence and the third-party notices and exits — anything else on the command line is ignored, since the engine takes its configuration from UCI and the environment.

PAWNSTAR_THREADS, read once at startup, sets the initial Lazy SMP thread count; unset or not a positive integer, the default is every logical CPU. A GUI can override it at any time with setoption name Threads.

Beyond the standard UCI commands — UCI protocol under Architecture lists every one of them, with the go variants and the info fields — two engine-specific commands are available at the prompt:

license        print the engine's licence and the third-party notices the shipped data obliges
bench          search 16 fixed positions to a fixed depth; print "<nodes> nodes <nps> nps"
bench <depth>  the same at an explicit depth (the default is 13)

bench is deterministic: single-threaded, book off, on its own pinned 64 MB transposition table, so its node count does not move with the Hash or Threads options. The signature is 5,617,906 nodes, asserted by a golden-signature test. PAWNSTAR_BENCH_DEBUG=1 additionally dumps each position's best move and diagnostic counters after its search, for comparison against the C++ engine's bench; normal bench output is unchanged without it.

There is no eval, nnue, getboard, bookmoves, dbg or help command — the C++ engine has those, this port does not; its search diagnostics are reached from tests instead (dbgxClear/dbgxPrint, Search diagnostics). An unrecognised command is ignored in silence.

One behaviour worth knowing before driving the engine from a harness: ucinewgame clears the transposition table and the eval cache as well as resetting the position, the node count and the clock, as the C++ and Rust engines do, so a position repeated after ucinewgame searches the same tree each time. position alone keeps both tables, which is what carries the TT across the moves of one game; repeating a position with only position + go depth N in one session therefore gives shrinking node counts. Releases up to 2.2.0 cleared neither on ucinewgame, and only Clear Hash did; release 2.3.0 (2026-11-08) changed that.

UCI options

The options the uci response advertises, in the order it prints them:

A setoption naming an option that does not exist is ignored, and so is a value that will not parse as the number its option wants — the option keeps what it had.

The NNUE net

NNUE is the only evaluator, and its net is in the binary: NewGame installs the embedded v20 net at construction, so there is no net file to find and no working-directory dependency. (The C++ engine loads nnue/pawnstar-v20.bin from the working directory and falls back to its embedded copy; this port has the embedded copy alone.) To play with a different net:

setoption name EvalFile value /path/to/net.bin   # load another RNNUE1 net
setoption name EvalFile value <embedded>         # back to the built-in net ("default", or no value at all, do the same)

A net that fails the container's checks is refused, and the net already loaded keeps playing: the refusal names the field, the file's value and the engine's own, and a second line names the net still in play — both lines on stdout as info string and on stderr, because a harness keeps stderr and routinely drops info lines. Nothing is ever substituted silently. The only way to have no evaluator at all is a build whose own embedded net is unusable; the next go then refuses to search and returns bestmove 0000, which no harness can mistake for a played game, rather than evaluate a node with no network.

See NNUE evaluation under Architecture for the network's shape, its container format and the gates on it.

Architecture

Board representation

position (engine/position.go) is a value type; makeMove and makeNullMove operate on a caller-owned copy. Game maintains a posStack []position history stack (capacity 512, heap-allocated); undoing a move is a slice truncation — there is no unmake logic.

The struct holds:

There is no per-side score accumulator: the former handcrafted evaluator (PST/material scores[2]int) has been removed — NNUE is the only evaluator (see below).

bitboard (engine/bitboard.go) is a uint64 with methods for common set operations (popCount, lsb, popLsb, shifts in all eight directions).

Move encoding

move (engine/move.go) is a packed int64:

bits  0– 5   to square
bits  6–11   from square
bits 12–14   moving piece
bits 15–17   captured piece (noPiece if non-capture)
bits 18–21   move type (nonCapture/capture/promotionKnight/…/castling)
bit     22   reserved (formerly gives-check; no longer computed)
bits 23–24   transposition node type (nodeType)
bits 25–32   transposition depth searched (int8)
bits 33–40   transposition age / generation (uint8)
bits 41–63   score (signed 23-bit)

move.equal/isNone mask to the identity bits (0–21), so the score and TT metadata never affect identity. move(0) is the null sentinel (moveNone()). String() outputs UCI long-algebraic notation (e2e4, e7e8q). Bits 23–63 are dual-purpose: a move-ordering sort score (withScore/score, bits 41–63) during search, or packed {score, depth, nodeType, age} metadata inside a transposition entry (withTTData/setTTAge). A move is only ever one or the other, so the spare bits are shared — which lets a TT cell be exactly two 64-bit words for the lockless table.

Move lists use a stack-resident moveList (a fixed [256]move array + count; engine/movegen.go): the hot paths (perft, searchAlphaBeta, searchQuiescent) declare a local var ml moveList and call generateLegalMovesInto/generateLegalCapturesInto, so move generation is allocation-free (escape analysis keeps ml on the stack). Cold callers (UCI setup, opening book, tests) use the slice-returning generateLegalMoves wrapper, which copies into a right-sized heap slice. This replaced a per-node make([]move, 0, 64) that heap-allocated on every node.

Attack generation

engine/tables.go holds all precomputed data initialised once at startup via init():

Move generation

engine/movegen.go implements fully legal move generation. generateLegalMovesInto and generateLegalCapturesInto are the entry points (with generateLegalMoves as the slice-returning wrapper for cold callers).

Pin computation

Before generating non-king moves, computePins (engine/pins.go) identifies absolutely pinned pieces:

  1. Find candidate pinners: enemy sliders (bishops/rooks/queens) on a bishop or rook ray from the king.
  2. For each candidate pinner, collect the squares strictly between the king and the pinner (interveningSquares).
  3. If exactly one friendly piece occupies that ray segment, it is pinned. Its legal destination set is restricted to that ray (including the pinner's square, so the pinner can be captured).

The result is a pins struct with a pinned bitboard and a [64]bitboard of allowed destination sets indexed by square. allowedSquares(sq) returns the restriction for a pinned piece, or all squares for an unpinned one.

generateMoves proceeds in this order:

  1. Build the king's forbidden-square set — compute all enemy attacks, temporarily removing the king from the occupancy so that X-ray attacks through it are included. Pawn attacks are generated by shift; all other enemy pieces iterate over their attack sets.

  2. King moves — generate moves to non-forbidden squares; separate captures and quiet moves.

  3. Double-check short-circuit — if the king is in double check, only king moves are legal; return immediately.

  4. Single-check restrictions — restrict the allowed capture set to the checker's square, and the allowed non-capture set to the squares between the king and the checker (interveningSquares).

  5. Piece moves (knight, bishop, rook, queen) — for each piece, generate attacks, mask by pins.allowedSquares(from), then split into captures and quiet moves.

  6. Castling — only when not in check, with the transit squares unoccupied and unattacked.

  7. Pawn moves — all pawn move types are generated inline by bulk bitboard shifts:

    • Single and double pushes (masked by empty squares and the allowed non-capture set)
    • Diagonal captures west and east (masked by enemy pieces and the allowed capture set)
    • Promotions (push and capture variants, four piece types each)
    • En-passant: candidates are found via reverse pawn-attack lookup; each candidate is additionally tested for the rare horizontal discovered check — with both pawns removed from the king's rank, check whether a rook or queen on that rank now attacks the king.
    • Pin constraints applied per candidate pawn via pins.allowedSquares.

Game (engine/game.go) owns only the state shared across Lazy SMP threads: the lockless transposition table and eval cache, the opening book, the chess clock, the threadCount, and the posStack []position game-history stack. Everything else — history, killers, continuation history, countermoves, the NNUE accumulator stack, node counts — is per-thread, living on each thread's searchState so the concurrent search never contends. isCancelPending is an atomic.Bool set by stopThinking or by the time-check logic inside the search.

The search uses Lazy SMP (as in the C++ engine): searchRootNode runs threadCount threads, each an independent iterative-deepening search of the whole root sharing only the lockless transposition table and eval cache. The main thread (id 0) is authoritative — it prints info, manages time, and returns the move — while helper threads deepen the shared TT, desynchronised by a Stockfish-style iteration-skip schedule so they explore diverse lines. Thread count defaults to 1 (raised by main() from PAWNSTAR_THREADS/NumCPU, or the UCI Threads option). All per-thread state (history, killers, continuation history, countermoves, accumulator, diagnostics) lives on each thread's searchState, so nothing is shared except the two lockless tables — the concurrent search is data-race free with no locks.

searchState

The search is split by layer — per-thread state in engine/search.go, the root driver in engine/searchroot.go, the main recursion in engine/searchalphabeta.go, quiescence in engine/searchquiescent.go, move ordering in engine/moveorder.go. All recursive search functions take *searchState rather than *Game directly:

searchState
├── posStack            []position        copy-make stack; seeds with 1 entry (current position)
├── hashStack           []hashStackEntry  compact (hash, halfMoveClock) record for repetition detection
├── killers             [maxPly][2]move   quiet moves that caused beta cutoffs, indexed by ply
├── history             historyTable      per-thread history heuristic (per-thread to avoid contention)
├── countermoves        [contKeys]move    best quiet refutation keyed by the previous move
├── continuationHistory []int16           1-ply continuation history, keyed by [prev.pieceTo()][move.pieceTo()]
├── accStack            []nnueAccumulator lazy NNUE accumulator per ply (+ accValid []bool)
├── nodeCount           int               nodes searched this iteration
├── seldepth            int               deepest ply reached (UCI info seldepth)
├── dbg                 *debugX           diagnostics: global dbgx for the main thread, a throwaway per helper
└── game                *Game             pointer to shared state (TT + eval cache, clock, cancel)

hashStackEntry packs the Zobrist hash (top 56 bits) and the half-move clock (low 8 bits) into a single uint64 — 8 bytes, versus 160 bytes for a full position — keeping the repetition scan cache-friendly. Repetition detection compares only the top 56 hash bits (ample for a scan window of at most ~100 plies); a zero clock byte marks a pawn move or capture, the boundary that stops the scan. Castling advances the clock, as FIDE's fifty-move rule and FEN's halfmove clock count it, so the scan runs on past a castling move and finds nothing there: castling takes away rights the hash carries. newSearchStateFromGame(game) builds the search state: it converts all entries in game.posStack to compact hashStackEntry records (preserving the full game history for three-fold repetition detection), then seeds posStack with just the current position. Only truly shared state — the lockless TT + eval cache, the read-only time control, and the atomic cancel flag — is reached through the game *Game pointer; the history/killers/countermove/continuation tables and the accumulator stack are all local to this searchState.

Iterative deepening

searchRootNode drives iterative deepening from startDepth (3):

  1. Return the opening book move if available; return immediately for forced moves (single legal move).
  2. Run the ordering pass (orderRootMoves) to score and order the root moves. The pass polls the cancel flag after each move; a move whose search was interrupted is never scored, because the cancel sentinel would truncate into the 23-bit score field as about +3,957,070 and sort first (releases up to 2.2.0 played that move, with no info line). What happens depends on whether the search has a hard limit: a positive hard deadline (after Move Overhead) as under wtime/btime or movetime, or go nodes. go depth, go infinite, bench and a ponder search before ponderhit have none.
    • No hard limit: one pass at startDepth (3), as always. Bench and fixed-depth results are unchanged by everything below.
    • A hard limit (since 2.3.1): a depth-1 pass (limitedOrderingDepth) runs first, with the PV extension switched off for that pass alone (searchState.pvExtensionSuppressed: on a table warm from deeper searches the extension keeps the depth from ever falling along stored lines, and even a depth-1 pass ran on to maxPly, up to ~750k nodes against ~2,000). If it completes, the moves are stably sorted by it, an info depth 1 line is printed and the depth-3 pass searches them in that order. The depth-3 pass can outlast the whole budget (369k nodes from a cold table and 464 ms on a warm one, against a budget of about 80 ms at 8+0.08), which is why 2.3.0 and earlier could reach the deadline with no root move completed.
    • If a pass is cut by the deadline, stop or the node limit, the moves it did not complete are marked unsearched (unsearchedRootMoveScore, below every real score) and keep list order after those that completed. A cut depth-3 pass is set aside whole and the completed depth-1 order is used. The root's TT move is then played when it is in the list and its entry is deeper than startDepth (a search never stores its root as the root, only when the root recurs inside it as an interior node, so such an entry comes from an earlier, deeper search, most often the one two plies back), else the best completed move; if no move's search completed, the TT move at any depth when it is in the list, else the first generated move.
  3. For each depth from startDepth+1 to maxPly:
    • Search all root moves in a single full-window pass [initialAlpha, initialBeta]: alpha starts at the minimum and is raised as moves improve, so PVS null-windows every move after the first. There is no aspiration window (the C++ engine tested and rejected aspiration; a fixed-depth cross-engine BK diff confirmed it was the largest Go↔C++ divergence, so Go dropped it). Combined with shared-xorshift64star Zobrist hashing, matched score scale, a per-move null-window check, and matched PV capture, all 24 Bratko-Kopec positions now match the C++ reference bit-for-bit — identical bestmove, score, node count, and PV at fixed depth (verified at depths 8, 10 and 12, single-threaded, book off; at depth 12 the per-position diagnostic counters — cutoffs, TT hits, prunes, reductions, extensions — are identical too).
    • Apply early-exit heuristics (Standard clock only): stop early if the best move is consistent and/or the score is stable across depths, as a fraction of the allocated time budget.

Time allocation (Standard clock): allocated = timeRemaining / movesRemaining. Hard stop = max(100ms, min(allocated × 2, timeRemaining − 1s)), less Move Overhead and floored at 1 ms (go movetime is timeRemaining − Move Overhead, floored at 1 ms the same way), so every timed search has a hard limit. The hard deadline (and any go nodes limit) is polled every 2048 nodes (nodeCount & 0x7FF == 0) — a coarser interval let a node-heavy batch overrun the deadline; 2048 keeps the overrun sub-millisecond. During a ponder search hardDeadlineNanos holds a no-deadline sentinel, so the poll never fires until ponderhit swaps in a real deadline.

searchAlphaBeta highlights

The margins carry over unchanged from the C++ engine (the NNUE eval is the same centipawn scale). At non-PV, non-check nodes a static eval is computed once and drives both reverse futility pruning and the null-move gate. The null-window predicate beta == alpha+1 is recomputed per move against the live alpha (not precomputed once before the loop) — at a PV node, once an earlier move raises alpha to beta−1 the remaining moves are effectively null-window and LMP/LMR must engage; this is required for bit-identical parity with C++.

Technique Parameters
Check extension A node in check is searched one ply deeper; quiescence re-enters searchAlphaBeta (rather than standing pat) when in check
Internal iterative reduction −1 ply at depth ≥ noTTReduceMinDepth when there is no TT move
Reverse futility pruning non-PV non-check: return eval when depth ≤ rfpMaxDepth and eval − rfpMargin·depth ≥ beta
Null-move pruning R = 4; only when eval ≥ beta and there is enough material (no zugzwang); skipped in check / null-move positions
Late move pruning skip quiet moves at depth ≤ lmpMaxDepth once moveIdx ≥ lmpBase + depth²
Principal variation search (PVS) first move full window; later moves null-window; re-search full window on fail-high
Late move reduction (LMR) null-window non-check: −1 from move index > 3; −2 from index > 6 (depth > 3); −3 from index > 12; re-search at full depth on fail-high
Quiescence SEE pruning stop at the first losing capture (keys on the negative-SEE sign of losing captures in move ordering)
Transposition table Cut/All hits return early if score is conclusive; PV hits extend depth by 1 (off during the root's depth-1 ordering pass)

The pruning/reduction stack was worth +183 Elo (SPRT, 10+0.1); the check extension plus the countermove/continuation-history move ordering a further +160 Elo (both recorded 2026-07-01, measured against the engine of that date; the machine was not recorded).

Known limit: the PV extension is unbounded on a warm table. Each table hit on a stored PV entry adds back the ply the move took away, so along an old principal line the depth never falls. On a table warm from earlier searches, 18.4% of release 2.3.0's first depth-4 lines reached seldepth 40 or more (3.2% from a cold table), up to 62; it is capped by maxPly (64) and overflows nothing. It is not fixed, because a fix changes the bench and needs its own measurement across all three ports; 2.3.1 only keeps it out of the root's depth-1 ordering pass. Under Lazy SMP each thread walks the move list independently; parallelism comes from many whole-tree searches sharing the lockless transposition table, not from splitting a node.

Move ordering

Within searchAlphaBeta, moves are ordered by scoreAndSortMoves, a banded scheme ported from the C++ engine (keyed by prevMove, the move played at the parent):

  1. TT move — tried first, before generating the full legal move list; on a beta cutoff, saves generating and scoring all moves.
  2. Remaining legal moves sorted into disjoint score bands:
    • Winning captures/promotions — winningCaptureBase (1<<20) + SEE, on top.
    • Killers — the two quiet moves that caused beta cutoffs at this ply (killers[ply][0/1]), scoring 1<<19 + 1 and 1<<19.
    • Countermove — the best quiet refutation recorded for prevMove (1<<19 − 1).
    • Other quiet moves — history + continuationHistory, clamped just below the countermove.
    • Losing captures — their negative SEE, sinking below the quiet moves (this sign is what quiescence SEE pruning keys on).

On a beta cutoff or alpha raise, recordGood credits the move to the history and continuation-history tables; a quiet cutoff additionally records it as a killer and as the countermove to prevMove. The countermove table and 1-ply continuation history live on the searchState and persist across a search.

Transposition table

Single table (engine/transposition.go) sized from hashTableMB (64 MB, the value uci advertises as the Hash default and the same as the C++ kHashtableMegabytes and the Rust HASHTABLE_MEGABYTES — table size changes the collision pattern and so the node count at a fixed depth, so the three ports are only bit-exact while their defaults agree). The entry count is rounded up to the next power of 2 so entries are indexed by hash & mask (a bitmask) rather than modulo.

Lockless — Hyatt's XOR trick (ported from the C++ engine). All of score, depth, node type and age are packed into the move's spare bits (see Move encoding), so a cell holds just two 64-bit words:

data  atomic.Uint64   the packed move (move identity + score/depth/nodeType/age)
key   atomic.Uint64   hash ^ data

find loads both words with relaxed atomics and accepts the cell only when key ^ data == hash. This one check does two jobs:

Each individual word is an atomic.Uint64 (relaxed load/store), so no single word is ever torn and Go's race detector stays quiet; the XOR key supplies the cross-word consistency that per-word atomicity alone cannot. Racing writers resolve to a benign last-writer-wins.

Replacement policy (record): overwrite when the slot is empty, the existing entry is from an older generation (cur.ttAge() != currentAge), the new depth is ≥ the stored depth, or the new node is PV.

Aging: currentAge uint8 is bumped by age() (O(1), wraps at 256) at the start of each root search; record stamps it onto each entry via setTTAge.

API: find(hash) → (transposition, bool) returns {hash, move} with depth()/nodeType() accessors (the score is read via move.score()) straight out of the packed move; record(hash, m, depth, nt) takes a move whose search score is already packed via m.withScore(score).

Evaluation

The engine evaluates exclusively with the embedded NNUE network (see below); scores are in centipawns from the perspective of the side to move. The evaluator entry point and fifty-move scaling live in engine/evaluate.go; the lockless eval cache in engine/evalcache.go:

Eval cache: results are cached in the lockless evalHashTable (~8 MB, ported from the C++ EvalCache): each slot is a single atomic.Uint64 packing the top 48 bits of the hash and a 16-bit score, so a load/store is atomic with no lock and a foreign/evicted entry fails the key check and reads as a miss. The cached value is the raw, clock-independent eval; clear() is called whenever the loaded net changes (EvalFile).

Fifty-move scaling: scaleByRule50 ramps the raw eval toward draw as the halfmove clock climbs past 20 plies (rule50ScaleThreshold), applied on the way out of the cache (never stored), so the search has a gradient to make progress rather than shuffle a won-but-unconverted position (fixes leaks like KBN-vs-K).

Static Exchange Evaluation (engine/see.go) simulates the sequence of captures on a square using the least-valuable-attacker method, propagating scores backwards so each side can choose not to recapture if it would lose material. evaluateStaticExchange is MakeMove-free (it applies the capture to a bitboard seeBoard and detects check with seeAttackersTo) and is used in move ordering and quiescence pruning to distinguish winning from losing captures. Piece values here are the simplified P=100, N/B=300, R=500, Q=900.

NNUE evaluation

The engine/nnue/ package is the engine's only evaluator, a direct Go port of the C++ Pawnstar NNUE — a Chess768 → 1024 → 1 network with 8 horizontally mirrored king buckets, 8 material output heads and SCReLU activation, quantised (QA=255, QB=64, scale=400). It reads the shared RNNUE1 net container directly (64-byte self-describing header + little-endian weight arrays), the one format every reckless-technology chess engine loads; the shipped net, engine/nnue/pawnstar-v20.bin, is embedded in the binary via go:embed. The package has no engine imports — positions cross the boundary as an nnue.Board (raw uint64 bitboards + uint8 piece codes), built by the small bridge in engine/nnue_bridge.go, which also hosts EnableNNUE/LoadNNUEFile and the search-band clamp. When first ported it measured +572 Elo over the engine's former handcrafted evaluation (fixed-depth self-play SPRT); that handcrafted eval has since been removed.

Provenance of the shipped network

The shipped net, engine/nnue/pawnstar-v20.bin — v20, of release 2.0.0 — is trained entirely on Leela Chess Zero self-play data, and is the same blob byte for byte in pawnstar, pawnstar-rs and pawnstar-go, which is what makes the three ports' fixed-depth node counts comparable at all. Its strength against v12, and the attribution for the earlier networks, which were trained on PlentyChess self-play data, are at the top of this README: The evaluation network.

Opening book

openingBook (engine/book.go) parses engine/book.txt — 3,328 opening lines, 3,244 of them built from the Lichess open database, which is dedicated to the public domain under Creative Commons CC0 1.0, so those lines carry no third party's restriction; the remaining 84 each end in a move this engine chose itself, for a position where every database move is marked questionable, and the file's own header says which they are. It is a byte-for-byte copy of the book pawnstar built with its tools/make_book.cpp and screened with its tools/filter_book, and ships as pawnstar.book, and the three ports' books are identical by design; the 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, and nothing here regenerates it. CC0 waives attribution, so the credit in THIRD-PARTY-NOTICES.md is given because it is right, not because anything obliges it. The book is embedded in the binary via go:embed (engine/book_embed.go) so no external file is needed, and .gitattributes marks it -text so no CRLF checkout can change the bytes that go in. loadOpeningBook replays each line from the start position and maps Zobrist hashes to candidate next moves. A move written with a trailing ? is questionable: it is replayed so the rest of the line still parses, but is never offered by getMove — matching the C++ book. The shipped book is marked: filter_book ran pawnstar's own NNUE at depth 12 over it and marked every move scoring more than 100 cp below its position's best, so the engine answers a book move it would not play itself and never offers it. getMove returns a random candidate, giving variety across games: candidates are stored with repeats, once per line that plays the move from the position, so a uniform pick is frequency-weighted — by the number of book lines through a move, not by a game count, since each line was pruned where the generator's thresholds stopped it and so appears exactly once.

History heuristic

historyTable (engine/history.go) is a butterfly table — counts[2][4096] indexed by side-to-move and the move's from/to squares — counting how often each move raised alpha or caused a beta cutoff anywhere in the search tree. Pooling across plies (it replaced a per-ply [maxPly][4096] table) concentrates the statistics where positions repeat across branches and transpositions, and the explicit colour dimension replaces the accidental colour proxy that ply parity provided. Counts are added to the quiet-move sort score by scoreAndSortMoves (alongside continuation history). The table lives on each searchState (per-thread, so Lazy SMP threads don't contend) and starts fresh each search.

UCI protocol

Game.HandleCommand (engine/uci.go; engine state in engine/game.go, the chess clock in engine/clock.go) processes commands on the calling goroutine. Supported:

Command Notes
uci Prints engine id and uciok
isready Prints readyok
license Prints the engine's licence and the third-party notices the shipped data obliges - the condensed form of THIRD-PARTY-NOTICES.md, in wording shared with the C++, Rust and trebuchet engines. Printing only: it reads and writes no engine state
ucinewgame Stops search, clears the TT and the eval cache, resets position and clock
position startpos [moves ...] Sets position from start FEN, applies move list
position fen <fen> [moves ...] Sets position from FEN, applies move list
go wtime <ms> btime <ms> [winc <ms> binc <ms>] [movestogo <n>] Standard clock; without movestogo, moves-to-go is a decreasing horizon max(40−move, 5). Increment is parsed but not folded into the budget (SPRT-neutral)
go movetime <ms> Fixed time per move
go depth <n> Fixed depth
go infinite Search until stop
go nodes <n> Search until the node limit (checked per thread)
go searchmoves <m…> Restrict the root search to the given moves. The list ends at the next recognised go keyword, so go searchmoves e2e4 depth 10 is a depth-10 search restricted to e2e4
go ... ponder Search on the opponent's time; no bestmove until ponderhit/stop
ponderhit Predicted move was played — convert the ponder search to a timed one (budget from now)
bench / bench <depth> Node-count benchmark over the 16 C++-reference (Bratko-Kopec) positions at depth benchDepth=13 (or an explicit <depth>); deterministic, single-threaded, book off, on a pinned 64 MB TT (signature independent of the Hash option). Current signature: 5,617,906 nodes (since release 2.0.0's net and shape; 6,601,454 with the v12 net at v12's shape, 6,888,983 with the earlier butterfly history), pinned by a golden-signature test
stop Signals search goroutines to halt
quit Stops search and exits
setoption name OwnBook value <true|false> Consult the opening book (false forces a real search)
setoption name EvalFile value <path|<embedded>> Load an external RNNUE1 net, or reload the embedded one (a refused net leaves the net already loaded playing, and says so on stdout and stderr)
setoption name Threads value <n> Lazy SMP search-thread count
setoption name Hash value <mb> Resize the transposition table (spin, default 64, 1–4096 MB)
setoption name Clear Hash Clear the TT and eval cache
setoption name Move Overhead value <ms> Time reserved from every deadline for GUI/network lag
setoption name Ponder value <true|false> Advertises pondering support (the GUI drives it via go ponder/ponderhit)

info lines carry depth, seldepth, score cp/score mate N, time, nodes, nps, hashfull, and pv. main.go sets the thread count from PAWNSTAR_THREADS/NumCPU, then reads stdin line-by-line and delegates each command to game.HandleCommand (NNUE is installed by NewGame).

Pondering (go ponder / ponderhit / Ponder option) searches on the opponent's time until the predicted move is played (ponderhit, which converts it to a timed search budgeted from that moment) or stop. The live clock is two atomic.Int64s on Game — armed on the UCI goroutine before the search starts, mutated only by ponderhit — so the concurrent read/write is data-race free (verified under -race by TestPonderRace). bestmove is deferred while pondering and emitted as bestmove <m> ponder <reply>.

Search diagnostics

engine/debug.go defines a global dbgx debugX struct with counters for beta cutoffs, TT hits by node type, null-move/LMR/PVS attempt and fail counts, the pruning/reduction techniques (check extensions, IIR, RFP, LMP, qsearch SEE prunes, the three LMR tiers), draw detection, and killer move beta cutoffs. The search reaches them through searchState.dbg: the main thread points at the global dbgx, each helper thread at a throwaway, so the counters neither race nor contend under Lazy SMP (helper counts are discarded). Call dbgxClear() before a search and dbgxPrint() after to inspect single-threaded search behaviour. Counters accumulate across searches unless explicitly reset.

License

pawnstar-go 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 (engine/nnue/pawnstar-v20.bin) is the one Pawnstar ships, under the same license — the same blob byte for byte in pawnstar, pawnstar-rs and pawnstar-go. It was trained on data that is not ours, which obliges a notice: THIRD-PARTY-NOTICES.md carries it, the license UCI command and pawnstar-go --license print it, and every release's documentation bundle ships it. This module has no third-party code dependencies, so that notice is the whole of what it owes: the opening book was built from the CC0-dedicated Lichess open database, and CC0 waives attribution, so the credit THIRD-PARTY-NOTICES.md gives Lichess is owed to nobody — it is there because saying where the lines came from is right.

← All five engines