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
39 typedef __m512i vec_t;
40 #define vec_load(a) _mm512_load_si512(a)
41 #define vec_store(a,b) _mm512_store_si512(a,b)
42 #define vec_add_16(a,b) _mm512_add_epi16(a,b)
43 #define vec_sub_16(a,b) _mm512_sub_epi16(a,b)
44 static constexpr IndexType NumRegs = 8; // only 8 are needed
47 typedef __m256i vec_t;
48 #define vec_load(a) _mm256_load_si256(a)
49 #define vec_store(a,b) _mm256_store_si256(a,b)
50 #define vec_add_16(a,b) _mm256_add_epi16(a,b)
51 #define vec_sub_16(a,b) _mm256_sub_epi16(a,b)
52 static constexpr IndexType NumRegs = 16;
55 typedef __m128i vec_t;
56 #define vec_load(a) (*(a))
57 #define vec_store(a,b) *(a)=(b)
58 #define vec_add_16(a,b) _mm_add_epi16(a,b)
59 #define vec_sub_16(a,b) _mm_sub_epi16(a,b)
60 static constexpr IndexType NumRegs = Is64Bit ? 16 : 8;
64 #define vec_load(a) (*(a))
65 #define vec_store(a,b) *(a)=(b)
66 #define vec_add_16(a,b) _mm_add_pi16(a,b)
67 #define vec_sub_16(a,b) _mm_sub_pi16(a,b)
68 static constexpr IndexType NumRegs = 8;
71 typedef int16x8_t vec_t;
72 #define vec_load(a) (*(a))
73 #define vec_store(a,b) *(a)=(b)
74 #define vec_add_16(a,b) vaddq_s16(a,b)
75 #define vec_sub_16(a,b) vsubq_s16(a,b)
76 static constexpr IndexType NumRegs = 16;
83 // Input feature converter
84 class FeatureTransformer {
87 // Number of output dimensions for one side
88 static constexpr IndexType HalfDimensions = TransformedFeatureDimensions;
91 static constexpr IndexType TileHeight = NumRegs * sizeof(vec_t) / 2;
92 static_assert(HalfDimensions % TileHeight == 0, "TileHeight must divide HalfDimensions");
97 using OutputType = TransformedFeatureType;
99 // Number of input/output dimensions
100 static constexpr IndexType InputDimensions = FeatureSet::Dimensions;
101 static constexpr IndexType OutputDimensions = HalfDimensions * 2;
103 // Size of forward propagation buffer
104 static constexpr std::size_t BufferSize =
105 OutputDimensions * sizeof(OutputType);
107 // Hash value embedded in the evaluation file
108 static constexpr std::uint32_t get_hash_value() {
109 return FeatureSet::HashValue ^ OutputDimensions;
112 // Read network parameters
113 bool read_parameters(std::istream& stream) {
114 for (std::size_t i = 0; i < HalfDimensions; ++i)
115 biases[i] = read_little_endian<BiasType>(stream);
116 for (std::size_t i = 0; i < HalfDimensions * InputDimensions; ++i)
117 weights[i] = read_little_endian<WeightType>(stream);
118 return !stream.fail();
121 // Write network parameters
122 bool write_parameters(std::ostream& stream) const {
123 for (std::size_t i = 0; i < HalfDimensions; ++i)
124 write_little_endian<BiasType>(stream, biases[i]);
125 for (std::size_t i = 0; i < HalfDimensions * InputDimensions; ++i)
126 write_little_endian<WeightType>(stream, weights[i]);
127 return !stream.fail();
130 // Convert input features
131 void transform(const Position& pos, OutputType* output) const {
132 update_accumulator(pos, WHITE);
133 update_accumulator(pos, BLACK);
135 const auto& accumulation = pos.state()->accumulator.accumulation;
137 #if defined(USE_AVX512)
138 constexpr IndexType NumChunks = HalfDimensions / (SimdWidth * 2);
139 static_assert(HalfDimensions % (SimdWidth * 2) == 0);
140 const __m512i Control = _mm512_setr_epi64(0, 2, 4, 6, 1, 3, 5, 7);
141 const __m512i Zero = _mm512_setzero_si512();
143 #elif defined(USE_AVX2)
144 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
145 constexpr int Control = 0b11011000;
146 const __m256i Zero = _mm256_setzero_si256();
148 #elif defined(USE_SSE2)
149 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
152 const __m128i Zero = _mm_setzero_si128();
154 const __m128i k0x80s = _mm_set1_epi8(-128);
157 #elif defined(USE_MMX)
158 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
159 const __m64 k0x80s = _mm_set1_pi8(-128);
161 #elif defined(USE_NEON)
162 constexpr IndexType NumChunks = HalfDimensions / (SimdWidth / 2);
163 const int8x8_t Zero = {0};
166 const Color perspectives[2] = {pos.side_to_move(), ~pos.side_to_move()};
167 for (IndexType p = 0; p < 2; ++p) {
168 const IndexType offset = HalfDimensions * p;
170 #if defined(USE_AVX512)
171 auto out = reinterpret_cast<__m512i*>(&output[offset]);
172 for (IndexType j = 0; j < NumChunks; ++j) {
173 __m512i sum0 = _mm512_load_si512(
174 &reinterpret_cast<const __m512i*>(accumulation[perspectives[p]])[j * 2 + 0]);
175 __m512i sum1 = _mm512_load_si512(
176 &reinterpret_cast<const __m512i*>(accumulation[perspectives[p]])[j * 2 + 1]);
177 _mm512_store_si512(&out[j], _mm512_permutexvar_epi64(Control,
178 _mm512_max_epi8(_mm512_packs_epi16(sum0, sum1), Zero)));
181 #elif defined(USE_AVX2)
182 auto out = reinterpret_cast<__m256i*>(&output[offset]);
183 for (IndexType j = 0; j < NumChunks; ++j) {
184 __m256i sum0 = _mm256_load_si256(
185 &reinterpret_cast<const __m256i*>(accumulation[perspectives[p]])[j * 2 + 0]);
186 __m256i sum1 = _mm256_load_si256(
187 &reinterpret_cast<const __m256i*>(accumulation[perspectives[p]])[j * 2 + 1]);
188 _mm256_store_si256(&out[j], _mm256_permute4x64_epi64(_mm256_max_epi8(
189 _mm256_packs_epi16(sum0, sum1), Zero), Control));
192 #elif defined(USE_SSE2)
193 auto out = reinterpret_cast<__m128i*>(&output[offset]);
194 for (IndexType j = 0; j < NumChunks; ++j) {
195 __m128i sum0 = _mm_load_si128(&reinterpret_cast<const __m128i*>(
196 accumulation[perspectives[p]])[j * 2 + 0]);
197 __m128i sum1 = _mm_load_si128(&reinterpret_cast<const __m128i*>(
198 accumulation[perspectives[p]])[j * 2 + 1]);
199 const __m128i packedbytes = _mm_packs_epi16(sum0, sum1);
201 _mm_store_si128(&out[j],
204 _mm_max_epi8(packedbytes, Zero)
206 _mm_subs_epi8(_mm_adds_epi8(packedbytes, k0x80s), k0x80s)
212 #elif defined(USE_MMX)
213 auto out = reinterpret_cast<__m64*>(&output[offset]);
214 for (IndexType j = 0; j < NumChunks; ++j) {
215 __m64 sum0 = *(&reinterpret_cast<const __m64*>(
216 accumulation[perspectives[p]])[j * 2 + 0]);
217 __m64 sum1 = *(&reinterpret_cast<const __m64*>(
218 accumulation[perspectives[p]])[j * 2 + 1]);
219 const __m64 packedbytes = _mm_packs_pi16(sum0, sum1);
220 out[j] = _mm_subs_pi8(_mm_adds_pi8(packedbytes, k0x80s), k0x80s);
223 #elif defined(USE_NEON)
224 const auto out = reinterpret_cast<int8x8_t*>(&output[offset]);
225 for (IndexType j = 0; j < NumChunks; ++j) {
226 int16x8_t sum = reinterpret_cast<const int16x8_t*>(
227 accumulation[perspectives[p]])[j];
228 out[j] = vmax_s8(vqmovn_s16(sum), Zero);
232 for (IndexType j = 0; j < HalfDimensions; ++j) {
233 BiasType sum = accumulation[static_cast<int>(perspectives[p])][j];
234 output[offset + j] = static_cast<OutputType>(
235 std::max<int>(0, std::min<int>(127, sum)));
246 void update_accumulator(const Position& pos, const Color perspective) const {
248 // The size must be enough to contain the largest possible update.
249 // That might depend on the feature set and generally relies on the
250 // feature set's update cost calculation to be correct and never
251 // allow updates with more added/removed features than MaxActiveDimensions.
252 using IndexList = ValueList<IndexType, FeatureSet::MaxActiveDimensions>;
255 // Gcc-10.2 unnecessarily spills AVX2 registers if this array
256 // is defined in the VECTOR code below, once in each branch
260 // Look for a usable accumulator of an earlier position. We keep track
261 // of the estimated gain in terms of features to be added/subtracted.
262 StateInfo *st = pos.state(), *next = nullptr;
263 int gain = FeatureSet::refresh_cost(pos);
264 while (st->accumulator.state[perspective] == EMPTY)
266 // This governs when a full feature refresh is needed and how many
267 // updates are better than just one full refresh.
268 if ( FeatureSet::requires_refresh(st, perspective)
269 || (gain -= FeatureSet::update_cost(st) + 1) < 0)
275 if (st->accumulator.state[perspective] == COMPUTED)
280 // Update incrementally in two steps. First, we update the "next"
281 // accumulator. Then, we update the current accumulator (pos.state()).
283 // Gather all features to be updated.
284 const Square ksq = pos.square<KING>(perspective);
285 IndexList removed[2], added[2];
286 FeatureSet::append_changed_indices(
287 ksq, next, perspective, removed[0], added[0]);
288 for (StateInfo *st2 = pos.state(); st2 != next; st2 = st2->previous)
289 FeatureSet::append_changed_indices(
290 ksq, st2, perspective, removed[1], added[1]);
292 // Mark the accumulators as computed.
293 next->accumulator.state[perspective] = COMPUTED;
294 pos.state()->accumulator.state[perspective] = COMPUTED;
296 // Now update the accumulators listed in states_to_update[], where the last element is a sentinel.
297 StateInfo *states_to_update[3] =
298 { next, next == pos.state() ? nullptr : pos.state(), nullptr };
300 for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
303 auto accTile = reinterpret_cast<vec_t*>(
304 &st->accumulator.accumulation[perspective][j * TileHeight]);
305 for (IndexType k = 0; k < NumRegs; ++k)
306 acc[k] = vec_load(&accTile[k]);
308 for (IndexType i = 0; states_to_update[i]; ++i)
310 // Difference calculation for the deactivated features
311 for (const auto index : removed[i])
313 const IndexType offset = HalfDimensions * index + j * TileHeight;
314 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
315 for (IndexType k = 0; k < NumRegs; ++k)
316 acc[k] = vec_sub_16(acc[k], column[k]);
319 // Difference calculation for the activated features
320 for (const auto index : added[i])
322 const IndexType offset = HalfDimensions * index + j * TileHeight;
323 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
324 for (IndexType k = 0; k < NumRegs; ++k)
325 acc[k] = vec_add_16(acc[k], column[k]);
329 accTile = reinterpret_cast<vec_t*>(
330 &states_to_update[i]->accumulator.accumulation[perspective][j * TileHeight]);
331 for (IndexType k = 0; k < NumRegs; ++k)
332 vec_store(&accTile[k], acc[k]);
337 for (IndexType i = 0; states_to_update[i]; ++i)
339 std::memcpy(states_to_update[i]->accumulator.accumulation[perspective],
340 st->accumulator.accumulation[perspective],
341 HalfDimensions * sizeof(BiasType));
342 st = states_to_update[i];
344 // Difference calculation for the deactivated features
345 for (const auto index : removed[i])
347 const IndexType offset = HalfDimensions * index;
349 for (IndexType j = 0; j < HalfDimensions; ++j)
350 st->accumulator.accumulation[perspective][j] -= weights[offset + j];
353 // Difference calculation for the activated features
354 for (const auto index : added[i])
356 const IndexType offset = HalfDimensions * index;
358 for (IndexType j = 0; j < HalfDimensions; ++j)
359 st->accumulator.accumulation[perspective][j] += weights[offset + j];
366 // Refresh the accumulator
367 auto& accumulator = pos.state()->accumulator;
368 accumulator.state[perspective] = COMPUTED;
370 FeatureSet::append_active_indices(pos, perspective, active);
373 for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
375 auto biasesTile = reinterpret_cast<const vec_t*>(
376 &biases[j * TileHeight]);
377 for (IndexType k = 0; k < NumRegs; ++k)
378 acc[k] = biasesTile[k];
380 for (const auto index : active)
382 const IndexType offset = HalfDimensions * index + j * TileHeight;
383 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
385 for (unsigned k = 0; k < NumRegs; ++k)
386 acc[k] = vec_add_16(acc[k], column[k]);
389 auto accTile = reinterpret_cast<vec_t*>(
390 &accumulator.accumulation[perspective][j * TileHeight]);
391 for (unsigned k = 0; k < NumRegs; k++)
392 vec_store(&accTile[k], acc[k]);
396 std::memcpy(accumulator.accumulation[perspective], biases,
397 HalfDimensions * sizeof(BiasType));
399 for (const auto index : active)
401 const IndexType offset = HalfDimensions * index;
403 for (IndexType j = 0; j < HalfDimensions; ++j)
404 accumulator.accumulation[perspective][j] += weights[offset + j];
414 using BiasType = std::int16_t;
415 using WeightType = std::int16_t;
417 alignas(CacheLineSize) BiasType biases[HalfDimensions];
418 alignas(CacheLineSize) WeightType weights[HalfDimensions * InputDimensions];
421 } // namespace Stockfish::Eval::NNUE
423 #endif // #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED