]> git.sesse.net Git - stockfish/blob - src/nnue/nnue_feature_transformer.h
f49777b50bbe3f6809acd358399ae9b5dbf1bda1
[stockfish] / src / nnue / nnue_feature_transformer.h
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2020 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 #include "features/index_list.h"
27
28 #include <cstring> // std::memset()
29
30 namespace Eval::NNUE {
31
32   // If vector instructions are enabled, we update and refresh the
33   // accumulator tile by tile such that each tile fits in the CPU's
34   // vector registers.
35   #define VECTOR
36
37   #ifdef USE_AVX512
38   typedef __m512i vec_t;
39   #define vec_load(a) _mm512_load_si512(a)
40   #define vec_store(a,b) _mm512_store_si512(a,b)
41   #define vec_add_16(a,b) _mm512_add_epi16(a,b)
42   #define vec_sub_16(a,b) _mm512_sub_epi16(a,b)
43   static constexpr IndexType kNumRegs = 8; // only 8 are needed
44
45   #elif USE_AVX2
46   typedef __m256i vec_t;
47   #define vec_load(a) _mm256_load_si256(a)
48   #define vec_store(a,b) _mm256_store_si256(a,b)
49   #define vec_add_16(a,b) _mm256_add_epi16(a,b)
50   #define vec_sub_16(a,b) _mm256_sub_epi16(a,b)
51   static constexpr IndexType kNumRegs = 16;
52
53   #elif USE_SSE2
54   typedef __m128i vec_t;
55   #define vec_load(a) (*(a))
56   #define vec_store(a,b) *(a)=(b)
57   #define vec_add_16(a,b) _mm_add_epi16(a,b)
58   #define vec_sub_16(a,b) _mm_sub_epi16(a,b)
59   static constexpr IndexType kNumRegs = Is64Bit ? 16 : 8;
60
61   #elif USE_MMX
62   typedef __m64 vec_t;
63   #define vec_load(a) (*(a))
64   #define vec_store(a,b) *(a)=(b)
65   #define vec_add_16(a,b) _mm_add_pi16(a,b)
66   #define vec_sub_16(a,b) _mm_sub_pi16(a,b)
67   static constexpr IndexType kNumRegs = 8;
68
69   #elif USE_NEON
70   typedef int16x8_t vec_t;
71   #define vec_load(a) (*(a))
72   #define vec_store(a,b) *(a)=(b)
73   #define vec_add_16(a,b) vaddq_s16(a,b)
74   #define vec_sub_16(a,b) vsubq_s16(a,b)
75   static constexpr IndexType kNumRegs = 16;
76
77   #else
78   #undef VECTOR
79
80   #endif
81
82   // Input feature converter
83   class FeatureTransformer {
84
85    private:
86     // Number of output dimensions for one side
87     static constexpr IndexType kHalfDimensions = kTransformedFeatureDimensions;
88
89     #ifdef VECTOR
90     static constexpr IndexType kTileHeight = kNumRegs * sizeof(vec_t) / 2;
91     static_assert(kHalfDimensions % kTileHeight == 0, "kTileHeight must divide kHalfDimensions");
92     #endif
93
94    public:
95     // Output type
96     using OutputType = TransformedFeatureType;
97
98     // Number of input/output dimensions
99     static constexpr IndexType kInputDimensions = RawFeatures::kDimensions;
100     static constexpr IndexType kOutputDimensions = kHalfDimensions * 2;
101
102     // Size of forward propagation buffer
103     static constexpr std::size_t kBufferSize =
104         kOutputDimensions * sizeof(OutputType);
105
106     // Hash value embedded in the evaluation file
107     static constexpr std::uint32_t GetHashValue() {
108
109       return RawFeatures::kHashValue ^ kOutputDimensions;
110     }
111
112     // Read network parameters
113     bool ReadParameters(std::istream& stream) {
114
115       for (std::size_t i = 0; i < kHalfDimensions; ++i)
116         biases_[i] = read_little_endian<BiasType>(stream);
117       for (std::size_t i = 0; i < kHalfDimensions * kInputDimensions; ++i)
118         weights_[i] = read_little_endian<WeightType>(stream);
119       return !stream.fail();
120     }
121
122     // Convert input features
123     void Transform(const Position& pos, OutputType* output) const {
124
125       UpdateAccumulator(pos, WHITE);
126       UpdateAccumulator(pos, BLACK);
127
128       const auto& accumulation = pos.state()->accumulator.accumulation;
129
130   #if defined(USE_AVX512)
131       constexpr IndexType kNumChunks = kHalfDimensions / (kSimdWidth * 2);
132       static_assert(kHalfDimensions % (kSimdWidth * 2) == 0);
133       const __m512i kControl = _mm512_setr_epi64(0, 2, 4, 6, 1, 3, 5, 7);
134       const __m512i kZero = _mm512_setzero_si512();
135
136   #elif defined(USE_AVX2)
137       constexpr IndexType kNumChunks = kHalfDimensions / kSimdWidth;
138       constexpr int kControl = 0b11011000;
139       const __m256i kZero = _mm256_setzero_si256();
140
141   #elif defined(USE_SSE2)
142       constexpr IndexType kNumChunks = kHalfDimensions / kSimdWidth;
143
144   #ifdef USE_SSE41
145       const __m128i kZero = _mm_setzero_si128();
146   #else
147       const __m128i k0x80s = _mm_set1_epi8(-128);
148   #endif
149
150   #elif defined(USE_MMX)
151       constexpr IndexType kNumChunks = kHalfDimensions / kSimdWidth;
152       const __m64 k0x80s = _mm_set1_pi8(-128);
153
154   #elif defined(USE_NEON)
155       constexpr IndexType kNumChunks = kHalfDimensions / (kSimdWidth / 2);
156       const int8x8_t kZero = {0};
157   #endif
158
159       const Color perspectives[2] = {pos.side_to_move(), ~pos.side_to_move()};
160       for (IndexType p = 0; p < 2; ++p) {
161         const IndexType offset = kHalfDimensions * p;
162
163   #if defined(USE_AVX512)
164         auto out = reinterpret_cast<__m512i*>(&output[offset]);
165         for (IndexType j = 0; j < kNumChunks; ++j) {
166           __m512i sum0 = _mm512_load_si512(
167               &reinterpret_cast<const __m512i*>(accumulation[perspectives[p]][0])[j * 2 + 0]);
168           __m512i sum1 = _mm512_load_si512(
169               &reinterpret_cast<const __m512i*>(accumulation[perspectives[p]][0])[j * 2 + 1]);
170           _mm512_store_si512(&out[j], _mm512_permutexvar_epi64(kControl,
171               _mm512_max_epi8(_mm512_packs_epi16(sum0, sum1), kZero)));
172         }
173
174   #elif defined(USE_AVX2)
175         auto out = reinterpret_cast<__m256i*>(&output[offset]);
176         for (IndexType j = 0; j < kNumChunks; ++j) {
177           __m256i sum0 = _mm256_load_si256(
178               &reinterpret_cast<const __m256i*>(accumulation[perspectives[p]][0])[j * 2 + 0]);
179           __m256i sum1 = _mm256_load_si256(
180               &reinterpret_cast<const __m256i*>(accumulation[perspectives[p]][0])[j * 2 + 1]);
181           _mm256_store_si256(&out[j], _mm256_permute4x64_epi64(_mm256_max_epi8(
182               _mm256_packs_epi16(sum0, sum1), kZero), kControl));
183         }
184
185   #elif defined(USE_SSE2)
186         auto out = reinterpret_cast<__m128i*>(&output[offset]);
187         for (IndexType j = 0; j < kNumChunks; ++j) {
188           __m128i sum0 = _mm_load_si128(&reinterpret_cast<const __m128i*>(
189               accumulation[perspectives[p]][0])[j * 2 + 0]);
190           __m128i sum1 = _mm_load_si128(&reinterpret_cast<const __m128i*>(
191               accumulation[perspectives[p]][0])[j * 2 + 1]);
192       const __m128i packedbytes = _mm_packs_epi16(sum0, sum1);
193
194           _mm_store_si128(&out[j],
195
196   #ifdef USE_SSE41
197               _mm_max_epi8(packedbytes, kZero)
198   #else
199               _mm_subs_epi8(_mm_adds_epi8(packedbytes, k0x80s), k0x80s)
200   #endif
201
202           );
203         }
204
205   #elif defined(USE_MMX)
206         auto out = reinterpret_cast<__m64*>(&output[offset]);
207         for (IndexType j = 0; j < kNumChunks; ++j) {
208           __m64 sum0 = *(&reinterpret_cast<const __m64*>(
209               accumulation[perspectives[p]][0])[j * 2 + 0]);
210           __m64 sum1 = *(&reinterpret_cast<const __m64*>(
211               accumulation[perspectives[p]][0])[j * 2 + 1]);
212           const __m64 packedbytes = _mm_packs_pi16(sum0, sum1);
213           out[j] = _mm_subs_pi8(_mm_adds_pi8(packedbytes, k0x80s), k0x80s);
214         }
215
216   #elif defined(USE_NEON)
217         const auto out = reinterpret_cast<int8x8_t*>(&output[offset]);
218         for (IndexType j = 0; j < kNumChunks; ++j) {
219           int16x8_t sum = reinterpret_cast<const int16x8_t*>(
220               accumulation[perspectives[p]][0])[j];
221           out[j] = vmax_s8(vqmovn_s16(sum), kZero);
222         }
223
224   #else
225         for (IndexType j = 0; j < kHalfDimensions; ++j) {
226           BiasType sum = accumulation[static_cast<int>(perspectives[p])][0][j];
227           output[offset + j] = static_cast<OutputType>(
228               std::max<int>(0, std::min<int>(127, sum)));
229         }
230   #endif
231
232       }
233   #if defined(USE_MMX)
234       _mm_empty();
235   #endif
236     }
237
238    private:
239     void UpdateAccumulator(const Position& pos, const Color c) const {
240
241   #ifdef VECTOR
242       // Gcc-10.2 unnecessarily spills AVX2 registers if this array
243       // is defined in the VECTOR code below, once in each branch
244       vec_t acc[kNumRegs];
245   #endif
246
247       // Look for a usable accumulator of an earlier position. We keep track
248       // of the estimated gain in terms of features to be added/subtracted.
249       StateInfo *st = pos.state(), *next = nullptr;
250       int gain = popcount(pos.pieces()) - 2;
251       while (st->accumulator.state[c] == EMPTY)
252       {
253         auto& dp = st->dirtyPiece;
254         // The first condition tests whether an incremental update is
255         // possible at all: if this side's king has moved, it is not possible.
256         static_assert(std::is_same_v<RawFeatures::SortedTriggerSet,
257               Features::CompileTimeList<Features::TriggerEvent, Features::TriggerEvent::kFriendKingMoved>>,
258               "Current code assumes that only kFriendlyKingMoved refresh trigger is being used.");
259         if (   dp.piece[0] == make_piece(c, KING)
260             || (gain -= dp.dirty_num + 1) < 0)
261           break;
262         next = st;
263         st = st->previous;
264       }
265
266       if (st->accumulator.state[c] == COMPUTED)
267       {
268         if (next == nullptr)
269           return;
270
271         // Update incrementally in two steps. First, we update the "next"
272         // accumulator. Then, we update the current accumulator (pos.state()).
273
274         // Gather all features to be updated. This code assumes HalfKP features
275         // only and doesn't support refresh triggers.
276         static_assert(std::is_same_v<Features::FeatureSet<Features::HalfKP<Features::Side::kFriend>>,
277                                      RawFeatures>);
278         Features::IndexList removed[2], added[2];
279         Features::HalfKP<Features::Side::kFriend>::AppendChangedIndices(pos,
280             next->dirtyPiece, c, &removed[0], &added[0]);
281         for (StateInfo *st2 = pos.state(); st2 != next; st2 = st2->previous)
282           Features::HalfKP<Features::Side::kFriend>::AppendChangedIndices(pos,
283               st2->dirtyPiece, c, &removed[1], &added[1]);
284
285         // Mark the accumulators as computed.
286         next->accumulator.state[c] = COMPUTED;
287         pos.state()->accumulator.state[c] = COMPUTED;
288
289         // Now update the accumulators listed in info[], where the last element is a sentinel.
290         StateInfo *info[3] =
291           { next, next == pos.state() ? nullptr : pos.state(), nullptr };
292   #ifdef VECTOR
293         for (IndexType j = 0; j < kHalfDimensions / kTileHeight; ++j)
294         {
295           // Load accumulator
296           auto accTile = reinterpret_cast<vec_t*>(
297             &st->accumulator.accumulation[c][0][j * kTileHeight]);
298           for (IndexType k = 0; k < kNumRegs; ++k)
299             acc[k] = vec_load(&accTile[k]);
300
301           for (IndexType i = 0; info[i]; ++i)
302           {
303             // Difference calculation for the deactivated features
304             for (const auto index : removed[i])
305             {
306               const IndexType offset = kHalfDimensions * index + j * kTileHeight;
307               auto column = reinterpret_cast<const vec_t*>(&weights_[offset]);
308               for (IndexType k = 0; k < kNumRegs; ++k)
309                 acc[k] = vec_sub_16(acc[k], column[k]);
310             }
311
312             // Difference calculation for the activated features
313             for (const auto index : added[i])
314             {
315               const IndexType offset = kHalfDimensions * index + j * kTileHeight;
316               auto column = reinterpret_cast<const vec_t*>(&weights_[offset]);
317               for (IndexType k = 0; k < kNumRegs; ++k)
318                 acc[k] = vec_add_16(acc[k], column[k]);
319             }
320
321             // Store accumulator
322             accTile = reinterpret_cast<vec_t*>(
323               &info[i]->accumulator.accumulation[c][0][j * kTileHeight]);
324             for (IndexType k = 0; k < kNumRegs; ++k)
325               vec_store(&accTile[k], acc[k]);
326           }
327         }
328
329   #else
330         for (IndexType i = 0; info[i]; ++i)
331         {
332           std::memcpy(info[i]->accumulator.accumulation[c][0],
333               st->accumulator.accumulation[c][0],
334               kHalfDimensions * sizeof(BiasType));
335           st = info[i];
336
337           // Difference calculation for the deactivated features
338           for (const auto index : removed[i])
339           {
340             const IndexType offset = kHalfDimensions * index;
341
342             for (IndexType j = 0; j < kHalfDimensions; ++j)
343               st->accumulator.accumulation[c][0][j] -= weights_[offset + j];
344           }
345
346           // Difference calculation for the activated features
347           for (const auto index : added[i])
348           {
349             const IndexType offset = kHalfDimensions * index;
350
351             for (IndexType j = 0; j < kHalfDimensions; ++j)
352               st->accumulator.accumulation[c][0][j] += weights_[offset + j];
353           }
354         }
355   #endif
356       }
357       else
358       {
359         // Refresh the accumulator
360         auto& accumulator = pos.state()->accumulator;
361         accumulator.state[c] = COMPUTED;
362         Features::IndexList active;
363         Features::HalfKP<Features::Side::kFriend>::AppendActiveIndices(pos, c, &active);
364
365   #ifdef VECTOR
366         for (IndexType j = 0; j < kHalfDimensions / kTileHeight; ++j)
367         {
368           auto biasesTile = reinterpret_cast<const vec_t*>(
369               &biases_[j * kTileHeight]);
370           for (IndexType k = 0; k < kNumRegs; ++k)
371             acc[k] = biasesTile[k];
372
373           for (const auto index : active)
374           {
375             const IndexType offset = kHalfDimensions * index + j * kTileHeight;
376             auto column = reinterpret_cast<const vec_t*>(&weights_[offset]);
377
378             for (unsigned k = 0; k < kNumRegs; ++k)
379               acc[k] = vec_add_16(acc[k], column[k]);
380           }
381
382           auto accTile = reinterpret_cast<vec_t*>(
383               &accumulator.accumulation[c][0][j * kTileHeight]);
384           for (unsigned k = 0; k < kNumRegs; k++)
385             vec_store(&accTile[k], acc[k]);
386         }
387
388   #else
389         std::memcpy(accumulator.accumulation[c][0], biases_,
390             kHalfDimensions * sizeof(BiasType));
391
392         for (const auto index : active)
393         {
394           const IndexType offset = kHalfDimensions * index;
395
396           for (IndexType j = 0; j < kHalfDimensions; ++j)
397             accumulator.accumulation[c][0][j] += weights_[offset + j];
398         }
399   #endif
400       }
401
402   #if defined(USE_MMX)
403       _mm_empty();
404   #endif
405     }
406
407     using BiasType = std::int16_t;
408     using WeightType = std::int16_t;
409
410     alignas(kCacheLineSize) BiasType biases_[kHalfDimensions];
411     alignas(kCacheLineSize)
412         WeightType weights_[kHalfDimensions * kInputDimensions];
413   };
414
415 }  // namespace Eval::NNUE
416
417 #endif // #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED