Files
Rigby/src/eval.cpp
T
rektdieandclaude 15258f952a 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>
2026-11-15 21:27:38 +01:00

316 lines
11 KiB
C++

#include "eval.h"
#include <algorithm>
#include <iterator>
#include <cmath>
#include <cstdlib>
#include "nnue.h"
#include "policy.h"
namespace rigby::eval {
namespace {
constexpr int MATE = 30000;
constexpr int QS_MAX_PLY = 32;
// The network is trained so that sigmoid(cp / 400) is the expected score, so
// Q = 2 * sigmoid(cp / 400) - 1 = tanh(cp / 800).
constexpr float Q_SCALE = 2.0f * float(nnue::SCALE);
constexpr int SEE_VALUE[6] = {100, 300, 310, 500, 900, 0};
// Positional piece-square bonuses, white's view, used by the policy.
int mg_pst[6][64];
int pst_mg(int type, int sq) {
const int f = file_of(sq);
const int r = rank_of(sq);
const int center = std::abs(2 * f - 7) + std::abs(2 * r - 7); // 2..14
const bool central_file = f == 3 || f == 4;
switch (type) {
case PAWN:
return (r >= 1 && r <= 6) ? (r - 1) * 6 + (central_file ? (r - 1) * 4 : 0) : 0;
case KNIGHT:
return 24 - center * 4;
case BISHOP:
return 12 - center * 2;
case ROOK:
return (r == 6 ? 20 : 0) + (central_file ? 6 : 0);
case QUEEN:
return 6 - center;
default: // KING: stay sheltered
return -std::min(r, 3) * 25 + ((f <= 2 || f >= 6) ? 15 : -15);
}
}
int victim_type(const Position& pos, Move m) { return m.is_en_passant() ? PAWN : piece_type(pos.piece_on(m.to())); }
} // namespace
bool see_ge(const Position& pos, Move m, int threshold) {
// Castling, en passant and promotions are taken as an even trade.
if (m.is_castle() || m.is_en_passant() || m.is_promotion()) return threshold <= 0;
const int from = m.from();
const int to = m.to();
// `swap` is what the side to move is ahead of the threshold if the exchange
// stops now, seen from the side that just captured.
int swap = (pos.piece_on(to) == NO_PIECE ? 0 : SEE_VALUE[piece_type(pos.piece_on(to))]) - threshold;
if (swap < 0) return false;
swap = SEE_VALUE[piece_type(pos.piece_on(from))] - swap;
if (swap <= 0) return true;
u64 occ = pos.occupancy() ^ bb(from) ^ bb(to);
u64 attackers = pos.attackers_to(to, occ);
const u64 diagonal = pos.pieces[BISHOP] | pos.pieces[QUEEN];
const u64 straight = pos.pieces[ROOK] | pos.pieces[QUEEN];
int stm = pos.stm;
int result = 1;
for (;;) {
stm ^= 1;
attackers &= occ;
const u64 ours = attackers & pos.colors[stm];
if (!ours) break;
result ^= 1;
// Recapture with the least valuable piece; taking it off the board may
// open a line for a slider behind it.
u64 b;
if ((b = ours & pos.pieces[PAWN])) {
if ((swap = SEE_VALUE[PAWN] - swap) < result) break;
occ ^= bb(lsb(b));
attackers |= attacks::bishop(to, occ) & diagonal;
} else if ((b = ours & pos.pieces[KNIGHT])) {
if ((swap = SEE_VALUE[KNIGHT] - swap) < result) break;
occ ^= bb(lsb(b));
} else if ((b = ours & pos.pieces[BISHOP])) {
if ((swap = SEE_VALUE[BISHOP] - swap) < result) break;
occ ^= bb(lsb(b));
attackers |= attacks::bishop(to, occ) & diagonal;
} else if ((b = ours & pos.pieces[ROOK])) {
if ((swap = SEE_VALUE[ROOK] - swap) < result) break;
occ ^= bb(lsb(b));
attackers |= attacks::rook(to, occ) & straight;
} else if ((b = ours & pos.pieces[QUEEN])) {
if ((swap = SEE_VALUE[QUEEN] - swap) < result) break;
occ ^= bb(lsb(b));
attackers |= (attacks::bishop(to, occ) & diagonal) | (attacks::rook(to, occ) & straight);
} else {
// Only the king is left: it may recapture only if nothing defends the square.
return (attackers & ~pos.colors[stm]) ? result ^ 1 : result;
}
}
return result;
}
void init() {
for (int type = PAWN; type <= KING; type++) {
for (int sq = 0; sq < 64; sq++) {
mg_pst[type][sq] = pst_mg(type, sq);
}
}
nnue::init();
rigby::policy::init();
}
int static_eval(const Position& pos) { return nnue::evaluate(pos); }
namespace {
// `acc` is the network's accumulator for `pos`; each child gets its own,
// updated from it, instead of being rebuilt from the whole board.
int qsearch(const Position& pos, const nnue::Accumulator& acc, int alpha, int beta, int ply) {
const bool in_check = pos.in_check();
int best = -MATE + ply;
int stand_pat = 0;
if (!in_check) {
stand_pat = nnue::evaluate(acc, pos.stm);
if (stand_pat >= beta || ply >= QS_MAX_PLY) return stand_pat;
best = stand_pat;
alpha = std::max(alpha, stand_pat);
}
// Out of check only captures and queen promotions are searched, so only
// those are generated; a position without any of them is still checked
// for stalemate.
MoveList list;
if (in_check) {
generate_legal(pos, list);
if (list.empty()) return -MATE + ply;
if (ply >= QS_MAX_PLY) return nnue::evaluate(acc, pos.stm);
} else {
generate_noisy(pos, list);
if (list.empty()) return has_legal_move(pos) ? best : 0;
}
Move moves[256];
int scores[256];
int count = 0;
for (Move m : list) {
const bool tactical = m.is_capture() || (m.is_promotion() && m.promo_type() == QUEEN);
if (!in_check && !tactical) continue;
int score = 0;
if (m.is_capture()) {
const int victim = victim_type(pos, m);
// Delta pruning: even winning the piece for free cannot reach alpha.
if (!in_check && !m.is_promotion() && stand_pat + SEE_VALUE[victim] + 200 <= alpha) continue;
// Captures that lose material in the exchange on the square.
if (!in_check && !see_ge(pos, m, 0)) continue;
score = SEE_VALUE[victim] * 16 - piece_type(pos.piece_on(m.from()));
}
if (m.is_promotion()) score += SEE_VALUE[m.promo_type()] * 16;
moves[count] = m;
scores[count++] = score;
}
for (int i = 0; i < count; i++) {
int best_idx = i;
for (int j = i + 1; j < count; j++)
if (scores[j] > scores[best_idx]) best_idx = j;
std::swap(moves[i], moves[best_idx]);
std::swap(scores[i], scores[best_idx]);
nnue::Accumulator child_acc;
nnue::update(acc, pos, moves[i], child_acc);
Position child = pos;
child.make_move(moves[i]);
const int score = -qsearch(child, child_acc, -beta, -alpha, ply + 1);
if (score > best) {
best = score;
if (score > alpha) {
alpha = score;
if (alpha >= beta) break;
}
}
}
return best;
}
} // namespace
int quiescence(const Position& pos, int alpha, int beta, int ply) {
nnue::Accumulator acc;
nnue::refresh(pos, acc);
return qsearch(pos, acc, alpha, beta, 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();
const u64 their_pawns = pos.pieces_of(them, PAWN);
const u64 pawn_threats = them == WHITE ? (((their_pawns << 7) & ~FILE_H_BB) | ((their_pawns << 9) & ~FILE_A_BB))
: (((their_pawns >> 7) & ~FILE_A_BB) | ((their_pawns >> 9) & ~FILE_H_BB));
// Squares from which each piece type would give a direct check.
const int eksq = pos.king_square(them);
u64 check_squares[6];
check_squares[PAWN] = attacks::pawn[them][eksq];
check_squares[KNIGHT] = attacks::knight[eksq];
check_squares[BISHOP] = attacks::bishop(eksq, occ);
check_squares[ROOK] = attacks::rook(eksq, occ);
check_squares[QUEEN] = check_squares[BISHOP] | check_squares[ROOK];
check_squares[KING] = 0;
// Whether the opponent wins the piece on a square in an exchange started
// with their least valuable attacker. Worked out once per square.
Position their_turn = pos;
their_turn.stm = them;
int hanging_cache[64];
std::fill(std::begin(hanging_cache), std::end(hanging_cache), -1);
const auto hanging = [&](int sq) {
if (hanging_cache[sq] < 0) {
const u64 attackers = pos.attackers_to(sq, occ) & pos.colors[them];
int lva = -1;
for (int t = PAWN; t <= KING && lva < 0; t++)
if (attackers & pos.pieces[t]) lva = lsb(attackers & pos.pieces[t]);
bool wins = false;
if (lva >= 0) {
// A king can only take a piece nothing defends.
if (piece_type(pos.piece_on(lva)) == KING)
wins = !(pos.attackers_to(sq, occ) & pos.colors[us]);
else
wins = see_ge(their_turn, Move(lva, sq, Move::CAPTURE), 1);
}
hanging_cache[sq] = wins;
}
return hanging_cache[sq] == 1;
};
const float inv_temp = 1.0f / std::max(temperature, 0.01f);
float max_logit = -1e30f;
for (int i = 0; i < moves.size(); i++) {
const Move m = moves[i];
const int from = m.from();
const int to = m.to();
const int type = piece_type(pos.piece_on(from));
float s = 0.0f;
// Captures are tried early, unless the exchange on the square loses material.
if (m.is_capture())
s += (see_ge(pos, m, 0) ? 1.0f : -1.0f) + 0.004f * SEE_VALUE[victim_type(pos, m)] -
0.0015f * SEE_VALUE[type];
if (m.is_promotion()) s += m.promo_type() == QUEEN ? 2.5f : -2.5f;
if (m.is_castle()) s += 0.8f;
s += 0.01f * float(mg_pst[type][relative_square(us, to)] - mg_pst[type][relative_square(us, from)]);
if (type != PAWN && type != KING) {
if (m.is_capture() && (pawn_threats & bb(to))) s -= 0.004f * SEE_VALUE[type];
// Moving a piece the opponent could win (to a pawn or any other attacker).
if (hanging(from)) s += 0.003f * SEE_VALUE[type];
}
// A quiet move that puts the piece where the exchange loses it (to a
// pawn, or to any attacker it is not defended well enough against).
if (!m.is_capture() && !m.is_promotion() && !see_ge(pos, m, 0)) s -= 0.004f * SEE_VALUE[type];
if (check_squares[m.is_promotion() ? m.promo_type() : type] & bb(to)) s += 0.5f;
if (bias) s += bias[i];
out[i] = s * 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;
}
float cp_to_q(int cp) { return std::tanh(float(cp) / Q_SCALE); }
int q_to_cp(float q) {
q = std::clamp(q, -0.9999f, 0.9999f);
return int(std::lround(Q_SCALE * std::atanh(q)));
}
} // namespace rigby::eval