]> git.sesse.net Git - stockfish/blob - src/nnue/nnue_feature_transformer.h
Exporting the currently loaded network file
[stockfish] / src / nnue / nnue_feature_transformer.h
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2021 The Stockfish developers (see AUTHORS file)
4
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.
9
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.
14
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/>.
17 */
18
19 // A class that converts the input features of the NNUE evaluation function
20
21 #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED
22 #define NNUE_FEATURE_TRANSFORMER_H_INCLUDED
23
24 #include "nnue_common.h"
25 #include "nnue_architecture.h"
26
27 #include "../misc.h"
28
29 #include <cstring> // std::memset()
30
31 namespace Stockfish::Eval::NNUE {
32
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
35   // vector registers.
36   #define VECTOR
37
38   #ifdef USE_AVX512
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
45
46   #elif USE_AVX2
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;
53
54   #elif USE_SSE2
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;
61
62   #elif USE_MMX
63   typedef __m64 vec_t;
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;
69
70   #elif USE_NEON
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;
77
78   #else
79   #undef VECTOR
80
81   #endif
82
83   // Input feature converter
84   class FeatureTransformer {
85
86    private:
87     // Number of output dimensions for one side
88     static constexpr IndexType HalfDimensions = TransformedFeatureDimensions;
89
90     #ifdef VECTOR
91     static constexpr IndexType TileHeight = NumRegs * sizeof(vec_t) / 2;
92     static_assert(HalfDimensions % TileHeight == 0, "TileHeight must divide HalfDimensions");
93     #endif
94
95    public:
96     // Output type
97     using OutputType = TransformedFeatureType;
98
99     // Number of input/output dimensions
100     static constexpr IndexType InputDimensions = FeatureSet::Dimensions;
101     static constexpr IndexType OutputDimensions = HalfDimensions * 2;
102
103     // Size of forward propagation buffer
104     static constexpr std::size_t BufferSize =
105         OutputDimensions * sizeof(OutputType);
106
107     // Hash value embedded in the evaluation file
108     static constexpr std::uint32_t get_hash_value() {
109       return FeatureSet::HashValue ^ OutputDimensions;
110     }
111
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();
119     }
120
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();
128     }
129
130     // Convert input features
131     void transform(const Position& pos, OutputType* output) const {
132       update_accumulator(pos, WHITE);
133       update_accumulator(pos, BLACK);
134
135       const auto& accumulation = pos.state()->accumulator.accumulation;
136
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();
142
143   #elif defined(USE_AVX2)
144       constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
145       constexpr int Control = 0b11011000;
146       const __m256i Zero = _mm256_setzero_si256();
147
148   #elif defined(USE_SSE2)
149       constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
150
151   #ifdef USE_SSE41
152       const __m128i Zero = _mm_setzero_si128();
153   #else
154       const __m128i k0x80s = _mm_set1_epi8(-128);
155   #endif
156
157   #elif defined(USE_MMX)
158       constexpr IndexType NumChunks = HalfDimensions / SimdWidth;
159       const __m64 k0x80s = _mm_set1_pi8(-128);
160
161   #elif defined(USE_NEON)
162       constexpr IndexType NumChunks = HalfDimensions / (SimdWidth / 2);
163       const int8x8_t Zero = {0};
164   #endif
165
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;
169
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)));
179         }
180
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));
190         }
191
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);
200
201           _mm_store_si128(&out[j],
202
203   #ifdef USE_SSE41
204               _mm_max_epi8(packedbytes, Zero)
205   #else
206               _mm_subs_epi8(_mm_adds_epi8(packedbytes, k0x80s), k0x80s)
207   #endif
208
209           );
210         }
211
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);
221         }
222
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);
229         }
230
231   #else
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)));
236         }
237   #endif
238
239       }
240   #if defined(USE_MMX)
241       _mm_empty();
242   #endif
243     }
244
245    private:
246     void update_accumulator(const Position& pos, const Color perspective) const {
247
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>;
253
254   #ifdef VECTOR
255       // Gcc-10.2 unnecessarily spills AVX2 registers if this array
256       // is defined in the VECTOR code below, once in each branch
257       vec_t acc[NumRegs];
258   #endif
259
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)
265       {
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)
270           break;
271         next = st;
272         st = st->previous;
273       }
274
275       if (st->accumulator.state[perspective] == COMPUTED)
276       {
277         if (next == nullptr)
278           return;
279
280         // Update incrementally in two steps. First, we update the "next"
281         // accumulator. Then, we update the current accumulator (pos.state()).
282
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]);
291
292         // Mark the accumulators as computed.
293         next->accumulator.state[perspective] = COMPUTED;
294         pos.state()->accumulator.state[perspective] = COMPUTED;
295
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 };
299   #ifdef VECTOR
300         for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
301         {
302           // Load accumulator
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]);
307
308           for (IndexType i = 0; states_to_update[i]; ++i)
309           {
310             // Difference calculation for the deactivated features
311             for (const auto index : removed[i])
312             {
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]);
317             }
318
319             // Difference calculation for the activated features
320             for (const auto index : added[i])
321             {
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]);
326             }
327
328             // Store accumulator
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]);
333           }
334         }
335
336   #else
337         for (IndexType i = 0; states_to_update[i]; ++i)
338         {
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];
343
344           // Difference calculation for the deactivated features
345           for (const auto index : removed[i])
346           {
347             const IndexType offset = HalfDimensions * index;
348
349             for (IndexType j = 0; j < HalfDimensions; ++j)
350               st->accumulator.accumulation[perspective][j] -= weights[offset + j];
351           }
352
353           // Difference calculation for the activated features
354           for (const auto index : added[i])
355           {
356             const IndexType offset = HalfDimensions * index;
357
358             for (IndexType j = 0; j < HalfDimensions; ++j)
359               st->accumulator.accumulation[perspective][j] += weights[offset + j];
360           }
361         }
362   #endif
363       }
364       else
365       {
366         // Refresh the accumulator
367         auto& accumulator = pos.state()->accumulator;
368         accumulator.state[perspective] = COMPUTED;
369         IndexList active;
370         FeatureSet::append_active_indices(pos, perspective, active);
371
372   #ifdef VECTOR
373         for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
374         {
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];
379
380           for (const auto index : active)
381           {
382             const IndexType offset = HalfDimensions * index + j * TileHeight;
383             auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
384
385             for (unsigned k = 0; k < NumRegs; ++k)
386               acc[k] = vec_add_16(acc[k], column[k]);
387           }
388
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]);
393         }
394
395   #else
396         std::memcpy(accumulator.accumulation[perspective], biases,
397             HalfDimensions * sizeof(BiasType));
398
399         for (const auto index : active)
400         {
401           const IndexType offset = HalfDimensions * index;
402
403           for (IndexType j = 0; j < HalfDimensions; ++j)
404             accumulator.accumulation[perspective][j] += weights[offset + j];
405         }
406   #endif
407       }
408
409   #if defined(USE_MMX)
410       _mm_empty();
411   #endif
412     }
413
414     using BiasType = std::int16_t;
415     using WeightType = std::int16_t;
416
417     alignas(CacheLineSize) BiasType biases[HalfDimensions];
418     alignas(CacheLineSize) WeightType weights[HalfDimensions * InputDimensions];
419   };
420
421 }  // namespace Stockfish::Eval::NNUE
422
423 #endif // #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED