]> git.sesse.net Git - stockfish/blob - src/nnue/layers/affine_transform.h
fc65c34339ff35bb44f69dee3a85285de69eb51b
[stockfish] / src / nnue / layers / affine_transform.h
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2023 The Stockfish developers (see AUTHORS file)
4
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.
9
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.
14
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/>.
17 */
18
19 // Definition of layer AffineTransform of NNUE evaluation function
20
21 #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED
22 #define NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED
23
24 #include <cstdint>
25 #include <iostream>
26
27 #include "../nnue_common.h"
28 #include "simd.h"
29
30 /*
31   This file contains the definition for a fully connected layer (aka affine transform).
32
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
38 */
39
40 namespace Stockfish::Eval::NNUE::Layers {
41
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)
47   {
48 # if defined(USE_SSE2) || defined(USE_NEON_DOTPROD) || defined(USE_NEON)
49 # if defined(USE_SSE2)
50     // At least a multiple of 16, with SSE2.
51     constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;
52     const __m128i Zeros = _mm_setzero_si128();
53     const auto inputVector = reinterpret_cast<const __m128i*>(input);
54
55 # elif defined(USE_NEON_DOTPROD)
56     constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;
57     const auto inputVector = reinterpret_cast<const int8x16_t*>(input);
58
59 # elif defined(USE_NEON)
60     constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;
61     const auto inputVector = reinterpret_cast<const int8x8_t*>(input);
62 # endif
63
64     for (IndexType i = 0; i < OutputDimensions; ++i) {
65       const IndexType offset = i * PaddedInputDimensions;
66
67 # if defined(USE_SSE2)
68       __m128i sumLo = _mm_cvtsi32_si128(biases[i]);
69       __m128i sumHi = Zeros;
70       const auto row = reinterpret_cast<const __m128i*>(&weights[offset]);
71       for (IndexType j = 0; j < NumChunks; ++j) {
72         __m128i row_j = _mm_load_si128(&row[j]);
73         __m128i input_j = _mm_load_si128(&inputVector[j]);
74         __m128i extendedRowLo = _mm_srai_epi16(_mm_unpacklo_epi8(row_j, row_j), 8);
75         __m128i extendedRowHi = _mm_srai_epi16(_mm_unpackhi_epi8(row_j, row_j), 8);
76         __m128i extendedInputLo = _mm_unpacklo_epi8(input_j, Zeros);
77         __m128i extendedInputHi = _mm_unpackhi_epi8(input_j, Zeros);
78         __m128i productLo = _mm_madd_epi16(extendedRowLo, extendedInputLo);
79         __m128i productHi = _mm_madd_epi16(extendedRowHi, extendedInputHi);
80         sumLo = _mm_add_epi32(sumLo, productLo);
81         sumHi = _mm_add_epi32(sumHi, productHi);
82       }
83       __m128i sum = _mm_add_epi32(sumLo, sumHi);
84       __m128i sumHigh_64 = _mm_shuffle_epi32(sum, _MM_SHUFFLE(1, 0, 3, 2));
85       sum = _mm_add_epi32(sum, sumHigh_64);
86       __m128i sum_second_32 = _mm_shufflelo_epi16(sum, _MM_SHUFFLE(1, 0, 3, 2));
87       sum = _mm_add_epi32(sum, sum_second_32);
88       output[i] = _mm_cvtsi128_si32(sum);
89
90 # elif defined(USE_NEON_DOTPROD)
91       int32x4_t sum = {biases[i]};
92       const auto row = reinterpret_cast<const int8x16_t*>(&weights[offset]);
93       for (IndexType j = 0; j < NumChunks; ++j) {
94         sum = vdotq_s32(sum, inputVector[j], row[j]);
95       }
96       output[i] = vaddvq_s32(sum);
97
98 # elif defined(USE_NEON)
99       int32x4_t sum = {biases[i]};
100       const auto row = reinterpret_cast<const int8x8_t*>(&weights[offset]);
101       for (IndexType j = 0; j < NumChunks; ++j) {
102         int16x8_t product = vmull_s8(inputVector[j * 2], row[j * 2]);
103         product = vmlal_s8(product, inputVector[j * 2 + 1], row[j * 2 + 1]);
104         sum = vpadalq_s16(sum, product);
105       }
106       output[i] = sum[0] + sum[1] + sum[2] + sum[3];
107
108 # endif
109     }
110 # else
111   std::memcpy(output, biases, sizeof(std::int32_t) * OutputDimensions);
112
113   // Traverse weights in transpose order to take advantage of input sparsity
114   for (IndexType i = 0; i < InputDimensions; ++i)
115       if (input[i]) {
116           const std::int8_t* w = &weights[i];
117           const int in = input[i];
118           for (IndexType j = 0; j < OutputDimensions; ++j)
119               output[j] += w[j * PaddedInputDimensions] * in;
120       }
121 # endif
122   }
123 #endif
124
125   template <IndexType InDims, IndexType OutDims>
126   class AffineTransform {
127    public:
128     // Input/output type
129     using InputType = std::uint8_t;
130     using OutputType = std::int32_t;
131
132     // Number of input/output dimensions
133     static constexpr IndexType InputDimensions = InDims;
134     static constexpr IndexType OutputDimensions = OutDims;
135
136     static constexpr IndexType PaddedInputDimensions =
137       ceil_to_multiple<IndexType>(InputDimensions, MaxSimdWidth);
138     static constexpr IndexType PaddedOutputDimensions =
139       ceil_to_multiple<IndexType>(OutputDimensions, MaxSimdWidth);
140
141     using OutputBuffer = OutputType[PaddedOutputDimensions];
142
143     // Hash value embedded in the evaluation file
144     static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {
145       std::uint32_t hashValue = 0xCC03DAE4u;
146       hashValue += OutputDimensions;
147       hashValue ^= prevHash >> 1;
148       hashValue ^= prevHash << 31;
149       return hashValue;
150     }
151
152     static constexpr IndexType get_weight_index_scrambled(IndexType i)
153     {
154       return
155         (i / 4) % (PaddedInputDimensions / 4) * OutputDimensions * 4 +
156         i / PaddedInputDimensions * 4 +
157         i % 4;
158     }
159
160     static constexpr IndexType get_weight_index(IndexType i)
161     {
162 #if defined (USE_SSSE3)
163       return get_weight_index_scrambled(i);
164 #else
165       return i;
166 #endif
167     }
168
169     // Read network parameters
170     bool read_parameters(std::istream& stream) {
171       read_little_endian<BiasType>(stream, biases, OutputDimensions);
172       for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
173         weights[get_weight_index(i)] = read_little_endian<WeightType>(stream);
174
175       return !stream.fail();
176     }
177
178     // Write network parameters
179     bool write_parameters(std::ostream& stream) const {
180       write_little_endian<BiasType>(stream, biases, OutputDimensions);
181
182       for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
183         write_little_endian<WeightType>(stream, weights[get_weight_index(i)]);
184
185       return !stream.fail();
186     }
187     // Forward propagation
188     void propagate(
189         const InputType* input, OutputType* output) const {
190
191 #if defined (USE_SSSE3)
192
193       if constexpr (OutputDimensions > 1)
194       {
195
196 #if defined (USE_AVX512)
197       using vec_t = __m512i;
198       #define vec_setzero _mm512_setzero_si512
199       #define vec_set_32 _mm512_set1_epi32
200       #define vec_add_dpbusd_32 Simd::m512_add_dpbusd_epi32
201       #define vec_add_dpbusd_32x2 Simd::m512_add_dpbusd_epi32x2
202       #define vec_hadd Simd::m512_hadd
203 #elif defined (USE_AVX2)
204       using vec_t = __m256i;
205       #define vec_setzero _mm256_setzero_si256
206       #define vec_set_32 _mm256_set1_epi32
207       #define vec_add_dpbusd_32 Simd::m256_add_dpbusd_epi32
208       #define vec_add_dpbusd_32x2 Simd::m256_add_dpbusd_epi32x2
209       #define vec_hadd Simd::m256_hadd
210 #elif defined (USE_SSSE3)
211       using vec_t = __m128i;
212       #define vec_setzero _mm_setzero_si128
213       #define vec_set_32 _mm_set1_epi32
214       #define vec_add_dpbusd_32 Simd::m128_add_dpbusd_epi32
215       #define vec_add_dpbusd_32x2 Simd::m128_add_dpbusd_epi32x2
216       #define vec_hadd Simd::m128_hadd
217 #endif
218
219         static constexpr IndexType OutputSimdWidth = sizeof(vec_t) / sizeof(OutputType);
220
221         static_assert(OutputDimensions % OutputSimdWidth == 0);
222
223         constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 8) / 4;
224         constexpr IndexType NumRegs = OutputDimensions / OutputSimdWidth;
225
226         const auto input32 = reinterpret_cast<const std::int32_t*>(input);
227         const vec_t* biasvec = reinterpret_cast<const vec_t*>(biases);
228         vec_t acc[NumRegs];
229         for (IndexType k = 0; k < NumRegs; ++k)
230           acc[k] = biasvec[k];
231
232         for (IndexType i = 0; i < NumChunks; i += 2)
233         {
234           const vec_t in0 = vec_set_32(input32[i + 0]);
235           const vec_t in1 = vec_set_32(input32[i + 1]);
236           const auto col0 = reinterpret_cast<const vec_t*>(&weights[(i + 0) * OutputDimensions * 4]);
237           const auto col1 = reinterpret_cast<const vec_t*>(&weights[(i + 1) * OutputDimensions * 4]);
238           for (IndexType k = 0; k < NumRegs; ++k)
239             vec_add_dpbusd_32x2(acc[k], in0, col0[k], in1, col1[k]);
240         }
241
242         vec_t* outptr = reinterpret_cast<vec_t*>(output);
243         for (IndexType k = 0; k < NumRegs; ++k)
244           outptr[k] = acc[k];
245
246 # undef vec_setzero
247 # undef vec_set_32
248 # undef vec_add_dpbusd_32
249 # undef vec_add_dpbusd_32x2
250 # undef vec_hadd
251
252       }
253       else if constexpr (OutputDimensions == 1)
254       {
255
256 // We cannot use AVX512 for the last layer because there's only 32 inputs and the buffer is not padded to 64 elements.
257 #if defined (USE_AVX2)
258       using vec_t = __m256i;
259       #define vec_setzero _mm256_setzero_si256
260       #define vec_set_32 _mm256_set1_epi32
261       #define vec_add_dpbusd_32 Simd::m256_add_dpbusd_epi32
262       #define vec_add_dpbusd_32x2 Simd::m256_add_dpbusd_epi32x2
263       #define vec_hadd Simd::m256_hadd
264 #elif defined (USE_SSSE3)
265       using vec_t = __m128i;
266       #define vec_setzero _mm_setzero_si128
267       #define vec_set_32 _mm_set1_epi32
268       #define vec_add_dpbusd_32 Simd::m128_add_dpbusd_epi32
269       #define vec_add_dpbusd_32x2 Simd::m128_add_dpbusd_epi32x2
270       #define vec_hadd Simd::m128_hadd
271 #endif
272
273         const auto inputVector = reinterpret_cast<const vec_t*>(input);
274
275         static constexpr IndexType InputSimdWidth = sizeof(vec_t) / sizeof(InputType);
276
277         static_assert(PaddedInputDimensions % InputSimdWidth == 0);
278
279         constexpr IndexType NumChunks = PaddedInputDimensions / InputSimdWidth;
280         vec_t sum0 = vec_setzero();
281         const auto row0 = reinterpret_cast<const vec_t*>(&weights[0]);
282
283         for (int j = 0; j < int(NumChunks); ++j)
284         {
285           const vec_t in = inputVector[j];
286           vec_add_dpbusd_32(sum0, in, row0[j]);
287         }
288         output[0] = vec_hadd(sum0, biases[0]);
289
290 # undef vec_setzero
291 # undef vec_set_32
292 # undef vec_add_dpbusd_32
293 # undef vec_add_dpbusd_32x2
294 # undef vec_hadd
295
296       }
297 #else
298       // Use old implementation for the other architectures.
299       affine_transform_non_ssse3<
300         InputDimensions,
301         PaddedInputDimensions,
302         OutputDimensions>(output, weights, biases, input);
303 #endif
304     }
305
306    private:
307     using BiasType = OutputType;
308     using WeightType = std::int8_t;
309
310     alignas(CacheLineSize) BiasType biases[OutputDimensions];
311     alignas(CacheLineSize) WeightType weights[OutputDimensions * PaddedInputDimensions];
312   };
313
314 }  // namespace Stockfish::Eval::NNUE::Layers
315
316 #endif // #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED