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=<net> (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 <noreply@anthropic.com>
This commit is contained in:
1 parent
1c9d2beec3
commit
15258f952a
8 files changed
+313
-5
No files matched your search
@@ -6,6 +6,7 @@
|
||||
#include <cstdlib>
|
||||
|
||||
#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();
|
||||
|
||||
+3
-2
@@ -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,
|
||||
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
#include "policy.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <bit>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <vector>
|
||||
|
||||
#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<i8> 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<i8> 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<i8>& 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<const i8*>(gRigbyPolicyData);
|
||||
return set(std::vector<i8>(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 == "<empty>") return load_builtin();
|
||||
std::ifstream in(path, std::ios::binary);
|
||||
if (!in) return false;
|
||||
std::vector<char> raw((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
return set(std::vector<i8>(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<i16> acc;
|
||||
static thread_local std::vector<i16> 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<int>(acc[i], 0, Q);
|
||||
const int b = std::clamp<int>(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
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
#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
|
||||
@@ -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";
|
||||
|
||||
+43
@@ -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 <empty>");
|
||||
// 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<std::pair<float, std::string>> 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;
|
||||
|
||||
Reference in new issue
Block a user