Files
Rigby/src/policy.cpp
T
rektdieandclaude 53553c351a perf: hand-written SIMD for all network inference
The value and policy networks now run on hand-written vector kernels
(src/simd.h) instead of plain loops left to the auto-vectoriser. Paths for
AVX-512BW (VNNI dpwssd when present), AVX2 (AVX-VNNI when present), SSE2
(SSE4.1 sign extend when present) and NEON, chosen at compile time by
-march=native, plus a scalar fallback (-DRIGBY_NO_SIMD).

All arithmetic is exact integer maths, so every path gives the same results
as before and the bench is unchanged.

Value net:
- refresh sums the feature rows in registers, one tile at a time, and
  writes the accumulator once instead of once per piece
- update adds and subtracts the changed rows in one vector pass
- evaluate does SCReLU as v * (v * w) with mullo + madd; v * w fits
  16 bits because the output weights are at most 32767 / QA = 128 (now
  checked on load; the v1 net's largest is 127), and each half's sum fits
  32 bits (static_assert)

Policy net:
- the hidden layer sums the i8 rows (sign-extended on load) into
  register tiles of 8 vectors; row by row in memory was 1.8x slower
- CReLU and the pairwise product in one vector pass
- the output dot products run four moves at a time, sharing the loads of
  the activations (output stage about 20% faster than one at a time)

Tried and dropped: software prefetch of the weight rows (slower), storing
the policy's first layer as i16 to skip the sign extend (slower: the
accumulation is bound by memory, not by the extend).

Measured on a Ryzen 9 5900X (AVX2), bench 50000, four runs each:
main 4.43M nps, this 5.21M nps (+18%).

Checked: bench 615835 identical for AVX2, SSE2, SSE4.1 and scalar builds;
AVX-512 (skylake-avx512, icelake-server) and AVX-VNNI (alderlake) builds
compile; the NEON kernels compile for aarch64 (not run). UCI: uci,
isready, position, go nodes, setoption PolicyFile.

Bench: 615835

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:30:56 +01:00

215 lines
7.0 KiB
C++

#include "policy.h"
#include <algorithm>
#include <array>
#include <bit>
#include <cstdio>
#include <fstream>
#include <iterator>
#include <vector>
#include "simd.h"
#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.
const i8* rows[32];
int count = 0;
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;
rows[count++] = &net.l0w[size_t(feature) * h];
}
// Output rows of the moves.
const i8* out_rows[256];
int out_idx[256];
for (int m = 0; m < moves.size(); m++) {
out_idx[m] = move_index(pos, moves[m]);
out_rows[m] = &net.l1w[size_t(out_idx[m]) * half];
}
static thread_local std::vector<i16> acc;
static thread_local std::vector<i16> act;
acc.resize(size_t(h));
act.resize(size_t(half));
simd::accumulate(acc.data(), net.l0b.data(), rows, count, h);
// CReLU on both halves, multiplied pairwise: values up to Q * Q.
{
using namespace simd;
const vi16 lo = set1(0), hi = set1(Q);
int i = 0;
for (; i + LANES <= half; i += LANES) {
const vi16 a = clamp(simd::load(&acc[i]), lo, hi);
const vi16 b = clamp(simd::load(&acc[i + half]), lo, hi);
store(&act[i], mullo(a, b));
}
for (; i < half; i++) act[i] = i16(std::clamp<int>(acc[i], 0, Q) * std::clamp<int>(acc[i + half], 0, Q));
}
// One dot product per move, at most half * Q^3 (fits 32 bits); four moves
// at a time share the activation loads.
int sums[256];
int m = 0;
for (; m + 4 <= moves.size(); m += 4) simd::dot4(act.data(), out_rows + m, half, sums + m);
for (; m < moves.size(); m++) sums[m] = simd::dot(act.data(), out_rows[m], half);
for (m = 0; m < moves.size(); m++)
out[m] = float(sums[m]) / float(Q * Q * Q) + float(net.l1b[out_idx[m]]) / float(Q);
}
} // namespace rigby::policy