Hand-written SIMD for all network inference #21

Merged
claude merged 1 commits from simd-inference into main 2026-11-16 15:43:58 +01:00
3 changed files with 329 additions and 38 deletions

No files matched your search

+44 -19
View File
@@ -1,11 +1,13 @@
#include "nnue.h" #include "nnue.h"
#include <algorithm> #include <algorithm>
#include <climits>
#include <cstdio> #include <cstdio>
#include <cstdlib> #include <cstdlib>
#include <cstring> #include <cstring>
#include "incbin.h" #include "incbin.h"
#include "simd.h"
#ifndef EVALFILE #ifndef EVALFILE
#error "EVALFILE must name the network file (the Makefile sets it)" #error "EVALFILE must name the network file (the Makefile sets it)"
@@ -35,10 +37,13 @@ inline int feature(int perspective, int piece, int sq) {
return 384 * theirs + 64 * piece_type(piece) + rel_sq; return 384 * theirs + 64 * piece_type(piece) + rel_sq;
} }
inline i64 screlu(i16 x) { // The output layer squares the clamped hidden value with v * (v * w): v * w
const i64 y = std::clamp<i64>(x, 0, QA); // must fit 16 bits, so the weights are checked on load.
return y * y; constexpr int MAX_L1W = 32767 / QA;
}
// Each half's dot product is summed in 32 bits.
static_assert(i64(HIDDEN) * QA * QA * MAX_L1W <= INT_MAX);
static_assert(HIDDEN % simd::LANES == 0);
} // namespace } // namespace
@@ -49,22 +54,26 @@ void init() {
std::exit(1); std::exit(1);
} }
std::memcpy(&net, gRigbyNetData, sizeof(Network)); std::memcpy(&net, gRigbyNetData, sizeof(Network));
for (int i = 0; i < 2 * HIDDEN; i++) {
if (std::abs(net.l1w[i]) > MAX_L1W) {
std::fprintf(stderr, "network %s has an output weight of %d, the limit is %d\n", EVALFILE, net.l1w[i],
MAX_L1W);
std::exit(1);
}
}
} }
void refresh(const Position& pos, Accumulator& acc) { void refresh(const Position& pos, Accumulator& acc) {
std::memcpy(acc.values[WHITE], net.l0b, sizeof(net.l0b)); const i16* rows[2][32];
std::memcpy(acc.values[BLACK], net.l0b, sizeof(net.l0b)); int count = 0;
u64 occ = pos.occupancy(); u64 occ = pos.occupancy();
while (occ) { while (occ) {
const int sq = pop_lsb(occ); const int sq = pop_lsb(occ);
const int piece = pos.piece_on(sq); const int piece = pos.piece_on(sq);
for (int side : {WHITE, BLACK}) { rows[WHITE][count] = net.l0w[feature(WHITE, piece, sq)];
const i16* w = net.l0w[feature(side, piece, sq)]; rows[BLACK][count++] = net.l0w[feature(BLACK, piece, sq)];
i16* v = acc.values[side];
for (int i = 0; i < HIDDEN; i++) v[i] = i16(v[i] + w[i]);
}
} }
for (int side : {WHITE, BLACK}) simd::accumulate(acc.values[side], net.l0b, rows[side], count, HIDDEN);
} }
void update(const Accumulator& before, const Position& pos, Move m, Accumulator& after) { void update(const Accumulator& before, const Position& pos, Move m, Accumulator& after) {
@@ -107,15 +116,23 @@ void update(const Accumulator& before, const Position& pos, Move m, Accumulator&
i16* dst = after.values[side]; i16* dst = after.values[side];
const i16* a0 = net.l0w[add[side][0]]; const i16* a0 = net.l0w[add[side][0]];
const i16* s0 = net.l0w[sub[side][0]]; const i16* s0 = net.l0w[sub[side][0]];
using simd::load, simd::store, simd::LANES;
if (adds == 1 && subs == 1) { if (adds == 1 && subs == 1) {
for (int i = 0; i < HIDDEN; i++) dst[i] = i16(src[i] + a0[i] - s0[i]); for (int i = 0; i < HIDDEN; i += LANES)
store(dst + i, simd::sub(simd::add(load(src + i), load(a0 + i)), load(s0 + i)));
} else if (adds == 1) { // capture or capture-promotion } else if (adds == 1) { // capture or capture-promotion
const i16* s1 = net.l0w[sub[side][1]]; const i16* s1 = net.l0w[sub[side][1]];
for (int i = 0; i < HIDDEN; i++) dst[i] = i16(src[i] + a0[i] - s0[i] - s1[i]); for (int i = 0; i < HIDDEN; i += LANES) {
const simd::vi16 added = simd::add(load(src + i), load(a0 + i));
store(dst + i, simd::sub(simd::sub(added, load(s0 + i)), load(s1 + i)));
}
} else { // castling } else { // castling
const i16* a1 = net.l0w[add[side][1]]; const i16* a1 = net.l0w[add[side][1]];
const i16* s1 = net.l0w[sub[side][1]]; const i16* s1 = net.l0w[sub[side][1]];
for (int i = 0; i < HIDDEN; i++) dst[i] = i16(src[i] + a0[i] + a1[i] - s0[i] - s1[i]); for (int i = 0; i < HIDDEN; i += LANES) {
const simd::vi16 added = simd::add(simd::add(load(src + i), load(a0 + i)), load(a1 + i));
store(dst + i, simd::sub(simd::sub(added, load(s0 + i)), load(s1 + i)));
}
} }
} }
} }
@@ -124,10 +141,18 @@ int evaluate(const Accumulator& acc, int stm) {
const i16* us = acc.values[stm]; const i16* us = acc.values[stm];
const i16* them = acc.values[stm ^ 1]; const i16* them = acc.values[stm ^ 1];
// 256 products of up to QA^2 * |w| overflow 32 bits in the worst case. // SCReLU as v * (v * w) with v clamped to [0, QA]: exact, since v * w fits
i64 out = 0; // 16 bits and each half's sum fits 32 (checked above).
for (int i = 0; i < HIDDEN; i++) out += screlu(us[i]) * net.l1w[i]; using namespace simd;
for (int i = 0; i < HIDDEN; i++) out += screlu(them[i]) * net.l1w[HIDDEN + i]; const vi16 lo = set1(0), hi = set1(QA);
vi32 sum_us = zero32(), sum_them = zero32();
for (int i = 0; i < HIDDEN; i += LANES) {
const vi16 u = clamp(load(us + i), lo, hi);
const vi16 t = clamp(load(them + i), lo, hi);
sum_us = dot(sum_us, mullo(u, load(net.l1w + i)), u);
sum_them = dot(sum_them, mullo(t, load(net.l1w + HIDDEN + i)), t);
}
i64 out = i64(reduce(sum_us)) + reduce(sum_them);
out /= QA; out /= QA;
out += net.l1b; out += net.l1b;
+37 -19
View File
@@ -8,6 +8,8 @@
#include <iterator> #include <iterator>
#include <vector> #include <vector>
#include "simd.h"
#ifdef POLICYFILE #ifdef POLICYFILE
#include "incbin.h" #include "incbin.h"
INCBIN(RigbyPolicy, POLICYFILE); INCBIN(RigbyPolicy, POLICYFILE);
@@ -160,12 +162,8 @@ void logits(const Position& pos, const MoveList& moves, float* out) {
const u64 defences = threats_by(pos, us); const u64 defences = threats_by(pos, us);
// Hidden layer: bias plus one column per active input. // Hidden layer: bias plus one column per active input.
static thread_local std::vector<i16> acc; const i8* rows[32];
static thread_local std::vector<i16> act; int count = 0;
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(); u64 occ = pos.occupancy();
while (occ) { while (occ) {
const int sq = pop_lsb(occ); const int sq = pop_lsb(occ);
@@ -173,24 +171,44 @@ void logits(const Position& pos, const MoveList& moves, float* out) {
int feature = 384 * (piece_color(piece) != us) + 64 * piece_type(piece) + (sq ^ flip); int feature = 384 * (piece_color(piece) != us) + 64 * piece_type(piece) + (sq ^ flip);
if (threats & bb(sq)) feature += 768; if (threats & bb(sq)) feature += 768;
if (defences & bb(sq)) feature += 1536; if (defences & bb(sq)) feature += 1536;
const i8* w = &net.l0w[size_t(feature) * h]; rows[count++] = &net.l0w[size_t(feature) * h];
for (int i = 0; i < h; i++) acc[i] = i16(acc[i] + w[i]);
} }
// 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. // 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); using namespace simd;
const int b = std::clamp<int>(acc[i + half], 0, Q); const vi16 lo = set1(0), hi = set1(Q);
act[i] = i16(a * b); 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));
} }
for (int m = 0; m < moves.size(); m++) { // One dot product per move, at most half * Q^3 (fits 32 bits); four moves
const int idx = move_index(pos, moves[m]); // at a time share the activation loads.
const i8* w = &net.l1w[size_t(idx) * half]; int sums[256];
int sum = 0; int m = 0;
for (int i = 0; i < half; i++) sum += int(act[i]) * int(w[i]); for (; m + 4 <= moves.size(); m += 4) simd::dot4(act.data(), out_rows + m, half, sums + m);
out[m] = float(sum) / float(Q * Q * Q) + float(net.l1b[idx]) / float(Q); 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 } // namespace rigby::policy
+248
View File
@@ -0,0 +1,248 @@
#pragma once
// Hand-written vector kernels for the networks, one set per instruction set,
// picked at compile time (the Makefile builds with -march=native;
// -DRIGBY_NO_SIMD forces the scalar fallback). Every op is
// exact integer arithmetic, so all paths give the same results as the scalar
// fallback, and the bench does not depend on the machine.
#include <cstdint>
#include "types.h"
#if defined(RIGBY_NO_SIMD)
#define RIGBY_SIMD_SCALAR
#elif defined(__AVX512F__) && defined(__AVX512BW__)
#define RIGBY_SIMD_AVX512
#include <immintrin.h>
#elif defined(__AVX2__)
#define RIGBY_SIMD_AVX2
#include <immintrin.h>
#elif defined(__SSE2__) || defined(_M_X64) || defined(_M_AMD64)
#define RIGBY_SIMD_SSE2
#include <immintrin.h>
#elif defined(__ARM_NEON) && defined(__aarch64__)
#define RIGBY_SIMD_NEON
#include <arm_neon.h>
#else
#define RIGBY_SIMD_SCALAR
#endif
namespace rigby::simd {
using i32 = std::int32_t;
// vi16: LANES 16-bit lanes. vi32: 32-bit sums of the same register width.
// ACC_REGS: registers a kernel may keep accumulating in without spilling.
#if defined(RIGBY_SIMD_AVX512)
using vi16 = __m512i;
using vi32 = __m512i;
constexpr int LANES = 32;
constexpr int ACC_REGS = 16;
constexpr const char* NAME = "avx512";
inline vi16 load(const i16* p) { return _mm512_loadu_si512(p); }
inline vi16 load(const i8* p) { return _mm512_cvtepi8_epi16(_mm256_loadu_si256(reinterpret_cast<const __m256i*>(p))); }
inline void store(i16* p, vi16 v) { _mm512_storeu_si512(p, v); }
inline vi16 set1(i16 x) { return _mm512_set1_epi16(x); }
inline vi16 add(vi16 a, vi16 b) { return _mm512_add_epi16(a, b); }
inline vi16 sub(vi16 a, vi16 b) { return _mm512_sub_epi16(a, b); }
inline vi16 min(vi16 a, vi16 b) { return _mm512_min_epi16(a, b); }
inline vi16 max(vi16 a, vi16 b) { return _mm512_max_epi16(a, b); }
inline vi16 mullo(vi16 a, vi16 b) { return _mm512_mullo_epi16(a, b); }
inline vi32 zero32() { return _mm512_setzero_si512(); }
inline vi32 add32(vi32 a, vi32 b) { return _mm512_add_epi32(a, b); }
// acc + a[2i] * b[2i] + a[2i+1] * b[2i+1] in each 32-bit lane.
inline vi32 dot(vi32 acc, vi16 a, vi16 b) {
#if defined(__AVX512VNNI__)
return _mm512_dpwssd_epi32(acc, a, b);
#else
return _mm512_add_epi32(acc, _mm512_madd_epi16(a, b));
#endif
}
inline i32 reduce(vi32 v) { return _mm512_reduce_add_epi32(v); }
#elif defined(RIGBY_SIMD_AVX2)
using vi16 = __m256i;
using vi32 = __m256i;
constexpr int LANES = 16;
constexpr int ACC_REGS = 8;
constexpr const char* NAME = "avx2";
inline vi16 load(const i16* p) { return _mm256_loadu_si256(reinterpret_cast<const __m256i*>(p)); }
inline vi16 load(const i8* p) { return _mm256_cvtepi8_epi16(_mm_loadu_si128(reinterpret_cast<const __m128i*>(p))); }
inline void store(i16* p, vi16 v) { _mm256_storeu_si256(reinterpret_cast<__m256i*>(p), v); }
inline vi16 set1(i16 x) { return _mm256_set1_epi16(x); }
inline vi16 add(vi16 a, vi16 b) { return _mm256_add_epi16(a, b); }
inline vi16 sub(vi16 a, vi16 b) { return _mm256_sub_epi16(a, b); }
inline vi16 min(vi16 a, vi16 b) { return _mm256_min_epi16(a, b); }
inline vi16 max(vi16 a, vi16 b) { return _mm256_max_epi16(a, b); }
inline vi16 mullo(vi16 a, vi16 b) { return _mm256_mullo_epi16(a, b); }
inline vi32 zero32() { return _mm256_setzero_si256(); }
inline vi32 add32(vi32 a, vi32 b) { return _mm256_add_epi32(a, b); }
inline vi32 dot(vi32 acc, vi16 a, vi16 b) {
#if defined(__AVXVNNI__)
return _mm256_dpwssd_avx_epi32(acc, a, b);
#else
return _mm256_add_epi32(acc, _mm256_madd_epi16(a, b));
#endif
}
inline i32 reduce(vi32 v) {
__m128i x = _mm_add_epi32(_mm256_castsi256_si128(v), _mm256_extracti128_si256(v, 1));
x = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
x = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(2, 3, 0, 1)));
return _mm_cvtsi128_si32(x);
}
#elif defined(RIGBY_SIMD_SSE2)
using vi16 = __m128i;
using vi32 = __m128i;
constexpr int LANES = 8;
constexpr int ACC_REGS = 8;
constexpr const char* NAME = "sse2";
inline vi16 load(const i16* p) { return _mm_loadu_si128(reinterpret_cast<const __m128i*>(p)); }
inline vi16 load(const i8* p) {
const __m128i x = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(p));
#if defined(__SSE4_1__)
return _mm_cvtepi8_epi16(x);
#else
return _mm_srai_epi16(_mm_unpacklo_epi8(x, x), 8);
#endif
}
inline void store(i16* p, vi16 v) { _mm_storeu_si128(reinterpret_cast<__m128i*>(p), v); }
inline vi16 set1(i16 x) { return _mm_set1_epi16(x); }
inline vi16 add(vi16 a, vi16 b) { return _mm_add_epi16(a, b); }
inline vi16 sub(vi16 a, vi16 b) { return _mm_sub_epi16(a, b); }
inline vi16 min(vi16 a, vi16 b) { return _mm_min_epi16(a, b); }
inline vi16 max(vi16 a, vi16 b) { return _mm_max_epi16(a, b); }
inline vi16 mullo(vi16 a, vi16 b) { return _mm_mullo_epi16(a, b); }
inline vi32 zero32() { return _mm_setzero_si128(); }
inline vi32 add32(vi32 a, vi32 b) { return _mm_add_epi32(a, b); }
inline vi32 dot(vi32 acc, vi16 a, vi16 b) { return _mm_add_epi32(acc, _mm_madd_epi16(a, b)); }
inline i32 reduce(vi32 x) {
x = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
x = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(2, 3, 0, 1)));
return _mm_cvtsi128_si32(x);
}
#elif defined(RIGBY_SIMD_NEON)
using vi16 = int16x8_t;
using vi32 = int32x4_t;
constexpr int LANES = 8;
constexpr int ACC_REGS = 16;
constexpr const char* NAME = "neon";
inline vi16 load(const i16* p) { return vld1q_s16(p); }
inline vi16 load(const i8* p) { return vmovl_s8(vld1_s8(p)); }
inline void store(i16* p, vi16 v) { vst1q_s16(p, v); }
inline vi16 set1(i16 x) { return vdupq_n_s16(x); }
inline vi16 add(vi16 a, vi16 b) { return vaddq_s16(a, b); }
inline vi16 sub(vi16 a, vi16 b) { return vsubq_s16(a, b); }
inline vi16 min(vi16 a, vi16 b) { return vminq_s16(a, b); }
inline vi16 max(vi16 a, vi16 b) { return vmaxq_s16(a, b); }
inline vi16 mullo(vi16 a, vi16 b) { return vmulq_s16(a, b); }
inline vi32 zero32() { return vdupq_n_s32(0); }
inline vi32 add32(vi32 a, vi32 b) { return vaddq_s32(a, b); }
// Pairs lanes differently from x86's madd, but every caller only needs the total.
inline vi32 dot(vi32 acc, vi16 a, vi16 b) {
acc = vmlal_s16(acc, vget_low_s16(a), vget_low_s16(b));
return vmlal_high_s16(acc, a, b);
}
inline i32 reduce(vi32 v) { return vaddvq_s32(v); }
#else
// One lane: the generic kernels below become the plain scalar loops.
using vi16 = i16;
using vi32 = i32;
constexpr int LANES = 1;
constexpr int ACC_REGS = 8;
constexpr const char* NAME = "scalar";
inline vi16 load(const i16* p) { return *p; }
inline vi16 load(const i8* p) { return *p; }
inline void store(i16* p, vi16 v) { *p = v; }
inline vi16 set1(i16 x) { return x; }
inline vi16 add(vi16 a, vi16 b) { return i16(a + b); }
inline vi16 sub(vi16 a, vi16 b) { return i16(a - b); }
inline vi16 min(vi16 a, vi16 b) { return a < b ? a : b; }
inline vi16 max(vi16 a, vi16 b) { return a > b ? a : b; }
inline vi16 mullo(vi16 a, vi16 b) { return i16(a * b); }
inline vi32 zero32() { return 0; }
inline vi32 add32(vi32 a, vi32 b) { return a + b; }
inline vi32 dot(vi32 acc, vi16 a, vi16 b) { return acc + i32(a) * i32(b); }
inline i32 reduce(vi32 v) { return v; }
#endif
inline vi16 clamp(vi16 x, vi16 lo, vi16 hi) { return min(max(x, lo), hi); }
namespace detail {
// R registers wide: dst = base + rows[0] + ... + rows[count - 1], from `offset`.
template <int R, typename B, typename W>
inline void accumulate_tile(i16* dst, const B* base, const W* const* rows, int count, int offset) {
vi16 r[R];
for (int k = 0; k < R; k++) r[k] = load(base + offset + k * LANES);
for (int f = 0; f < count; f++) {
const W* w = rows[f] + offset;
for (int k = 0; k < R; k++) r[k] = add(r[k], load(w + k * LANES));
}
for (int k = 0; k < R; k++) store(dst + offset + k * LANES, r[k]);
}
} // namespace detail
// dst[i] = base[i] + sum of rows[f][i] for i < n, wrapping in 16 bits like the
// scalar sum in any order. Rows are summed in registers one tile at a time,
// so dst is written once instead of once per row.
template <int TILE_REGS = ACC_REGS, typename B, typename W>
inline void accumulate(i16* dst, const B* base, const W* const* rows, int count, int n) {
constexpr int TILE = TILE_REGS * LANES;
int i = 0;
for (; i + TILE <= n; i += TILE) detail::accumulate_tile<TILE_REGS>(dst, base, rows, count, i);
for (; i + LANES <= n; i += LANES) detail::accumulate_tile<1>(dst, base, rows, count, i);
for (; i < n; i++) {
i16 v = i16(base[i]);
for (int f = 0; f < count; f++) v = i16(v + rows[f][i]);
dst[i] = v;
}
}
// Sum of a[i] * b[i] for i < n, in 32 bits (the caller makes sure it fits).
template <typename W>
inline i32 dot(const i16* a, const W* b, int n) {
vi32 s0 = zero32(), s1 = zero32();
int i = 0;
for (; i + 2 * LANES <= n; i += 2 * LANES) {
s0 = dot(s0, load(a + i), load(b + i));
s1 = dot(s1, load(a + i + LANES), load(b + i + LANES));
}
for (; i + LANES <= n; i += LANES) s0 = dot(s0, load(a + i), load(b + i));
i32 sum = reduce(add32(s0, s1));
for (; i < n; i++) sum += i32(a[i]) * i32(b[i]);
return sum;
}
// dot(a, b[k], n) for four rows at once, sharing the loads of `a`.
template <typename W>
inline void dot4(const i16* a, const W* const* b, int n, i32* out) {
vi32 s[4] = {zero32(), zero32(), zero32(), zero32()};
int i = 0;
for (; i + LANES <= n; i += LANES) {
const vi16 x = load(a + i);
for (int k = 0; k < 4; k++) s[k] = dot(s[k], x, load(b[k] + i));
}
for (int k = 0; k < 4; k++) {
out[k] = reduce(s[k]);
for (int j = i; j < n; j++) out[k] += i32(a[j]) * i32(b[k][j]);
}
}
} // namespace rigby::simd