Path: blob/master/src/nnue/layers/affine_transform.h
376 views
/*1Stockfish, a UCI chess playing engine derived from Glaurung 2.12Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)34Stockfish is free software: you can redistribute it and/or modify5it under the terms of the GNU General Public License as published by6the Free Software Foundation, either version 3 of the License, or7(at your option) any later version.89Stockfish is distributed in the hope that it will be useful,10but WITHOUT ANY WARRANTY; without even the implied warranty of11MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12GNU General Public License for more details.1314You should have received a copy of the GNU General Public License15along with this program. If not, see <http://www.gnu.org/licenses/>.16*/1718// Definition of layer AffineTransform of NNUE evaluation function1920#ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED21#define NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED2223#include <cstdint>24#include <iostream>2526#include "../nnue_common.h"27#include "../simd.h"2829/*30This file contains the definition for a fully connected layer (aka affine transform).3132- expected use-case is for when PaddedInputDimensions == 32 and InputDimensions <= 32.33- that's why AVX512 is hard to implement34- expected use-case is small layers35- inputs are processed in chunks of 4, weights are respectively transposed36- accumulation happens directly to int32s37*/3839namespace Stockfish::Eval::NNUE::Layers {4041#if defined(USE_SSSE3) || defined(USE_NEON_DOTPROD)42#define ENABLE_SEQ_OPT43#endif4445// Fallback implementation for older/other architectures.46// Requires the input to be padded to at least 16 values.47#ifndef ENABLE_SEQ_OPT4849template<IndexType InputDimensions, IndexType PaddedInputDimensions, IndexType OutputDimensions>50static void affine_transform_non_ssse3(std::int32_t* output,51const std::int8_t* weights,52const std::int32_t* biases,53const std::uint8_t* input) {54#if defined(USE_SSE2) || defined(USE_NEON)55#if defined(USE_SSE2)56// At least a multiple of 16, with SSE2.57constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;58const __m128i Zeros = _mm_setzero_si128();59const auto inputVector = reinterpret_cast<const __m128i*>(input);6061#elif defined(USE_NEON)62constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;63const auto inputVector = reinterpret_cast<const int8x8_t*>(input);64#endif6566for (IndexType i = 0; i < OutputDimensions; ++i)67{68const IndexType offset = i * PaddedInputDimensions;6970#if defined(USE_SSE2)71__m128i sumLo = _mm_cvtsi32_si128(biases[i]);72__m128i sumHi = Zeros;73const auto row = reinterpret_cast<const __m128i*>(&weights[offset]);74for (IndexType j = 0; j < NumChunks; ++j)75{76__m128i row_j = _mm_load_si128(&row[j]);77__m128i input_j = _mm_load_si128(&inputVector[j]);78__m128i extendedRowLo = _mm_srai_epi16(_mm_unpacklo_epi8(row_j, row_j), 8);79__m128i extendedRowHi = _mm_srai_epi16(_mm_unpackhi_epi8(row_j, row_j), 8);80__m128i extendedInputLo = _mm_unpacklo_epi8(input_j, Zeros);81__m128i extendedInputHi = _mm_unpackhi_epi8(input_j, Zeros);82__m128i productLo = _mm_madd_epi16(extendedRowLo, extendedInputLo);83__m128i productHi = _mm_madd_epi16(extendedRowHi, extendedInputHi);84sumLo = _mm_add_epi32(sumLo, productLo);85sumHi = _mm_add_epi32(sumHi, productHi);86}87__m128i sum = _mm_add_epi32(sumLo, sumHi);88__m128i sumHigh_64 = _mm_shuffle_epi32(sum, _MM_SHUFFLE(1, 0, 3, 2));89sum = _mm_add_epi32(sum, sumHigh_64);90__m128i sum_second_32 = _mm_shufflelo_epi16(sum, _MM_SHUFFLE(1, 0, 3, 2));91sum = _mm_add_epi32(sum, sum_second_32);92output[i] = _mm_cvtsi128_si32(sum);9394#elif defined(USE_NEON)9596int32x4_t sum = {biases[i]};97const auto row = reinterpret_cast<const int8x8_t*>(&weights[offset]);98for (IndexType j = 0; j < NumChunks; ++j)99{100int16x8_t product = vmull_s8(inputVector[j * 2], row[j * 2]);101product = vmlal_s8(product, inputVector[j * 2 + 1], row[j * 2 + 1]);102sum = vpadalq_s16(sum, product);103}104output[i] = SIMD::neon_m128_reduce_add_epi32(sum);105106#endif107}108#else109std::memcpy(output, biases, sizeof(std::int32_t) * OutputDimensions);110111// Traverse weights in transpose order to take advantage of input sparsity112for (IndexType i = 0; i < InputDimensions; ++i)113if (input[i])114{115const std::int8_t* w = &weights[i];116const int in = input[i];117for (IndexType j = 0; j < OutputDimensions; ++j)118output[j] += w[j * PaddedInputDimensions] * in;119}120#endif121}122123#endif // !ENABLE_SEQ_OPT124125template<IndexType InDims, IndexType OutDims>126class AffineTransform {127public:128// Input/output type129using InputType = std::uint8_t;130using OutputType = std::int32_t;131132// Number of input/output dimensions133static constexpr IndexType InputDimensions = InDims;134static constexpr IndexType OutputDimensions = OutDims;135136static constexpr IndexType PaddedInputDimensions =137ceil_to_multiple<IndexType>(InputDimensions, MaxSimdWidth);138static constexpr IndexType PaddedOutputDimensions =139ceil_to_multiple<IndexType>(OutputDimensions, MaxSimdWidth);140141using OutputBuffer = OutputType[PaddedOutputDimensions];142143// Hash value embedded in the evaluation file144static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {145std::uint32_t hashValue = 0xCC03DAE4u;146hashValue += OutputDimensions;147hashValue ^= prevHash >> 1;148hashValue ^= prevHash << 31;149return hashValue;150}151152static constexpr IndexType get_weight_index_scrambled(IndexType i) {153return (i / 4) % (PaddedInputDimensions / 4) * OutputDimensions * 4154+ i / PaddedInputDimensions * 4 + i % 4;155}156157static constexpr IndexType get_weight_index(IndexType i) {158#ifdef ENABLE_SEQ_OPT159return get_weight_index_scrambled(i);160#else161return i;162#endif163}164165// Read network parameters166bool read_parameters(std::istream& stream) {167read_little_endian<BiasType>(stream, biases, OutputDimensions);168for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)169weights[get_weight_index(i)] = read_little_endian<WeightType>(stream);170171return !stream.fail();172}173174// Write network parameters175bool write_parameters(std::ostream& stream) const {176write_little_endian<BiasType>(stream, biases, OutputDimensions);177178for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)179write_little_endian<WeightType>(stream, weights[get_weight_index(i)]);180181return !stream.fail();182}183// Forward propagation184void propagate(const InputType* input, OutputType* output) const {185186#ifdef ENABLE_SEQ_OPT187188if constexpr (OutputDimensions > 1)189{190#if defined(USE_AVX512)191using vec_t = __m512i;192#define vec_set_32 _mm512_set1_epi32193#define vec_add_dpbusd_32 SIMD::m512_add_dpbusd_epi32194#elif defined(USE_AVX2)195using vec_t = __m256i;196#define vec_set_32 _mm256_set1_epi32197#define vec_add_dpbusd_32 SIMD::m256_add_dpbusd_epi32198#elif defined(USE_SSSE3)199using vec_t = __m128i;200#define vec_set_32 _mm_set1_epi32201#define vec_add_dpbusd_32 SIMD::m128_add_dpbusd_epi32202#elif defined(USE_NEON_DOTPROD)203using vec_t = int32x4_t;204#define vec_set_32 vdupq_n_s32205#define vec_add_dpbusd_32(acc, a, b) \206SIMD::dotprod_m128_add_dpbusd_epi32(acc, vreinterpretq_s8_s32(a), \207vreinterpretq_s8_s32(b))208#endif209210static constexpr IndexType OutputSimdWidth = sizeof(vec_t) / sizeof(OutputType);211212static_assert(OutputDimensions % OutputSimdWidth == 0);213214constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 8) / 4;215constexpr IndexType NumRegs = OutputDimensions / OutputSimdWidth;216217const auto input32 = reinterpret_cast<const std::int32_t*>(input);218const vec_t* biasvec = reinterpret_cast<const vec_t*>(biases);219vec_t acc[NumRegs];220for (IndexType k = 0; k < NumRegs; ++k)221acc[k] = biasvec[k];222223for (IndexType i = 0; i < NumChunks; ++i)224{225const vec_t in0 = vec_set_32(input32[i]);226const auto col0 =227reinterpret_cast<const vec_t*>(&weights[i * OutputDimensions * 4]);228229for (IndexType k = 0; k < NumRegs; ++k)230vec_add_dpbusd_32(acc[k], in0, col0[k]);231}232233vec_t* outptr = reinterpret_cast<vec_t*>(output);234for (IndexType k = 0; k < NumRegs; ++k)235outptr[k] = acc[k];236237#undef vec_set_32238#undef vec_add_dpbusd_32239}240else if constexpr (OutputDimensions == 1)241{242// We cannot use AVX512 for the last layer because there are only 32 inputs243// and the buffer is not padded to 64 elements.244#if defined(USE_AVX2)245using vec_t = __m256i;246#define vec_setzero() _mm256_setzero_si256()247#define vec_add_dpbusd_32 SIMD::m256_add_dpbusd_epi32248#define vec_hadd SIMD::m256_hadd249#elif defined(USE_SSSE3)250using vec_t = __m128i;251#define vec_setzero() _mm_setzero_si128()252#define vec_add_dpbusd_32 SIMD::m128_add_dpbusd_epi32253#define vec_hadd SIMD::m128_hadd254#elif defined(USE_NEON_DOTPROD)255using vec_t = int32x4_t;256#define vec_setzero() vdupq_n_s32(0)257#define vec_add_dpbusd_32(acc, a, b) \258SIMD::dotprod_m128_add_dpbusd_epi32(acc, vreinterpretq_s8_s32(a), \259vreinterpretq_s8_s32(b))260#define vec_hadd SIMD::neon_m128_hadd261#endif262263const auto inputVector = reinterpret_cast<const vec_t*>(input);264265static constexpr IndexType InputSimdWidth = sizeof(vec_t) / sizeof(InputType);266267static_assert(PaddedInputDimensions % InputSimdWidth == 0);268269constexpr IndexType NumChunks = PaddedInputDimensions / InputSimdWidth;270vec_t sum0 = vec_setzero();271const auto row0 = reinterpret_cast<const vec_t*>(&weights[0]);272273for (int j = 0; j < int(NumChunks); ++j)274{275const vec_t in = inputVector[j];276vec_add_dpbusd_32(sum0, in, row0[j]);277}278output[0] = vec_hadd(sum0, biases[0]);279280#undef vec_setzero281#undef vec_add_dpbusd_32282#undef vec_hadd283}284#else285// Use old implementation for the other architectures.286affine_transform_non_ssse3<InputDimensions, PaddedInputDimensions, OutputDimensions>(287output, weights, biases, input);288#endif289}290291private:292using BiasType = OutputType;293using WeightType = std::int8_t;294295alignas(CacheLineSize) BiasType biases[OutputDimensions];296alignas(CacheLineSize) WeightType weights[OutputDimensions * PaddedInputDimensions];297};298299} // namespace Stockfish::Eval::NNUE::Layers300301#endif // #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED302303304