]> git.sesse.net Git - stockfish/blob - src/nnue/layers/affine_transform.h
Avoid unnecessary stores in the affine transform
[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       const auto output = reinterpret_cast<OutputType*>(buffer);
255       const auto inputVector = reinterpret_cast<const vec_t*>(input);
256
257       static_assert(OutputDimensions % OutputSimdWidth == 0 || OutputDimensions == 1);
258
259       // OutputDimensions is either 1 or a multiple of SimdWidth
260       // because then it is also an input dimension.
261       if constexpr (OutputDimensions % OutputSimdWidth == 0)
262       {
263           static_assert(InputDimensions % 16 == 0);
264
265           constexpr IndexType NumChunks = InputDimensions / 4;
266           constexpr IndexType NumRegs = OutputDimensions / OutputSimdWidth;
267
268           const auto input32 = reinterpret_cast<const std::int32_t*>(input);
269           const vec_t* biasvec = reinterpret_cast<const vec_t*>(biases);
270           vec_t outs[NumRegs];
271           for (IndexType k = 0; k < NumRegs; ++k)
272               outs[k] = biasvec[k];
273
274           for (IndexType i = 0; i < NumChunks; i += 4)
275           {
276               const vec_t in0 = vec_set_32(input32[i + 0]);
277               const vec_t in1 = vec_set_32(input32[i + 1]);
278               const vec_t in2 = vec_set_32(input32[i + 2]);
279               const vec_t in3 = vec_set_32(input32[i + 3]);
280               const auto col0 = reinterpret_cast<const vec_t*>(&weights[(i + 0) * OutputDimensions * 4]);
281               const auto col1 = reinterpret_cast<const vec_t*>(&weights[(i + 1) * OutputDimensions * 4]);
282               const auto col2 = reinterpret_cast<const vec_t*>(&weights[(i + 2) * OutputDimensions * 4]);
283               const auto col3 = reinterpret_cast<const vec_t*>(&weights[(i + 3) * OutputDimensions * 4]);
284               for (IndexType k = 0; k < NumRegs; ++k)
285                   vec_add_dpbusd_32x4(outs[k], in0, col0[k], in1, col1[k], in2, col2[k], in3, col3[k]);
286           }
287
288           vec_t* outptr = reinterpret_cast<vec_t*>(output);
289           for (IndexType k = 0; k < NumRegs; ++k)
290               outptr[k] = outs[k];
291       }
292       else if constexpr (OutputDimensions == 1)
293       {
294           static_assert(InputDimensions % 4 == 0);
295
296 #if defined (USE_AVX512)
297           if constexpr (PaddedInputDimensions % (SimdWidth * 2) != 0)
298           {
299               constexpr IndexType NumChunks = PaddedInputDimensions / SimdWidth;
300               const auto inputVector256 = reinterpret_cast<const __m256i*>(input);
301
302               __m256i sum0 = _mm256_setzero_si256();
303               const auto row0 = reinterpret_cast<const __m256i*>(&weights[0]);
304
305               for (int j = 0; j < (int)NumChunks; ++j)
306               {
307                   const __m256i in = inputVector256[j];
308                   m256_add_dpbusd_epi32(sum0, in, row0[j]);
309               }
310               output[0] = m256_hadd(sum0, biases[0]);
311           }
312           else
313 #endif
314           {
315 #if defined (USE_AVX512)
316               constexpr IndexType NumChunks = PaddedInputDimensions / (SimdWidth * 2);
317 #else
318               constexpr IndexType NumChunks = PaddedInputDimensions / SimdWidth;
319 #endif
320               vec_t sum0 = vec_setzero();
321               const auto row0 = reinterpret_cast<const vec_t*>(&weights[0]);
322
323               for (int j = 0; j < (int)NumChunks; ++j)
324               {
325                   const vec_t in = inputVector[j];
326                   vec_add_dpbusd_32(sum0, in, row0[j]);
327               }
328               output[0] = vec_hadd(sum0, biases[0]);
329           }
330       }
331
332 #else
333
334 // Use old implementation for the other architectures.
335
336       auto output = reinterpret_cast<OutputType*>(buffer);
337
338 #if defined(USE_SSE2)
339       // At least a multiple of 16, with SSE2.
340       static_assert(InputDimensions % SimdWidth == 0);
341       constexpr IndexType NumChunks = InputDimensions / SimdWidth;
342       const __m128i Zeros = _mm_setzero_si128();
343       const auto inputVector = reinterpret_cast<const __m128i*>(input);
344
345 #elif defined(USE_MMX)
346       static_assert(InputDimensions % SimdWidth == 0);
347       constexpr IndexType NumChunks = InputDimensions / SimdWidth;
348       const __m64 Zeros = _mm_setzero_si64();
349       const auto inputVector = reinterpret_cast<const __m64*>(input);
350
351 #elif defined(USE_NEON)
352       static_assert(InputDimensions % SimdWidth == 0);
353       constexpr IndexType NumChunks = InputDimensions / SimdWidth;
354       const auto inputVector = reinterpret_cast<const int8x8_t*>(input);
355 #endif
356
357       for (IndexType i = 0; i < OutputDimensions; ++i) {
358         const IndexType offset = i * PaddedInputDimensions;
359
360 #if defined(USE_SSE2)
361         __m128i sumLo = _mm_cvtsi32_si128(biases[i]);
362         __m128i sumHi = Zeros;
363         const auto row = reinterpret_cast<const __m128i*>(&weights[offset]);
364         for (IndexType j = 0; j < NumChunks; ++j) {
365           __m128i row_j = _mm_load_si128(&row[j]);
366           __m128i input_j = _mm_load_si128(&inputVector[j]);
367           __m128i extendedRowLo = _mm_srai_epi16(_mm_unpacklo_epi8(row_j, row_j), 8);
368           __m128i extendedRowHi = _mm_srai_epi16(_mm_unpackhi_epi8(row_j, row_j), 8);
369           __m128i extendedInputLo = _mm_unpacklo_epi8(input_j, Zeros);
370           __m128i extendedInputHi = _mm_unpackhi_epi8(input_j, Zeros);
371           __m128i productLo = _mm_madd_epi16(extendedRowLo, extendedInputLo);
372           __m128i productHi = _mm_madd_epi16(extendedRowHi, extendedInputHi);
373           sumLo = _mm_add_epi32(sumLo, productLo);
374           sumHi = _mm_add_epi32(sumHi, productHi);
375         }
376         __m128i sum = _mm_add_epi32(sumLo, sumHi);
377         __m128i sumHigh_64 = _mm_shuffle_epi32(sum, _MM_SHUFFLE(1, 0, 3, 2));
378         sum = _mm_add_epi32(sum, sumHigh_64);
379         __m128i sum_second_32 = _mm_shufflelo_epi16(sum, _MM_SHUFFLE(1, 0, 3, 2));
380         sum = _mm_add_epi32(sum, sum_second_32);
381         output[i] = _mm_cvtsi128_si32(sum);
382
383 #elif defined(USE_MMX)
384         __m64 sumLo = _mm_cvtsi32_si64(biases[i]);
385         __m64 sumHi = Zeros;
386         const auto row = reinterpret_cast<const __m64*>(&weights[offset]);
387         for (IndexType j = 0; j < NumChunks; ++j) {
388           __m64 row_j = row[j];
389           __m64 input_j = inputVector[j];
390           __m64 extendedRowLo = _mm_srai_pi16(_mm_unpacklo_pi8(row_j, row_j), 8);
391           __m64 extendedRowHi = _mm_srai_pi16(_mm_unpackhi_pi8(row_j, row_j), 8);
392           __m64 extendedInputLo = _mm_unpacklo_pi8(input_j, Zeros);
393           __m64 extendedInputHi = _mm_unpackhi_pi8(input_j, Zeros);
394           __m64 productLo = _mm_madd_pi16(extendedRowLo, extendedInputLo);
395           __m64 productHi = _mm_madd_pi16(extendedRowHi, extendedInputHi);
396           sumLo = _mm_add_pi32(sumLo, productLo);
397           sumHi = _mm_add_pi32(sumHi, productHi);
398         }
399         __m64 sum = _mm_add_pi32(sumLo, sumHi);
400         sum = _mm_add_pi32(sum, _mm_unpackhi_pi32(sum, sum));
401         output[i] = _mm_cvtsi64_si32(sum);
402
403 #elif defined(USE_NEON)
404         int32x4_t sum = {biases[i]};
405         const auto row = reinterpret_cast<const int8x8_t*>(&weights[offset]);
406         for (IndexType j = 0; j < NumChunks; ++j) {
407           int16x8_t product = vmull_s8(inputVector[j * 2], row[j * 2]);
408           product = vmlal_s8(product, inputVector[j * 2 + 1], row[j * 2 + 1]);
409           sum = vpadalq_s16(sum, product);
410         }
411         output[i] = sum[0] + sum[1] + sum[2] + sum[3];
412
413 #else
414         OutputType sum = biases[i];
415         for (IndexType j = 0; j < InputDimensions; ++j) {
416           sum += weights[offset + j] * input[j];
417         }
418         output[i] = sum;
419 #endif
420
421       }
422 #if defined(USE_MMX)
423       _mm_empty();
424 #endif
425
426 #endif
427
428       return output;
429     }
430
431    private:
432     using BiasType = OutputType;
433     using WeightType = std::int8_t;
434
435     PreviousLayer previousLayer;
436
437     alignas(CacheLineSize) BiasType biases[OutputDimensions];
438     alignas(CacheLineSize) WeightType weights[OutputDimensions * PaddedInputDimensions];
439   };
440
441 }  // namespace Stockfish::Eval::NNUE::Layers
442
443 #endif // #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED