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
26 #include <type_traits>
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, const std::int8_t* weights, const std::int32_t* biases, const std::uint8_t* input)
48 # if defined(USE_SSE2)
49 // At least a multiple of 16, with SSE2.
50 constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;
51 const __m128i Zeros = _mm_setzero_si128();
52 const auto inputVector = reinterpret_cast<const __m128i*>(input);
54 # elif defined(USE_MMX)
55 constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 8) / 8;
56 const __m64 Zeros = _mm_setzero_si64();
57 const auto inputVector = reinterpret_cast<const __m64*>(input);
59 # elif defined(USE_NEON_DOTPROD)
60 constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;
61 const auto inputVector = reinterpret_cast<const int8x16_t*>(input);
63 # elif defined(USE_NEON)
64 constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;
65 const auto inputVector = reinterpret_cast<const int8x8_t*>(input);
68 for (IndexType i = 0; i < OutputDimensions; ++i) {
69 const IndexType offset = i * PaddedInputDimensions;
71 # if defined(USE_SSE2)
72 __m128i sumLo = _mm_cvtsi32_si128(biases[i]);
73 __m128i sumHi = Zeros;
74 const auto row = reinterpret_cast<const __m128i*>(&weights[offset]);
75 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_MMX)
95 __m64 sumLo = _mm_cvtsi32_si64(biases[i]);
97 const auto row = reinterpret_cast<const __m64*>(&weights[offset]);
98 for (IndexType j = 0; j < NumChunks; ++j) {
100 __m64 input_j = inputVector[j];
101 __m64 extendedRowLo = _mm_srai_pi16(_mm_unpacklo_pi8(row_j, row_j), 8);
102 __m64 extendedRowHi = _mm_srai_pi16(_mm_unpackhi_pi8(row_j, row_j), 8);
103 __m64 extendedInputLo = _mm_unpacklo_pi8(input_j, Zeros);
104 __m64 extendedInputHi = _mm_unpackhi_pi8(input_j, Zeros);
105 __m64 productLo = _mm_madd_pi16(extendedRowLo, extendedInputLo);
106 __m64 productHi = _mm_madd_pi16(extendedRowHi, extendedInputHi);
107 sumLo = _mm_add_pi32(sumLo, productLo);
108 sumHi = _mm_add_pi32(sumHi, productHi);
110 __m64 sum = _mm_add_pi32(sumLo, sumHi);
111 sum = _mm_add_pi32(sum, _mm_unpackhi_pi32(sum, sum));
112 output[i] = _mm_cvtsi64_si32(sum);
114 # elif defined(USE_NEON_DOTPROD)
115 int32x4_t sum = {biases[i]};
116 const auto row = reinterpret_cast<const int8x16_t*>(&weights[offset]);
117 for (IndexType j = 0; j < NumChunks; ++j) {
118 sum = vdotq_s32(sum, inputVector[j], row[j]);
120 output[i] = vaddvq_s32(sum);
122 # elif defined(USE_NEON)
123 int32x4_t sum = {biases[i]};
124 const auto row = reinterpret_cast<const int8x8_t*>(&weights[offset]);
125 for (IndexType j = 0; j < NumChunks; ++j) {
126 int16x8_t product = vmull_s8(inputVector[j * 2], row[j * 2]);
127 product = vmlal_s8(product, inputVector[j * 2 + 1], row[j * 2 + 1]);
128 sum = vpadalq_s16(sum, product);
130 output[i] = sum[0] + sum[1] + sum[2] + sum[3];
133 std::int32_t sum = biases[i];
134 for (IndexType j = 0; j < InputDimensions; ++j) {
135 sum += weights[offset + j] * input[j];
141 # if defined(USE_MMX)
147 template <IndexType InDims, IndexType OutDims>
148 class AffineTransform {
151 using InputType = std::uint8_t;
152 using OutputType = std::int32_t;
154 // Number of input/output dimensions
155 static constexpr IndexType InputDimensions = InDims;
156 static constexpr IndexType OutputDimensions = OutDims;
158 static constexpr IndexType PaddedInputDimensions =
159 ceil_to_multiple<IndexType>(InputDimensions, MaxSimdWidth);
160 static constexpr IndexType PaddedOutputDimensions =
161 ceil_to_multiple<IndexType>(OutputDimensions, MaxSimdWidth);
163 using OutputBuffer = OutputType[PaddedOutputDimensions];
165 // Hash value embedded in the evaluation file
166 static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {
167 std::uint32_t hashValue = 0xCC03DAE4u;
168 hashValue += OutputDimensions;
169 hashValue ^= prevHash >> 1;
170 hashValue ^= prevHash << 31;
174 static constexpr IndexType get_weight_index_scrambled(IndexType i)
177 (i / 4) % (PaddedInputDimensions / 4) * OutputDimensions * 4 +
178 i / PaddedInputDimensions * 4 +
182 static constexpr IndexType get_weight_index(IndexType i)
184 #if defined (USE_SSSE3)
185 return get_weight_index_scrambled(i);
191 // Read network parameters
192 bool read_parameters(std::istream& stream) {
193 read_little_endian<BiasType>(stream, biases, OutputDimensions);
194 for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
195 weights[get_weight_index(i)] = read_little_endian<WeightType>(stream);
197 return !stream.fail();
200 // Write network parameters
201 bool write_parameters(std::ostream& stream) const {
202 write_little_endian<BiasType>(stream, biases, OutputDimensions);
204 for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
205 write_little_endian<WeightType>(stream, weights[get_weight_index(i)]);
207 return !stream.fail();
209 // Forward propagation
211 const InputType* input, OutputType* output) const {
213 #if defined (USE_AVX512)
214 using vec_t = __m512i;
215 #define vec_setzero _mm512_setzero_si512
216 #define vec_set_32 _mm512_set1_epi32
217 #define vec_add_dpbusd_32 Simd::m512_add_dpbusd_epi32
218 #define vec_add_dpbusd_32x2 Simd::m512_add_dpbusd_epi32x2
219 #define vec_hadd Simd::m512_hadd
220 #elif defined (USE_AVX2)
221 using vec_t = __m256i;
222 #define vec_setzero _mm256_setzero_si256
223 #define vec_set_32 _mm256_set1_epi32
224 #define vec_add_dpbusd_32 Simd::m256_add_dpbusd_epi32
225 #define vec_add_dpbusd_32x2 Simd::m256_add_dpbusd_epi32x2
226 #define vec_hadd Simd::m256_hadd
227 #elif defined (USE_SSSE3)
228 using vec_t = __m128i;
229 #define vec_setzero _mm_setzero_si128
230 #define vec_set_32 _mm_set1_epi32
231 #define vec_add_dpbusd_32 Simd::m128_add_dpbusd_epi32
232 #define vec_add_dpbusd_32x2 Simd::m128_add_dpbusd_epi32x2
233 #define vec_hadd Simd::m128_hadd
236 #if defined (USE_SSSE3)
237 const auto inputVector = reinterpret_cast<const vec_t*>(input);
239 static constexpr IndexType OutputSimdWidth = sizeof(vec_t) / sizeof(OutputType);
241 static_assert(OutputDimensions % OutputSimdWidth == 0 || OutputDimensions == 1);
243 if constexpr (OutputDimensions % OutputSimdWidth == 0)
245 constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 8) / 4;
246 constexpr IndexType NumRegs = OutputDimensions / OutputSimdWidth;
248 const auto input32 = reinterpret_cast<const std::int32_t*>(input);
249 const vec_t* biasvec = reinterpret_cast<const vec_t*>(biases);
251 for (IndexType k = 0; k < NumRegs; ++k)
254 for (IndexType i = 0; i < NumChunks; i += 2)
256 const vec_t in0 = vec_set_32(input32[i + 0]);
257 const vec_t in1 = vec_set_32(input32[i + 1]);
258 const auto col0 = reinterpret_cast<const vec_t*>(&weights[(i + 0) * OutputDimensions * 4]);
259 const auto col1 = reinterpret_cast<const vec_t*>(&weights[(i + 1) * OutputDimensions * 4]);
260 for (IndexType k = 0; k < NumRegs; ++k)
261 vec_add_dpbusd_32x2(acc[k], in0, col0[k], in1, col1[k]);
264 vec_t* outptr = reinterpret_cast<vec_t*>(output);
265 for (IndexType k = 0; k < NumRegs; ++k)
268 else if constexpr (OutputDimensions == 1)
270 constexpr IndexType NumChunks = PaddedInputDimensions / SimdWidth;
271 vec_t sum0 = vec_setzero();
272 const auto row0 = reinterpret_cast<const vec_t*>(&weights[0]);
274 for (int j = 0; j < (int)NumChunks; ++j)
276 const vec_t in = inputVector[j];
277 vec_add_dpbusd_32(sum0, in, row0[j]);
279 output[0] = vec_hadd(sum0, biases[0]);
284 # undef vec_add_dpbusd_32
285 # undef vec_add_dpbusd_32x2
288 // Use old implementation for the other architectures.
289 affine_transform_non_ssse3<
291 PaddedInputDimensions,
292 OutputDimensions>(output, weights, biases, input);
297 using BiasType = OutputType;
298 using WeightType = std::int8_t;
300 alignas(CacheLineSize) BiasType biases[OutputDimensions];
301 alignas(CacheLineSize) WeightType weights[OutputDimensions * PaddedInputDimensions];
304 } // namespace Stockfish::Eval::NNUE::Layers
306 #endif // #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED