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 // If vector instructions are enabled, we update and refresh the
32 // accumulator tile by tile such that each tile fits in the CPU's
36 static_assert(PSQTBuckets == 8, "Assumed by the current choice of constants.");
39 typedef __m512i vec_t;
40 typedef __m256i psqt_vec_t;
41 #define vec_load(a) _mm512_load_si512(a)
42 #define vec_store(a,b) _mm512_store_si512(a,b)
43 #define vec_add_16(a,b) _mm512_add_epi16(a,b)
44 #define vec_sub_16(a,b) _mm512_sub_epi16(a,b)
45 #define vec_load_psqt(a) _mm256_load_si256(a)
46 #define vec_store_psqt(a,b) _mm256_store_si256(a,b)
47 #define vec_add_psqt_32(a,b) _mm256_add_epi32(a,b)
48 #define vec_sub_psqt_32(a,b) _mm256_sub_epi32(a,b)
49 #define vec_zero_psqt() _mm256_setzero_si256()
50 static constexpr IndexType NumRegs = 8; // only 8 are needed
51 static constexpr IndexType NumPsqtRegs = 1;
54 typedef __m256i vec_t;
55 typedef __m256i psqt_vec_t;
56 #define vec_load(a) _mm256_load_si256(a)
57 #define vec_store(a,b) _mm256_store_si256(a,b)
58 #define vec_add_16(a,b) _mm256_add_epi16(a,b)
59 #define vec_sub_16(a,b) _mm256_sub_epi16(a,b)
60 #define vec_load_psqt(a) _mm256_load_si256(a)
61 #define vec_store_psqt(a,b) _mm256_store_si256(a,b)
62 #define vec_add_psqt_32(a,b) _mm256_add_epi32(a,b)
63 #define vec_sub_psqt_32(a,b) _mm256_sub_epi32(a,b)
64 #define vec_zero_psqt() _mm256_setzero_si256()
65 static constexpr IndexType NumRegs = 16;
66 static constexpr IndexType NumPsqtRegs = 1;
69 typedef __m128i vec_t;
70 typedef __m128i psqt_vec_t;
71 #define vec_load(a) (*(a))
72 #define vec_store(a,b) *(a)=(b)
73 #define vec_add_16(a,b) _mm_add_epi16(a,b)
74 #define vec_sub_16(a,b) _mm_sub_epi16(a,b)
75 #define vec_load_psqt(a) (*(a))
76 #define vec_store_psqt(a,b) *(a)=(b)
77 #define vec_add_psqt_32(a,b) _mm_add_epi32(a,b)
78 #define vec_sub_psqt_32(a,b) _mm_sub_epi32(a,b)
79 #define vec_zero_psqt() _mm_setzero_si128()
80 static constexpr IndexType NumRegs = Is64Bit ? 16 : 8;
81 static constexpr IndexType NumPsqtRegs = 2;
85 typedef __m64 psqt_vec_t;
86 #define vec_load(a) (*(a))
87 #define vec_store(a,b) *(a)=(b)
88 #define vec_add_16(a,b) _mm_add_pi16(a,b)
89 #define vec_sub_16(a,b) _mm_sub_pi16(a,b)
90 #define vec_load_psqt(a) (*(a))
91 #define vec_store_psqt(a,b) *(a)=(b)
92 #define vec_add_psqt_32(a,b) _mm_add_pi32(a,b)
93 #define vec_sub_psqt_32(a,b) _mm_sub_pi32(a,b)
94 #define vec_zero_psqt() _mm_setzero_si64()
95 static constexpr IndexType NumRegs = 8;
96 static constexpr IndexType NumPsqtRegs = 4;
99 typedef int16x8_t vec_t;
100 typedef int32x4_t psqt_vec_t;
101 #define vec_load(a) (*(a))
102 #define vec_store(a,b) *(a)=(b)
103 #define vec_add_16(a,b) vaddq_s16(a,b)
104 #define vec_sub_16(a,b) vsubq_s16(a,b)
105 #define vec_load_psqt(a) (*(a))
106 #define vec_store_psqt(a,b) *(a)=(b)
107 #define vec_add_psqt_32(a,b) vaddq_s32(a,b)
108 #define vec_sub_psqt_32(a,b) vsubq_s32(a,b)
109 #define vec_zero_psqt() psqt_vec_t{0}
110 static constexpr IndexType NumRegs = 16;
111 static constexpr IndexType NumPsqtRegs = 2;
118 // Input feature converter
119 class FeatureTransformer {
122 // Number of output dimensions for one side
123 static constexpr IndexType HalfDimensions = TransformedFeatureDimensions;
126 static constexpr IndexType TileHeight = NumRegs * sizeof(vec_t) / 2;
127 static constexpr IndexType PsqtTileHeight = NumPsqtRegs * sizeof(psqt_vec_t) / 4;
128 static_assert(HalfDimensions % TileHeight == 0, "TileHeight must divide HalfDimensions");
129 static_assert(PSQTBuckets % PsqtTileHeight == 0, "PsqtTileHeight must divide PSQTBuckets");
134 using OutputType = TransformedFeatureType;
136 // Number of input/output dimensions
137 static constexpr IndexType InputDimensions = FeatureSet::Dimensions;
138 static constexpr IndexType OutputDimensions = HalfDimensions * 2;
140 // Size of forward propagation buffer
141 static constexpr std::size_t BufferSize =
142 OutputDimensions * sizeof(OutputType);
144 // Hash value embedded in the evaluation file
145 static constexpr std::uint32_t get_hash_value() {
146 return FeatureSet::HashValue ^ OutputDimensions;
149 // Read network parameters
150 bool read_parameters(std::istream& stream) {
152 read_little_endian<BiasType >(stream, biases , HalfDimensions );
153 read_little_endian<WeightType >(stream, weights , HalfDimensions * InputDimensions);
154 read_little_endian<PSQTWeightType>(stream, psqtWeights, PSQTBuckets * InputDimensions);
156 return !stream.fail();
159 // Write network parameters
160 bool write_parameters(std::ostream& stream) const {
162 write_little_endian<BiasType >(stream, biases , HalfDimensions );
163 write_little_endian<WeightType >(stream, weights , HalfDimensions * InputDimensions);
164 write_little_endian<PSQTWeightType>(stream, psqtWeights, PSQTBuckets * InputDimensions);
166 return !stream.fail();
169 // Convert input features
170 std::int32_t transform(const Position& pos, OutputType* output, int bucket) const {
171 update_accumulator(pos, WHITE);
172 update_accumulator(pos, BLACK);
174 const Color perspectives[2] = {pos.side_to_move(), ~pos.side_to_move()};
175 const auto& accumulation = pos.state()->accumulator.accumulation;
176 const auto& psqtAccumulation = pos.state()->accumulator.psqtAccumulation;
179 psqtAccumulation[perspectives[0]][bucket]
180 - psqtAccumulation[perspectives[1]][bucket]
184 #if defined(USE_AVX512)
186 constexpr IndexType NumChunks = HalfDimensions / (SimdWidth * 2);
187 static_assert(HalfDimensions % (SimdWidth * 2) == 0);
188 const __m512i Control = _mm512_setr_epi64(0, 2, 4, 6, 1, 3, 5, 7);
189 const __m512i Zero = _mm512_setzero_si512();
191 for (IndexType p = 0; p < 2; ++p)
193 const IndexType offset = HalfDimensions * p;
194 auto out = reinterpret_cast<__m512i*>(&output[offset]);
195 for (IndexType j = 0; j < NumChunks; ++j)
197 __m512i sum0 = _mm512_load_si512(&reinterpret_cast<const __m512i*>
198 (accumulation[perspectives[p]])[j * 2 + 0]);
199 __m512i sum1 = _mm512_load_si512(&reinterpret_cast<const __m512i*>
200 (accumulation[perspectives[p]])[j * 2 + 1]);
202 _mm512_store_si512(&out[j], _mm512_permutexvar_epi64(Control,
203 _mm512_max_epi8(_mm512_packs_epi16(sum0, sum1), Zero)));
208 #elif defined(USE_AVX2)
210 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
211 constexpr int Control = 0b11011000;
212 const __m256i Zero = _mm256_setzero_si256();
214 for (IndexType p = 0; p < 2; ++p)
216 const IndexType offset = HalfDimensions * p;
217 auto out = reinterpret_cast<__m256i*>(&output[offset]);
218 for (IndexType j = 0; j < NumChunks; ++j)
220 __m256i sum0 = _mm256_load_si256(&reinterpret_cast<const __m256i*>
221 (accumulation[perspectives[p]])[j * 2 + 0]);
222 __m256i sum1 = _mm256_load_si256(&reinterpret_cast<const __m256i*>
223 (accumulation[perspectives[p]])[j * 2 + 1]);
225 _mm256_store_si256(&out[j], _mm256_permute4x64_epi64(
226 _mm256_max_epi8(_mm256_packs_epi16(sum0, sum1), Zero), Control));
231 #elif defined(USE_SSE2)
234 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
235 const __m128i Zero = _mm_setzero_si128();
237 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
238 const __m128i k0x80s = _mm_set1_epi8(-128);
241 for (IndexType p = 0; p < 2; ++p)
243 const IndexType offset = HalfDimensions * p;
244 auto out = reinterpret_cast<__m128i*>(&output[offset]);
245 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);
254 _mm_store_si128(&out[j], _mm_max_epi8(packedbytes, Zero));
256 _mm_store_si128(&out[j], _mm_subs_epi8(_mm_adds_epi8(packedbytes, k0x80s), k0x80s));
262 #elif defined(USE_MMX)
264 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
265 const __m64 k0x80s = _mm_set1_pi8(-128);
267 for (IndexType p = 0; p < 2; ++p)
269 const IndexType offset = HalfDimensions * p;
270 auto out = reinterpret_cast<__m64*>(&output[offset]);
271 for (IndexType j = 0; j < NumChunks; ++j)
273 __m64 sum0 = *(&reinterpret_cast<const __m64*>(accumulation[perspectives[p]])[j * 2 + 0]);
274 __m64 sum1 = *(&reinterpret_cast<const __m64*>(accumulation[perspectives[p]])[j * 2 + 1]);
275 const __m64 packedbytes = _mm_packs_pi16(sum0, sum1);
276 out[j] = _mm_subs_pi8(_mm_adds_pi8(packedbytes, k0x80s), k0x80s);
282 #elif defined(USE_NEON)
284 constexpr IndexType NumChunks = HalfDimensions / (SimdWidth / 2);
285 const int8x8_t Zero = {0};
287 for (IndexType p = 0; p < 2; ++p)
289 const IndexType offset = HalfDimensions * p;
290 const auto out = reinterpret_cast<int8x8_t*>(&output[offset]);
291 for (IndexType j = 0; j < NumChunks; ++j)
293 int16x8_t sum = reinterpret_cast<const int16x8_t*>(accumulation[perspectives[p]])[j];
294 out[j] = vmax_s8(vqmovn_s16(sum), Zero);
301 for (IndexType p = 0; p < 2; ++p)
303 const IndexType offset = HalfDimensions * p;
304 for (IndexType j = 0; j < HalfDimensions; ++j)
306 BiasType sum = accumulation[perspectives[p]][j];
307 output[offset + j] = static_cast<OutputType>(std::max<int>(0, std::min<int>(127, sum)));
314 } // end of function transform()
319 void update_accumulator(const Position& pos, const Color perspective) const {
321 // The size must be enough to contain the largest possible update.
322 // That might depend on the feature set and generally relies on the
323 // feature set's update cost calculation to be correct and never
324 // allow updates with more added/removed features than MaxActiveDimensions.
325 using IndexList = ValueList<IndexType, FeatureSet::MaxActiveDimensions>;
328 // Gcc-10.2 unnecessarily spills AVX2 registers if this array
329 // is defined in the VECTOR code below, once in each branch
331 psqt_vec_t psqt[NumPsqtRegs];
334 // Look for a usable accumulator of an earlier position. We keep track
335 // of the estimated gain in terms of features to be added/subtracted.
336 StateInfo *st = pos.state(), *next = nullptr;
337 int gain = FeatureSet::refresh_cost(pos);
338 while (st->accumulator.state[perspective] == EMPTY)
340 // This governs when a full feature refresh is needed and how many
341 // updates are better than just one full refresh.
342 if ( FeatureSet::requires_refresh(st, perspective)
343 || (gain -= FeatureSet::update_cost(st) + 1) < 0)
349 if (st->accumulator.state[perspective] == COMPUTED)
354 // Update incrementally in two steps. First, we update the "next"
355 // accumulator. Then, we update the current accumulator (pos.state()).
357 // Gather all features to be updated.
358 const Square ksq = pos.square<KING>(perspective);
359 IndexList removed[2], added[2];
360 FeatureSet::append_changed_indices(
361 ksq, next, perspective, removed[0], added[0]);
362 for (StateInfo *st2 = pos.state(); st2 != next; st2 = st2->previous)
363 FeatureSet::append_changed_indices(
364 ksq, st2, perspective, removed[1], added[1]);
366 // Mark the accumulators as computed.
367 next->accumulator.state[perspective] = COMPUTED;
368 pos.state()->accumulator.state[perspective] = COMPUTED;
370 // Now update the accumulators listed in states_to_update[], where the last element is a sentinel.
371 StateInfo *states_to_update[3] =
372 { next, next == pos.state() ? nullptr : pos.state(), nullptr };
374 for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
377 auto accTile = reinterpret_cast<vec_t*>(
378 &st->accumulator.accumulation[perspective][j * TileHeight]);
379 for (IndexType k = 0; k < NumRegs; ++k)
380 acc[k] = vec_load(&accTile[k]);
382 for (IndexType i = 0; states_to_update[i]; ++i)
384 // Difference calculation for the deactivated features
385 for (const auto index : removed[i])
387 const IndexType offset = HalfDimensions * index + j * TileHeight;
388 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
389 for (IndexType k = 0; k < NumRegs; ++k)
390 acc[k] = vec_sub_16(acc[k], column[k]);
393 // Difference calculation for the activated features
394 for (const auto index : added[i])
396 const IndexType offset = HalfDimensions * index + j * TileHeight;
397 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
398 for (IndexType k = 0; k < NumRegs; ++k)
399 acc[k] = vec_add_16(acc[k], column[k]);
403 accTile = reinterpret_cast<vec_t*>(
404 &states_to_update[i]->accumulator.accumulation[perspective][j * TileHeight]);
405 for (IndexType k = 0; k < NumRegs; ++k)
406 vec_store(&accTile[k], acc[k]);
410 for (IndexType j = 0; j < PSQTBuckets / PsqtTileHeight; ++j)
413 auto accTilePsqt = reinterpret_cast<psqt_vec_t*>(
414 &st->accumulator.psqtAccumulation[perspective][j * PsqtTileHeight]);
415 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
416 psqt[k] = vec_load_psqt(&accTilePsqt[k]);
418 for (IndexType i = 0; states_to_update[i]; ++i)
420 // Difference calculation for the deactivated features
421 for (const auto index : removed[i])
423 const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
424 auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
425 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
426 psqt[k] = vec_sub_psqt_32(psqt[k], columnPsqt[k]);
429 // Difference calculation for the activated features
430 for (const auto index : added[i])
432 const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
433 auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
434 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
435 psqt[k] = vec_add_psqt_32(psqt[k], columnPsqt[k]);
439 accTilePsqt = reinterpret_cast<psqt_vec_t*>(
440 &states_to_update[i]->accumulator.psqtAccumulation[perspective][j * PsqtTileHeight]);
441 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
442 vec_store_psqt(&accTilePsqt[k], psqt[k]);
447 for (IndexType i = 0; states_to_update[i]; ++i)
449 std::memcpy(states_to_update[i]->accumulator.accumulation[perspective],
450 st->accumulator.accumulation[perspective],
451 HalfDimensions * sizeof(BiasType));
453 for (std::size_t k = 0; k < PSQTBuckets; ++k)
454 states_to_update[i]->accumulator.psqtAccumulation[perspective][k] = st->accumulator.psqtAccumulation[perspective][k];
456 st = states_to_update[i];
458 // Difference calculation for the deactivated features
459 for (const auto index : removed[i])
461 const IndexType offset = HalfDimensions * index;
463 for (IndexType j = 0; j < HalfDimensions; ++j)
464 st->accumulator.accumulation[perspective][j] -= weights[offset + j];
466 for (std::size_t k = 0; k < PSQTBuckets; ++k)
467 st->accumulator.psqtAccumulation[perspective][k] -= psqtWeights[index * PSQTBuckets + k];
470 // Difference calculation for the activated features
471 for (const auto index : added[i])
473 const IndexType offset = HalfDimensions * index;
475 for (IndexType j = 0; j < HalfDimensions; ++j)
476 st->accumulator.accumulation[perspective][j] += weights[offset + j];
478 for (std::size_t k = 0; k < PSQTBuckets; ++k)
479 st->accumulator.psqtAccumulation[perspective][k] += psqtWeights[index * PSQTBuckets + k];
486 // Refresh the accumulator
487 auto& accumulator = pos.state()->accumulator;
488 accumulator.state[perspective] = COMPUTED;
490 FeatureSet::append_active_indices(pos, perspective, active);
493 for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
495 auto biasesTile = reinterpret_cast<const vec_t*>(
496 &biases[j * TileHeight]);
497 for (IndexType k = 0; k < NumRegs; ++k)
498 acc[k] = biasesTile[k];
500 for (const auto index : active)
502 const IndexType offset = HalfDimensions * index + j * TileHeight;
503 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
505 for (unsigned k = 0; k < NumRegs; ++k)
506 acc[k] = vec_add_16(acc[k], column[k]);
509 auto accTile = reinterpret_cast<vec_t*>(
510 &accumulator.accumulation[perspective][j * TileHeight]);
511 for (unsigned k = 0; k < NumRegs; k++)
512 vec_store(&accTile[k], acc[k]);
515 for (IndexType j = 0; j < PSQTBuckets / PsqtTileHeight; ++j)
517 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
518 psqt[k] = vec_zero_psqt();
520 for (const auto index : active)
522 const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
523 auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
525 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
526 psqt[k] = vec_add_psqt_32(psqt[k], columnPsqt[k]);
529 auto accTilePsqt = reinterpret_cast<psqt_vec_t*>(
530 &accumulator.psqtAccumulation[perspective][j * PsqtTileHeight]);
531 for (std::size_t k = 0; k < NumPsqtRegs; ++k)
532 vec_store_psqt(&accTilePsqt[k], psqt[k]);
536 std::memcpy(accumulator.accumulation[perspective], biases,
537 HalfDimensions * sizeof(BiasType));
539 for (std::size_t k = 0; k < PSQTBuckets; ++k)
540 accumulator.psqtAccumulation[perspective][k] = 0;
542 for (const auto index : active)
544 const IndexType offset = HalfDimensions * index;
546 for (IndexType j = 0; j < HalfDimensions; ++j)
547 accumulator.accumulation[perspective][j] += weights[offset + j];
549 for (std::size_t k = 0; k < PSQTBuckets; ++k)
550 accumulator.psqtAccumulation[perspective][k] += psqtWeights[index * PSQTBuckets + k];
560 using BiasType = std::int16_t;
561 using WeightType = std::int16_t;
562 using PSQTWeightType = std::int32_t;
564 alignas(CacheLineSize) BiasType biases[HalfDimensions];
565 alignas(CacheLineSize) WeightType weights[HalfDimensions * InputDimensions];
566 alignas(CacheLineSize) PSQTWeightType psqtWeights[InputDimensions * PSQTBuckets];
569 } // namespace Stockfish::Eval::NNUE
571 #endif // #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED