]> git.sesse.net Git - stockfish/blob - src/nnue/layers/affine_transform.h
New NNUE architecture and net
[stockfish] / src / nnue / layers / affine_transform.h
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2021 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 <iostream>
25 #include "../nnue_common.h"
26
27 namespace Stockfish::Eval::NNUE::Layers {
28
29   // Affine transformation layer
30   template <typename PreviousLayer, IndexType OutDims>
31   class AffineTransform {
32    public:
33     // Input/output type
34     using InputType = typename PreviousLayer::OutputType;
35     using OutputType = std::int32_t;
36     static_assert(std::is_same<InputType, std::uint8_t>::value, "");
37
38     // Number of input/output dimensions
39     static constexpr IndexType InputDimensions =
40         PreviousLayer::OutputDimensions;
41     static constexpr IndexType OutputDimensions = OutDims;
42     static constexpr IndexType PaddedInputDimensions =
43         ceil_to_multiple<IndexType>(InputDimensions, MaxSimdWidth);
44 #if defined (USE_AVX512)
45     static constexpr const IndexType OutputSimdWidth = SimdWidth / 2;
46 #elif defined (USE_SSSE3)
47     static constexpr const IndexType OutputSimdWidth = SimdWidth / 4;
48 #endif
49
50     // Size of forward propagation buffer used in this layer
51     static constexpr std::size_t SelfBufferSize =
52         ceil_to_multiple(OutputDimensions * sizeof(OutputType), CacheLineSize);
53
54     // Size of the forward propagation buffer used from the input layer to this layer
55     static constexpr std::size_t BufferSize =
56         PreviousLayer::BufferSize + SelfBufferSize;
57
58     // Hash value embedded in the evaluation file
59     static constexpr std::uint32_t get_hash_value() {
60       std::uint32_t hashValue = 0xCC03DAE4u;
61       hashValue += OutputDimensions;
62       hashValue ^= PreviousLayer::get_hash_value() >> 1;
63       hashValue ^= PreviousLayer::get_hash_value() << 31;
64       return hashValue;
65     }
66
67     // Read network parameters
68     bool read_parameters(std::istream& stream) {
69       if (!previousLayer.read_parameters(stream)) return false;
70       for (std::size_t i = 0; i < OutputDimensions; ++i)
71         biases[i] = read_little_endian<BiasType>(stream);
72       for (std::size_t i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
73 #if !defined (USE_SSSE3)
74         weights[i] = read_little_endian<WeightType>(stream);
75 #else
76         weights[
77           (i / 4) % (PaddedInputDimensions / 4) * OutputDimensions * 4 +
78           i / PaddedInputDimensions * 4 +
79           i % 4
80         ] = read_little_endian<WeightType>(stream);
81 #endif
82
83       return !stream.fail();
84     }
85
86     // Write network parameters
87     bool write_parameters(std::ostream& stream) const {
88       if (!previousLayer.write_parameters(stream)) return false;
89       for (std::size_t i = 0; i < OutputDimensions; ++i)
90           write_little_endian<BiasType>(stream, biases[i]);
91 #if !defined (USE_SSSE3)
92       for (std::size_t i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
93           write_little_endian<WeightType>(stream, weights[i]);
94 #else
95       std::unique_ptr<WeightType[]> unscrambledWeights = std::make_unique<WeightType[]>(OutputDimensions * PaddedInputDimensions);
96       for (std::size_t i = 0; i < OutputDimensions * PaddedInputDimensions; ++i) {
97           unscrambledWeights[i] =
98               weights[
99                 (i / 4) % (PaddedInputDimensions / 4) * OutputDimensions * 4 +
100                 i / PaddedInputDimensions * 4 +
101                 i % 4
102               ];
103       }
104
105       for (std::size_t i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
106           write_little_endian<WeightType>(stream, unscrambledWeights[i]);
107 #endif
108
109       return !stream.fail();
110     }
111
112     // Forward propagation
113     const OutputType* propagate(
114         const TransformedFeatureType* transformedFeatures, char* buffer) const {
115       const auto input = previousLayer.propagate(
116           transformedFeatures, buffer + SelfBufferSize);
117
118 #if defined (USE_AVX512)
119
120       [[maybe_unused]] const __m512i Ones512 = _mm512_set1_epi16(1);
121
122       [[maybe_unused]] auto m512_hadd = [](__m512i sum, int bias) -> int {
123         return _mm512_reduce_add_epi32(sum) + bias;
124       };
125
126       [[maybe_unused]] auto m512_add_dpbusd_epi32 = [=](__m512i& acc, __m512i a, __m512i b) {
127 #if defined (USE_VNNI)
128         acc = _mm512_dpbusd_epi32(acc, a, b);
129 #else
130         __m512i product0 = _mm512_maddubs_epi16(a, b);
131         product0 = _mm512_madd_epi16(product0, Ones512);
132         acc = _mm512_add_epi32(acc, product0);
133 #endif
134       };
135
136       [[maybe_unused]] auto m512_add_dpbusd_epi32x4 = [=](__m512i& acc, __m512i a0, __m512i b0, __m512i a1, __m512i b1,
137                                                                         __m512i a2, __m512i b2, __m512i a3, __m512i b3) {
138 #if defined (USE_VNNI)
139         acc = _mm512_dpbusd_epi32(acc, a0, b0);
140         acc = _mm512_dpbusd_epi32(acc, a1, b1);
141         acc = _mm512_dpbusd_epi32(acc, a2, b2);
142         acc = _mm512_dpbusd_epi32(acc, a3, b3);
143 #else
144         __m512i product0 = _mm512_maddubs_epi16(a0, b0);
145         __m512i product1 = _mm512_maddubs_epi16(a1, b1);
146         __m512i product2 = _mm512_maddubs_epi16(a2, b2);
147         __m512i product3 = _mm512_maddubs_epi16(a3, b3);
148         product0 = _mm512_adds_epi16(product0, product1);
149         product0 = _mm512_madd_epi16(product0, Ones512);
150         product2 = _mm512_adds_epi16(product2, product3);
151         product2 = _mm512_madd_epi16(product2, Ones512);
152         acc = _mm512_add_epi32(acc, _mm512_add_epi32(product0, product2));
153 #endif
154       };
155
156 #endif
157 #if defined (USE_AVX2)
158
159       [[maybe_unused]] const __m256i Ones256 = _mm256_set1_epi16(1);
160
161       [[maybe_unused]] auto m256_hadd = [](__m256i sum, int bias) -> int {
162         __m128i sum128 = _mm_add_epi32(_mm256_castsi256_si128(sum), _mm256_extracti128_si256(sum, 1));
163         sum128 = _mm_add_epi32(sum128, _mm_shuffle_epi32(sum128, _MM_PERM_BADC));
164         sum128 = _mm_add_epi32(sum128, _mm_shuffle_epi32(sum128, _MM_PERM_CDAB));
165         return _mm_cvtsi128_si32(sum128) + bias;
166       };
167
168       [[maybe_unused]] auto m256_add_dpbusd_epi32 = [=](__m256i& acc, __m256i a, __m256i b) {
169 #if defined (USE_VNNI)
170         acc = _mm256_dpbusd_epi32(acc, a, b);
171 #else
172         __m256i product0 = _mm256_maddubs_epi16(a, b);
173         product0 = _mm256_madd_epi16(product0, Ones256);
174         acc = _mm256_add_epi32(acc, product0);
175 #endif
176       };
177
178       [[maybe_unused]] auto m256_add_dpbusd_epi32x4 = [=](__m256i& acc, __m256i a0, __m256i b0, __m256i a1, __m256i b1,
179                                                                         __m256i a2, __m256i b2, __m256i a3, __m256i b3) {
180 #if defined (USE_VNNI)
181         acc = _mm256_dpbusd_epi32(acc, a0, b0);
182         acc = _mm256_dpbusd_epi32(acc, a1, b1);
183         acc = _mm256_dpbusd_epi32(acc, a2, b2);
184         acc = _mm256_dpbusd_epi32(acc, a3, b3);
185 #else
186         __m256i product0 = _mm256_maddubs_epi16(a0, b0);
187         __m256i product1 = _mm256_maddubs_epi16(a1, b1);
188         __m256i product2 = _mm256_maddubs_epi16(a2, b2);
189         __m256i product3 = _mm256_maddubs_epi16(a3, b3);
190         product0 = _mm256_adds_epi16(product0, product1);
191         product0 = _mm256_madd_epi16(product0, Ones256);
192         product2 = _mm256_adds_epi16(product2, product3);
193         product2 = _mm256_madd_epi16(product2, Ones256);
194         acc = _mm256_add_epi32(acc, _mm256_add_epi32(product0, product2));
195 #endif
196       };
197
198 #endif
199 #if defined (USE_SSSE3)
200
201       [[maybe_unused]] const __m128i Ones128 = _mm_set1_epi16(1);
202
203       [[maybe_unused]] auto m128_hadd = [](__m128i sum, int bias) -> int {
204         sum = _mm_add_epi32(sum, _mm_shuffle_epi32(sum, 0x4E)); //_MM_PERM_BADC
205         sum = _mm_add_epi32(sum, _mm_shuffle_epi32(sum, 0xB1)); //_MM_PERM_CDAB
206         return _mm_cvtsi128_si32(sum) + bias;
207       };
208
209       [[maybe_unused]] auto m128_add_dpbusd_epi32 = [=](__m128i& acc, __m128i a, __m128i b) {
210         __m128i product0 = _mm_maddubs_epi16(a, b);
211         product0 = _mm_madd_epi16(product0, Ones128);
212         acc = _mm_add_epi32(acc, product0);
213       };
214
215       [[maybe_unused]] auto m128_add_dpbusd_epi32x4 = [=](__m128i& acc, __m128i a0, __m128i b0, __m128i a1, __m128i b1,
216                                                                         __m128i a2, __m128i b2, __m128i a3, __m128i b3) {
217         __m128i product0 = _mm_maddubs_epi16(a0, b0);
218         __m128i product1 = _mm_maddubs_epi16(a1, b1);
219         __m128i product2 = _mm_maddubs_epi16(a2, b2);
220         __m128i product3 = _mm_maddubs_epi16(a3, b3);
221         product0 = _mm_adds_epi16(product0, product1);
222         product0 = _mm_madd_epi16(product0, Ones128);
223         product2 = _mm_adds_epi16(product2, product3);
224         product2 = _mm_madd_epi16(product2, Ones128);
225         acc = _mm_add_epi32(acc, _mm_add_epi32(product0, product2));
226       };
227
228 #endif
229
230 #if defined (USE_AVX512)
231       using vec_t = __m512i;
232       #define vec_setzero _mm512_setzero_si512
233       #define vec_set_32 _mm512_set1_epi32
234       auto& vec_add_dpbusd_32 = m512_add_dpbusd_epi32;
235       auto& vec_add_dpbusd_32x4 = m512_add_dpbusd_epi32x4;
236       auto& vec_hadd = m512_hadd;
237 #elif defined (USE_AVX2)
238       using vec_t = __m256i;
239       #define vec_setzero _mm256_setzero_si256
240       #define vec_set_32 _mm256_set1_epi32
241       auto& vec_add_dpbusd_32 = m256_add_dpbusd_epi32;
242       auto& vec_add_dpbusd_32x4 = m256_add_dpbusd_epi32x4;
243       auto& vec_hadd = m256_hadd;
244 #elif defined (USE_SSSE3)
245       using vec_t = __m128i;
246       #define vec_setzero _mm_setzero_si128
247       #define vec_set_32 _mm_set1_epi32
248       auto& vec_add_dpbusd_32 = m128_add_dpbusd_epi32;
249       auto& vec_add_dpbusd_32x4 = m128_add_dpbusd_epi32x4;
250       auto& vec_hadd = m128_hadd;
251 #endif
252
253 #if defined (USE_SSSE3)
254       // Different layout, we process 4 inputs at a time, always.
255       static_assert(InputDimensions % 4 == 0);
256
257       const auto output = reinterpret_cast<OutputType*>(buffer);
258       const auto inputVector = reinterpret_cast<const vec_t*>(input);
259
260       static_assert(OutputDimensions % OutputSimdWidth == 0 || OutputDimensions == 1);
261
262       // OutputDimensions is either 1 or a multiple of SimdWidth
263       // because then it is also an input dimension.
264       if constexpr (OutputDimensions % OutputSimdWidth == 0)
265       {
266           constexpr IndexType NumChunks = InputDimensions / 4;
267
268           const auto input32 = reinterpret_cast<const std::int32_t*>(input);
269           vec_t* outptr = reinterpret_cast<vec_t*>(output);
270           std::memcpy(output, biases, OutputDimensions * sizeof(OutputType));
271
272           for (int i = 0; i < (int)NumChunks - 3; i += 4)
273           {
274               const vec_t in0 = vec_set_32(input32[i + 0]);
275               const vec_t in1 = vec_set_32(input32[i + 1]);
276               const vec_t in2 = vec_set_32(input32[i + 2]);
277               const vec_t in3 = vec_set_32(input32[i + 3]);
278               const auto col0 = reinterpret_cast<const vec_t*>(&weights[(i + 0) * OutputDimensions * 4]);
279               const auto col1 = reinterpret_cast<const vec_t*>(&weights[(i + 1) * OutputDimensions * 4]);
280               const auto col2 = reinterpret_cast<const vec_t*>(&weights[(i + 2) * OutputDimensions * 4]);
281               const auto col3 = reinterpret_cast<const vec_t*>(&weights[(i + 3) * OutputDimensions * 4]);
282               for (int j = 0; j * OutputSimdWidth < OutputDimensions; ++j)
283                   vec_add_dpbusd_32x4(outptr[j], in0, col0[j], in1, col1[j], in2, col2[j], in3, col3[j]);
284           }
285       }
286       else if constexpr (OutputDimensions == 1)
287       {
288 #if defined (USE_AVX512)
289           if constexpr (PaddedInputDimensions % (SimdWidth * 2) != 0)
290           {
291               constexpr IndexType NumChunks = PaddedInputDimensions / SimdWidth;
292               const auto inputVector256 = reinterpret_cast<const __m256i*>(input);
293
294               __m256i sum0 = _mm256_setzero_si256();
295               const auto row0 = reinterpret_cast<const __m256i*>(&weights[0]);
296
297               for (int j = 0; j < (int)NumChunks; ++j)
298               {
299                   const __m256i in = inputVector256[j];
300                   m256_add_dpbusd_epi32(sum0, in, row0[j]);
301               }
302               output[0] = m256_hadd(sum0, biases[0]);
303           }
304           else
305 #endif
306           {
307 #if defined (USE_AVX512)
308               constexpr IndexType NumChunks = PaddedInputDimensions / (SimdWidth * 2);
309 #else
310               constexpr IndexType NumChunks = PaddedInputDimensions / SimdWidth;
311 #endif
312               vec_t sum0 = vec_setzero();
313               const auto row0 = reinterpret_cast<const vec_t*>(&weights[0]);
314
315               for (int j = 0; j < (int)NumChunks; ++j)
316               {
317                   const vec_t in = inputVector[j];
318                   vec_add_dpbusd_32(sum0, in, row0[j]);
319               }
320               output[0] = vec_hadd(sum0, biases[0]);
321           }
322       }
323
324 #else
325
326 // Use old implementation for the other architectures.
327
328       auto output = reinterpret_cast<OutputType*>(buffer);
329
330 #if defined(USE_SSE2)
331       // At least a multiple of 16, with SSE2.
332       static_assert(InputDimensions % SimdWidth == 0);
333       constexpr IndexType NumChunks = InputDimensions / SimdWidth;
334       const __m128i Zeros = _mm_setzero_si128();
335       const auto inputVector = reinterpret_cast<const __m128i*>(input);
336
337 #elif defined(USE_MMX)
338       static_assert(InputDimensions % SimdWidth == 0);
339       constexpr IndexType NumChunks = InputDimensions / SimdWidth;
340       const __m64 Zeros = _mm_setzero_si64();
341       const auto inputVector = reinterpret_cast<const __m64*>(input);
342
343 #elif defined(USE_NEON)
344       static_assert(InputDimensions % SimdWidth == 0);
345       constexpr IndexType NumChunks = InputDimensions / SimdWidth;
346       const auto inputVector = reinterpret_cast<const int8x8_t*>(input);
347 #endif
348
349       for (IndexType i = 0; i < OutputDimensions; ++i) {
350         const IndexType offset = i * PaddedInputDimensions;
351
352 #if defined(USE_SSE2)
353         __m128i sumLo = _mm_cvtsi32_si128(biases[i]);
354         __m128i sumHi = Zeros;
355         const auto row = reinterpret_cast<const __m128i*>(&weights[offset]);
356         for (IndexType j = 0; j < NumChunks; ++j) {
357           __m128i row_j = _mm_load_si128(&row[j]);
358           __m128i input_j = _mm_load_si128(&inputVector[j]);
359           __m128i extendedRowLo = _mm_srai_epi16(_mm_unpacklo_epi8(row_j, row_j), 8);
360           __m128i extendedRowHi = _mm_srai_epi16(_mm_unpackhi_epi8(row_j, row_j), 8);
361           __m128i extendedInputLo = _mm_unpacklo_epi8(input_j, Zeros);
362           __m128i extendedInputHi = _mm_unpackhi_epi8(input_j, Zeros);
363           __m128i productLo = _mm_madd_epi16(extendedRowLo, extendedInputLo);
364           __m128i productHi = _mm_madd_epi16(extendedRowHi, extendedInputHi);
365           sumLo = _mm_add_epi32(sumLo, productLo);
366           sumHi = _mm_add_epi32(sumHi, productHi);
367         }
368         __m128i sum = _mm_add_epi32(sumLo, sumHi);
369         __m128i sumHigh_64 = _mm_shuffle_epi32(sum, _MM_SHUFFLE(1, 0, 3, 2));
370         sum = _mm_add_epi32(sum, sumHigh_64);
371         __m128i sum_second_32 = _mm_shufflelo_epi16(sum, _MM_SHUFFLE(1, 0, 3, 2));
372         sum = _mm_add_epi32(sum, sum_second_32);
373         output[i] = _mm_cvtsi128_si32(sum);
374
375 #elif defined(USE_MMX)
376         __m64 sumLo = _mm_cvtsi32_si64(biases[i]);
377         __m64 sumHi = Zeros;
378         const auto row = reinterpret_cast<const __m64*>(&weights[offset]);
379         for (IndexType j = 0; j < NumChunks; ++j) {
380           __m64 row_j = row[j];
381           __m64 input_j = inputVector[j];
382           __m64 extendedRowLo = _mm_srai_pi16(_mm_unpacklo_pi8(row_j, row_j), 8);
383           __m64 extendedRowHi = _mm_srai_pi16(_mm_unpackhi_pi8(row_j, row_j), 8);
384           __m64 extendedInputLo = _mm_unpacklo_pi8(input_j, Zeros);
385           __m64 extendedInputHi = _mm_unpackhi_pi8(input_j, Zeros);
386           __m64 productLo = _mm_madd_pi16(extendedRowLo, extendedInputLo);
387           __m64 productHi = _mm_madd_pi16(extendedRowHi, extendedInputHi);
388           sumLo = _mm_add_pi32(sumLo, productLo);
389           sumHi = _mm_add_pi32(sumHi, productHi);
390         }
391         __m64 sum = _mm_add_pi32(sumLo, sumHi);
392         sum = _mm_add_pi32(sum, _mm_unpackhi_pi32(sum, sum));
393         output[i] = _mm_cvtsi64_si32(sum);
394
395 #elif defined(USE_NEON)
396         int32x4_t sum = {biases[i]};
397         const auto row = reinterpret_cast<const int8x8_t*>(&weights[offset]);
398         for (IndexType j = 0; j < NumChunks; ++j) {
399           int16x8_t product = vmull_s8(inputVector[j * 2], row[j * 2]);
400           product = vmlal_s8(product, inputVector[j * 2 + 1], row[j * 2 + 1]);
401           sum = vpadalq_s16(sum, product);
402         }
403         output[i] = sum[0] + sum[1] + sum[2] + sum[3];
404
405 #else
406         OutputType sum = biases[i];
407         for (IndexType j = 0; j < InputDimensions; ++j) {
408           sum += weights[offset + j] * input[j];
409         }
410         output[i] = sum;
411 #endif
412
413       }
414 #if defined(USE_MMX)
415       _mm_empty();
416 #endif
417
418 #endif
419
420       return output;
421     }
422
423    private:
424     using BiasType = OutputType;
425     using WeightType = std::int8_t;
426
427     PreviousLayer previousLayer;
428
429     alignas(CacheLineSize) BiasType biases[OutputDimensions];
430     alignas(CacheLineSize) WeightType weights[OutputDimensions * PaddedInputDimensions];
431   };
432
433 }  // namespace Stockfish::Eval::NNUE::Layers
434
435 #endif // #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED