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 // Convert input features
122 void transform(const Position& pos, OutputType* output) const {
123 update_accumulator(pos, WHITE);
124 update_accumulator(pos, BLACK);
126 const auto& accumulation = pos.state()->accumulator.accumulation;
128 #if defined(USE_AVX512)
129 constexpr IndexType NumChunks = HalfDimensions / (SimdWidth * 2);
130 static_assert(HalfDimensions % (SimdWidth * 2) == 0);
131 const __m512i Control = _mm512_setr_epi64(0, 2, 4, 6, 1, 3, 5, 7);
132 const __m512i Zero = _mm512_setzero_si512();
134 #elif defined(USE_AVX2)
135 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
136 constexpr int Control = 0b11011000;
137 const __m256i Zero = _mm256_setzero_si256();
139 #elif defined(USE_SSE2)
140 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
143 const __m128i Zero = _mm_setzero_si128();
145 const __m128i k0x80s = _mm_set1_epi8(-128);
148 #elif defined(USE_MMX)
149 constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
150 const __m64 k0x80s = _mm_set1_pi8(-128);
152 #elif defined(USE_NEON)
153 constexpr IndexType NumChunks = HalfDimensions / (SimdWidth / 2);
154 const int8x8_t Zero = {0};
157 const Color perspectives[2] = {pos.side_to_move(), ~pos.side_to_move()};
158 for (IndexType p = 0; p < 2; ++p) {
159 const IndexType offset = HalfDimensions * p;
161 #if defined(USE_AVX512)
162 auto out = reinterpret_cast<__m512i*>(&output[offset]);
163 for (IndexType j = 0; j < NumChunks; ++j) {
164 __m512i sum0 = _mm512_load_si512(
165 &reinterpret_cast<const __m512i*>(accumulation[perspectives[p]])[j * 2 + 0]);
166 __m512i sum1 = _mm512_load_si512(
167 &reinterpret_cast<const __m512i*>(accumulation[perspectives[p]])[j * 2 + 1]);
168 _mm512_store_si512(&out[j], _mm512_permutexvar_epi64(Control,
169 _mm512_max_epi8(_mm512_packs_epi16(sum0, sum1), Zero)));
172 #elif defined(USE_AVX2)
173 auto out = reinterpret_cast<__m256i*>(&output[offset]);
174 for (IndexType j = 0; j < NumChunks; ++j) {
175 __m256i sum0 = _mm256_load_si256(
176 &reinterpret_cast<const __m256i*>(accumulation[perspectives[p]])[j * 2 + 0]);
177 __m256i sum1 = _mm256_load_si256(
178 &reinterpret_cast<const __m256i*>(accumulation[perspectives[p]])[j * 2 + 1]);
179 _mm256_store_si256(&out[j], _mm256_permute4x64_epi64(_mm256_max_epi8(
180 _mm256_packs_epi16(sum0, sum1), Zero), Control));
183 #elif defined(USE_SSE2)
184 auto out = reinterpret_cast<__m128i*>(&output[offset]);
185 for (IndexType j = 0; j < NumChunks; ++j) {
186 __m128i sum0 = _mm_load_si128(&reinterpret_cast<const __m128i*>(
187 accumulation[perspectives[p]])[j * 2 + 0]);
188 __m128i sum1 = _mm_load_si128(&reinterpret_cast<const __m128i*>(
189 accumulation[perspectives[p]])[j * 2 + 1]);
190 const __m128i packedbytes = _mm_packs_epi16(sum0, sum1);
192 _mm_store_si128(&out[j],
195 _mm_max_epi8(packedbytes, Zero)
197 _mm_subs_epi8(_mm_adds_epi8(packedbytes, k0x80s), k0x80s)
203 #elif defined(USE_MMX)
204 auto out = reinterpret_cast<__m64*>(&output[offset]);
205 for (IndexType j = 0; j < NumChunks; ++j) {
206 __m64 sum0 = *(&reinterpret_cast<const __m64*>(
207 accumulation[perspectives[p]])[j * 2 + 0]);
208 __m64 sum1 = *(&reinterpret_cast<const __m64*>(
209 accumulation[perspectives[p]])[j * 2 + 1]);
210 const __m64 packedbytes = _mm_packs_pi16(sum0, sum1);
211 out[j] = _mm_subs_pi8(_mm_adds_pi8(packedbytes, k0x80s), k0x80s);
214 #elif defined(USE_NEON)
215 const auto out = reinterpret_cast<int8x8_t*>(&output[offset]);
216 for (IndexType j = 0; j < NumChunks; ++j) {
217 int16x8_t sum = reinterpret_cast<const int16x8_t*>(
218 accumulation[perspectives[p]])[j];
219 out[j] = vmax_s8(vqmovn_s16(sum), Zero);
223 for (IndexType j = 0; j < HalfDimensions; ++j) {
224 BiasType sum = accumulation[static_cast<int>(perspectives[p])][j];
225 output[offset + j] = static_cast<OutputType>(
226 std::max<int>(0, std::min<int>(127, sum)));
237 void update_accumulator(const Position& pos, const Color perspective) const {
239 // The size must be enough to contain the largest possible update.
240 // That might depend on the feature set and generally relies on the
241 // feature set's update cost calculation to be correct and never
242 // allow updates with more added/removed features than MaxActiveDimensions.
243 using IndexList = ValueList<IndexType, FeatureSet::MaxActiveDimensions>;
246 // Gcc-10.2 unnecessarily spills AVX2 registers if this array
247 // is defined in the VECTOR code below, once in each branch
251 // Look for a usable accumulator of an earlier position. We keep track
252 // of the estimated gain in terms of features to be added/subtracted.
253 StateInfo *st = pos.state(), *next = nullptr;
254 int gain = FeatureSet::refresh_cost(pos);
255 while (st->accumulator.state[perspective] == EMPTY)
257 // This governs when a full feature refresh is needed and how many
258 // updates are better than just one full refresh.
259 if ( FeatureSet::requires_refresh(st, perspective)
260 || (gain -= FeatureSet::update_cost(st) + 1) < 0)
266 if (st->accumulator.state[perspective] == COMPUTED)
271 // Update incrementally in two steps. First, we update the "next"
272 // accumulator. Then, we update the current accumulator (pos.state()).
274 // Gather all features to be updated.
275 const Square ksq = pos.square<KING>(perspective);
276 IndexList removed[2], added[2];
277 FeatureSet::append_changed_indices(
278 ksq, next, perspective, removed[0], added[0]);
279 for (StateInfo *st2 = pos.state(); st2 != next; st2 = st2->previous)
280 FeatureSet::append_changed_indices(
281 ksq, st2, perspective, removed[1], added[1]);
283 // Mark the accumulators as computed.
284 next->accumulator.state[perspective] = COMPUTED;
285 pos.state()->accumulator.state[perspective] = COMPUTED;
287 // Now update the accumulators listed in states_to_update[], where the last element is a sentinel.
288 StateInfo *states_to_update[3] =
289 { next, next == pos.state() ? nullptr : pos.state(), nullptr };
291 for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
294 auto accTile = reinterpret_cast<vec_t*>(
295 &st->accumulator.accumulation[perspective][j * TileHeight]);
296 for (IndexType k = 0; k < NumRegs; ++k)
297 acc[k] = vec_load(&accTile[k]);
299 for (IndexType i = 0; states_to_update[i]; ++i)
301 // Difference calculation for the deactivated features
302 for (const auto index : removed[i])
304 const IndexType offset = HalfDimensions * index + j * TileHeight;
305 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
306 for (IndexType k = 0; k < NumRegs; ++k)
307 acc[k] = vec_sub_16(acc[k], column[k]);
310 // Difference calculation for the activated features
311 for (const auto index : added[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_add_16(acc[k], column[k]);
320 accTile = reinterpret_cast<vec_t*>(
321 &states_to_update[i]->accumulator.accumulation[perspective][j * TileHeight]);
322 for (IndexType k = 0; k < NumRegs; ++k)
323 vec_store(&accTile[k], acc[k]);
328 for (IndexType i = 0; states_to_update[i]; ++i)
330 std::memcpy(states_to_update[i]->accumulator.accumulation[perspective],
331 st->accumulator.accumulation[perspective],
332 HalfDimensions * sizeof(BiasType));
333 st = states_to_update[i];
335 // Difference calculation for the deactivated features
336 for (const auto index : removed[i])
338 const IndexType offset = HalfDimensions * index;
340 for (IndexType j = 0; j < HalfDimensions; ++j)
341 st->accumulator.accumulation[perspective][j] -= weights[offset + j];
344 // Difference calculation for the activated features
345 for (const auto index : added[i])
347 const IndexType offset = HalfDimensions * index;
349 for (IndexType j = 0; j < HalfDimensions; ++j)
350 st->accumulator.accumulation[perspective][j] += weights[offset + j];
357 // Refresh the accumulator
358 auto& accumulator = pos.state()->accumulator;
359 accumulator.state[perspective] = COMPUTED;
361 FeatureSet::append_active_indices(pos, perspective, active);
364 for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
366 auto biasesTile = reinterpret_cast<const vec_t*>(
367 &biases[j * TileHeight]);
368 for (IndexType k = 0; k < NumRegs; ++k)
369 acc[k] = biasesTile[k];
371 for (const auto index : active)
373 const IndexType offset = HalfDimensions * index + j * TileHeight;
374 auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
376 for (unsigned k = 0; k < NumRegs; ++k)
377 acc[k] = vec_add_16(acc[k], column[k]);
380 auto accTile = reinterpret_cast<vec_t*>(
381 &accumulator.accumulation[perspective][j * TileHeight]);
382 for (unsigned k = 0; k < NumRegs; k++)
383 vec_store(&accTile[k], acc[k]);
387 std::memcpy(accumulator.accumulation[perspective], biases,
388 HalfDimensions * sizeof(BiasType));
390 for (const auto index : active)
392 const IndexType offset = HalfDimensions * index;
394 for (IndexType j = 0; j < HalfDimensions; ++j)
395 accumulator.accumulation[perspective][j] += weights[offset + j];
405 using BiasType = std::int16_t;
406 using WeightType = std::int16_t;
408 alignas(CacheLineSize) BiasType biases[HalfDimensions];
409 alignas(CacheLineSize) WeightType weights[HalfDimensions * InputDimensions];
412 } // namespace Stockfish::Eval::NNUE
414 #endif // #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED