]> git.sesse.net Git - stockfish/blob - src/nnue/nnue_feature_transformer.h
Cleanup and simplify NNUE code.
[stockfish] / src / nnue / nnue_feature_transformer.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 // A class that converts the input features of the NNUE evaluation function
20
21 #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED
22 #define NNUE_FEATURE_TRANSFORMER_H_INCLUDED
23
24 #include "nnue_common.h"
25 #include "nnue_architecture.h"
26
27 #include "../misc.h"
28
29 #include <cstring> // std::memset()
30
31 namespace Stockfish::Eval::NNUE {
32
33   // If vector instructions are enabled, we update and refresh the
34   // accumulator tile by tile such that each tile fits in the CPU's
35   // vector registers.
36   #define VECTOR
37
38   #ifdef USE_AVX512
39   typedef __m512i vec_t;
40   #define vec_load(a) _mm512_load_si512(a)
41   #define vec_store(a,b) _mm512_store_si512(a,b)
42   #define vec_add_16(a,b) _mm512_add_epi16(a,b)
43   #define vec_sub_16(a,b) _mm512_sub_epi16(a,b)
44   static constexpr IndexType NumRegs = 8; // only 8 are needed
45
46   #elif USE_AVX2
47   typedef __m256i vec_t;
48   #define vec_load(a) _mm256_load_si256(a)
49   #define vec_store(a,b) _mm256_store_si256(a,b)
50   #define vec_add_16(a,b) _mm256_add_epi16(a,b)
51   #define vec_sub_16(a,b) _mm256_sub_epi16(a,b)
52   static constexpr IndexType NumRegs = 16;
53
54   #elif USE_SSE2
55   typedef __m128i vec_t;
56   #define vec_load(a) (*(a))
57   #define vec_store(a,b) *(a)=(b)
58   #define vec_add_16(a,b) _mm_add_epi16(a,b)
59   #define vec_sub_16(a,b) _mm_sub_epi16(a,b)
60   static constexpr IndexType NumRegs = Is64Bit ? 16 : 8;
61
62   #elif USE_MMX
63   typedef __m64 vec_t;
64   #define vec_load(a) (*(a))
65   #define vec_store(a,b) *(a)=(b)
66   #define vec_add_16(a,b) _mm_add_pi16(a,b)
67   #define vec_sub_16(a,b) _mm_sub_pi16(a,b)
68   static constexpr IndexType NumRegs = 8;
69
70   #elif USE_NEON
71   typedef int16x8_t vec_t;
72   #define vec_load(a) (*(a))
73   #define vec_store(a,b) *(a)=(b)
74   #define vec_add_16(a,b) vaddq_s16(a,b)
75   #define vec_sub_16(a,b) vsubq_s16(a,b)
76   static constexpr IndexType NumRegs = 16;
77
78   #else
79   #undef VECTOR
80
81   #endif
82
83   // Input feature converter
84   class FeatureTransformer {
85
86    private:
87     // Number of output dimensions for one side
88     static constexpr IndexType HalfDimensions = TransformedFeatureDimensions;
89
90     #ifdef VECTOR
91     static constexpr IndexType TileHeight = NumRegs * sizeof(vec_t) / 2;
92     static_assert(HalfDimensions % TileHeight == 0, "TileHeight must divide HalfDimensions");
93     #endif
94
95    public:
96     // Output type
97     using OutputType = TransformedFeatureType;
98
99     // Number of input/output dimensions
100     static constexpr IndexType InputDimensions = FeatureSet::Dimensions;
101     static constexpr IndexType OutputDimensions = HalfDimensions * 2;
102
103     // Size of forward propagation buffer
104     static constexpr std::size_t BufferSize =
105         OutputDimensions * sizeof(OutputType);
106
107     // Hash value embedded in the evaluation file
108     static constexpr std::uint32_t get_hash_value() {
109       return FeatureSet::HashValue ^ OutputDimensions;
110     }
111
112     // Read network parameters
113     bool read_parameters(std::istream& stream) {
114       for (std::size_t i = 0; i < HalfDimensions; ++i)
115         biases[i] = read_little_endian<BiasType>(stream);
116       for (std::size_t i = 0; i < HalfDimensions * InputDimensions; ++i)
117         weights[i] = read_little_endian<WeightType>(stream);
118       return !stream.fail();
119     }
120
121     // Convert input features
122     void transform(const Position& pos, OutputType* output) const {
123       update_accumulator(pos, WHITE);
124       update_accumulator(pos, BLACK);
125
126       const auto& accumulation = pos.state()->accumulator.accumulation;
127
128   #if defined(USE_AVX512)
129       constexpr IndexType NumChunks = HalfDimensions / (SimdWidth * 2);
130       static_assert(HalfDimensions % (SimdWidth * 2) == 0);
131       const __m512i Control = _mm512_setr_epi64(0, 2, 4, 6, 1, 3, 5, 7);
132       const __m512i Zero = _mm512_setzero_si512();
133
134   #elif defined(USE_AVX2)
135       constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
136       constexpr int Control = 0b11011000;
137       const __m256i Zero = _mm256_setzero_si256();
138
139   #elif defined(USE_SSE2)
140       constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
141
142   #ifdef USE_SSE41
143       const __m128i Zero = _mm_setzero_si128();
144   #else
145       const __m128i k0x80s = _mm_set1_epi8(-128);
146   #endif
147
148   #elif defined(USE_MMX)
149       constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
150       const __m64 k0x80s = _mm_set1_pi8(-128);
151
152   #elif defined(USE_NEON)
153       constexpr IndexType NumChunks = HalfDimensions / (SimdWidth / 2);
154       const int8x8_t Zero = {0};
155   #endif
156
157       const Color perspectives[2] = {pos.side_to_move(), ~pos.side_to_move()};
158       for (IndexType p = 0; p < 2; ++p) {
159         const IndexType offset = HalfDimensions * p;
160
161   #if defined(USE_AVX512)
162         auto out = reinterpret_cast<__m512i*>(&output[offset]);
163         for (IndexType j = 0; j < NumChunks; ++j) {
164           __m512i sum0 = _mm512_load_si512(
165               &reinterpret_cast<const __m512i*>(accumulation[perspectives[p]])[j * 2 + 0]);
166           __m512i sum1 = _mm512_load_si512(
167               &reinterpret_cast<const __m512i*>(accumulation[perspectives[p]])[j * 2 + 1]);
168           _mm512_store_si512(&out[j], _mm512_permutexvar_epi64(Control,
169               _mm512_max_epi8(_mm512_packs_epi16(sum0, sum1), Zero)));
170         }
171
172   #elif defined(USE_AVX2)
173         auto out = reinterpret_cast<__m256i*>(&output[offset]);
174         for (IndexType j = 0; j < NumChunks; ++j) {
175           __m256i sum0 = _mm256_load_si256(
176               &reinterpret_cast<const __m256i*>(accumulation[perspectives[p]])[j * 2 + 0]);
177           __m256i sum1 = _mm256_load_si256(
178               &reinterpret_cast<const __m256i*>(accumulation[perspectives[p]])[j * 2 + 1]);
179           _mm256_store_si256(&out[j], _mm256_permute4x64_epi64(_mm256_max_epi8(
180               _mm256_packs_epi16(sum0, sum1), Zero), Control));
181         }
182
183   #elif defined(USE_SSE2)
184         auto out = reinterpret_cast<__m128i*>(&output[offset]);
185         for (IndexType j = 0; j < NumChunks; ++j) {
186           __m128i sum0 = _mm_load_si128(&reinterpret_cast<const __m128i*>(
187               accumulation[perspectives[p]])[j * 2 + 0]);
188           __m128i sum1 = _mm_load_si128(&reinterpret_cast<const __m128i*>(
189               accumulation[perspectives[p]])[j * 2 + 1]);
190       const __m128i packedbytes = _mm_packs_epi16(sum0, sum1);
191
192           _mm_store_si128(&out[j],
193
194   #ifdef USE_SSE41
195               _mm_max_epi8(packedbytes, Zero)
196   #else
197               _mm_subs_epi8(_mm_adds_epi8(packedbytes, k0x80s), k0x80s)
198   #endif
199
200           );
201         }
202
203   #elif defined(USE_MMX)
204         auto out = reinterpret_cast<__m64*>(&output[offset]);
205         for (IndexType j = 0; j < NumChunks; ++j) {
206           __m64 sum0 = *(&reinterpret_cast<const __m64*>(
207               accumulation[perspectives[p]])[j * 2 + 0]);
208           __m64 sum1 = *(&reinterpret_cast<const __m64*>(
209               accumulation[perspectives[p]])[j * 2 + 1]);
210           const __m64 packedbytes = _mm_packs_pi16(sum0, sum1);
211           out[j] = _mm_subs_pi8(_mm_adds_pi8(packedbytes, k0x80s), k0x80s);
212         }
213
214   #elif defined(USE_NEON)
215         const auto out = reinterpret_cast<int8x8_t*>(&output[offset]);
216         for (IndexType j = 0; j < NumChunks; ++j) {
217           int16x8_t sum = reinterpret_cast<const int16x8_t*>(
218               accumulation[perspectives[p]])[j];
219           out[j] = vmax_s8(vqmovn_s16(sum), Zero);
220         }
221
222   #else
223         for (IndexType j = 0; j < HalfDimensions; ++j) {
224           BiasType sum = accumulation[static_cast<int>(perspectives[p])][j];
225           output[offset + j] = static_cast<OutputType>(
226               std::max<int>(0, std::min<int>(127, sum)));
227         }
228   #endif
229
230       }
231   #if defined(USE_MMX)
232       _mm_empty();
233   #endif
234     }
235
236    private:
237     void update_accumulator(const Position& pos, const Color perspective) const {
238
239       // The size must be enough to contain the largest possible update.
240       // That might depend on the feature set and generally relies on the
241       // feature set's update cost calculation to be correct and never
242       // allow updates with more added/removed features than MaxActiveDimensions.
243       using IndexList = ValueList<IndexType, FeatureSet::MaxActiveDimensions>;
244
245   #ifdef VECTOR
246       // Gcc-10.2 unnecessarily spills AVX2 registers if this array
247       // is defined in the VECTOR code below, once in each branch
248       vec_t acc[NumRegs];
249   #endif
250
251       // Look for a usable accumulator of an earlier position. We keep track
252       // of the estimated gain in terms of features to be added/subtracted.
253       StateInfo *st = pos.state(), *next = nullptr;
254       int gain = FeatureSet::refresh_cost(pos);
255       while (st->accumulator.state[perspective] == EMPTY)
256       {
257         // This governs when a full feature refresh is needed and how many
258         // updates are better than just one full refresh.
259         if (   FeatureSet::requires_refresh(st, perspective)
260             || (gain -= FeatureSet::update_cost(st) + 1) < 0)
261           break;
262         next = st;
263         st = st->previous;
264       }
265
266       if (st->accumulator.state[perspective] == COMPUTED)
267       {
268         if (next == nullptr)
269           return;
270
271         // Update incrementally in two steps. First, we update the "next"
272         // accumulator. Then, we update the current accumulator (pos.state()).
273
274         // Gather all features to be updated.
275         const Square ksq = pos.square<KING>(perspective);
276         IndexList removed[2], added[2];
277         FeatureSet::append_changed_indices(
278           ksq, next, perspective, removed[0], added[0]);
279         for (StateInfo *st2 = pos.state(); st2 != next; st2 = st2->previous)
280           FeatureSet::append_changed_indices(
281             ksq, st2, perspective, removed[1], added[1]);
282
283         // Mark the accumulators as computed.
284         next->accumulator.state[perspective] = COMPUTED;
285         pos.state()->accumulator.state[perspective] = COMPUTED;
286
287         // Now update the accumulators listed in states_to_update[], where the last element is a sentinel.
288         StateInfo *states_to_update[3] =
289           { next, next == pos.state() ? nullptr : pos.state(), nullptr };
290   #ifdef VECTOR
291         for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
292         {
293           // Load accumulator
294           auto accTile = reinterpret_cast<vec_t*>(
295             &st->accumulator.accumulation[perspective][j * TileHeight]);
296           for (IndexType k = 0; k < NumRegs; ++k)
297             acc[k] = vec_load(&accTile[k]);
298
299           for (IndexType i = 0; states_to_update[i]; ++i)
300           {
301             // Difference calculation for the deactivated features
302             for (const auto index : removed[i])
303             {
304               const IndexType offset = HalfDimensions * index + j * TileHeight;
305               auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
306               for (IndexType k = 0; k < NumRegs; ++k)
307                 acc[k] = vec_sub_16(acc[k], column[k]);
308             }
309
310             // Difference calculation for the activated features
311             for (const auto index : added[i])
312             {
313               const IndexType offset = HalfDimensions * index + j * TileHeight;
314               auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
315               for (IndexType k = 0; k < NumRegs; ++k)
316                 acc[k] = vec_add_16(acc[k], column[k]);
317             }
318
319             // Store accumulator
320             accTile = reinterpret_cast<vec_t*>(
321               &states_to_update[i]->accumulator.accumulation[perspective][j * TileHeight]);
322             for (IndexType k = 0; k < NumRegs; ++k)
323               vec_store(&accTile[k], acc[k]);
324           }
325         }
326
327   #else
328         for (IndexType i = 0; states_to_update[i]; ++i)
329         {
330           std::memcpy(states_to_update[i]->accumulator.accumulation[perspective],
331               st->accumulator.accumulation[perspective],
332               HalfDimensions * sizeof(BiasType));
333           st = states_to_update[i];
334
335           // Difference calculation for the deactivated features
336           for (const auto index : removed[i])
337           {
338             const IndexType offset = HalfDimensions * index;
339
340             for (IndexType j = 0; j < HalfDimensions; ++j)
341               st->accumulator.accumulation[perspective][j] -= weights[offset + j];
342           }
343
344           // Difference calculation for the activated features
345           for (const auto index : added[i])
346           {
347             const IndexType offset = HalfDimensions * index;
348
349             for (IndexType j = 0; j < HalfDimensions; ++j)
350               st->accumulator.accumulation[perspective][j] += weights[offset + j];
351           }
352         }
353   #endif
354       }
355       else
356       {
357         // Refresh the accumulator
358         auto& accumulator = pos.state()->accumulator;
359         accumulator.state[perspective] = COMPUTED;
360         IndexList active;
361         FeatureSet::append_active_indices(pos, perspective, active);
362
363   #ifdef VECTOR
364         for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
365         {
366           auto biasesTile = reinterpret_cast<const vec_t*>(
367               &biases[j * TileHeight]);
368           for (IndexType k = 0; k < NumRegs; ++k)
369             acc[k] = biasesTile[k];
370
371           for (const auto index : active)
372           {
373             const IndexType offset = HalfDimensions * index + j * TileHeight;
374             auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
375
376             for (unsigned k = 0; k < NumRegs; ++k)
377               acc[k] = vec_add_16(acc[k], column[k]);
378           }
379
380           auto accTile = reinterpret_cast<vec_t*>(
381               &accumulator.accumulation[perspective][j * TileHeight]);
382           for (unsigned k = 0; k < NumRegs; k++)
383             vec_store(&accTile[k], acc[k]);
384         }
385
386   #else
387         std::memcpy(accumulator.accumulation[perspective], biases,
388             HalfDimensions * sizeof(BiasType));
389
390         for (const auto index : active)
391         {
392           const IndexType offset = HalfDimensions * index;
393
394           for (IndexType j = 0; j < HalfDimensions; ++j)
395             accumulator.accumulation[perspective][j] += weights[offset + j];
396         }
397   #endif
398       }
399
400   #if defined(USE_MMX)
401       _mm_empty();
402   #endif
403     }
404
405     using BiasType = std::int16_t;
406     using WeightType = std::int16_t;
407
408     alignas(CacheLineSize) BiasType biases[HalfDimensions];
409     alignas(CacheLineSize) WeightType weights[HalfDimensions * InputDimensions];
410   };
411
412 }  // namespace Stockfish::Eval::NNUE
413
414 #endif // #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED