2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2023 The Stockfish developers (see AUTHORS file)
5 Stockfish is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 Stockfish is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 // Definition of layer AffineTransform of NNUE evaluation function
21 #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED
22 #define NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED
27 #include "../nnue_common.h"
31 This file contains the definition for a fully connected layer (aka affine transform).
33 - expected use-case is for when PaddedInputDimensions == 32 and InputDimensions <= 32.
34 - that's why AVX512 is hard to implement
35 - expected use-case is small layers
36 - inputs are processed in chunks of 4, weights are respectively transposed
37 - accumulation happens directly to int32s
40 namespace Stockfish::Eval::NNUE::Layers {
42 // Fallback implementation for older/other architectures.
43 // Requires the input to be padded to at least 16 values.
44 #if !defined(USE_SSSE3)
45 template<IndexType InputDimensions, IndexType PaddedInputDimensions, IndexType OutputDimensions>
46 static void affine_transform_non_ssse3(std::int32_t* output,
47 const std::int8_t* weights,
48 const std::int32_t* biases,
49 const std::uint8_t* input) {
50 #if defined(USE_SSE2) || defined(USE_NEON_DOTPROD) || defined(USE_NEON)
52 // At least a multiple of 16, with SSE2.
53 constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;
54 const __m128i Zeros = _mm_setzero_si128();
55 const auto inputVector = reinterpret_cast<const __m128i*>(input);
57 #elif defined(USE_NEON_DOTPROD)
58 constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;
59 const auto inputVector = reinterpret_cast<const int8x16_t*>(input);
61 #elif defined(USE_NEON)
62 constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;
63 const auto inputVector = reinterpret_cast<const int8x8_t*>(input);
66 for (IndexType i = 0; i < OutputDimensions; ++i)
68 const IndexType offset = i * PaddedInputDimensions;
71 __m128i sumLo = _mm_cvtsi32_si128(biases[i]);
72 __m128i sumHi = Zeros;
73 const auto row = reinterpret_cast<const __m128i*>(&weights[offset]);
74 for (IndexType j = 0; j < NumChunks; ++j)
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);
84 sumLo = _mm_add_epi32(sumLo, productLo);
85 sumHi = _mm_add_epi32(sumHi, productHi);
87 __m128i sum = _mm_add_epi32(sumLo, sumHi);
88 __m128i sumHigh_64 = _mm_shuffle_epi32(sum, _MM_SHUFFLE(1, 0, 3, 2));
89 sum = _mm_add_epi32(sum, sumHigh_64);
90 __m128i sum_second_32 = _mm_shufflelo_epi16(sum, _MM_SHUFFLE(1, 0, 3, 2));
91 sum = _mm_add_epi32(sum, sum_second_32);
92 output[i] = _mm_cvtsi128_si32(sum);
94 #elif defined(USE_NEON_DOTPROD)
95 int32x4_t sum = {biases[i]};
96 const auto row = reinterpret_cast<const int8x16_t*>(&weights[offset]);
97 for (IndexType j = 0; j < NumChunks; ++j)
99 sum = vdotq_s32(sum, inputVector[j], row[j]);
101 output[i] = vaddvq_s32(sum);
103 #elif defined(USE_NEON)
104 int32x4_t sum = {biases[i]};
105 const auto row = reinterpret_cast<const int8x8_t*>(&weights[offset]);
106 for (IndexType j = 0; j < NumChunks; ++j)
108 int16x8_t product = vmull_s8(inputVector[j * 2], row[j * 2]);
109 product = vmlal_s8(product, inputVector[j * 2 + 1], row[j * 2 + 1]);
110 sum = vpadalq_s16(sum, product);
112 output[i] = sum[0] + sum[1] + sum[2] + sum[3];
117 std::memcpy(output, biases, sizeof(std::int32_t) * OutputDimensions);
119 // Traverse weights in transpose order to take advantage of input sparsity
120 for (IndexType i = 0; i < InputDimensions; ++i)
123 const std::int8_t* w = &weights[i];
124 const int in = input[i];
125 for (IndexType j = 0; j < OutputDimensions; ++j)
126 output[j] += w[j * PaddedInputDimensions] * in;
132 template<IndexType InDims, IndexType OutDims>
133 class AffineTransform {
136 using InputType = std::uint8_t;
137 using OutputType = std::int32_t;
139 // Number of input/output dimensions
140 static constexpr IndexType InputDimensions = InDims;
141 static constexpr IndexType OutputDimensions = OutDims;
143 static constexpr IndexType PaddedInputDimensions =
144 ceil_to_multiple<IndexType>(InputDimensions, MaxSimdWidth);
145 static constexpr IndexType PaddedOutputDimensions =
146 ceil_to_multiple<IndexType>(OutputDimensions, MaxSimdWidth);
148 using OutputBuffer = OutputType[PaddedOutputDimensions];
150 // Hash value embedded in the evaluation file
151 static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {
152 std::uint32_t hashValue = 0xCC03DAE4u;
153 hashValue += OutputDimensions;
154 hashValue ^= prevHash >> 1;
155 hashValue ^= prevHash << 31;
159 static constexpr IndexType get_weight_index_scrambled(IndexType i) {
160 return (i / 4) % (PaddedInputDimensions / 4) * OutputDimensions * 4
161 + i / PaddedInputDimensions * 4 + i % 4;
164 static constexpr IndexType get_weight_index(IndexType i) {
165 #if defined(USE_SSSE3)
166 return get_weight_index_scrambled(i);
172 // Read network parameters
173 bool read_parameters(std::istream& stream) {
174 read_little_endian<BiasType>(stream, biases, OutputDimensions);
175 for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
176 weights[get_weight_index(i)] = read_little_endian<WeightType>(stream);
178 return !stream.fail();
181 // Write network parameters
182 bool write_parameters(std::ostream& stream) const {
183 write_little_endian<BiasType>(stream, biases, OutputDimensions);
185 for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
186 write_little_endian<WeightType>(stream, weights[get_weight_index(i)]);
188 return !stream.fail();
190 // Forward propagation
191 void propagate(const InputType* input, OutputType* output) const {
193 #if defined(USE_SSSE3)
195 if constexpr (OutputDimensions > 1)
198 #if defined(USE_AVX512)
199 using vec_t = __m512i;
200 #define vec_setzero _mm512_setzero_si512
201 #define vec_set_32 _mm512_set1_epi32
202 #define vec_add_dpbusd_32 Simd::m512_add_dpbusd_epi32
203 #define vec_add_dpbusd_32x2 Simd::m512_add_dpbusd_epi32x2
204 #define vec_hadd Simd::m512_hadd
205 #elif defined(USE_AVX2)
206 using vec_t = __m256i;
207 #define vec_setzero _mm256_setzero_si256
208 #define vec_set_32 _mm256_set1_epi32
209 #define vec_add_dpbusd_32 Simd::m256_add_dpbusd_epi32
210 #define vec_add_dpbusd_32x2 Simd::m256_add_dpbusd_epi32x2
211 #define vec_hadd Simd::m256_hadd
212 #elif defined(USE_SSSE3)
213 using vec_t = __m128i;
214 #define vec_setzero _mm_setzero_si128
215 #define vec_set_32 _mm_set1_epi32
216 #define vec_add_dpbusd_32 Simd::m128_add_dpbusd_epi32
217 #define vec_add_dpbusd_32x2 Simd::m128_add_dpbusd_epi32x2
218 #define vec_hadd Simd::m128_hadd
221 static constexpr IndexType OutputSimdWidth = sizeof(vec_t) / sizeof(OutputType);
223 static_assert(OutputDimensions % OutputSimdWidth == 0);
225 constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 8) / 4;
226 constexpr IndexType NumRegs = OutputDimensions / OutputSimdWidth;
228 const auto input32 = reinterpret_cast<const std::int32_t*>(input);
229 const vec_t* biasvec = reinterpret_cast<const vec_t*>(biases);
231 for (IndexType k = 0; k < NumRegs; ++k)
234 for (IndexType i = 0; i < NumChunks; i += 2)
236 const vec_t in0 = vec_set_32(input32[i + 0]);
237 const vec_t in1 = vec_set_32(input32[i + 1]);
239 reinterpret_cast<const vec_t*>(&weights[(i + 0) * OutputDimensions * 4]);
241 reinterpret_cast<const vec_t*>(&weights[(i + 1) * OutputDimensions * 4]);
242 for (IndexType k = 0; k < NumRegs; ++k)
243 vec_add_dpbusd_32x2(acc[k], in0, col0[k], in1, col1[k]);
246 vec_t* outptr = reinterpret_cast<vec_t*>(output);
247 for (IndexType k = 0; k < NumRegs; ++k)
252 #undef vec_add_dpbusd_32
253 #undef vec_add_dpbusd_32x2
256 else if constexpr (OutputDimensions == 1)
259 // We cannot use AVX512 for the last layer because there are only 32 inputs
260 // and the buffer is not padded to 64 elements.
261 #if defined(USE_AVX2)
262 using vec_t = __m256i;
263 #define vec_setzero _mm256_setzero_si256
264 #define vec_set_32 _mm256_set1_epi32
265 #define vec_add_dpbusd_32 Simd::m256_add_dpbusd_epi32
266 #define vec_add_dpbusd_32x2 Simd::m256_add_dpbusd_epi32x2
267 #define vec_hadd Simd::m256_hadd
268 #elif defined(USE_SSSE3)
269 using vec_t = __m128i;
270 #define vec_setzero _mm_setzero_si128
271 #define vec_set_32 _mm_set1_epi32
272 #define vec_add_dpbusd_32 Simd::m128_add_dpbusd_epi32
273 #define vec_add_dpbusd_32x2 Simd::m128_add_dpbusd_epi32x2
274 #define vec_hadd Simd::m128_hadd
277 const auto inputVector = reinterpret_cast<const vec_t*>(input);
279 static constexpr IndexType InputSimdWidth = sizeof(vec_t) / sizeof(InputType);
281 static_assert(PaddedInputDimensions % InputSimdWidth == 0);
283 constexpr IndexType NumChunks = PaddedInputDimensions / InputSimdWidth;
284 vec_t sum0 = vec_setzero();
285 const auto row0 = reinterpret_cast<const vec_t*>(&weights[0]);
287 for (int j = 0; j < int(NumChunks); ++j)
289 const vec_t in = inputVector[j];
290 vec_add_dpbusd_32(sum0, in, row0[j]);
292 output[0] = vec_hadd(sum0, biases[0]);
296 #undef vec_add_dpbusd_32
297 #undef vec_add_dpbusd_32x2
301 // Use old implementation for the other architectures.
302 affine_transform_non_ssse3<InputDimensions, PaddedInputDimensions, OutputDimensions>(
303 output, weights, biases, input);
308 using BiasType = OutputType;
309 using WeightType = std::int8_t;
311 alignas(CacheLineSize) BiasType biases[OutputDimensions];
312 alignas(CacheLineSize) WeightType weights[OutputDimensions * PaddedInputDimensions];
315 } // namespace Stockfish::Eval::NNUE::Layers
317 #endif // #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED