#include "nnue.h" #include #include #include #include #include "incbin.h" #ifndef EVALFILE #error "EVALFILE must name the network file (the Makefile sets it)" #endif INCBIN(RigbyNet, EVALFILE); namespace rigby::nnue { namespace { // Layout of bullet's quantised.bin, padded by bullet to a multiple of 64 bytes. struct alignas(64) Network { i16 l0w[768][HIDDEN]; // feature-major: one HIDDEN-wide column per input i16 l0b[HIDDEN]; i16 l1w[2 * HIDDEN]; // side to move's half first i16 l1b; }; Network net; // Input index from one side's point of view: its own pieces first, and the // board flipped vertically for black (bullet's Chess768). inline int feature(int perspective, int piece, int sq) { const int theirs = piece_color(piece) != perspective; const int rel_sq = perspective == WHITE ? sq : sq ^ 56; return 384 * theirs + 64 * piece_type(piece) + rel_sq; } inline i64 screlu(i16 x) { const i64 y = std::clamp(x, 0, QA); return y * y; } } // namespace void init() { if (gRigbyNetSize < sizeof(Network)) { std::fprintf(stderr, "network %s is %u bytes, expected at least %u\n", EVALFILE, unsigned(gRigbyNetSize), unsigned(sizeof(Network))); std::exit(1); } std::memcpy(&net, gRigbyNetData, sizeof(Network)); } int evaluate(const Position& pos) { alignas(64) i16 us[HIDDEN]; alignas(64) i16 them[HIDDEN]; std::memcpy(us, net.l0b, sizeof(us)); std::memcpy(them, net.l0b, sizeof(them)); const int stm = pos.stm; u64 occ = pos.occupancy(); while (occ) { const int sq = pop_lsb(occ); const int piece = pos.piece_on(sq); const i16* w_us = net.l0w[feature(stm, piece, sq)]; const i16* w_them = net.l0w[feature(stm ^ 1, piece, sq)]; for (int i = 0; i < HIDDEN; i++) { us[i] = i16(us[i] + w_us[i]); them[i] = i16(them[i] + w_them[i]); } } // 256 products of up to QA^2 * |w| overflow 32 bits in the worst case. i64 out = 0; for (int i = 0; i < HIDDEN; i++) out += screlu(us[i]) * net.l1w[i]; for (int i = 0; i < HIDDEN; i++) out += screlu(them[i]) * net.l1w[HIDDEN + i]; out /= QA; out += net.l1b; out *= SCALE; out /= i64(QA) * QB; return int(out); } } // namespace rigby::nnue