2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2022 The Stockfish developers (see AUTHORS file)
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.
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.
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/>.
19 // A class that converts the input features of the NNUE evaluation function
21 #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED
22 #define NNUE_FEATURE_TRANSFORMER_H_INCLUDED
24 #include "nnue_common.h"
25 #include "nnue_architecture.h"
27 #include <cstring> // std::memset()
29 namespace Stockfish::Eval::NNUE {
31 using BiasType = std::int16_t;
32 using WeightType = std::int16_t;
33 using PSQTWeightType = std::int32_t;
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
40 static_assert(PSQTBuckets % 8 == 0,
41 "Per feature PSQT values cannot be processed at granularity lower than 8 at a time.");
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_mul_16(a,b) _mm512_mullo_epi16(a,b)
51 #define vec_zero() _mm512_setzero_epi32()
52 #define vec_set_16(a) _mm512_set1_epi16(a)
53 #define vec_max_16(a,b) _mm512_max_epi16(a,b)
54 #define vec_min_16(a,b) _mm512_min_epi16(a,b)
55 inline vec_t vec_msb_pack_16(vec_t a, vec_t b){
56 vec_t compacted = _mm512_packs_epi16(_mm512_srli_epi16(a,7),_mm512_srli_epi16(b,7));
57 return _mm512_permutexvar_epi64(_mm512_setr_epi64(0, 2, 4, 6, 1, 3, 5, 7), compacted);
59 #define vec_load_psqt(a) _mm256_load_si256(a)
60 #define vec_store_psqt(a,b) _mm256_store_si256(a,b)
61 #define vec_add_psqt_32(a,b) _mm256_add_epi32(a,b)
62 #define vec_sub_psqt_32(a,b) _mm256_sub_epi32(a,b)
63 #define vec_zero_psqt() _mm256_setzero_si256()
64 #define NumRegistersSIMD 32
65 #define MaxChunkSize 64
68 typedef __m256i vec_t;
69 typedef __m256i psqt_vec_t;
70 #define vec_load(a) _mm256_load_si256(a)
71 #define vec_store(a,b) _mm256_store_si256(a,b)
72 #define vec_add_16(a,b) _mm256_add_epi16(a,b)
73 #define vec_sub_16(a,b) _mm256_sub_epi16(a,b)
74 #define vec_mul_16(a,b) _mm256_mullo_epi16(a,b)
75 #define vec_zero() _mm256_setzero_si256()
76 #define vec_set_16(a) _mm256_set1_epi16(a)
77 #define vec_max_16(a,b) _mm256_max_epi16(a,b)
78 #define vec_min_16(a,b) _mm256_min_epi16(a,b)
79 inline vec_t vec_msb_pack_16(vec_t a, vec_t b){
80 vec_t compacted = _mm256_packs_epi16(_mm256_srli_epi16(a,7), _mm256_srli_epi16(b,7));
81 return _mm256_permute4x64_epi64(compacted, 0b11011000);
83 #define vec_load_psqt(a) _mm256_load_si256(a)
84 #define vec_store_psqt(a,b) _mm256_store_si256(a,b)
85 #define vec_add_psqt_32(a,b) _mm256_add_epi32(a,b)
86 #define vec_sub_psqt_32(a,b) _mm256_sub_epi32(a,b)
87 #define vec_zero_psqt() _mm256_setzero_si256()
88 #define NumRegistersSIMD 16
89 #define MaxChunkSize 32
92 typedef __m128i vec_t;
93 typedef __m128i psqt_vec_t;
94 #define vec_load(a) (*(a))
95 #define vec_store(a,b) *(a)=(b)
96 #define vec_add_16(a,b) _mm_add_epi16(a,b)
97 #define vec_sub_16(a,b) _mm_sub_epi16(a,b)
98 #define vec_mul_16(a,b) _mm_mullo_epi16(a,b)
99 #define vec_zero() _mm_setzero_si128()
100 #define vec_set_16(a) _mm_set1_epi16(a)
101 #define vec_max_16(a,b) _mm_max_epi16(a,b)
102 #define vec_min_16(a,b) _mm_min_epi16(a,b)
103 #define vec_msb_pack_16(a,b) _mm_packs_epi16(_mm_srli_epi16(a,7),_mm_srli_epi16(b,7))
104 #define vec_load_psqt(a) (*(a))
105 #define vec_store_psqt(a,b) *(a)=(b)
106 #define vec_add_psqt_32(a,b) _mm_add_epi32(a,b)
107 #define vec_sub_psqt_32(a,b) _mm_sub_epi32(a,b)
108 #define vec_zero_psqt() _mm_setzero_si128()
109 #define NumRegistersSIMD (Is64Bit ? 16 : 8)
110 #define MaxChunkSize 16
114 typedef __m64 psqt_vec_t;
115 #define vec_load(a) (*(a))
116 #define vec_store(a,b) *(a)=(b)
117 #define vec_add_16(a,b) _mm_add_pi16(a,b)
118 #define vec_sub_16(a,b) _mm_sub_pi16(a,b)
119 #define vec_mul_16(a,b) _mm_mullo_pi16(a,b)
120 #define vec_zero() _mm_setzero_si64()
121 #define vec_set_16(a) _mm_set1_pi16(a)
122 inline vec_t vec_max_16(vec_t a,vec_t b){
123 vec_t comparison = _mm_cmpgt_pi16(a,b);
124 return _mm_or_si64(_mm_and_si64(comparison, a), _mm_andnot_si64(comparison, b));
126 inline vec_t vec_min_16(vec_t a,vec_t b){
127 vec_t comparison = _mm_cmpgt_pi16(a,b);
128 return _mm_or_si64(_mm_and_si64(comparison, b), _mm_andnot_si64(comparison, a));
130 #define vec_msb_pack_16(a,b) _mm_packs_pi16(_mm_srli_pi16(a,7),_mm_srli_pi16(b,7))
131 #define vec_load_psqt(a) (*(a))
132 #define vec_store_psqt(a,b) *(a)=(b)
133 #define vec_add_psqt_32(a,b) _mm_add_pi32(a,b)
134 #define vec_sub_psqt_32(a,b) _mm_sub_pi32(a,b)
135 #define vec_zero_psqt() _mm_setzero_si64()
136 #define vec_cleanup() _mm_empty()
137 #define NumRegistersSIMD 8
138 #define MaxChunkSize 8
141 typedef int16x8_t vec_t;
142 typedef int32x4_t psqt_vec_t;
143 #define vec_load(a) (*(a))
144 #define vec_store(a,b) *(a)=(b)
145 #define vec_add_16(a,b) vaddq_s16(a,b)
146 #define vec_sub_16(a,b) vsubq_s16(a,b)
147 #define vec_mul_16(a,b) vmulq_s16(a,b)
148 #define vec_zero() vec_t{0}
149 #define vec_set_16(a) vdupq_n_s16(a)
150 #define vec_max_16(a,b) vmaxq_s16(a,b)
151 #define vec_min_16(a,b) vminq_s16(a,b)
152 inline vec_t vec_msb_pack_16(vec_t a, vec_t b){
153 const int8x8_t shifta = vshrn_n_s16(a, 7);
154 const int8x8_t shiftb = vshrn_n_s16(b, 7);
155 const int8x16_t compacted = vcombine_s8(shifta,shiftb);
156 return *reinterpret_cast<const vec_t*> (&compacted);
158 #define vec_load_psqt(a) (*(a))
159 #define vec_store_psqt(a,b) *(a)=(b)
160 #define vec_add_psqt_32(a,b) vaddq_s32(a,b)
161 #define vec_sub_psqt_32(a,b) vsubq_s32(a,b)
162 #define vec_zero_psqt() psqt_vec_t{0}
163 #define NumRegistersSIMD 16
164 #define MaxChunkSize 16
174 // Compute optimal SIMD register count for feature transformer accumulation.
176 // We use __m* types as template arguments, which causes GCC to emit warnings
177 // about losing some attribute information. This is irrelevant to us as we
178 // only take their size, so the following pragma are harmless.
179 #if defined(__GNUC__)
180 #pragma GCC diagnostic push
181 #pragma GCC diagnostic ignored "-Wignored-attributes"
184 template <typename SIMDRegisterType,
188 static constexpr int BestRegisterCount()
190 #define RegisterSize sizeof(SIMDRegisterType)
191 #define LaneSize sizeof(LaneType)
193 static_assert(RegisterSize >= LaneSize);
194 static_assert(MaxRegisters <= NumRegistersSIMD);
195 static_assert(MaxRegisters > 0);
196 static_assert(NumRegistersSIMD > 0);
197 static_assert(RegisterSize % LaneSize == 0);
198 static_assert((NumLanes * LaneSize) % RegisterSize == 0);
200 const int ideal = (NumLanes * LaneSize) / RegisterSize;
201 if (ideal <= MaxRegisters)
204 // Look for the largest divisor of the ideal register count that is smaller than MaxRegisters
205 for (int divisor = MaxRegisters; divisor > 1; --divisor)
206 if (ideal % divisor == 0)
212 static constexpr int NumRegs = BestRegisterCount<vec_t, WeightType, TransformedFeatureDimensions, NumRegistersSIMD>();
213 static constexpr int NumPsqtRegs = BestRegisterCount<psqt_vec_t, PSQTWeightType, PSQTBuckets, NumRegistersSIMD>();
214 #if defined(__GNUC__)
215 #pragma GCC diagnostic pop
221 // Input feature converter
222 class FeatureTransformer {
225 // Number of output dimensions for one side
226 static constexpr IndexType HalfDimensions = TransformedFeatureDimensions;
229 static constexpr IndexType TileHeight = NumRegs * sizeof(vec_t) / 2;
230 static constexpr IndexType PsqtTileHeight = NumPsqtRegs * sizeof(psqt_vec_t) / 4;
231 static_assert(HalfDimensions % TileHeight == 0, "TileHeight must divide HalfDimensions");
232 static_assert(PSQTBuckets % PsqtTileHeight == 0, "PsqtTileHeight must divide PSQTBuckets");
237 using OutputType = TransformedFeatureType;
239 // Number of input/output dimensions
240 static constexpr IndexType InputDimensions = FeatureSet::Dimensions;
241 static constexpr IndexType OutputDimensions = HalfDimensions;
243 // Size of forward propagation buffer
244 static constexpr std::size_t BufferSize =
245 OutputDimensions * sizeof(OutputType);
247 // Hash value embedded in the evaluation file
248 static constexpr std::uint32_t get_hash_value() {
249 return FeatureSet::HashValue ^ (OutputDimensions * 2);
252 // Read network parameters
253 bool read_parameters(std::istream& stream) {
255 read_little_endian<BiasType >(stream, biases , HalfDimensions );
256 read_little_endian<WeightType >(stream, weights , HalfDimensions * InputDimensions);
257 read_little_endian<PSQTWeightType>(stream, psqtWeights, PSQTBuckets * InputDimensions);
259 return !stream.fail();
262 // Write network parameters
263 bool write_parameters(std::ostream& stream) const {
265 write_little_endian<BiasType >(stream, biases , HalfDimensions );
266 write_little_endian<WeightType >(stream, weights , HalfDimensions * InputDimensions);
267 write_little_endian<PSQTWeightType>(stream, psqtWeights, PSQTBuckets * InputDimensions);
269 return !stream.fail();
272 // Convert input features
273 std::int32_t transform(const Position& pos, OutputType* output, int bucket) const {
274 update_accumulator(pos, WHITE);
275 update_accumulator(pos, BLACK);
277 const Color perspectives[2] = {pos.side_to_move(), ~pos.side_to_move()};
278 const auto& accumulation = pos.state()->accumulator.accumulation;
279 const auto& psqtAccumulation = pos.state()->accumulator.psqtAccumulation;
282 psqtAccumulation[perspectives[0]][bucket]
283 - psqtAccumulation[perspectives[1]][bucket]
287 for (IndexType p = 0; p < 2; ++p)
289 const IndexType offset = (HalfDimensions / 2) * p;
293 constexpr IndexType OutputChunkSize = MaxChunkSize;
294 static_assert((HalfDimensions / 2) % OutputChunkSize == 0);
295 constexpr IndexType NumOutputChunks = HalfDimensions / 2 / OutputChunkSize;
297 vec_t Zero = vec_zero();
298 vec_t One = vec_set_16(127);
300 const vec_t* in0 = reinterpret_cast<const vec_t*>(&(accumulation[perspectives[p]][0]));
301 const vec_t* in1 = reinterpret_cast<const vec_t*>(&(accumulation[perspectives[p]][HalfDimensions / 2]));
302 vec_t* out = reinterpret_cast< vec_t*>(output + offset);
304 for (IndexType j = 0; j < NumOutputChunks; j += 1)
306 const vec_t sum0a = vec_max_16(vec_min_16(in0[j * 2 + 0], One), Zero);
307 const vec_t sum0b = vec_max_16(vec_min_16(in0[j * 2 + 1], One), Zero);
308 const vec_t sum1a = vec_max_16(vec_min_16(in1[j * 2 + 0], One), Zero);
309 const vec_t sum1b = vec_max_16(vec_min_16(in1[j * 2 + 1], One), Zero);
311 const vec_t pa = vec_mul_16(sum0a, sum1a);
312 const vec_t pb = vec_mul_16(sum0b, sum1b);
314 out[j] = vec_msb_pack_16(pa, pb);
319 for (IndexType j = 0; j < HalfDimensions / 2; ++j) {
320 BiasType sum0 = accumulation[static_cast<int>(perspectives[p])][j + 0];
321 BiasType sum1 = accumulation[static_cast<int>(perspectives[p])][j + HalfDimensions / 2];
322 sum0 = std::max<int>(0, std::min<int>(127, sum0));
323 sum1 = std::max<int>(0, std::min<int>(127, sum1));
324 output[offset + j] = static_cast<OutputType>(sum0 * sum1 / 128);
330 #if defined(vec_cleanup)
336 } // end of function transform()
341 void update_accumulator(const Position& pos, const Color perspective) const {
343 // The size must be enough to contain the largest possible update.
344 // That might depend on the feature set and generally relies on the
345 // feature set's update cost calculation to be correct and never
346 // allow updates with more added/removed features than MaxActiveDimensions.
349 // Gcc-10.2 unnecessarily spills AVX2 registers if this array
350 // is defined in the VECTOR code below, once in each branch
352 psqt_vec_t psqt[NumPsqtRegs];
355 // Look for a usable accumulator of an earlier position. We keep track
356 // of the estimated gain in terms of features to be added/subtracted.
357 StateInfo *st = pos.state(), *next = nullptr;
358 int gain = FeatureSet::refresh_cost(pos);
359 while (st->previous && !st->accumulator.computed[perspective])
361 // This governs when a full feature refresh is needed and how many
362 // updates are better than just one full refresh.
363 if ( FeatureSet::requires_refresh(st, perspective)
364 || (gain -= FeatureSet::update_cost(st) + 1) < 0)
370 if (st->accumulator.computed[perspective])
375 // Update incrementally in two steps. First, we update the "next"
376 // accumulator. Then, we update the current accumulator (pos.state()).
378 // Gather all features to be updated.
379 const Square ksq = pos.square<KING>(perspective);
380 FeatureSet::IndexList removed[2], added[2];
381 FeatureSet::append_changed_indices(
382 ksq, next->dirtyPiece, perspective, removed[0], added[0]);
383 for (StateInfo *st2 = pos.state(); st2 != next; st2 = st2->previous)
384 FeatureSet::append_changed_indices(
385 ksq, st2->dirtyPiece, perspective, removed[1], added[1]);
387 // Mark the accumulators as computed.
388 next->accumulator.computed[perspective] = true;
389 pos.state()->accumulator.computed[perspective] = true;
391 // Now update the accumulators listed in states_to_update[], where the last element is a sentinel.
392 StateInfo *states_to_update[3] =
393 { next, next == pos.state() ? nullptr : pos.state(), nullptr };
395 for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
398 auto accTile = reinterpret_cast<vec_t*>(
399 &st->accumulator.accumulation[perspective][j * TileHeight]);
400 for (IndexType k = 0; k < NumRegs; ++k)
401 acc[k] = vec_load(&accTile[k]);
403 for (IndexType i = 0; states_to_update[i]; ++i)
405 // Difference calculation for the deactivated features
406 for (const auto index : removed[i])
408 const IndexType offset = HalfDimensions * index + j * TileHeight;
409 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
410 for (IndexType k = 0; k < NumRegs; ++k)
411 acc[k] = vec_sub_16(acc[k], column[k]);
414 // Difference calculation for the activated features
415 for (const auto index : added[i])
417 const IndexType offset = HalfDimensions * index + j * TileHeight;
418 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
419 for (IndexType k = 0; k < NumRegs; ++k)
420 acc[k] = vec_add_16(acc[k], column[k]);
424 accTile = reinterpret_cast<vec_t*>(
425 &states_to_update[i]->accumulator.accumulation[perspective][j * TileHeight]);
426 for (IndexType k = 0; k < NumRegs; ++k)
427 vec_store(&accTile[k], acc[k]);
431 for (IndexType j = 0; j < PSQTBuckets / PsqtTileHeight; ++j)
434 auto accTilePsqt = reinterpret_cast<psqt_vec_t*>(
435 &st->accumulator.psqtAccumulation[perspective][j * PsqtTileHeight]);
436 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
437 psqt[k] = vec_load_psqt(&accTilePsqt[k]);
439 for (IndexType i = 0; states_to_update[i]; ++i)
441 // Difference calculation for the deactivated features
442 for (const auto index : removed[i])
444 const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
445 auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
446 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
447 psqt[k] = vec_sub_psqt_32(psqt[k], columnPsqt[k]);
450 // Difference calculation for the activated features
451 for (const auto index : added[i])
453 const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
454 auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
455 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
456 psqt[k] = vec_add_psqt_32(psqt[k], columnPsqt[k]);
460 accTilePsqt = reinterpret_cast<psqt_vec_t*>(
461 &states_to_update[i]->accumulator.psqtAccumulation[perspective][j * PsqtTileHeight]);
462 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
463 vec_store_psqt(&accTilePsqt[k], psqt[k]);
468 for (IndexType i = 0; states_to_update[i]; ++i)
470 std::memcpy(states_to_update[i]->accumulator.accumulation[perspective],
471 st->accumulator.accumulation[perspective],
472 HalfDimensions * sizeof(BiasType));
474 for (std::size_t k = 0; k < PSQTBuckets; ++k)
475 states_to_update[i]->accumulator.psqtAccumulation[perspective][k] = st->accumulator.psqtAccumulation[perspective][k];
477 st = states_to_update[i];
479 // Difference calculation for the deactivated features
480 for (const auto index : removed[i])
482 const IndexType offset = HalfDimensions * index;
484 for (IndexType j = 0; j < HalfDimensions; ++j)
485 st->accumulator.accumulation[perspective][j] -= weights[offset + j];
487 for (std::size_t k = 0; k < PSQTBuckets; ++k)
488 st->accumulator.psqtAccumulation[perspective][k] -= psqtWeights[index * PSQTBuckets + k];
491 // Difference calculation for the activated features
492 for (const auto index : added[i])
494 const IndexType offset = HalfDimensions * index;
496 for (IndexType j = 0; j < HalfDimensions; ++j)
497 st->accumulator.accumulation[perspective][j] += weights[offset + j];
499 for (std::size_t k = 0; k < PSQTBuckets; ++k)
500 st->accumulator.psqtAccumulation[perspective][k] += psqtWeights[index * PSQTBuckets + k];
507 // Refresh the accumulator
508 auto& accumulator = pos.state()->accumulator;
509 accumulator.computed[perspective] = true;
510 FeatureSet::IndexList active;
511 FeatureSet::append_active_indices(pos, perspective, active);
514 for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
516 auto biasesTile = reinterpret_cast<const vec_t*>(
517 &biases[j * TileHeight]);
518 for (IndexType k = 0; k < NumRegs; ++k)
519 acc[k] = biasesTile[k];
521 for (const auto index : active)
523 const IndexType offset = HalfDimensions * index + j * TileHeight;
524 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
526 for (unsigned k = 0; k < NumRegs; ++k)
527 acc[k] = vec_add_16(acc[k], column[k]);
530 auto accTile = reinterpret_cast<vec_t*>(
531 &accumulator.accumulation[perspective][j * TileHeight]);
532 for (unsigned k = 0; k < NumRegs; k++)
533 vec_store(&accTile[k], acc[k]);
536 for (IndexType j = 0; j < PSQTBuckets / PsqtTileHeight; ++j)
538 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
539 psqt[k] = vec_zero_psqt();
541 for (const auto index : active)
543 const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
544 auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
546 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
547 psqt[k] = vec_add_psqt_32(psqt[k], columnPsqt[k]);
550 auto accTilePsqt = reinterpret_cast<psqt_vec_t*>(
551 &accumulator.psqtAccumulation[perspective][j * PsqtTileHeight]);
552 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
553 vec_store_psqt(&accTilePsqt[k], psqt[k]);
557 std::memcpy(accumulator.accumulation[perspective], biases,
558 HalfDimensions * sizeof(BiasType));
560 for (std::size_t k = 0; k < PSQTBuckets; ++k)
561 accumulator.psqtAccumulation[perspective][k] = 0;
563 for (const auto index : active)
565 const IndexType offset = HalfDimensions * index;
567 for (IndexType j = 0; j < HalfDimensions; ++j)
568 accumulator.accumulation[perspective][j] += weights[offset + j];
570 for (std::size_t k = 0; k < PSQTBuckets; ++k)
571 accumulator.psqtAccumulation[perspective][k] += psqtWeights[index * PSQTBuckets + k];
581 alignas(CacheLineSize) BiasType biases[HalfDimensions];
582 alignas(CacheLineSize) WeightType weights[HalfDimensions * InputDimensions];
583 alignas(CacheLineSize) PSQTWeightType psqtWeights[InputDimensions * PSQTBuckets];
586 } // namespace Stockfish::Eval::NNUE
588 #endif // #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED