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