From 15258f952a522642b8ea0f4a643480d95d6a490b Mon Sep 17 00:00:00 2001 From: rektdie Date: Sun, 15 Nov 2026 21:27:38 +0100 Subject: [PATCH] feat: policy network inference src/policy.cpp runs the network train/policy writes: 3072 threat inputs (side to move's view, flipped horizontally when its king is on files e-h, +768 attacked, +1536 defended), a hidden layer with CReLU and pairwise product, and one output row per move, i8 weights scaled by 128. The hidden width is read from the file's size, so any trained width loads. When a network is loaded, eval::policy uses its logits plus the butterfly-history bias instead of the move heuristics; the temperature and softmax are unchanged. A network is built in with make POLICYFILE= (default: none, so the engine plays as before) or loaded at runtime with the UCI option PolicyFile. policyfens prints the priors of the trainer's --check positions. Checked: with a smoke-trained network policyfens matches the trainer's float output to a few tenths of a percent in all six positions (black to move, mirrored king, castling, promotion). Speed with a network: -13% nps at 512 hidden, -41% at 2048. A zero network built in with POLICYFILE gives uniform priors. Without a network the bench is unchanged. Bench: 529903 Co-Authored-By: Claude Opus 5.5 --- Makefile | 9 +++ README.md | 11 ++- src/eval.cpp | 20 +++++ src/eval.h | 5 +- src/policy.cpp | 196 +++++++++++++++++++++++++++++++++++++++++++++++++ src/policy.h | 33 +++++++++ src/types.h | 1 + src/uci.cpp | 43 +++++++++++ 8 files changed, 313 insertions(+), 5 deletions(-) create mode 100644 src/policy.cpp create mode 100644 src/policy.h diff --git a/Makefile b/Makefile index ea8fadf..afc7dc8 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,6 @@ # Rigby - MCTS chess engine # OpenBench calls: make EXE= [EVALFILE=] [CXX=] +# A policy network is built in with POLICYFILE= (default: none). SRC_DIR := src OBJ_DIR := obj @@ -7,6 +8,8 @@ OBJ_DIR := obj EXE ?= Rigby # The value network embedded into the binary EVALFILE ?= networks/rigby-value-v1.bin +# The policy network embedded into the binary; none means move heuristics +POLICYFILE ?= CXX ?= clang++ ifeq ($(origin CXX),default) CXX := clang++ @@ -57,6 +60,9 @@ else endif CXXFLAGS += -DEVALFILE=\"$(EVALFILE)\" +ifneq ($(POLICYFILE),) + CXXFLAGS += -DPOLICYFILE=\"$(POLICYFILE)\" +endif CXXFLAGS += $(ARCH_FLAGS) LDFLAGS += $(ARCH_FLAGS) @@ -78,6 +84,9 @@ $(OBJ_DIR): # Rebuild the network's translation unit when the network changes $(OBJ_DIR)/nnue.o: $(EVALFILE) +ifneq ($(POLICYFILE),) +$(OBJ_DIR)/policy.o: $(POLICYFILE) +endif -include $(DEPS) diff --git a/README.md b/README.md index e39d5e0..5b97866 100644 --- a/README.md +++ b/README.md @@ -18,8 +18,10 @@ Every change is validated with SPRT on OpenBench. two-fold repetition, 50-move and insufficient-material draws inside the tree. - Value: a `(768 -> 128)x2 -> 1` network trained with bullet on Lc0 data (`networks/rigby-value-v1.bin`, embedded at build time; see `train/README.md`), - behind a capture-only quiescence search. Policy: move heuristics (captures, - promotions, checks, pawn threats) until a policy network exists. + behind a capture-only quiescence search. +- Policy: a network trained on Lc0 visit distributions (`train/policy`), loaded + with `PolicyFile` or built in with `POLICYFILE`; without one, move heuristics + (captures, promotions, checks, pawn threats). - Tree reuse between moves: the subtree of the new position is packed to the front of the node arena in place, so it costs no extra memory. - When the arena is full, the least visited parts of the tree are cut back to @@ -38,7 +40,8 @@ make EXE=Rigby-dev make EVALFILE=path/to/quantised.bin ``` -`EVALFILE` defaults to `networks/rigby-value-v1.bin`. +`EVALFILE` defaults to `networks/rigby-value-v1.bin`. `POLICYFILE=` builds a +policy network in; by default there is none and the move heuristics are used. Compiling with `-DRIGBY_VERIFY_TREE` checks the whole tree before and after every reuse and after every collection (legal moves, visit counts) and aborts on the first @@ -60,6 +63,7 @@ Extra commands: | `perft ` | Perft with per-move breakdown | | `perftsuite [maxdepth]` | Standard perft positions with expected counts | | `perftfile [maxdepth]` | Perft of every ` ;D1 ;D2 ...` line of a file (e.g. a Chess960 suite) | +| `policyfens` | Policy network priors of fixed positions, to compare with the trainer's `--check` | | `bench [playouts]` | Fixed playout search over the bench positions | `go depth N` limits the mean playout depth. `nodes` in `info` lines are playouts. @@ -87,6 +91,7 @@ terminal). | FPUReduction | 30 | First-play urgency reduction x100. | | PolicyTemp | 100 | Policy softmax temperature x100. | | UCI_Chess960 | false | Write and read castling as the king taking its rook (`e1h1`). | +| PolicyFile | `` | Policy network file to use instead of the built-in one or the heuristics. | ## Bench diff --git a/src/eval.cpp b/src/eval.cpp index 8d5d301..945a1a9 100644 --- a/src/eval.cpp +++ b/src/eval.cpp @@ -6,6 +6,7 @@ #include #include "nnue.h" +#include "policy.h" namespace rigby::eval { @@ -113,6 +114,7 @@ void init() { } } nnue::init(); + rigby::policy::init(); } int static_eval(const Position& pos) { return nnue::evaluate(pos); } @@ -200,6 +202,24 @@ int quiescence(const Position& pos, int alpha, int beta, int ply) { float value(const Position& pos) { return cp_to_q(quiescence(pos, -MATE, MATE, 0)); } void policy(const Position& pos, const MoveList& moves, float temperature, const float* bias, float* out) { + if (rigby::policy::loaded()) { + // The network's logits, shifted by the search's bias. + rigby::policy::logits(pos, moves, out); + const float inv_temp = 1.0f / std::max(temperature, 0.01f); + float max_logit = -1e30f; + for (int i = 0; i < moves.size(); i++) { + out[i] = (out[i] + (bias ? bias[i] : 0.0f)) * inv_temp; + max_logit = std::max(max_logit, out[i]); + } + float total = 0.0f; + for (int i = 0; i < moves.size(); i++) { + out[i] = std::exp(out[i] - max_logit); + total += out[i]; + } + for (int i = 0; i < moves.size(); i++) out[i] /= total; + return; + } + const int us = pos.stm; const int them = us ^ 1; const u64 occ = pos.occupancy(); diff --git a/src/eval.h b/src/eval.h index b01d464..dc079fa 100644 --- a/src/eval.h +++ b/src/eval.h @@ -5,7 +5,8 @@ namespace rigby::eval { // Value: the network trained on Lc0 data, behind a capture-only quiescence -// search. Policy: move heuristics until a policy network exists. +// search. Policy: the policy network when one is loaded (see policy.h), +// otherwise move heuristics. void init(); @@ -23,7 +24,7 @@ int quiescence(const Position& pos, int alpha, int beta, int ply); float value(const Position& pos); // Writes softmax-normalised priors for `moves` into `out`. `bias`, when not -// null, is added to each move's logit before the softmax. +// null, is added to each move's logit before the softmax (and the temperature). void policy(const Position& pos, const MoveList& moves, float temperature, const float* bias, float* out); // Conversion between centipawns and Q in [-1, 1]. One scale for both directions, diff --git a/src/policy.cpp b/src/policy.cpp new file mode 100644 index 0000000..d3ab335 --- /dev/null +++ b/src/policy.cpp @@ -0,0 +1,196 @@ +#include "policy.h" + +#include +#include +#include +#include +#include +#include +#include + +#ifdef POLICYFILE +#include "incbin.h" +INCBIN(RigbyPolicy, POLICYFILE); +#endif + +namespace rigby::policy { + +namespace { + +constexpr int Q = 128; + +// Weights as the trainer writes them (montytrain's save_quantised): l0w is +// feature-major ([input][hidden]), l1w move-major ([output][hidden / 2]). +struct Network { + int hidden = 0; + std::vector l0w, l0b, l1w, l1b; +}; + +Network net; + +// --- Output index (train/policy/src/inputs.rs map_move_to_index) --- + +// Squares a piece of each type could ever move to from a square, on an empty +// board, from white's side (pawns: one step forward or diagonally forward). +struct Tables { + u64 destinations[64][6]; + int offsets[6][65]; +}; + +const Tables& tables() { + static const Tables t = [] { + Tables t{}; + for (int sq = 0; sq < 64; sq++) { + const u64 b = bb(sq); + t.destinations[sq][PAWN] = ((b & ~FILE_A_BB) << 7) | (b << 8) | ((b & ~FILE_H_BB) << 9); + t.destinations[sq][KNIGHT] = attacks::knight[sq]; + t.destinations[sq][BISHOP] = attacks::bishop(sq, 0); + t.destinations[sq][ROOK] = attacks::rook(sq, 0); + t.destinations[sq][QUEEN] = attacks::queen(sq, 0); + t.destinations[sq][KING] = attacks::king[sq]; + } + int current = 0; + for (int pc = 0; pc < 6; pc++) { + for (int sq = 0; sq < 64; sq++) { + t.offsets[pc][sq] = current; + current += popcount(t.destinations[sq][pc]); + } + t.offsets[pc][64] = current; + } + return t; + }(); + return t; +} + +constexpr int PROMO_STRIDE = 22; + +// Squares attacked by `side`, sliders seeing through the other side's king. +u64 threats_by(const Position& pos, int side) { + const u64 occ = pos.occupancy() ^ pos.pieces_of(side ^ 1, KING); + u64 threats = 0; + u64 b = pos.pieces_of(side, ROOK) | pos.pieces_of(side, QUEEN); + while (b) threats |= attacks::rook(pop_lsb(b), occ); + b = pos.pieces_of(side, BISHOP) | pos.pieces_of(side, QUEEN); + while (b) threats |= attacks::bishop(pop_lsb(b), occ); + b = pos.pieces_of(side, KNIGHT); + while (b) threats |= attacks::knight[pop_lsb(b)]; + threats |= attacks::king[pos.king_square(side)]; + b = pos.pieces_of(side, PAWN); + while (b) threats |= attacks::pawn[side][pop_lsb(b)]; + return threats; +} + +bool set(std::vector data) { + // size = INPUTS * h + h + (h / 2) * OUTPUTS + OUTPUTS + const size_t per_hidden = INPUTS + 1 + OUTPUTS / 2; + if (data.size() <= OUTPUTS || (data.size() - OUTPUTS) % per_hidden) return false; + const int h = int((data.size() - OUTPUTS) / per_hidden); + if (h % 2) return false; + + Network n; + n.hidden = h; + auto it = data.begin(); + const auto take = [&](std::vector& v, size_t count) { + v.assign(it, it + std::ptrdiff_t(count)); + it += std::ptrdiff_t(count); + }; + take(n.l0w, size_t(INPUTS) * h); + take(n.l0b, h); + take(n.l1w, size_t(OUTPUTS) * (h / 2)); + take(n.l1b, OUTPUTS); + net = std::move(n); + return true; +} + +bool load_builtin() { +#ifdef POLICYFILE + const auto* p = reinterpret_cast(gRigbyPolicyData); + return set(std::vector(p, p + gRigbyPolicySize)); +#else + net = Network{}; + return true; +#endif +} + +} // namespace + +void init() { + tables(); + if (!load_builtin()) { + std::fprintf(stderr, "built-in policy network has the wrong size\n"); + net = Network{}; + } +} + +bool load(const std::string& path) { + if (path.empty() || path == "") return load_builtin(); + std::ifstream in(path, std::ios::binary); + if (!in) return false; + std::vector raw((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + return set(std::vector(raw.begin(), raw.end())); +} + +bool loaded() { return net.hidden > 0; } + +int hidden() { return net.hidden; } + +int move_index(const Position& pos, Move m) { + const Tables& t = tables(); + const int hm = file_of(pos.king_square(pos.stm)) > 3 ? 7 : 0; + const int flip = hm ^ (pos.stm == BLACK ? 56 : 0); + const int src = m.from() ^ flip; + const int dst = m.to() ^ flip; + const int specials = t.offsets[KING][64]; + + if (m.is_promotion()) + return specials + PROMO_STRIDE * (m.promo_type() - KNIGHT) + 2 * file_of(src) + file_of(dst); + if (m.is_castle()) return specials + 4 * PROMO_STRIDE + ((m.flag() == Move::KING_CASTLE) ^ (hm == 0)); + if (m.flag() == Move::DOUBLE_PUSH) return specials + 4 * PROMO_STRIDE + 2 + file_of(src); + const int pc = piece_type(pos.piece_on(m.from())); + const u64 below = t.destinations[src][pc] & (bb(dst) - 1); + return t.offsets[pc][src] + popcount(below); +} + +void logits(const Position& pos, const MoveList& moves, float* out) { + const int h = net.hidden; + const int half = h / 2; + const int us = pos.stm; + const int flip = (us == BLACK ? 56 : 0) ^ (file_of(pos.king_square(us)) > 3 ? 7 : 0); + const u64 threats = threats_by(pos, us ^ 1); + const u64 defences = threats_by(pos, us); + + // Hidden layer: bias plus one column per active input. + static thread_local std::vector acc; + static thread_local std::vector act; + acc.resize(size_t(h)); + act.resize(size_t(half)); + for (int i = 0; i < h; i++) acc[i] = net.l0b[i]; + + u64 occ = pos.occupancy(); + while (occ) { + const int sq = pop_lsb(occ); + const int piece = pos.piece_on(sq); + int feature = 384 * (piece_color(piece) != us) + 64 * piece_type(piece) + (sq ^ flip); + if (threats & bb(sq)) feature += 768; + if (defences & bb(sq)) feature += 1536; + const i8* w = &net.l0w[size_t(feature) * h]; + for (int i = 0; i < h; i++) acc[i] = i16(acc[i] + w[i]); + } + + // CReLU on both halves, multiplied pairwise: values up to Q * Q. + for (int i = 0; i < half; i++) { + const int a = std::clamp(acc[i], 0, Q); + const int b = std::clamp(acc[i + half], 0, Q); + act[i] = i16(a * b); + } + + for (int m = 0; m < moves.size(); m++) { + const int idx = move_index(pos, moves[m]); + const i8* w = &net.l1w[size_t(idx) * half]; + int sum = 0; + for (int i = 0; i < half; i++) sum += int(act[i]) * int(w[i]); + out[m] = float(sum) / float(Q * Q * Q) + float(net.l1b[idx]) / float(Q); + } +} + +} // namespace rigby::policy diff --git a/src/policy.h b/src/policy.h new file mode 100644 index 0000000..bf05409 --- /dev/null +++ b/src/policy.h @@ -0,0 +1,33 @@ +#pragma once + +#include + +#include "position.h" + +namespace rigby::policy { + +// Policy network trained on Lc0 visit distributions (train/policy): +// 3072 threat inputs -> HIDDEN, CReLU, pairwise product (HIDDEN / 2), then one +// output row per move, i8 weights quantised by 128. HIDDEN is read from the +// file's size, so any trained width loads. +constexpr int INPUTS = 3072; +constexpr int OUTPUTS = 3920; + +// Loads the network built into the binary (Makefile POLICYFILE), if there is one. +void init(); + +// Loads a network file, replacing the current one; an empty path goes back to +// the built-in network (or none). False, keeping the old one, if the file does +// not have the size of a network. +bool load(const std::string& path); + +bool loaded(); +int hidden(); + +// Raw logits of `moves` in `pos` (before any temperature). Requires loaded(). +void logits(const Position& pos, const MoveList& moves, float* out); + +// The output row of a move, as the trainer maps it (exposed for tests). +int move_index(const Position& pos, Move m); + +} // namespace rigby::policy diff --git a/src/types.h b/src/types.h index 8d8d9fd..a345e53 100644 --- a/src/types.h +++ b/src/types.h @@ -11,6 +11,7 @@ using u32 = std::uint32_t; using u16 = std::uint16_t; using u8 = std::uint8_t; using i64 = std::int64_t; +using i8 = std::int8_t; using i16 = std::int16_t; constexpr std::string_view START_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; diff --git a/src/uci.cpp b/src/uci.cpp index 9256f40..cf56e01 100644 --- a/src/uci.cpp +++ b/src/uci.cpp @@ -13,6 +13,7 @@ #include "eval.h" #include "mcts.h" #include "perft.h" +#include "policy.h" #include "position.h" #include "pretty.h" #include "uci_io.h" @@ -54,6 +55,8 @@ void print_id() { send("option name Threads type spin default 1 min 1 max 1"); send("option name MoveOverhead type spin default 20 min 0 max 5000"); send("option name UCI_Chess960 type check default false"); + // A policy network file to use instead of the built-in one (or the move heuristics). + send("option name PolicyFile type string default "); // Search constants, exposed as integers (x100) so SPSA can tune them. send("option name CPuct type spin default 160 min 1 max 1000"); send("option name RootCPuct type spin default 233 min 1 max 1000"); @@ -75,6 +78,12 @@ void set_option(Engine& e, std::istringstream& is) { chess960 = value == "true"; return; } + if (lname == "policyfile") { + if (!policy::load(value)) send("info string cannot load policy network " + value); + else if (policy::loaded()) send("info string policy network " + std::to_string(policy::hidden()) + " hidden"); + else send("info string no policy network, using move heuristics"); + return; + } int v = 0; try { @@ -269,6 +278,40 @@ void uci_loop() { std::snprintf(line, sizeof(line), "%6d cp %s", eval::static_eval(pos), fen); send(line); } + } else if (cmd == "policyfens") { + // Same positions as the policy trainer's --check, to compare inference + static constexpr const char* FENS[] = { + "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", + "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1", + "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1", + "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R b KQkq - 0 1", + "6k1/5pp1/1p2p2p/1Pq1Pn2/2P2P2/6P1/4Q1BP/6K1 w - - 1 30", + "8/2P2k2/8/8/8/8/5K2/8 w - - 0 1", + }; + if (!policy::loaded()) { + send("info string no policy network loaded"); + continue; + } + for (const char* fen : FENS) { + Position pos; + pos.set_fen(fen); + MoveList moves; + generate_legal(pos, moves); + float priors[256]; + eval::policy(pos, moves, 1.0f, nullptr, priors); + std::vector> lines; + for (int i = 0; i < moves.size(); i++) lines.push_back({priors[i], pos.uci(moves[i])}); + std::sort(lines.begin(), lines.end(), [](const auto& a, const auto& b) { + return a.first != b.first ? a.first > b.first : a.second < b.second; + }); + send(""); + send(fen); + for (const auto& [p, uci] : lines) { + char line[64]; + std::snprintf(line, sizeof(line), " %-6s %6.2f%%", uci.c_str(), p * 100.0f); + send(line); + } + } } else if (cmd == "perft") { int depth = 5; is >> depth;