2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2021 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_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
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
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)
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
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
121 // Compute optimal SIMD register count for feature transformer accumulation.
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 #pragma GCC diagnostic push
127 #pragma GCC diagnostic ignored "-Wignored-attributes"
129 template <typename SIMDRegisterType,
133 static constexpr int BestRegisterCount()
135 #define RegisterSize sizeof(SIMDRegisterType)
136 #define LaneSize sizeof(LaneType)
138 static_assert(RegisterSize >= LaneSize);
139 static_assert(MaxRegisters <= NumRegistersSIMD);
140 static_assert(MaxRegisters > 0);
141 static_assert(NumRegistersSIMD > 0);
142 static_assert(RegisterSize % LaneSize == 0);
143 static_assert((NumLanes * LaneSize) % RegisterSize == 0);
145 const int ideal = (NumLanes * LaneSize) / RegisterSize;
146 if (ideal <= MaxRegisters)
149 // Look for the largest divisor of the ideal register count that is smaller than MaxRegisters
150 for (int divisor = MaxRegisters; divisor > 1; --divisor)
151 if (ideal % divisor == 0)
157 static constexpr int NumRegs = BestRegisterCount<vec_t, WeightType, TransformedFeatureDimensions, NumRegistersSIMD>();
158 static constexpr int NumPsqtRegs = BestRegisterCount<psqt_vec_t, PSQTWeightType, PSQTBuckets, NumRegistersSIMD>();
160 #pragma GCC diagnostic pop
166 // Input feature converter
167 class FeatureTransformer {
170 // Number of output dimensions for one side
171 static constexpr IndexType HalfDimensions = TransformedFeatureDimensions;
174 static constexpr IndexType TileHeight = NumRegs * sizeof(vec_t) / 2;
175 static constexpr IndexType PsqtTileHeight = NumPsqtRegs * sizeof(psqt_vec_t) / 4;
176 static_assert(HalfDimensions % TileHeight == 0, "TileHeight must divide HalfDimensions");
177 static_assert(PSQTBuckets % PsqtTileHeight == 0, "PsqtTileHeight must divide PSQTBuckets");
182 using OutputType = TransformedFeatureType;
184 // Number of input/output dimensions
185 static constexpr IndexType InputDimensions = FeatureSet::Dimensions;
186 static constexpr IndexType OutputDimensions = HalfDimensions * 2;
188 // Size of forward propagation buffer
189 static constexpr std::size_t BufferSize =
190 OutputDimensions * sizeof(OutputType);
192 // Hash value embedded in the evaluation file
193 static constexpr std::uint32_t get_hash_value() {
194 return FeatureSet::HashValue ^ OutputDimensions;
197 // Read network parameters
198 bool read_parameters(std::istream& stream) {
200 read_little_endian<BiasType >(stream, biases , HalfDimensions );
201 read_little_endian<WeightType >(stream, weights , HalfDimensions * InputDimensions);
202 read_little_endian<PSQTWeightType>(stream, psqtWeights, PSQTBuckets * InputDimensions);
204 return !stream.fail();
207 // Write network parameters
208 bool write_parameters(std::ostream& stream) const {
210 write_little_endian<BiasType >(stream, biases , HalfDimensions );
211 write_little_endian<WeightType >(stream, weights , HalfDimensions * InputDimensions);
212 write_little_endian<PSQTWeightType>(stream, psqtWeights, PSQTBuckets * InputDimensions);
214 return !stream.fail();
217 // Convert input features
218 std::int32_t transform(const Position& pos, OutputType* output, int bucket) const {
219 update_accumulator(pos, WHITE);
220 update_accumulator(pos, BLACK);
222 const Color perspectives[2] = {pos.side_to_move(), ~pos.side_to_move()};
223 const auto& accumulation = pos.state()->accumulator.accumulation;
224 const auto& psqtAccumulation = pos.state()->accumulator.psqtAccumulation;
227 psqtAccumulation[perspectives[0]][bucket]
228 - psqtAccumulation[perspectives[1]][bucket]
232 #if defined(USE_AVX512)
234 constexpr IndexType NumChunks = HalfDimensions / (SimdWidth * 2);
235 static_assert(HalfDimensions % (SimdWidth * 2) == 0);
236 const __m512i Control = _mm512_setr_epi64(0, 2, 4, 6, 1, 3, 5, 7);
237 const __m512i Zero = _mm512_setzero_si512();
239 for (IndexType p = 0; p < 2; ++p)
241 const IndexType offset = HalfDimensions * p;
242 auto out = reinterpret_cast<__m512i*>(&output[offset]);
243 for (IndexType j = 0; j < NumChunks; ++j)
245 __m512i sum0 = _mm512_load_si512(&reinterpret_cast<const __m512i*>
246 (accumulation[perspectives[p]])[j * 2 + 0]);
247 __m512i sum1 = _mm512_load_si512(&reinterpret_cast<const __m512i*>
248 (accumulation[perspectives[p]])[j * 2 + 1]);
250 _mm512_store_si512(&out[j], _mm512_permutexvar_epi64(Control,
251 _mm512_max_epi8(_mm512_packs_epi16(sum0, sum1), Zero)));
256 #elif defined(USE_AVX2)
258 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
259 constexpr int Control = 0b11011000;
260 const __m256i Zero = _mm256_setzero_si256();
262 for (IndexType p = 0; p < 2; ++p)
264 const IndexType offset = HalfDimensions * p;
265 auto out = reinterpret_cast<__m256i*>(&output[offset]);
266 for (IndexType j = 0; j < NumChunks; ++j)
268 __m256i sum0 = _mm256_load_si256(&reinterpret_cast<const __m256i*>
269 (accumulation[perspectives[p]])[j * 2 + 0]);
270 __m256i sum1 = _mm256_load_si256(&reinterpret_cast<const __m256i*>
271 (accumulation[perspectives[p]])[j * 2 + 1]);
273 _mm256_store_si256(&out[j], _mm256_permute4x64_epi64(
274 _mm256_max_epi8(_mm256_packs_epi16(sum0, sum1), Zero), Control));
279 #elif defined(USE_SSE2)
282 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
283 const __m128i Zero = _mm_setzero_si128();
285 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
286 const __m128i k0x80s = _mm_set1_epi8(-128);
289 for (IndexType p = 0; p < 2; ++p)
291 const IndexType offset = HalfDimensions * p;
292 auto out = reinterpret_cast<__m128i*>(&output[offset]);
293 for (IndexType j = 0; j < NumChunks; ++j)
295 __m128i sum0 = _mm_load_si128(&reinterpret_cast<const __m128i*>
296 (accumulation[perspectives[p]])[j * 2 + 0]);
297 __m128i sum1 = _mm_load_si128(&reinterpret_cast<const __m128i*>
298 (accumulation[perspectives[p]])[j * 2 + 1]);
299 const __m128i packedbytes = _mm_packs_epi16(sum0, sum1);
302 _mm_store_si128(&out[j], _mm_max_epi8(packedbytes, Zero));
304 _mm_store_si128(&out[j], _mm_subs_epi8(_mm_adds_epi8(packedbytes, k0x80s), k0x80s));
310 #elif defined(USE_MMX)
312 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
313 const __m64 k0x80s = _mm_set1_pi8(-128);
315 for (IndexType p = 0; p < 2; ++p)
317 const IndexType offset = HalfDimensions * p;
318 auto out = reinterpret_cast<__m64*>(&output[offset]);
319 for (IndexType j = 0; j < NumChunks; ++j)
321 __m64 sum0 = *(&reinterpret_cast<const __m64*>(accumulation[perspectives[p]])[j * 2 + 0]);
322 __m64 sum1 = *(&reinterpret_cast<const __m64*>(accumulation[perspectives[p]])[j * 2 + 1]);
323 const __m64 packedbytes = _mm_packs_pi16(sum0, sum1);
324 out[j] = _mm_subs_pi8(_mm_adds_pi8(packedbytes, k0x80s), k0x80s);
330 #elif defined(USE_NEON)
332 constexpr IndexType NumChunks = HalfDimensions / (SimdWidth / 2);
333 const int8x8_t Zero = {0};
335 for (IndexType p = 0; p < 2; ++p)
337 const IndexType offset = HalfDimensions * p;
338 const auto out = reinterpret_cast<int8x8_t*>(&output[offset]);
339 for (IndexType j = 0; j < NumChunks; ++j)
341 int16x8_t sum = reinterpret_cast<const int16x8_t*>(accumulation[perspectives[p]])[j];
342 out[j] = vmax_s8(vqmovn_s16(sum), Zero);
349 for (IndexType p = 0; p < 2; ++p)
351 const IndexType offset = HalfDimensions * p;
352 for (IndexType j = 0; j < HalfDimensions; ++j)
354 BiasType sum = accumulation[perspectives[p]][j];
355 output[offset + j] = static_cast<OutputType>(std::max<int>(0, std::min<int>(127, sum)));
362 } // end of function transform()
367 void update_accumulator(const Position& pos, const Color perspective) const {
369 // The size must be enough to contain the largest possible update.
370 // That might depend on the feature set and generally relies on the
371 // feature set's update cost calculation to be correct and never
372 // allow updates with more added/removed features than MaxActiveDimensions.
375 // Gcc-10.2 unnecessarily spills AVX2 registers if this array
376 // is defined in the VECTOR code below, once in each branch
378 psqt_vec_t psqt[NumPsqtRegs];
381 // Look for a usable accumulator of an earlier position. We keep track
382 // of the estimated gain in terms of features to be added/subtracted.
383 StateInfo *st = pos.state(), *next = nullptr;
384 int gain = FeatureSet::refresh_cost(pos);
385 while (st->previous && !st->accumulator.computed[perspective])
387 // This governs when a full feature refresh is needed and how many
388 // updates are better than just one full refresh.
389 if ( FeatureSet::requires_refresh(st, perspective)
390 || (gain -= FeatureSet::update_cost(st) + 1) < 0)
396 if (st->accumulator.computed[perspective])
401 // Update incrementally in two steps. First, we update the "next"
402 // accumulator. Then, we update the current accumulator (pos.state()).
404 // Gather all features to be updated.
405 const Square ksq = pos.square<KING>(perspective);
406 FeatureSet::IndexList removed[2], added[2];
407 FeatureSet::append_changed_indices(
408 ksq, next->dirtyPiece, perspective, removed[0], added[0]);
409 for (StateInfo *st2 = pos.state(); st2 != next; st2 = st2->previous)
410 FeatureSet::append_changed_indices(
411 ksq, st2->dirtyPiece, perspective, removed[1], added[1]);
413 // Mark the accumulators as computed.
414 next->accumulator.computed[perspective] = true;
415 pos.state()->accumulator.computed[perspective] = true;
417 // Now update the accumulators listed in states_to_update[], where the last element is a sentinel.
418 StateInfo *states_to_update[3] =
419 { next, next == pos.state() ? nullptr : pos.state(), nullptr };
421 for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
424 auto accTile = reinterpret_cast<vec_t*>(
425 &st->accumulator.accumulation[perspective][j * TileHeight]);
426 for (IndexType k = 0; k < NumRegs; ++k)
427 acc[k] = vec_load(&accTile[k]);
429 for (IndexType i = 0; states_to_update[i]; ++i)
431 // Difference calculation for the deactivated features
432 for (const auto index : removed[i])
434 const IndexType offset = HalfDimensions * index + j * TileHeight;
435 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
436 for (IndexType k = 0; k < NumRegs; ++k)
437 acc[k] = vec_sub_16(acc[k], column[k]);
440 // Difference calculation for the activated features
441 for (const auto index : added[i])
443 const IndexType offset = HalfDimensions * index + j * TileHeight;
444 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
445 for (IndexType k = 0; k < NumRegs; ++k)
446 acc[k] = vec_add_16(acc[k], column[k]);
450 accTile = reinterpret_cast<vec_t*>(
451 &states_to_update[i]->accumulator.accumulation[perspective][j * TileHeight]);
452 for (IndexType k = 0; k < NumRegs; ++k)
453 vec_store(&accTile[k], acc[k]);
457 for (IndexType j = 0; j < PSQTBuckets / PsqtTileHeight; ++j)
460 auto accTilePsqt = reinterpret_cast<psqt_vec_t*>(
461 &st->accumulator.psqtAccumulation[perspective][j * PsqtTileHeight]);
462 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
463 psqt[k] = vec_load_psqt(&accTilePsqt[k]);
465 for (IndexType i = 0; states_to_update[i]; ++i)
467 // Difference calculation for the deactivated features
468 for (const auto index : removed[i])
470 const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
471 auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
472 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
473 psqt[k] = vec_sub_psqt_32(psqt[k], columnPsqt[k]);
476 // Difference calculation for the activated features
477 for (const auto index : added[i])
479 const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
480 auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
481 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
482 psqt[k] = vec_add_psqt_32(psqt[k], columnPsqt[k]);
486 accTilePsqt = reinterpret_cast<psqt_vec_t*>(
487 &states_to_update[i]->accumulator.psqtAccumulation[perspective][j * PsqtTileHeight]);
488 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
489 vec_store_psqt(&accTilePsqt[k], psqt[k]);
494 for (IndexType i = 0; states_to_update[i]; ++i)
496 std::memcpy(states_to_update[i]->accumulator.accumulation[perspective],
497 st->accumulator.accumulation[perspective],
498 HalfDimensions * sizeof(BiasType));
500 for (std::size_t k = 0; k < PSQTBuckets; ++k)
501 states_to_update[i]->accumulator.psqtAccumulation[perspective][k] = st->accumulator.psqtAccumulation[perspective][k];
503 st = states_to_update[i];
505 // Difference calculation for the deactivated features
506 for (const auto index : removed[i])
508 const IndexType offset = HalfDimensions * index;
510 for (IndexType j = 0; j < HalfDimensions; ++j)
511 st->accumulator.accumulation[perspective][j] -= weights[offset + j];
513 for (std::size_t k = 0; k < PSQTBuckets; ++k)
514 st->accumulator.psqtAccumulation[perspective][k] -= psqtWeights[index * PSQTBuckets + k];
517 // Difference calculation for the activated features
518 for (const auto index : added[i])
520 const IndexType offset = HalfDimensions * index;
522 for (IndexType j = 0; j < HalfDimensions; ++j)
523 st->accumulator.accumulation[perspective][j] += weights[offset + j];
525 for (std::size_t k = 0; k < PSQTBuckets; ++k)
526 st->accumulator.psqtAccumulation[perspective][k] += psqtWeights[index * PSQTBuckets + k];
533 // Refresh the accumulator
534 auto& accumulator = pos.state()->accumulator;
535 accumulator.computed[perspective] = true;
536 FeatureSet::IndexList active;
537 FeatureSet::append_active_indices(pos, perspective, active);
540 for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
542 auto biasesTile = reinterpret_cast<const vec_t*>(
543 &biases[j * TileHeight]);
544 for (IndexType k = 0; k < NumRegs; ++k)
545 acc[k] = biasesTile[k];
547 for (const auto index : active)
549 const IndexType offset = HalfDimensions * index + j * TileHeight;
550 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
552 for (unsigned k = 0; k < NumRegs; ++k)
553 acc[k] = vec_add_16(acc[k], column[k]);
556 auto accTile = reinterpret_cast<vec_t*>(
557 &accumulator.accumulation[perspective][j * TileHeight]);
558 for (unsigned k = 0; k < NumRegs; k++)
559 vec_store(&accTile[k], acc[k]);
562 for (IndexType j = 0; j < PSQTBuckets / PsqtTileHeight; ++j)
564 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
565 psqt[k] = vec_zero_psqt();
567 for (const auto index : active)
569 const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
570 auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
572 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
573 psqt[k] = vec_add_psqt_32(psqt[k], columnPsqt[k]);
576 auto accTilePsqt = reinterpret_cast<psqt_vec_t*>(
577 &accumulator.psqtAccumulation[perspective][j * PsqtTileHeight]);
578 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
579 vec_store_psqt(&accTilePsqt[k], psqt[k]);
583 std::memcpy(accumulator.accumulation[perspective], biases,
584 HalfDimensions * sizeof(BiasType));
586 for (std::size_t k = 0; k < PSQTBuckets; ++k)
587 accumulator.psqtAccumulation[perspective][k] = 0;
589 for (const auto index : active)
591 const IndexType offset = HalfDimensions * index;
593 for (IndexType j = 0; j < HalfDimensions; ++j)
594 accumulator.accumulation[perspective][j] += weights[offset + j];
596 for (std::size_t k = 0; k < PSQTBuckets; ++k)
597 accumulator.psqtAccumulation[perspective][k] += psqtWeights[index * PSQTBuckets + k];
607 alignas(CacheLineSize) BiasType biases[HalfDimensions];
608 alignas(CacheLineSize) WeightType weights[HalfDimensions * InputDimensions];
609 alignas(CacheLineSize) PSQTWeightType psqtWeights[InputDimensions * PSQTBuckets];
612 } // namespace Stockfish::Eval::NNUE
614 #endif // #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED