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"
29 #include <cstring> // std::memset()
31 namespace Stockfish::Eval::NNUE {
33 // If vector instructions are enabled, we update and refresh the
34 // accumulator tile by tile such that each tile fits in the CPU's
38 static_assert(PSQTBuckets == 8, "Assumed by the current choice of constants.");
41 typedef __m512i vec_t;
42 typedef __m256i psqt_vec_t;
43 #define vec_load(a) _mm512_load_si512(a)
44 #define vec_store(a,b) _mm512_store_si512(a,b)
45 #define vec_add_16(a,b) _mm512_add_epi16(a,b)
46 #define vec_sub_16(a,b) _mm512_sub_epi16(a,b)
47 #define vec_load_psqt(a) _mm256_load_si256(a)
48 #define vec_store_psqt(a,b) _mm256_store_si256(a,b)
49 #define vec_add_psqt_32(a,b) _mm256_add_epi32(a,b)
50 #define vec_sub_psqt_32(a,b) _mm256_sub_epi32(a,b)
51 #define vec_zero_psqt() _mm256_setzero_si256()
52 static constexpr IndexType NumRegs = 8; // only 8 are needed
53 static constexpr IndexType NumPsqtRegs = 1;
56 typedef __m256i vec_t;
57 typedef __m256i psqt_vec_t;
58 #define vec_load(a) _mm256_load_si256(a)
59 #define vec_store(a,b) _mm256_store_si256(a,b)
60 #define vec_add_16(a,b) _mm256_add_epi16(a,b)
61 #define vec_sub_16(a,b) _mm256_sub_epi16(a,b)
62 #define vec_load_psqt(a) _mm256_load_si256(a)
63 #define vec_store_psqt(a,b) _mm256_store_si256(a,b)
64 #define vec_add_psqt_32(a,b) _mm256_add_epi32(a,b)
65 #define vec_sub_psqt_32(a,b) _mm256_sub_epi32(a,b)
66 #define vec_zero_psqt() _mm256_setzero_si256()
67 static constexpr IndexType NumRegs = 16;
68 static constexpr IndexType NumPsqtRegs = 1;
71 typedef __m128i vec_t;
72 typedef __m128i psqt_vec_t;
73 #define vec_load(a) (*(a))
74 #define vec_store(a,b) *(a)=(b)
75 #define vec_add_16(a,b) _mm_add_epi16(a,b)
76 #define vec_sub_16(a,b) _mm_sub_epi16(a,b)
77 #define vec_load_psqt(a) (*(a))
78 #define vec_store_psqt(a,b) *(a)=(b)
79 #define vec_add_psqt_32(a,b) _mm_add_epi32(a,b)
80 #define vec_sub_psqt_32(a,b) _mm_sub_epi32(a,b)
81 #define vec_zero_psqt() _mm_setzero_si128()
82 static constexpr IndexType NumRegs = Is64Bit ? 16 : 8;
83 static constexpr IndexType NumPsqtRegs = 2;
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 static constexpr IndexType NumRegs = 8;
98 static constexpr IndexType NumPsqtRegs = 4;
101 typedef int16x8_t vec_t;
102 typedef int32x4_t psqt_vec_t;
103 #define vec_load(a) (*(a))
104 #define vec_store(a,b) *(a)=(b)
105 #define vec_add_16(a,b) vaddq_s16(a,b)
106 #define vec_sub_16(a,b) vsubq_s16(a,b)
107 #define vec_load_psqt(a) (*(a))
108 #define vec_store_psqt(a,b) *(a)=(b)
109 #define vec_add_psqt_32(a,b) vaddq_s32(a,b)
110 #define vec_sub_psqt_32(a,b) vsubq_s32(a,b)
111 #define vec_zero_psqt() psqt_vec_t{0}
112 static constexpr IndexType NumRegs = 16;
113 static constexpr IndexType NumPsqtRegs = 2;
120 // Input feature converter
121 class FeatureTransformer {
124 // Number of output dimensions for one side
125 static constexpr IndexType HalfDimensions = TransformedFeatureDimensions;
127 static constexpr int LazyThreshold = 1400;
130 static constexpr IndexType TileHeight = NumRegs * sizeof(vec_t) / 2;
131 static constexpr IndexType PsqtTileHeight = NumPsqtRegs * sizeof(psqt_vec_t) / 4;
132 static_assert(HalfDimensions % TileHeight == 0, "TileHeight must divide HalfDimensions");
133 static_assert(PSQTBuckets % PsqtTileHeight == 0, "PsqtTileHeight must divide PSQTBuckets");
138 using OutputType = TransformedFeatureType;
140 // Number of input/output dimensions
141 static constexpr IndexType InputDimensions = FeatureSet::Dimensions;
142 static constexpr IndexType OutputDimensions = HalfDimensions * 2;
144 // Size of forward propagation buffer
145 static constexpr std::size_t BufferSize =
146 OutputDimensions * sizeof(OutputType);
148 // Hash value embedded in the evaluation file
149 static constexpr std::uint32_t get_hash_value() {
150 return FeatureSet::HashValue ^ OutputDimensions;
153 // Read network parameters
154 bool read_parameters(std::istream& stream) {
155 for (std::size_t i = 0; i < HalfDimensions; ++i)
156 biases[i] = read_little_endian<BiasType>(stream);
157 for (std::size_t i = 0; i < HalfDimensions * InputDimensions; ++i)
158 weights[i] = read_little_endian<WeightType>(stream);
159 for (std::size_t i = 0; i < PSQTBuckets * InputDimensions; ++i)
160 psqtWeights[i] = read_little_endian<PSQTWeightType>(stream);
161 return !stream.fail();
164 // Write network parameters
165 bool write_parameters(std::ostream& stream) const {
166 for (std::size_t i = 0; i < HalfDimensions; ++i)
167 write_little_endian<BiasType>(stream, biases[i]);
168 for (std::size_t i = 0; i < HalfDimensions * InputDimensions; ++i)
169 write_little_endian<WeightType>(stream, weights[i]);
170 return !stream.fail();
173 // Convert input features
174 std::pair<std::int32_t, bool> transform(const Position& pos, OutputType* output, int bucket) const {
175 update_accumulator(pos, WHITE);
176 update_accumulator(pos, BLACK);
178 const Color perspectives[2] = {pos.side_to_move(), ~pos.side_to_move()};
179 const auto& accumulation = pos.state()->accumulator.accumulation;
180 const auto& psqtAccumulation = pos.state()->accumulator.psqtAccumulation;
183 psqtAccumulation[static_cast<int>(perspectives[0])][bucket]
184 - psqtAccumulation[static_cast<int>(perspectives[1])][bucket]
187 if (abs(psqt) > LazyThreshold * OutputScale)
188 return { psqt, true };
190 #if defined(USE_AVX512)
191 constexpr IndexType NumChunks = HalfDimensions / (SimdWidth * 2);
192 static_assert(HalfDimensions % (SimdWidth * 2) == 0);
193 const __m512i Control = _mm512_setr_epi64(0, 2, 4, 6, 1, 3, 5, 7);
194 const __m512i Zero = _mm512_setzero_si512();
196 #elif defined(USE_AVX2)
197 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
198 constexpr int Control = 0b11011000;
199 const __m256i Zero = _mm256_setzero_si256();
201 #elif defined(USE_SSE2)
202 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
205 const __m128i Zero = _mm_setzero_si128();
207 const __m128i k0x80s = _mm_set1_epi8(-128);
210 #elif defined(USE_MMX)
211 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
212 const __m64 k0x80s = _mm_set1_pi8(-128);
214 #elif defined(USE_NEON)
215 constexpr IndexType NumChunks = HalfDimensions / (SimdWidth / 2);
216 const int8x8_t Zero = {0};
219 for (IndexType p = 0; p < 2; ++p) {
220 const IndexType offset = HalfDimensions * p;
222 #if defined(USE_AVX512)
223 auto out = reinterpret_cast<__m512i*>(&output[offset]);
224 for (IndexType j = 0; j < NumChunks; ++j) {
225 __m512i sum0 = _mm512_load_si512(
226 &reinterpret_cast<const __m512i*>(accumulation[perspectives[p]])[j * 2 + 0]);
227 __m512i sum1 = _mm512_load_si512(
228 &reinterpret_cast<const __m512i*>(accumulation[perspectives[p]])[j * 2 + 1]);
229 _mm512_store_si512(&out[j], _mm512_permutexvar_epi64(Control,
230 _mm512_max_epi8(_mm512_packs_epi16(sum0, sum1), Zero)));
233 #elif defined(USE_AVX2)
234 auto out = reinterpret_cast<__m256i*>(&output[offset]);
235 for (IndexType j = 0; j < NumChunks; ++j) {
236 __m256i sum0 = _mm256_load_si256(
237 &reinterpret_cast<const __m256i*>(accumulation[perspectives[p]])[j * 2 + 0]);
238 __m256i sum1 = _mm256_load_si256(
239 &reinterpret_cast<const __m256i*>(accumulation[perspectives[p]])[j * 2 + 1]);
240 _mm256_store_si256(&out[j], _mm256_permute4x64_epi64(_mm256_max_epi8(
241 _mm256_packs_epi16(sum0, sum1), Zero), Control));
244 #elif defined(USE_SSE2)
245 auto out = reinterpret_cast<__m128i*>(&output[offset]);
246 for (IndexType j = 0; j < NumChunks; ++j) {
247 __m128i sum0 = _mm_load_si128(&reinterpret_cast<const __m128i*>(
248 accumulation[perspectives[p]])[j * 2 + 0]);
249 __m128i sum1 = _mm_load_si128(&reinterpret_cast<const __m128i*>(
250 accumulation[perspectives[p]])[j * 2 + 1]);
251 const __m128i packedbytes = _mm_packs_epi16(sum0, sum1);
253 _mm_store_si128(&out[j],
256 _mm_max_epi8(packedbytes, Zero)
258 _mm_subs_epi8(_mm_adds_epi8(packedbytes, k0x80s), k0x80s)
264 #elif defined(USE_MMX)
265 auto out = reinterpret_cast<__m64*>(&output[offset]);
266 for (IndexType j = 0; j < NumChunks; ++j) {
267 __m64 sum0 = *(&reinterpret_cast<const __m64*>(
268 accumulation[perspectives[p]])[j * 2 + 0]);
269 __m64 sum1 = *(&reinterpret_cast<const __m64*>(
270 accumulation[perspectives[p]])[j * 2 + 1]);
271 const __m64 packedbytes = _mm_packs_pi16(sum0, sum1);
272 out[j] = _mm_subs_pi8(_mm_adds_pi8(packedbytes, k0x80s), k0x80s);
275 #elif defined(USE_NEON)
276 const auto out = reinterpret_cast<int8x8_t*>(&output[offset]);
277 for (IndexType j = 0; j < NumChunks; ++j) {
278 int16x8_t sum = reinterpret_cast<const int16x8_t*>(
279 accumulation[perspectives[p]])[j];
280 out[j] = vmax_s8(vqmovn_s16(sum), Zero);
284 for (IndexType j = 0; j < HalfDimensions; ++j) {
285 BiasType sum = accumulation[static_cast<int>(perspectives[p])][j];
286 output[offset + j] = static_cast<OutputType>(
287 std::max<int>(0, std::min<int>(127, sum)));
296 return { psqt, false };
300 void update_accumulator(const Position& pos, const Color perspective) const {
302 // The size must be enough to contain the largest possible update.
303 // That might depend on the feature set and generally relies on the
304 // feature set's update cost calculation to be correct and never
305 // allow updates with more added/removed features than MaxActiveDimensions.
306 using IndexList = ValueList<IndexType, FeatureSet::MaxActiveDimensions>;
309 // Gcc-10.2 unnecessarily spills AVX2 registers if this array
310 // is defined in the VECTOR code below, once in each branch
312 psqt_vec_t psqt[NumPsqtRegs];
315 // Look for a usable accumulator of an earlier position. We keep track
316 // of the estimated gain in terms of features to be added/subtracted.
317 StateInfo *st = pos.state(), *next = nullptr;
318 int gain = FeatureSet::refresh_cost(pos);
319 while (st->accumulator.state[perspective] == EMPTY)
321 // This governs when a full feature refresh is needed and how many
322 // updates are better than just one full refresh.
323 if ( FeatureSet::requires_refresh(st, perspective)
324 || (gain -= FeatureSet::update_cost(st) + 1) < 0)
330 if (st->accumulator.state[perspective] == COMPUTED)
335 // Update incrementally in two steps. First, we update the "next"
336 // accumulator. Then, we update the current accumulator (pos.state()).
338 // Gather all features to be updated.
339 const Square ksq = pos.square<KING>(perspective);
340 IndexList removed[2], added[2];
341 FeatureSet::append_changed_indices(
342 ksq, next, perspective, removed[0], added[0]);
343 for (StateInfo *st2 = pos.state(); st2 != next; st2 = st2->previous)
344 FeatureSet::append_changed_indices(
345 ksq, st2, perspective, removed[1], added[1]);
347 // Mark the accumulators as computed.
348 next->accumulator.state[perspective] = COMPUTED;
349 pos.state()->accumulator.state[perspective] = COMPUTED;
351 // Now update the accumulators listed in states_to_update[], where the last element is a sentinel.
352 StateInfo *states_to_update[3] =
353 { next, next == pos.state() ? nullptr : pos.state(), nullptr };
355 for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
358 auto accTile = reinterpret_cast<vec_t*>(
359 &st->accumulator.accumulation[perspective][j * TileHeight]);
360 for (IndexType k = 0; k < NumRegs; ++k)
361 acc[k] = vec_load(&accTile[k]);
363 for (IndexType i = 0; states_to_update[i]; ++i)
365 // Difference calculation for the deactivated features
366 for (const auto index : removed[i])
368 const IndexType offset = HalfDimensions * index + j * TileHeight;
369 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
370 for (IndexType k = 0; k < NumRegs; ++k)
371 acc[k] = vec_sub_16(acc[k], column[k]);
374 // Difference calculation for the activated features
375 for (const auto index : added[i])
377 const IndexType offset = HalfDimensions * index + j * TileHeight;
378 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
379 for (IndexType k = 0; k < NumRegs; ++k)
380 acc[k] = vec_add_16(acc[k], column[k]);
384 accTile = reinterpret_cast<vec_t*>(
385 &states_to_update[i]->accumulator.accumulation[perspective][j * TileHeight]);
386 for (IndexType k = 0; k < NumRegs; ++k)
387 vec_store(&accTile[k], acc[k]);
391 for (IndexType j = 0; j < PSQTBuckets / PsqtTileHeight; ++j)
394 auto accTilePsqt = reinterpret_cast<psqt_vec_t*>(
395 &st->accumulator.psqtAccumulation[perspective][j * PsqtTileHeight]);
396 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
397 psqt[k] = vec_load_psqt(&accTilePsqt[k]);
399 for (IndexType i = 0; states_to_update[i]; ++i)
401 // Difference calculation for the deactivated features
402 for (const auto index : removed[i])
404 const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
405 auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
406 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
407 psqt[k] = vec_sub_psqt_32(psqt[k], columnPsqt[k]);
410 // Difference calculation for the activated features
411 for (const auto index : added[i])
413 const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
414 auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
415 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
416 psqt[k] = vec_add_psqt_32(psqt[k], columnPsqt[k]);
420 accTilePsqt = reinterpret_cast<psqt_vec_t*>(
421 &states_to_update[i]->accumulator.psqtAccumulation[perspective][j * PsqtTileHeight]);
422 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
423 vec_store_psqt(&accTilePsqt[k], psqt[k]);
428 for (IndexType i = 0; states_to_update[i]; ++i)
430 std::memcpy(states_to_update[i]->accumulator.accumulation[perspective],
431 st->accumulator.accumulation[perspective],
432 HalfDimensions * sizeof(BiasType));
434 for (std::size_t k = 0; k < PSQTBuckets; ++k)
435 states_to_update[i]->accumulator.psqtAccumulation[perspective][k] = st->accumulator.psqtAccumulation[perspective][k];
437 st = states_to_update[i];
439 // Difference calculation for the deactivated features
440 for (const auto index : removed[i])
442 const IndexType offset = HalfDimensions * index;
444 for (IndexType j = 0; j < HalfDimensions; ++j)
445 st->accumulator.accumulation[perspective][j] -= weights[offset + j];
447 for (std::size_t k = 0; k < PSQTBuckets; ++k)
448 st->accumulator.psqtAccumulation[perspective][k] -= psqtWeights[index * PSQTBuckets + k];
451 // Difference calculation for the activated features
452 for (const auto index : added[i])
454 const IndexType offset = HalfDimensions * index;
456 for (IndexType j = 0; j < HalfDimensions; ++j)
457 st->accumulator.accumulation[perspective][j] += weights[offset + j];
459 for (std::size_t k = 0; k < PSQTBuckets; ++k)
460 st->accumulator.psqtAccumulation[perspective][k] += psqtWeights[index * PSQTBuckets + k];
467 // Refresh the accumulator
468 auto& accumulator = pos.state()->accumulator;
469 accumulator.state[perspective] = COMPUTED;
471 FeatureSet::append_active_indices(pos, perspective, active);
474 for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
476 auto biasesTile = reinterpret_cast<const vec_t*>(
477 &biases[j * TileHeight]);
478 for (IndexType k = 0; k < NumRegs; ++k)
479 acc[k] = biasesTile[k];
481 for (const auto index : active)
483 const IndexType offset = HalfDimensions * index + j * TileHeight;
484 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
486 for (unsigned k = 0; k < NumRegs; ++k)
487 acc[k] = vec_add_16(acc[k], column[k]);
490 auto accTile = reinterpret_cast<vec_t*>(
491 &accumulator.accumulation[perspective][j * TileHeight]);
492 for (unsigned k = 0; k < NumRegs; k++)
493 vec_store(&accTile[k], acc[k]);
496 for (IndexType j = 0; j < PSQTBuckets / PsqtTileHeight; ++j)
498 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
499 psqt[k] = vec_zero_psqt();
501 for (const auto index : active)
503 const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
504 auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
506 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
507 psqt[k] = vec_add_psqt_32(psqt[k], columnPsqt[k]);
510 auto accTilePsqt = reinterpret_cast<psqt_vec_t*>(
511 &accumulator.psqtAccumulation[perspective][j * PsqtTileHeight]);
512 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
513 vec_store_psqt(&accTilePsqt[k], psqt[k]);
517 std::memcpy(accumulator.accumulation[perspective], biases,
518 HalfDimensions * sizeof(BiasType));
520 for (std::size_t k = 0; k < PSQTBuckets; ++k)
521 accumulator.psqtAccumulation[perspective][k] = 0;
523 for (const auto index : active)
525 const IndexType offset = HalfDimensions * index;
527 for (IndexType j = 0; j < HalfDimensions; ++j)
528 accumulator.accumulation[perspective][j] += weights[offset + j];
530 for (std::size_t k = 0; k < PSQTBuckets; ++k)
531 accumulator.psqtAccumulation[perspective][k] += psqtWeights[index * PSQTBuckets + k];
541 using BiasType = std::int16_t;
542 using WeightType = std::int16_t;
543 using PSQTWeightType = std::int32_t;
545 alignas(CacheLineSize) BiasType biases[HalfDimensions];
546 alignas(CacheLineSize) WeightType weights[HalfDimensions * InputDimensions];
547 alignas(CacheLineSize) PSQTWeightType psqtWeights[InputDimensions * PSQTBuckets];
550 } // namespace Stockfish::Eval::NNUE
552 #endif // #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED