]> git.sesse.net Git - stockfish/blob - src/nnue/layers/affine_transform.h
Fix compilation after recent merge.
[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,
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)
51         #if defined(USE_SSE2)
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);
56
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);
60
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);
64         #endif
65
66     for (IndexType i = 0; i < OutputDimensions; ++i)
67     {
68         const IndexType offset = i * PaddedInputDimensions;
69
70         #if defined(USE_SSE2)
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)
75         {
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);
86         }
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);
93
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)
98         {
99             sum = vdotq_s32(sum, inputVector[j], row[j]);
100         }
101         output[i] = vaddvq_s32(sum);
102
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)
107         {
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);
111         }
112         output[i] = sum[0] + sum[1] + sum[2] + sum[3];
113
114         #endif
115     }
116     #else
117     std::memcpy(output, biases, sizeof(std::int32_t) * OutputDimensions);
118
119     // Traverse weights in transpose order to take advantage of input sparsity
120     for (IndexType i = 0; i < InputDimensions; ++i)
121         if (input[i])
122         {
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;
127         }
128     #endif
129 }
130 #endif
131
132 template<IndexType InDims, IndexType OutDims>
133 class AffineTransform {
134    public:
135     // Input/output type
136     using InputType  = std::uint8_t;
137     using OutputType = std::int32_t;
138
139     // Number of input/output dimensions
140     static constexpr IndexType InputDimensions  = InDims;
141     static constexpr IndexType OutputDimensions = OutDims;
142
143     static constexpr IndexType PaddedInputDimensions =
144       ceil_to_multiple<IndexType>(InputDimensions, MaxSimdWidth);
145     static constexpr IndexType PaddedOutputDimensions =
146       ceil_to_multiple<IndexType>(OutputDimensions, MaxSimdWidth);
147
148     using OutputBuffer = OutputType[PaddedOutputDimensions];
149
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;
156         return hashValue;
157     }
158
159     static constexpr IndexType get_weight_index_scrambled(IndexType i) {
160         return (i / 4) % (PaddedInputDimensions / 4) * OutputDimensions * 4
161              + i / PaddedInputDimensions * 4 + i % 4;
162     }
163
164     static constexpr IndexType get_weight_index(IndexType i) {
165 #if defined(USE_SSSE3)
166         return get_weight_index_scrambled(i);
167 #else
168         return i;
169 #endif
170     }
171
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);
177
178         return !stream.fail();
179     }
180
181     // Write network parameters
182     bool write_parameters(std::ostream& stream) const {
183         write_little_endian<BiasType>(stream, biases, OutputDimensions);
184
185         for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
186             write_little_endian<WeightType>(stream, weights[get_weight_index(i)]);
187
188         return !stream.fail();
189     }
190     // Forward propagation
191     void propagate(const InputType* input, OutputType* output) const {
192
193 #if defined(USE_SSSE3)
194
195         if constexpr (OutputDimensions > 1)
196         {
197
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
219     #endif
220
221             static constexpr IndexType OutputSimdWidth = sizeof(vec_t) / sizeof(OutputType);
222
223             static_assert(OutputDimensions % OutputSimdWidth == 0);
224
225             constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 8) / 4;
226             constexpr IndexType NumRegs   = OutputDimensions / OutputSimdWidth;
227
228             const auto   input32 = reinterpret_cast<const std::int32_t*>(input);
229             const vec_t* biasvec = reinterpret_cast<const vec_t*>(biases);
230             vec_t        acc[NumRegs];
231             for (IndexType k = 0; k < NumRegs; ++k)
232                 acc[k] = biasvec[k];
233
234             for (IndexType i = 0; i < NumChunks; i += 2)
235             {
236                 const vec_t in0 = vec_set_32(input32[i + 0]);
237                 const vec_t in1 = vec_set_32(input32[i + 1]);
238                 const auto  col0 =
239                   reinterpret_cast<const vec_t*>(&weights[(i + 0) * OutputDimensions * 4]);
240                 const auto col1 =
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]);
244             }
245
246             vec_t* outptr = reinterpret_cast<vec_t*>(output);
247             for (IndexType k = 0; k < NumRegs; ++k)
248                 outptr[k] = acc[k];
249
250     #undef vec_setzero
251     #undef vec_set_32
252     #undef vec_add_dpbusd_32
253     #undef vec_add_dpbusd_32x2
254     #undef vec_hadd
255         }
256         else if constexpr (OutputDimensions == 1)
257         {
258
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
275     #endif
276
277             const auto inputVector = reinterpret_cast<const vec_t*>(input);
278
279             static constexpr IndexType InputSimdWidth = sizeof(vec_t) / sizeof(InputType);
280
281             static_assert(PaddedInputDimensions % InputSimdWidth == 0);
282
283             constexpr IndexType NumChunks = PaddedInputDimensions / InputSimdWidth;
284             vec_t               sum0      = vec_setzero();
285             const auto          row0      = reinterpret_cast<const vec_t*>(&weights[0]);
286
287             for (int j = 0; j < int(NumChunks); ++j)
288             {
289                 const vec_t in = inputVector[j];
290                 vec_add_dpbusd_32(sum0, in, row0[j]);
291             }
292             output[0] = vec_hadd(sum0, biases[0]);
293
294     #undef vec_setzero
295     #undef vec_set_32
296     #undef vec_add_dpbusd_32
297     #undef vec_add_dpbusd_32x2
298     #undef vec_hadd
299         }
300 #else
301         // Use old implementation for the other architectures.
302         affine_transform_non_ssse3<InputDimensions, PaddedInputDimensions, OutputDimensions>(
303           output, weights, biases, input);
304 #endif
305     }
306
307    private:
308     using BiasType   = OutputType;
309     using WeightType = std::int8_t;
310
311     alignas(CacheLineSize) BiasType biases[OutputDimensions];
312     alignas(CacheLineSize) WeightType weights[OutputDimensions * PaddedInputDimensions];
313 };
314
315 }  // namespace Stockfish::Eval::NNUE::Layers
316
317 #endif  // #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED