From 53553c351a9fffff116445dc0304300111de3593 Mon Sep 17 00:00:00 2001 From: rektdie Date: Mon, 16 Nov 2026 15:30:56 +0100 Subject: [PATCH] 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 --- src/nnue.cpp | 63 +++++++++---- src/policy.cpp | 56 +++++++---- src/simd.h | 248 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 329 insertions(+), 38 deletions(-) create mode 100644 src/simd.h diff --git a/src/nnue.cpp b/src/nnue.cpp index e31b3a5..4b368e2 100644 --- a/src/nnue.cpp +++ b/src/nnue.cpp @@ -1,11 +1,13 @@ #include "nnue.h" #include +#include #include #include #include #include "incbin.h" +#include "simd.h" #ifndef EVALFILE #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; } -inline i64 screlu(i16 x) { - const i64 y = std::clamp(x, 0, QA); - return y * y; -} +// The output layer squares the clamped hidden value with v * (v * w): v * w +// must fit 16 bits, so the weights are checked on load. +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 @@ -49,22 +54,26 @@ void init() { std::exit(1); } 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) { - std::memcpy(acc.values[WHITE], net.l0b, sizeof(net.l0b)); - std::memcpy(acc.values[BLACK], net.l0b, sizeof(net.l0b)); - + const i16* rows[2][32]; + int count = 0; u64 occ = pos.occupancy(); while (occ) { const int sq = pop_lsb(occ); const int piece = pos.piece_on(sq); - for (int side : {WHITE, BLACK}) { - const i16* w = net.l0w[feature(side, piece, sq)]; - i16* v = acc.values[side]; - for (int i = 0; i < HIDDEN; i++) v[i] = i16(v[i] + w[i]); - } + rows[WHITE][count] = net.l0w[feature(WHITE, piece, sq)]; + rows[BLACK][count++] = net.l0w[feature(BLACK, piece, sq)]; } + 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) { @@ -107,15 +116,23 @@ void update(const Accumulator& before, const Position& pos, Move m, Accumulator& i16* dst = after.values[side]; const i16* a0 = net.l0w[add[side][0]]; const i16* s0 = net.l0w[sub[side][0]]; + using simd::load, simd::store, simd::LANES; 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 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 const i16* a1 = net.l0w[add[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* them = acc.values[stm ^ 1]; - // 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]; + // SCReLU as v * (v * w) with v clamped to [0, QA]: exact, since v * w fits + // 16 bits and each half's sum fits 32 (checked above). + using namespace simd; + 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 += net.l1b; diff --git a/src/policy.cpp b/src/policy.cpp index d3ab335..54070fc 100644 --- a/src/policy.cpp +++ b/src/policy.cpp @@ -8,6 +8,8 @@ #include #include +#include "simd.h" + #ifdef POLICYFILE #include "incbin.h" INCBIN(RigbyPolicy, POLICYFILE); @@ -160,12 +162,8 @@ void logits(const Position& pos, const MoveList& moves, float* out) { const u64 defences = threats_by(pos, us); // Hidden layer: bias plus one column per active input. - static thread_local std::vector acc; - static thread_local std::vector act; - acc.resize(size_t(h)); - act.resize(size_t(half)); - for (int i = 0; i < h; i++) acc[i] = net.l0b[i]; - + const i8* rows[32]; + int count = 0; u64 occ = pos.occupancy(); while (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); if (threats & bb(sq)) feature += 768; if (defences & bb(sq)) feature += 1536; - const i8* w = &net.l0w[size_t(feature) * h]; - for (int i = 0; i < h; i++) acc[i] = i16(acc[i] + w[i]); + 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 acc; + static thread_local std::vector 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. - for (int i = 0; i < half; i++) { - const int a = std::clamp(acc[i], 0, Q); - const int b = std::clamp(acc[i + half], 0, Q); - act[i] = i16(a * b); + { + 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(acc[i], 0, Q) * std::clamp(acc[i + half], 0, Q)); } - for (int m = 0; m < moves.size(); m++) { - const int idx = move_index(pos, moves[m]); - const i8* w = &net.l1w[size_t(idx) * half]; - int sum = 0; - for (int i = 0; i < half; i++) sum += int(act[i]) * int(w[i]); - out[m] = float(sum) / float(Q * Q * Q) + float(net.l1b[idx]) / float(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 diff --git a/src/simd.h b/src/simd.h new file mode 100644 index 0000000..7e7dae5 --- /dev/null +++ b/src/simd.h @@ -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 + +#include "types.h" + +#if defined(RIGBY_NO_SIMD) +#define RIGBY_SIMD_SCALAR +#elif defined(__AVX512F__) && defined(__AVX512BW__) +#define RIGBY_SIMD_AVX512 +#include +#elif defined(__AVX2__) +#define RIGBY_SIMD_AVX2 +#include +#elif defined(__SSE2__) || defined(_M_X64) || defined(_M_AMD64) +#define RIGBY_SIMD_SSE2 +#include +#elif defined(__ARM_NEON) && defined(__aarch64__) +#define RIGBY_SIMD_NEON +#include +#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(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(p)); } +inline vi16 load(const i8* p) { return _mm256_cvtepi8_epi16(_mm_loadu_si128(reinterpret_cast(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(p)); } +inline vi16 load(const i8* p) { + const __m128i x = _mm_loadl_epi64(reinterpret_cast(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 +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 +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(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 +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 +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