]> git.sesse.net Git - stockfish/blob - src/nnue/nnue_feature_transformer.h
Optimize the most common update accumalator cases w/o tiling
[stockfish] / src / nnue / nnue_feature_transformer.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 // 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 <algorithm>
25 #include <cassert>
26 #include <cstdint>
27 #include <cstring>
28 #include <iosfwd>
29 #include <utility>
30
31 #include "../position.h"
32 #include "../types.h"
33 #include "nnue_accumulator.h"
34 #include "nnue_architecture.h"
35 #include "nnue_common.h"
36
37 namespace Stockfish::Eval::NNUE {
38
39   using BiasType       = std::int16_t;
40   using WeightType     = std::int16_t;
41   using PSQTWeightType = std::int32_t;
42
43   // If vector instructions are enabled, we update and refresh the
44   // accumulator tile by tile such that each tile fits in the CPU's
45   // vector registers.
46   #define VECTOR
47
48   static_assert(PSQTBuckets % 8 == 0,
49     "Per feature PSQT values cannot be processed at granularity lower than 8 at a time.");
50
51   #ifdef USE_AVX512
52   using vec_t = __m512i;
53   using psqt_vec_t = __m256i;
54   #define vec_load(a) _mm512_load_si512(a)
55   #define vec_store(a,b) _mm512_store_si512(a,b)
56   #define vec_add_16(a,b) _mm512_add_epi16(a,b)
57   #define vec_sub_16(a,b) _mm512_sub_epi16(a,b)
58   #define vec_mul_16(a,b) _mm512_mullo_epi16(a,b)
59   #define vec_zero() _mm512_setzero_epi32()
60   #define vec_set_16(a) _mm512_set1_epi16(a)
61   #define vec_max_16(a,b) _mm512_max_epi16(a,b)
62   #define vec_min_16(a,b) _mm512_min_epi16(a,b)
63   inline vec_t vec_msb_pack_16(vec_t a, vec_t b){
64     vec_t compacted = _mm512_packs_epi16(_mm512_srli_epi16(a,7),_mm512_srli_epi16(b,7));
65     return _mm512_permutexvar_epi64(_mm512_setr_epi64(0, 2, 4, 6, 1, 3, 5, 7), compacted);
66   }
67   #define vec_load_psqt(a) _mm256_load_si256(a)
68   #define vec_store_psqt(a,b) _mm256_store_si256(a,b)
69   #define vec_add_psqt_32(a,b) _mm256_add_epi32(a,b)
70   #define vec_sub_psqt_32(a,b) _mm256_sub_epi32(a,b)
71   #define vec_zero_psqt() _mm256_setzero_si256()
72   #define NumRegistersSIMD 16
73   #define MaxChunkSize 64
74
75   #elif USE_AVX2
76   using vec_t = __m256i;
77   using psqt_vec_t = __m256i;
78   #define vec_load(a) _mm256_load_si256(a)
79   #define vec_store(a,b) _mm256_store_si256(a,b)
80   #define vec_add_16(a,b) _mm256_add_epi16(a,b)
81   #define vec_sub_16(a,b) _mm256_sub_epi16(a,b)
82   #define vec_mul_16(a,b) _mm256_mullo_epi16(a,b)
83   #define vec_zero() _mm256_setzero_si256()
84   #define vec_set_16(a) _mm256_set1_epi16(a)
85   #define vec_max_16(a,b) _mm256_max_epi16(a,b)
86   #define vec_min_16(a,b) _mm256_min_epi16(a,b)
87   inline vec_t vec_msb_pack_16(vec_t a, vec_t b){
88     vec_t compacted = _mm256_packs_epi16(_mm256_srli_epi16(a,7), _mm256_srli_epi16(b,7));
89     return _mm256_permute4x64_epi64(compacted, 0b11011000);
90   }
91   #define vec_load_psqt(a) _mm256_load_si256(a)
92   #define vec_store_psqt(a,b) _mm256_store_si256(a,b)
93   #define vec_add_psqt_32(a,b) _mm256_add_epi32(a,b)
94   #define vec_sub_psqt_32(a,b) _mm256_sub_epi32(a,b)
95   #define vec_zero_psqt() _mm256_setzero_si256()
96   #define NumRegistersSIMD 16
97   #define MaxChunkSize 32
98
99   #elif USE_SSE2
100   using vec_t = __m128i;
101   using psqt_vec_t = __m128i;
102   #define vec_load(a) (*(a))
103   #define vec_store(a,b) *(a)=(b)
104   #define vec_add_16(a,b) _mm_add_epi16(a,b)
105   #define vec_sub_16(a,b) _mm_sub_epi16(a,b)
106   #define vec_mul_16(a,b) _mm_mullo_epi16(a,b)
107   #define vec_zero() _mm_setzero_si128()
108   #define vec_set_16(a) _mm_set1_epi16(a)
109   #define vec_max_16(a,b) _mm_max_epi16(a,b)
110   #define vec_min_16(a,b) _mm_min_epi16(a,b)
111   #define vec_msb_pack_16(a,b) _mm_packs_epi16(_mm_srli_epi16(a,7),_mm_srli_epi16(b,7))
112   #define vec_load_psqt(a) (*(a))
113   #define vec_store_psqt(a,b) *(a)=(b)
114   #define vec_add_psqt_32(a,b) _mm_add_epi32(a,b)
115   #define vec_sub_psqt_32(a,b) _mm_sub_epi32(a,b)
116   #define vec_zero_psqt() _mm_setzero_si128()
117   #define NumRegistersSIMD (Is64Bit ? 16 : 8)
118   #define MaxChunkSize 16
119
120   #elif USE_NEON
121   using vec_t = int16x8_t;
122   using psqt_vec_t = int32x4_t;
123   #define vec_load(a) (*(a))
124   #define vec_store(a,b) *(a)=(b)
125   #define vec_add_16(a,b) vaddq_s16(a,b)
126   #define vec_sub_16(a,b) vsubq_s16(a,b)
127   #define vec_mul_16(a,b) vmulq_s16(a,b)
128   #define vec_zero() vec_t{0}
129   #define vec_set_16(a) vdupq_n_s16(a)
130   #define vec_max_16(a,b) vmaxq_s16(a,b)
131   #define vec_min_16(a,b) vminq_s16(a,b)
132   inline vec_t vec_msb_pack_16(vec_t a, vec_t b){
133     const int8x8_t shifta = vshrn_n_s16(a, 7);
134     const int8x8_t shiftb = vshrn_n_s16(b, 7);
135     const int8x16_t compacted = vcombine_s8(shifta,shiftb);
136     return *reinterpret_cast<const vec_t*> (&compacted);
137   }
138   #define vec_load_psqt(a) (*(a))
139   #define vec_store_psqt(a,b) *(a)=(b)
140   #define vec_add_psqt_32(a,b) vaddq_s32(a,b)
141   #define vec_sub_psqt_32(a,b) vsubq_s32(a,b)
142   #define vec_zero_psqt() psqt_vec_t{0}
143   #define NumRegistersSIMD 16
144   #define MaxChunkSize 16
145
146   #else
147   #undef VECTOR
148
149   #endif
150
151
152   #ifdef VECTOR
153
154       // Compute optimal SIMD register count for feature transformer accumulation.
155
156       // We use __m* types as template arguments, which causes GCC to emit warnings
157       // about losing some attribute information. This is irrelevant to us as we
158       // only take their size, so the following pragma are harmless.
159       #if defined(__GNUC__)
160       #pragma GCC diagnostic push
161       #pragma GCC diagnostic ignored "-Wignored-attributes"
162       #endif
163
164       template <typename SIMDRegisterType,
165                 typename LaneType,
166                 int      NumLanes,
167                 int      MaxRegisters>
168       static constexpr int BestRegisterCount()
169       {
170           #define RegisterSize  sizeof(SIMDRegisterType)
171           #define LaneSize      sizeof(LaneType)
172
173           static_assert(RegisterSize >= LaneSize);
174           static_assert(MaxRegisters <= NumRegistersSIMD);
175           static_assert(MaxRegisters > 0);
176           static_assert(NumRegistersSIMD > 0);
177           static_assert(RegisterSize % LaneSize == 0);
178           static_assert((NumLanes * LaneSize) % RegisterSize == 0);
179
180           const int ideal = (NumLanes * LaneSize) / RegisterSize;
181           if (ideal <= MaxRegisters)
182             return ideal;
183
184           // Look for the largest divisor of the ideal register count that is smaller than MaxRegisters
185           for (int divisor = MaxRegisters; divisor > 1; --divisor)
186             if (ideal % divisor == 0)
187               return divisor;
188
189           return 1;
190       }
191
192       static constexpr int NumRegs     = BestRegisterCount<vec_t, WeightType, TransformedFeatureDimensions, NumRegistersSIMD>();
193       static constexpr int NumPsqtRegs = BestRegisterCount<psqt_vec_t, PSQTWeightType, PSQTBuckets, NumRegistersSIMD>();
194       #if defined(__GNUC__)
195       #pragma GCC diagnostic pop
196       #endif
197   #endif
198
199
200
201   // Input feature converter
202   class FeatureTransformer {
203
204    private:
205     // Number of output dimensions for one side
206     static constexpr IndexType HalfDimensions = TransformedFeatureDimensions;
207
208     #ifdef VECTOR
209     static constexpr IndexType TileHeight = NumRegs * sizeof(vec_t) / 2;
210     static constexpr IndexType PsqtTileHeight = NumPsqtRegs * sizeof(psqt_vec_t) / 4;
211     static_assert(HalfDimensions % TileHeight == 0, "TileHeight must divide HalfDimensions");
212     static_assert(PSQTBuckets % PsqtTileHeight == 0, "PsqtTileHeight must divide PSQTBuckets");
213     #endif
214
215    public:
216     // Output type
217     using OutputType = TransformedFeatureType;
218
219     // Number of input/output dimensions
220     static constexpr IndexType InputDimensions = FeatureSet::Dimensions;
221     static constexpr IndexType OutputDimensions = HalfDimensions;
222
223     // Size of forward propagation buffer
224     static constexpr std::size_t BufferSize =
225         OutputDimensions * sizeof(OutputType);
226
227     // Hash value embedded in the evaluation file
228     static constexpr std::uint32_t get_hash_value() {
229       return FeatureSet::HashValue ^ (OutputDimensions * 2);
230     }
231
232     // Read network parameters
233     bool read_parameters(std::istream& stream) {
234
235       read_leb_128<BiasType      >(stream, biases     , HalfDimensions                  );
236       read_leb_128<WeightType    >(stream, weights    , HalfDimensions * InputDimensions);
237       read_leb_128<PSQTWeightType>(stream, psqtWeights, PSQTBuckets    * InputDimensions);
238
239       return !stream.fail();
240     }
241
242     // Write network parameters
243     bool write_parameters(std::ostream& stream) const {
244
245       write_leb_128<BiasType      >(stream, biases     , HalfDimensions                  );
246       write_leb_128<WeightType    >(stream, weights    , HalfDimensions * InputDimensions);
247       write_leb_128<PSQTWeightType>(stream, psqtWeights, PSQTBuckets    * InputDimensions);
248
249       return !stream.fail();
250     }
251
252     // Convert input features
253     std::int32_t transform(const Position& pos, OutputType* output, int bucket) const {
254       update_accumulator<WHITE>(pos);
255       update_accumulator<BLACK>(pos);
256
257       const Color perspectives[2] = {pos.side_to_move(), ~pos.side_to_move()};
258       const auto& accumulation = pos.state()->accumulator.accumulation;
259       const auto& psqtAccumulation = pos.state()->accumulator.psqtAccumulation;
260
261       const auto psqt = (
262             psqtAccumulation[perspectives[0]][bucket]
263           - psqtAccumulation[perspectives[1]][bucket]
264         ) / 2;
265
266
267       for (IndexType p = 0; p < 2; ++p)
268       {
269           const IndexType offset = (HalfDimensions / 2) * p;
270
271 #if defined(VECTOR)
272
273           constexpr IndexType OutputChunkSize = MaxChunkSize;
274           static_assert((HalfDimensions / 2) % OutputChunkSize == 0);
275           constexpr IndexType NumOutputChunks = HalfDimensions / 2 / OutputChunkSize;
276
277           vec_t Zero = vec_zero();
278           vec_t One = vec_set_16(127);
279
280           const vec_t* in0 = reinterpret_cast<const vec_t*>(&(accumulation[perspectives[p]][0]));
281           const vec_t* in1 = reinterpret_cast<const vec_t*>(&(accumulation[perspectives[p]][HalfDimensions / 2]));
282                 vec_t* out = reinterpret_cast<      vec_t*>(output + offset);
283
284           for (IndexType j = 0; j < NumOutputChunks; j += 1)
285           {
286               const vec_t sum0a = vec_max_16(vec_min_16(in0[j * 2 + 0], One), Zero);
287               const vec_t sum0b = vec_max_16(vec_min_16(in0[j * 2 + 1], One), Zero);
288               const vec_t sum1a = vec_max_16(vec_min_16(in1[j * 2 + 0], One), Zero);
289               const vec_t sum1b = vec_max_16(vec_min_16(in1[j * 2 + 1], One), Zero);
290
291               const vec_t pa = vec_mul_16(sum0a, sum1a);
292               const vec_t pb = vec_mul_16(sum0b, sum1b);
293
294               out[j] = vec_msb_pack_16(pa, pb);
295           }
296
297 #else
298
299           for (IndexType j = 0; j < HalfDimensions / 2; ++j) {
300               BiasType sum0 = accumulation[static_cast<int>(perspectives[p])][j + 0];
301               BiasType sum1 = accumulation[static_cast<int>(perspectives[p])][j + HalfDimensions / 2];
302               sum0 = std::clamp<BiasType>(sum0, 0, 127);
303               sum1 = std::clamp<BiasType>(sum1, 0, 127);
304               output[offset + j] = static_cast<OutputType>(unsigned(sum0 * sum1) / 128);
305           }
306
307 #endif
308       }
309
310       return psqt;
311     } // end of function transform()
312
313     void hint_common_access(const Position& pos) const {
314       hint_common_access_for_perspective<WHITE>(pos);
315       hint_common_access_for_perspective<BLACK>(pos);
316     }
317
318    private:
319     template<Color Perspective>
320     [[nodiscard]] std::pair<StateInfo*, StateInfo*> try_find_computed_accumulator(const Position& pos) const {
321       // Look for a usable accumulator of an earlier position. We keep track
322       // of the estimated gain in terms of features to be added/subtracted.
323       StateInfo *st = pos.state(), *next = nullptr;
324       int gain = FeatureSet::refresh_cost(pos);
325       while (st->previous && !st->accumulator.computed[Perspective])
326       {
327         // This governs when a full feature refresh is needed and how many
328         // updates are better than just one full refresh.
329         if (   FeatureSet::requires_refresh(st, Perspective)
330             || (gain -= FeatureSet::update_cost(st) + 1) < 0)
331           break;
332         next = st;
333         st = st->previous;
334       }
335       return { st, next };
336     }
337
338     // NOTE: The parameter states_to_update is an array of position states, ending with nullptr.
339     //       All states must be sequential, that is states_to_update[i] must either be reachable
340     //       by repeatedly applying ->previous from states_to_update[i+1] or states_to_update[i] == nullptr.
341     //       computed_st must be reachable by repeatedly applying ->previous on states_to_update[0], if not nullptr.
342     template<Color Perspective, size_t N>
343     void update_accumulator_incremental(const Position& pos, StateInfo* computed_st, StateInfo* states_to_update[N]) const {
344       static_assert(N > 0);
345       assert(states_to_update[N-1] == nullptr);
346
347   #ifdef VECTOR
348       // Gcc-10.2 unnecessarily spills AVX2 registers if this array
349       // is defined in the VECTOR code below, once in each branch
350       vec_t acc[NumRegs];
351       psqt_vec_t psqt[NumPsqtRegs];
352   #endif
353
354       if (states_to_update[0] == nullptr)
355         return;
356
357       // Update incrementally going back through states_to_update.
358
359       // Gather all features to be updated.
360       const Square ksq = pos.square<KING>(Perspective);
361
362       // The size must be enough to contain the largest possible update.
363       // That might depend on the feature set and generally relies on the
364       // feature set's update cost calculation to be correct and never
365       // allow updates with more added/removed features than MaxActiveDimensions.
366       FeatureSet::IndexList removed[N-1], added[N-1];
367
368       {
369         int i = N-2; // last potential state to update. Skip last element because it must be nullptr.
370         while (states_to_update[i] == nullptr)
371           --i;
372
373         StateInfo* st2 = states_to_update[i];
374
375         for (; i >= 0; --i)
376         {
377           states_to_update[i]->accumulator.computed[Perspective] = true;
378
379           const StateInfo* end_state = i == 0 ? computed_st : states_to_update[i - 1];
380
381           for (; st2 != end_state; st2 = st2->previous)
382             FeatureSet::append_changed_indices<Perspective>(
383               ksq, st2->dirtyPiece, removed[i], added[i]);
384         }
385       }
386
387       StateInfo* st = computed_st;
388
389       // Now update the accumulators listed in states_to_update[], where the last element is a sentinel.
390 #ifdef VECTOR
391
392       if (   states_to_update[1] == nullptr
393           && (removed[0].size() == 1 || removed[0].size() == 2)
394           && added[0].size() == 1)
395       {
396           assert(states_to_update[0]);
397
398           auto accTileIn = reinterpret_cast<const vec_t*>(
399               &st->accumulator.accumulation[Perspective][0]);
400           auto accTileOut = reinterpret_cast<vec_t*>(
401               &states_to_update[0]->accumulator.accumulation[Perspective][0]);
402
403           const IndexType offsetR0 = HalfDimensions * removed[0][0];
404           auto columnR0 = reinterpret_cast<const vec_t*>(&weights[offsetR0]);
405           const IndexType offsetA = HalfDimensions * added[0][0];
406           auto columnA = reinterpret_cast<const vec_t*>(&weights[offsetA]);
407
408           if (removed[0].size() == 1)
409           {
410               for (IndexType k = 0; k < HalfDimensions * sizeof(std::int16_t) / sizeof(vec_t); ++k)
411                   accTileOut[k] = vec_add_16(vec_sub_16(accTileIn[k], columnR0[k]), columnA[k]);
412           }
413           else
414           {
415               const IndexType offsetR1 = HalfDimensions * removed[0][1];
416               auto columnR1 = reinterpret_cast<const vec_t*>(&weights[offsetR1]);
417
418               for (IndexType k = 0; k < HalfDimensions * sizeof(std::int16_t) / sizeof(vec_t); ++k)
419                   accTileOut[k] = vec_sub_16(
420                                       vec_add_16(accTileIn[k], columnA[k]),
421                                       vec_add_16(columnR0[k], columnR1[k]));       
422           }
423
424           auto accTilePsqtIn = reinterpret_cast<const psqt_vec_t*>(
425               &st->accumulator.psqtAccumulation[Perspective][0]);
426           auto accTilePsqtOut = reinterpret_cast<psqt_vec_t*>(
427               &states_to_update[0]->accumulator.psqtAccumulation[Perspective][0]);
428
429           const IndexType offsetPsqtR0 = PSQTBuckets * removed[0][0];
430           auto columnPsqtR0 = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offsetPsqtR0]);
431           const IndexType offsetPsqtA = PSQTBuckets * added[0][0];
432           auto columnPsqtA = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offsetPsqtA]);
433
434           if (removed[0].size() == 1)
435           {
436               for (std::size_t k = 0; k < PSQTBuckets * sizeof(std::int32_t) / sizeof(psqt_vec_t); ++k)
437                   accTilePsqtOut[k] = vec_add_psqt_32(vec_sub_psqt_32(
438                       accTilePsqtIn[k], columnPsqtR0[k]), columnPsqtA[k]);
439           }
440           else
441           {
442               const IndexType offsetPsqtR1 = PSQTBuckets * removed[0][1];
443               auto columnPsqtR1 = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offsetPsqtR1]);
444
445               for (std::size_t k = 0; k < PSQTBuckets * sizeof(std::int32_t) / sizeof(psqt_vec_t); ++k)
446                   accTilePsqtOut[k] = vec_sub_psqt_32(
447                                           vec_add_psqt_32(accTilePsqtIn[k], columnPsqtA[k]),
448                                           vec_add_psqt_32(columnPsqtR0[k], columnPsqtR1[k]));
449           }
450       }
451       else
452       {
453           for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
454           {
455             // Load accumulator
456             auto accTileIn = reinterpret_cast<const vec_t*>(
457               &st->accumulator.accumulation[Perspective][j * TileHeight]);
458             for (IndexType k = 0; k < NumRegs; ++k)
459               acc[k] = vec_load(&accTileIn[k]);
460
461             for (IndexType i = 0; states_to_update[i]; ++i)
462             {
463               // Difference calculation for the deactivated features
464               for (const auto index : removed[i])
465               {
466                 const IndexType offset = HalfDimensions * index + j * TileHeight;
467                 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
468                 for (IndexType k = 0; k < NumRegs; ++k)
469                   acc[k] = vec_sub_16(acc[k], column[k]);
470               }
471
472               // Difference calculation for the activated features
473               for (const auto index : added[i])
474               {
475                 const IndexType offset = HalfDimensions * index + j * TileHeight;
476                 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
477                 for (IndexType k = 0; k < NumRegs; ++k)
478                   acc[k] = vec_add_16(acc[k], column[k]);
479               }
480
481               // Store accumulator
482               auto accTileOut = reinterpret_cast<vec_t*>(
483                 &states_to_update[i]->accumulator.accumulation[Perspective][j * TileHeight]);
484               for (IndexType k = 0; k < NumRegs; ++k)
485                 vec_store(&accTileOut[k], acc[k]);
486             }
487           }
488
489           for (IndexType j = 0; j < PSQTBuckets / PsqtTileHeight; ++j)
490           {
491             // Load accumulator
492             auto accTilePsqtIn = reinterpret_cast<const psqt_vec_t*>(
493               &st->accumulator.psqtAccumulation[Perspective][j * PsqtTileHeight]);
494             for (std::size_t k = 0; k < NumPsqtRegs; ++k)
495               psqt[k] = vec_load_psqt(&accTilePsqtIn[k]);
496
497             for (IndexType i = 0; states_to_update[i]; ++i)
498             {
499               // Difference calculation for the deactivated features
500               for (const auto index : removed[i])
501               {
502                 const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
503                 auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
504                 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
505                   psqt[k] = vec_sub_psqt_32(psqt[k], columnPsqt[k]);
506               }
507
508               // Difference calculation for the activated features
509               for (const auto index : added[i])
510               {
511                 const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
512                 auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
513                 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
514                   psqt[k] = vec_add_psqt_32(psqt[k], columnPsqt[k]);
515               }
516
517               // Store accumulator
518               auto accTilePsqtOut = reinterpret_cast<psqt_vec_t*>(
519                 &states_to_update[i]->accumulator.psqtAccumulation[Perspective][j * PsqtTileHeight]);
520               for (std::size_t k = 0; k < NumPsqtRegs; ++k)
521                 vec_store_psqt(&accTilePsqtOut[k], psqt[k]);
522             }
523           }
524       }
525 #else
526       for (IndexType i = 0; states_to_update[i]; ++i)
527       {
528         std::memcpy(states_to_update[i]->accumulator.accumulation[Perspective],
529             st->accumulator.accumulation[Perspective],
530             HalfDimensions * sizeof(BiasType));
531
532         for (std::size_t k = 0; k < PSQTBuckets; ++k)
533           states_to_update[i]->accumulator.psqtAccumulation[Perspective][k] = st->accumulator.psqtAccumulation[Perspective][k];
534
535         st = states_to_update[i];
536
537         // Difference calculation for the deactivated features
538         for (const auto index : removed[i])
539         {
540           const IndexType offset = HalfDimensions * index;
541
542           for (IndexType j = 0; j < HalfDimensions; ++j)
543             st->accumulator.accumulation[Perspective][j] -= weights[offset + j];
544
545           for (std::size_t k = 0; k < PSQTBuckets; ++k)
546             st->accumulator.psqtAccumulation[Perspective][k] -= psqtWeights[index * PSQTBuckets + k];
547         }
548
549         // Difference calculation for the activated features
550         for (const auto index : added[i])
551         {
552           const IndexType offset = HalfDimensions * index;
553
554           for (IndexType j = 0; j < HalfDimensions; ++j)
555             st->accumulator.accumulation[Perspective][j] += weights[offset + j];
556
557           for (std::size_t k = 0; k < PSQTBuckets; ++k)
558             st->accumulator.psqtAccumulation[Perspective][k] += psqtWeights[index * PSQTBuckets + k];
559         }
560       }
561 #endif
562     }
563
564     template<Color Perspective>
565     void update_accumulator_refresh(const Position& pos) const {
566   #ifdef VECTOR
567       // Gcc-10.2 unnecessarily spills AVX2 registers if this array
568       // is defined in the VECTOR code below, once in each branch
569       vec_t acc[NumRegs];
570       psqt_vec_t psqt[NumPsqtRegs];
571   #endif
572
573       // Refresh the accumulator
574       // Could be extracted to a separate function because it's done in 2 places,
575       // but it's unclear if compilers would correctly handle register allocation.
576       auto& accumulator = pos.state()->accumulator;
577       accumulator.computed[Perspective] = true;
578       FeatureSet::IndexList active;
579       FeatureSet::append_active_indices<Perspective>(pos, active);
580
581 #ifdef VECTOR
582       for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
583       {
584         auto biasesTile = reinterpret_cast<const vec_t*>(
585             &biases[j * TileHeight]);
586         for (IndexType k = 0; k < NumRegs; ++k)
587           acc[k] = biasesTile[k];
588
589         for (const auto index : active)
590         {
591           const IndexType offset = HalfDimensions * index + j * TileHeight;
592           auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
593
594           for (unsigned k = 0; k < NumRegs; ++k)
595             acc[k] = vec_add_16(acc[k], column[k]);
596         }
597
598         auto accTile = reinterpret_cast<vec_t*>(
599             &accumulator.accumulation[Perspective][j * TileHeight]);
600         for (unsigned k = 0; k < NumRegs; k++)
601           vec_store(&accTile[k], acc[k]);
602       }
603
604       for (IndexType j = 0; j < PSQTBuckets / PsqtTileHeight; ++j)
605       {
606         for (std::size_t k = 0; k < NumPsqtRegs; ++k)
607           psqt[k] = vec_zero_psqt();
608
609         for (const auto index : active)
610         {
611           const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
612           auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
613
614           for (std::size_t k = 0; k < NumPsqtRegs; ++k)
615             psqt[k] = vec_add_psqt_32(psqt[k], columnPsqt[k]);
616         }
617
618         auto accTilePsqt = reinterpret_cast<psqt_vec_t*>(
619           &accumulator.psqtAccumulation[Perspective][j * PsqtTileHeight]);
620         for (std::size_t k = 0; k < NumPsqtRegs; ++k)
621           vec_store_psqt(&accTilePsqt[k], psqt[k]);
622       }
623
624 #else
625       std::memcpy(accumulator.accumulation[Perspective], biases,
626           HalfDimensions * sizeof(BiasType));
627
628       for (std::size_t k = 0; k < PSQTBuckets; ++k)
629         accumulator.psqtAccumulation[Perspective][k] = 0;
630
631       for (const auto index : active)
632       {
633         const IndexType offset = HalfDimensions * index;
634
635         for (IndexType j = 0; j < HalfDimensions; ++j)
636           accumulator.accumulation[Perspective][j] += weights[offset + j];
637
638         for (std::size_t k = 0; k < PSQTBuckets; ++k)
639           accumulator.psqtAccumulation[Perspective][k] += psqtWeights[index * PSQTBuckets + k];
640       }
641 #endif
642     }
643
644     template<Color Perspective>
645     void hint_common_access_for_perspective(const Position& pos) const {
646
647       // Works like update_accumulator, but performs less work.
648       // Updates ONLY the accumulator for pos.
649
650       // Look for a usable accumulator of an earlier position. We keep track
651       // of the estimated gain in terms of features to be added/subtracted.
652       // Fast early exit.
653       if (pos.state()->accumulator.computed[Perspective])
654         return;
655
656       auto [oldest_st, _] = try_find_computed_accumulator<Perspective>(pos);
657
658       if (oldest_st->accumulator.computed[Perspective])
659       {
660         // Only update current position accumulator to minimize work.
661         StateInfo* states_to_update[2] = { pos.state(), nullptr };
662         update_accumulator_incremental<Perspective, 2>(pos, oldest_st, states_to_update);
663       }
664       else
665       {
666         update_accumulator_refresh<Perspective>(pos);
667       }
668     }
669
670     template<Color Perspective>
671     void update_accumulator(const Position& pos) const {
672
673       auto [oldest_st, next] = try_find_computed_accumulator<Perspective>(pos);
674
675       if (oldest_st->accumulator.computed[Perspective])
676       {
677         if (next == nullptr)
678           return;
679
680         // Now update the accumulators listed in states_to_update[], where the last element is a sentinel.
681         // Currently we update 2 accumulators.
682         //     1. for the current position
683         //     2. the next accumulator after the computed one
684         // The heuristic may change in the future.
685         StateInfo *states_to_update[3] =
686           { next, next == pos.state() ? nullptr : pos.state(), nullptr };
687
688         update_accumulator_incremental<Perspective, 3>(pos, oldest_st, states_to_update);
689       }
690       else
691       {
692         update_accumulator_refresh<Perspective>(pos);
693       }
694     }
695
696     alignas(CacheLineSize) BiasType biases[HalfDimensions];
697     alignas(CacheLineSize) WeightType weights[HalfDimensions * InputDimensions];
698     alignas(CacheLineSize) PSQTWeightType psqtWeights[InputDimensions * PSQTBuckets];
699   };
700
701 }  // namespace Stockfish::Eval::NNUE
702
703 #endif // #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED