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:
rektdieandclaude committed 2026-11-15 21:27:38 +01:00
1 parent 1c9d2beec3
commit 15258f952a
8 files changed
+313 -5

No files matched your search

+20
View File
@@ -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();