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