]> git.sesse.net Git - stockfish/blob - src/nnue/nnue_feature_transformer.h
Do not use lazy evaluation inside NNUE
[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   static_assert(PSQTBuckets == 8, "Assumed by the current choice of constants.");
39
40   #ifdef USE_AVX512
41   typedef __m512i vec_t;
42   typedef __m256i psqt_vec_t;
43   #define vec_load(a) _mm512_load_si512(a)
44   #define vec_store(a,b) _mm512_store_si512(a,b)
45   #define vec_add_16(a,b) _mm512_add_epi16(a,b)
46   #define vec_sub_16(a,b) _mm512_sub_epi16(a,b)
47   #define vec_load_psqt(a) _mm256_load_si256(a)
48   #define vec_store_psqt(a,b) _mm256_store_si256(a,b)
49   #define vec_add_psqt_32(a,b) _mm256_add_epi32(a,b)
50   #define vec_sub_psqt_32(a,b) _mm256_sub_epi32(a,b)
51   #define vec_zero_psqt() _mm256_setzero_si256()
52   static constexpr IndexType NumRegs = 8; // only 8 are needed
53   static constexpr IndexType NumPsqtRegs = 1;
54
55   #elif USE_AVX2
56   typedef __m256i vec_t;
57   typedef __m256i psqt_vec_t;
58   #define vec_load(a) _mm256_load_si256(a)
59   #define vec_store(a,b) _mm256_store_si256(a,b)
60   #define vec_add_16(a,b) _mm256_add_epi16(a,b)
61   #define vec_sub_16(a,b) _mm256_sub_epi16(a,b)
62   #define vec_load_psqt(a) _mm256_load_si256(a)
63   #define vec_store_psqt(a,b) _mm256_store_si256(a,b)
64   #define vec_add_psqt_32(a,b) _mm256_add_epi32(a,b)
65   #define vec_sub_psqt_32(a,b) _mm256_sub_epi32(a,b)
66   #define vec_zero_psqt() _mm256_setzero_si256()
67   static constexpr IndexType NumRegs = 16;
68   static constexpr IndexType NumPsqtRegs = 1;
69
70   #elif USE_SSE2
71   typedef __m128i vec_t;
72   typedef __m128i psqt_vec_t;
73   #define vec_load(a) (*(a))
74   #define vec_store(a,b) *(a)=(b)
75   #define vec_add_16(a,b) _mm_add_epi16(a,b)
76   #define vec_sub_16(a,b) _mm_sub_epi16(a,b)
77   #define vec_load_psqt(a) (*(a))
78   #define vec_store_psqt(a,b) *(a)=(b)
79   #define vec_add_psqt_32(a,b) _mm_add_epi32(a,b)
80   #define vec_sub_psqt_32(a,b) _mm_sub_epi32(a,b)
81   #define vec_zero_psqt() _mm_setzero_si128()
82   static constexpr IndexType NumRegs = Is64Bit ? 16 : 8;
83   static constexpr IndexType NumPsqtRegs = 2;
84
85   #elif USE_MMX
86   typedef __m64 vec_t;
87   typedef __m64 psqt_vec_t;
88   #define vec_load(a) (*(a))
89   #define vec_store(a,b) *(a)=(b)
90   #define vec_add_16(a,b) _mm_add_pi16(a,b)
91   #define vec_sub_16(a,b) _mm_sub_pi16(a,b)
92   #define vec_load_psqt(a) (*(a))
93   #define vec_store_psqt(a,b) *(a)=(b)
94   #define vec_add_psqt_32(a,b) _mm_add_pi32(a,b)
95   #define vec_sub_psqt_32(a,b) _mm_sub_pi32(a,b)
96   #define vec_zero_psqt() _mm_setzero_si64()
97   static constexpr IndexType NumRegs = 8;
98   static constexpr IndexType NumPsqtRegs = 4;
99
100   #elif USE_NEON
101   typedef int16x8_t vec_t;
102   typedef int32x4_t psqt_vec_t;
103   #define vec_load(a) (*(a))
104   #define vec_store(a,b) *(a)=(b)
105   #define vec_add_16(a,b) vaddq_s16(a,b)
106   #define vec_sub_16(a,b) vsubq_s16(a,b)
107   #define vec_load_psqt(a) (*(a))
108   #define vec_store_psqt(a,b) *(a)=(b)
109   #define vec_add_psqt_32(a,b) vaddq_s32(a,b)
110   #define vec_sub_psqt_32(a,b) vsubq_s32(a,b)
111   #define vec_zero_psqt() psqt_vec_t{0}
112   static constexpr IndexType NumRegs = 16;
113   static constexpr IndexType NumPsqtRegs = 2;
114
115   #else
116   #undef VECTOR
117
118   #endif
119
120   // Input feature converter
121   class FeatureTransformer {
122
123    private:
124     // Number of output dimensions for one side
125     static constexpr IndexType HalfDimensions = TransformedFeatureDimensions;
126
127     #ifdef VECTOR
128     static constexpr IndexType TileHeight = NumRegs * sizeof(vec_t) / 2;
129     static constexpr IndexType PsqtTileHeight = NumPsqtRegs * sizeof(psqt_vec_t) / 4;
130     static_assert(HalfDimensions % TileHeight == 0, "TileHeight must divide HalfDimensions");
131     static_assert(PSQTBuckets % PsqtTileHeight == 0, "PsqtTileHeight must divide PSQTBuckets");
132     #endif
133
134    public:
135     // Output type
136     using OutputType = TransformedFeatureType;
137
138     // Number of input/output dimensions
139     static constexpr IndexType InputDimensions = FeatureSet::Dimensions;
140     static constexpr IndexType OutputDimensions = HalfDimensions * 2;
141
142     // Size of forward propagation buffer
143     static constexpr std::size_t BufferSize =
144         OutputDimensions * sizeof(OutputType);
145
146     // Hash value embedded in the evaluation file
147     static constexpr std::uint32_t get_hash_value() {
148       return FeatureSet::HashValue ^ OutputDimensions;
149     }
150
151     // Read network parameters
152     bool read_parameters(std::istream& stream) {
153       for (std::size_t i = 0; i < HalfDimensions; ++i)
154         biases[i] = read_little_endian<BiasType>(stream);
155       for (std::size_t i = 0; i < HalfDimensions * InputDimensions; ++i)
156         weights[i] = read_little_endian<WeightType>(stream);
157       for (std::size_t i = 0; i < PSQTBuckets * InputDimensions; ++i)
158         psqtWeights[i] = read_little_endian<PSQTWeightType>(stream);
159       return !stream.fail();
160     }
161
162     // Write network parameters
163     bool write_parameters(std::ostream& stream) const {
164       for (std::size_t i = 0; i < HalfDimensions; ++i)
165         write_little_endian<BiasType>(stream, biases[i]);
166       for (std::size_t i = 0; i < HalfDimensions * InputDimensions; ++i)
167         write_little_endian<WeightType>(stream, weights[i]);
168       return !stream.fail();
169     }
170
171     // Convert input features
172     std::int32_t transform(const Position& pos, OutputType* output, int bucket) const {
173       update_accumulator(pos, WHITE);
174       update_accumulator(pos, BLACK);
175
176       const Color perspectives[2] = {pos.side_to_move(), ~pos.side_to_move()};
177       const auto& accumulation = pos.state()->accumulator.accumulation;
178       const auto& psqtAccumulation = pos.state()->accumulator.psqtAccumulation;
179
180       const auto psqt = (
181             psqtAccumulation[static_cast<int>(perspectives[0])][bucket]
182           - psqtAccumulation[static_cast<int>(perspectives[1])][bucket]
183         ) / 2;
184
185   #if defined(USE_AVX512)
186       constexpr IndexType NumChunks = HalfDimensions / (SimdWidth * 2);
187       static_assert(HalfDimensions % (SimdWidth * 2) == 0);
188       const __m512i Control = _mm512_setr_epi64(0, 2, 4, 6, 1, 3, 5, 7);
189       const __m512i Zero = _mm512_setzero_si512();
190
191   #elif defined(USE_AVX2)
192       constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
193       constexpr int Control = 0b11011000;
194       const __m256i Zero = _mm256_setzero_si256();
195
196   #elif defined(USE_SSE2)
197       constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
198
199   #ifdef USE_SSE41
200       const __m128i Zero = _mm_setzero_si128();
201   #else
202       const __m128i k0x80s = _mm_set1_epi8(-128);
203   #endif
204
205   #elif defined(USE_MMX)
206       constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
207       const __m64 k0x80s = _mm_set1_pi8(-128);
208
209   #elif defined(USE_NEON)
210       constexpr IndexType NumChunks = HalfDimensions / (SimdWidth / 2);
211       const int8x8_t Zero = {0};
212   #endif
213
214       for (IndexType p = 0; p < 2; ++p) {
215         const IndexType offset = HalfDimensions * p;
216
217   #if defined(USE_AVX512)
218         auto out = reinterpret_cast<__m512i*>(&output[offset]);
219         for (IndexType j = 0; j < NumChunks; ++j) {
220           __m512i sum0 = _mm512_load_si512(
221               &reinterpret_cast<const __m512i*>(accumulation[perspectives[p]])[j * 2 + 0]);
222           __m512i sum1 = _mm512_load_si512(
223               &reinterpret_cast<const __m512i*>(accumulation[perspectives[p]])[j * 2 + 1]);
224           _mm512_store_si512(&out[j], _mm512_permutexvar_epi64(Control,
225               _mm512_max_epi8(_mm512_packs_epi16(sum0, sum1), Zero)));
226         }
227
228   #elif defined(USE_AVX2)
229         auto out = reinterpret_cast<__m256i*>(&output[offset]);
230         for (IndexType j = 0; j < NumChunks; ++j) {
231           __m256i sum0 = _mm256_load_si256(
232               &reinterpret_cast<const __m256i*>(accumulation[perspectives[p]])[j * 2 + 0]);
233           __m256i sum1 = _mm256_load_si256(
234               &reinterpret_cast<const __m256i*>(accumulation[perspectives[p]])[j * 2 + 1]);
235           _mm256_store_si256(&out[j], _mm256_permute4x64_epi64(_mm256_max_epi8(
236               _mm256_packs_epi16(sum0, sum1), Zero), Control));
237         }
238
239   #elif defined(USE_SSE2)
240         auto out = reinterpret_cast<__m128i*>(&output[offset]);
241         for (IndexType j = 0; j < NumChunks; ++j) {
242           __m128i sum0 = _mm_load_si128(&reinterpret_cast<const __m128i*>(
243               accumulation[perspectives[p]])[j * 2 + 0]);
244           __m128i sum1 = _mm_load_si128(&reinterpret_cast<const __m128i*>(
245               accumulation[perspectives[p]])[j * 2 + 1]);
246       const __m128i packedbytes = _mm_packs_epi16(sum0, sum1);
247
248           _mm_store_si128(&out[j],
249
250   #ifdef USE_SSE41
251               _mm_max_epi8(packedbytes, Zero)
252   #else
253               _mm_subs_epi8(_mm_adds_epi8(packedbytes, k0x80s), k0x80s)
254   #endif
255
256           );
257         }
258
259   #elif defined(USE_MMX)
260         auto out = reinterpret_cast<__m64*>(&output[offset]);
261         for (IndexType j = 0; j < NumChunks; ++j) {
262           __m64 sum0 = *(&reinterpret_cast<const __m64*>(
263               accumulation[perspectives[p]])[j * 2 + 0]);
264           __m64 sum1 = *(&reinterpret_cast<const __m64*>(
265               accumulation[perspectives[p]])[j * 2 + 1]);
266           const __m64 packedbytes = _mm_packs_pi16(sum0, sum1);
267           out[j] = _mm_subs_pi8(_mm_adds_pi8(packedbytes, k0x80s), k0x80s);
268         }
269
270   #elif defined(USE_NEON)
271         const auto out = reinterpret_cast<int8x8_t*>(&output[offset]);
272         for (IndexType j = 0; j < NumChunks; ++j) {
273           int16x8_t sum = reinterpret_cast<const int16x8_t*>(
274               accumulation[perspectives[p]])[j];
275           out[j] = vmax_s8(vqmovn_s16(sum), Zero);
276         }
277
278   #else
279         for (IndexType j = 0; j < HalfDimensions; ++j) {
280           BiasType sum = accumulation[static_cast<int>(perspectives[p])][j];
281           output[offset + j] = static_cast<OutputType>(
282               std::max<int>(0, std::min<int>(127, sum)));
283         }
284   #endif
285
286       }
287   #if defined(USE_MMX)
288       _mm_empty();
289   #endif
290
291       return psqt;
292     }
293
294    private:
295     void update_accumulator(const Position& pos, const Color perspective) const {
296
297       // The size must be enough to contain the largest possible update.
298       // That might depend on the feature set and generally relies on the
299       // feature set's update cost calculation to be correct and never
300       // allow updates with more added/removed features than MaxActiveDimensions.
301       using IndexList = ValueList<IndexType, FeatureSet::MaxActiveDimensions>;
302
303   #ifdef VECTOR
304       // Gcc-10.2 unnecessarily spills AVX2 registers if this array
305       // is defined in the VECTOR code below, once in each branch
306       vec_t acc[NumRegs];
307       psqt_vec_t psqt[NumPsqtRegs];
308   #endif
309
310       // Look for a usable accumulator of an earlier position. We keep track
311       // of the estimated gain in terms of features to be added/subtracted.
312       StateInfo *st = pos.state(), *next = nullptr;
313       int gain = FeatureSet::refresh_cost(pos);
314       while (st->accumulator.state[perspective] == EMPTY)
315       {
316         // This governs when a full feature refresh is needed and how many
317         // updates are better than just one full refresh.
318         if (   FeatureSet::requires_refresh(st, perspective)
319             || (gain -= FeatureSet::update_cost(st) + 1) < 0)
320           break;
321         next = st;
322         st = st->previous;
323       }
324
325       if (st->accumulator.state[perspective] == COMPUTED)
326       {
327         if (next == nullptr)
328           return;
329
330         // Update incrementally in two steps. First, we update the "next"
331         // accumulator. Then, we update the current accumulator (pos.state()).
332
333         // Gather all features to be updated.
334         const Square ksq = pos.square<KING>(perspective);
335         IndexList removed[2], added[2];
336         FeatureSet::append_changed_indices(
337           ksq, next, perspective, removed[0], added[0]);
338         for (StateInfo *st2 = pos.state(); st2 != next; st2 = st2->previous)
339           FeatureSet::append_changed_indices(
340             ksq, st2, perspective, removed[1], added[1]);
341
342         // Mark the accumulators as computed.
343         next->accumulator.state[perspective] = COMPUTED;
344         pos.state()->accumulator.state[perspective] = COMPUTED;
345
346         // Now update the accumulators listed in states_to_update[], where the last element is a sentinel.
347         StateInfo *states_to_update[3] =
348           { next, next == pos.state() ? nullptr : pos.state(), nullptr };
349   #ifdef VECTOR
350         for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
351         {
352           // Load accumulator
353           auto accTile = reinterpret_cast<vec_t*>(
354             &st->accumulator.accumulation[perspective][j * TileHeight]);
355           for (IndexType k = 0; k < NumRegs; ++k)
356             acc[k] = vec_load(&accTile[k]);
357
358           for (IndexType i = 0; states_to_update[i]; ++i)
359           {
360             // Difference calculation for the deactivated features
361             for (const auto index : removed[i])
362             {
363               const IndexType offset = HalfDimensions * index + j * TileHeight;
364               auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
365               for (IndexType k = 0; k < NumRegs; ++k)
366                 acc[k] = vec_sub_16(acc[k], column[k]);
367             }
368
369             // Difference calculation for the activated features
370             for (const auto index : added[i])
371             {
372               const IndexType offset = HalfDimensions * index + j * TileHeight;
373               auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
374               for (IndexType k = 0; k < NumRegs; ++k)
375                 acc[k] = vec_add_16(acc[k], column[k]);
376             }
377
378             // Store accumulator
379             accTile = reinterpret_cast<vec_t*>(
380               &states_to_update[i]->accumulator.accumulation[perspective][j * TileHeight]);
381             for (IndexType k = 0; k < NumRegs; ++k)
382               vec_store(&accTile[k], acc[k]);
383           }
384         }
385
386         for (IndexType j = 0; j < PSQTBuckets / PsqtTileHeight; ++j)
387         {
388           // Load accumulator
389           auto accTilePsqt = reinterpret_cast<psqt_vec_t*>(
390             &st->accumulator.psqtAccumulation[perspective][j * PsqtTileHeight]);
391           for (std::size_t k = 0; k < NumPsqtRegs; ++k)
392             psqt[k] = vec_load_psqt(&accTilePsqt[k]);
393
394           for (IndexType i = 0; states_to_update[i]; ++i)
395           {
396             // Difference calculation for the deactivated features
397             for (const auto index : removed[i])
398             {
399               const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
400               auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
401               for (std::size_t k = 0; k < NumPsqtRegs; ++k)
402                 psqt[k] = vec_sub_psqt_32(psqt[k], columnPsqt[k]);
403             }
404
405             // Difference calculation for the activated features
406             for (const auto index : added[i])
407             {
408               const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
409               auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
410               for (std::size_t k = 0; k < NumPsqtRegs; ++k)
411                 psqt[k] = vec_add_psqt_32(psqt[k], columnPsqt[k]);
412             }
413
414             // Store accumulator
415             accTilePsqt = reinterpret_cast<psqt_vec_t*>(
416               &states_to_update[i]->accumulator.psqtAccumulation[perspective][j * PsqtTileHeight]);
417             for (std::size_t k = 0; k < NumPsqtRegs; ++k)
418               vec_store_psqt(&accTilePsqt[k], psqt[k]);
419           }
420         }
421
422   #else
423         for (IndexType i = 0; states_to_update[i]; ++i)
424         {
425           std::memcpy(states_to_update[i]->accumulator.accumulation[perspective],
426               st->accumulator.accumulation[perspective],
427               HalfDimensions * sizeof(BiasType));
428
429           for (std::size_t k = 0; k < PSQTBuckets; ++k)
430             states_to_update[i]->accumulator.psqtAccumulation[perspective][k] = st->accumulator.psqtAccumulation[perspective][k];
431
432           st = states_to_update[i];
433
434           // Difference calculation for the deactivated features
435           for (const auto index : removed[i])
436           {
437             const IndexType offset = HalfDimensions * index;
438
439             for (IndexType j = 0; j < HalfDimensions; ++j)
440               st->accumulator.accumulation[perspective][j] -= weights[offset + j];
441
442             for (std::size_t k = 0; k < PSQTBuckets; ++k)
443               st->accumulator.psqtAccumulation[perspective][k] -= psqtWeights[index * PSQTBuckets + k];
444           }
445
446           // Difference calculation for the activated features
447           for (const auto index : added[i])
448           {
449             const IndexType offset = HalfDimensions * index;
450
451             for (IndexType j = 0; j < HalfDimensions; ++j)
452               st->accumulator.accumulation[perspective][j] += weights[offset + j];
453
454             for (std::size_t k = 0; k < PSQTBuckets; ++k)
455               st->accumulator.psqtAccumulation[perspective][k] += psqtWeights[index * PSQTBuckets + k];
456           }
457         }
458   #endif
459       }
460       else
461       {
462         // Refresh the accumulator
463         auto& accumulator = pos.state()->accumulator;
464         accumulator.state[perspective] = COMPUTED;
465         IndexList active;
466         FeatureSet::append_active_indices(pos, perspective, active);
467
468   #ifdef VECTOR
469         for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
470         {
471           auto biasesTile = reinterpret_cast<const vec_t*>(
472               &biases[j * TileHeight]);
473           for (IndexType k = 0; k < NumRegs; ++k)
474             acc[k] = biasesTile[k];
475
476           for (const auto index : active)
477           {
478             const IndexType offset = HalfDimensions * index + j * TileHeight;
479             auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
480
481             for (unsigned k = 0; k < NumRegs; ++k)
482               acc[k] = vec_add_16(acc[k], column[k]);
483           }
484
485           auto accTile = reinterpret_cast<vec_t*>(
486               &accumulator.accumulation[perspective][j * TileHeight]);
487           for (unsigned k = 0; k < NumRegs; k++)
488             vec_store(&accTile[k], acc[k]);
489         }
490
491         for (IndexType j = 0; j < PSQTBuckets / PsqtTileHeight; ++j)
492         {
493           for (std::size_t k = 0; k < NumPsqtRegs; ++k)
494             psqt[k] = vec_zero_psqt();
495
496           for (const auto index : active)
497           {
498             const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
499             auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
500
501             for (std::size_t k = 0; k < NumPsqtRegs; ++k)
502               psqt[k] = vec_add_psqt_32(psqt[k], columnPsqt[k]);
503           }
504
505           auto accTilePsqt = reinterpret_cast<psqt_vec_t*>(
506             &accumulator.psqtAccumulation[perspective][j * PsqtTileHeight]);
507           for (std::size_t k = 0; k < NumPsqtRegs; ++k)
508             vec_store_psqt(&accTilePsqt[k], psqt[k]);
509         }
510
511   #else
512         std::memcpy(accumulator.accumulation[perspective], biases,
513             HalfDimensions * sizeof(BiasType));
514
515         for (std::size_t k = 0; k < PSQTBuckets; ++k)
516           accumulator.psqtAccumulation[perspective][k] = 0;
517
518         for (const auto index : active)
519         {
520           const IndexType offset = HalfDimensions * index;
521
522           for (IndexType j = 0; j < HalfDimensions; ++j)
523             accumulator.accumulation[perspective][j] += weights[offset + j];
524
525           for (std::size_t k = 0; k < PSQTBuckets; ++k)
526             accumulator.psqtAccumulation[perspective][k] += psqtWeights[index * PSQTBuckets + k];
527         }
528   #endif
529       }
530
531   #if defined(USE_MMX)
532       _mm_empty();
533   #endif
534     }
535
536     using BiasType = std::int16_t;
537     using WeightType = std::int16_t;
538     using PSQTWeightType = std::int32_t;
539
540     alignas(CacheLineSize) BiasType biases[HalfDimensions];
541     alignas(CacheLineSize) WeightType weights[HalfDimensions * InputDimensions];
542     alignas(CacheLineSize) PSQTWeightType psqtWeights[InputDimensions * PSQTBuckets];
543   };
544
545 }  // namespace Stockfish::Eval::NNUE
546
547 #endif // #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED