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