]> git.sesse.net Git - stockfish/blob - src/nnue/nnue_feature_transformer.h
c3f012e412ec2415b726a469d080378b8049526d
[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_AVX2)
131       constexpr IndexType kNumChunks = kHalfDimensions / kSimdWidth;
132       constexpr int kControl = 0b11011000;
133       const __m256i kZero = _mm256_setzero_si256();
134
135   #elif defined(USE_SSE2)
136       constexpr IndexType kNumChunks = kHalfDimensions / kSimdWidth;
137
138   #ifdef USE_SSE41
139       const __m128i kZero = _mm_setzero_si128();
140   #else
141       const __m128i k0x80s = _mm_set1_epi8(-128);
142   #endif
143
144   #elif defined(USE_MMX)
145       constexpr IndexType kNumChunks = kHalfDimensions / kSimdWidth;
146       const __m64 k0x80s = _mm_set1_pi8(-128);
147
148   #elif defined(USE_NEON)
149       constexpr IndexType kNumChunks = kHalfDimensions / (kSimdWidth / 2);
150       const int8x8_t kZero = {0};
151   #endif
152
153       const Color perspectives[2] = {pos.side_to_move(), ~pos.side_to_move()};
154       for (IndexType p = 0; p < 2; ++p) {
155         const IndexType offset = kHalfDimensions * p;
156
157   #if defined(USE_AVX2)
158         auto out = reinterpret_cast<__m256i*>(&output[offset]);
159         for (IndexType j = 0; j < kNumChunks; ++j) {
160           __m256i sum0 = _mm256_load_si256(
161               &reinterpret_cast<const __m256i*>(accumulation[perspectives[p]][0])[j * 2 + 0]);
162           __m256i sum1 = _mm256_load_si256(
163             &reinterpret_cast<const __m256i*>(accumulation[perspectives[p]][0])[j * 2 + 1]);
164           _mm256_store_si256(&out[j], _mm256_permute4x64_epi64(_mm256_max_epi8(
165               _mm256_packs_epi16(sum0, sum1), kZero), kControl));
166         }
167
168   #elif defined(USE_SSE2)
169         auto out = reinterpret_cast<__m128i*>(&output[offset]);
170         for (IndexType j = 0; j < kNumChunks; ++j) {
171           __m128i sum0 = _mm_load_si128(&reinterpret_cast<const __m128i*>(
172               accumulation[perspectives[p]][0])[j * 2 + 0]);
173           __m128i sum1 = _mm_load_si128(&reinterpret_cast<const __m128i*>(
174               accumulation[perspectives[p]][0])[j * 2 + 1]);
175       const __m128i packedbytes = _mm_packs_epi16(sum0, sum1);
176
177           _mm_store_si128(&out[j],
178
179   #ifdef USE_SSE41
180             _mm_max_epi8(packedbytes, kZero)
181   #else
182             _mm_subs_epi8(_mm_adds_epi8(packedbytes, k0x80s), k0x80s)
183   #endif
184
185           );
186         }
187
188   #elif defined(USE_MMX)
189         auto out = reinterpret_cast<__m64*>(&output[offset]);
190         for (IndexType j = 0; j < kNumChunks; ++j) {
191           __m64 sum0 = *(&reinterpret_cast<const __m64*>(
192               accumulation[perspectives[p]][0])[j * 2 + 0]);
193           __m64 sum1 = *(&reinterpret_cast<const __m64*>(
194               accumulation[perspectives[p]][0])[j * 2 + 1]);
195           const __m64 packedbytes = _mm_packs_pi16(sum0, sum1);
196           out[j] = _mm_subs_pi8(_mm_adds_pi8(packedbytes, k0x80s), k0x80s);
197         }
198
199   #elif defined(USE_NEON)
200         const auto out = reinterpret_cast<int8x8_t*>(&output[offset]);
201         for (IndexType j = 0; j < kNumChunks; ++j) {
202           int16x8_t sum = reinterpret_cast<const int16x8_t*>(
203               accumulation[perspectives[p]][0])[j];
204           out[j] = vmax_s8(vqmovn_s16(sum), kZero);
205         }
206
207   #else
208         for (IndexType j = 0; j < kHalfDimensions; ++j) {
209           BiasType sum = accumulation[static_cast<int>(perspectives[p])][0][j];
210           output[offset + j] = static_cast<OutputType>(
211               std::max<int>(0, std::min<int>(127, sum)));
212         }
213   #endif
214
215       }
216   #if defined(USE_MMX)
217       _mm_empty();
218   #endif
219     }
220
221    private:
222     void UpdateAccumulator(const Position& pos, const Color c) const {
223
224   #ifdef VECTOR
225       // Gcc-10.2 unnecessarily spills AVX2 registers if this array
226       // is defined in the VECTOR code below, once in each branch
227       vec_t acc[kNumRegs];
228   #endif
229
230       // Look for a usable accumulator of an earlier position. We keep track
231       // of the estimated gain in terms of features to be added/subtracted.
232       StateInfo *st = pos.state(), *next = nullptr;
233       int gain = popcount(pos.pieces()) - 2;
234       while (st->accumulator.state[c] == EMPTY)
235       {
236         auto& dp = st->dirtyPiece;
237         // The first condition tests whether an incremental update is
238         // possible at all: if this side's king has moved, it is not possible.
239         static_assert(std::is_same_v<RawFeatures::SortedTriggerSet,
240               Features::CompileTimeList<Features::TriggerEvent, Features::TriggerEvent::kFriendKingMoved>>,
241               "Current code assumes that only kFriendlyKingMoved refresh trigger is being used.");
242         if (   dp.piece[0] == make_piece(c, KING)
243             || (gain -= dp.dirty_num + 1) < 0)
244           break;
245         next = st;
246         st = st->previous;
247       }
248
249       if (st->accumulator.state[c] == COMPUTED)
250       {
251         if (next == nullptr)
252           return;
253
254         // Update incrementally in two steps. First, we update the "next"
255         // accumulator. Then, we update the current accumulator (pos.state()).
256
257         // Gather all features to be updated. This code assumes HalfKP features
258         // only and doesn't support refresh triggers.
259         static_assert(std::is_same_v<Features::FeatureSet<Features::HalfKP<Features::Side::kFriend>>,
260                                      RawFeatures>);
261         Features::IndexList removed[2], added[2];
262         Features::HalfKP<Features::Side::kFriend>::AppendChangedIndices(pos,
263             next->dirtyPiece, c, &removed[0], &added[0]);
264         for (StateInfo *st2 = pos.state(); st2 != next; st2 = st2->previous)
265           Features::HalfKP<Features::Side::kFriend>::AppendChangedIndices(pos,
266               st2->dirtyPiece, c, &removed[1], &added[1]);
267
268         // Mark the accumulators as computed.
269         next->accumulator.state[c] = COMPUTED;
270         pos.state()->accumulator.state[c] = COMPUTED;
271
272         // Now update the accumulators listed in info[], where the last element is a sentinel.
273         StateInfo *info[3] =
274           { next, next == pos.state() ? nullptr : pos.state(), nullptr };
275   #ifdef VECTOR
276         for (IndexType j = 0; j < kHalfDimensions / kTileHeight; ++j)
277         {
278           // Load accumulator
279           auto accTile = reinterpret_cast<vec_t*>(
280             &st->accumulator.accumulation[c][0][j * kTileHeight]);
281           for (IndexType k = 0; k < kNumRegs; ++k)
282             acc[k] = vec_load(&accTile[k]);
283
284           for (IndexType i = 0; info[i]; ++i)
285           {
286             // Difference calculation for the deactivated features
287             for (const auto index : removed[i])
288             {
289               const IndexType offset = kHalfDimensions * index + j * kTileHeight;
290               auto column = reinterpret_cast<const vec_t*>(&weights_[offset]);
291               for (IndexType k = 0; k < kNumRegs; ++k)
292                 acc[k] = vec_sub_16(acc[k], column[k]);
293             }
294
295             // Difference calculation for the activated features
296             for (const auto index : added[i])
297             {
298               const IndexType offset = kHalfDimensions * index + j * kTileHeight;
299               auto column = reinterpret_cast<const vec_t*>(&weights_[offset]);
300               for (IndexType k = 0; k < kNumRegs; ++k)
301                 acc[k] = vec_add_16(acc[k], column[k]);
302             }
303
304             // Store accumulator
305             accTile = reinterpret_cast<vec_t*>(
306               &info[i]->accumulator.accumulation[c][0][j * kTileHeight]);
307             for (IndexType k = 0; k < kNumRegs; ++k)
308               vec_store(&accTile[k], acc[k]);
309           }
310         }
311
312   #else
313         for (IndexType i = 0; info[i]; ++i)
314         {
315           std::memcpy(info[i]->accumulator.accumulation[c][0],
316               st->accumulator.accumulation[c][0],
317               kHalfDimensions * sizeof(BiasType));
318           st = info[i];
319
320           // Difference calculation for the deactivated features
321           for (const auto index : removed[i])
322           {
323             const IndexType offset = kHalfDimensions * index;
324
325             for (IndexType j = 0; j < kHalfDimensions; ++j)
326               st->accumulator.accumulation[c][0][j] -= weights_[offset + j];
327           }
328
329           // Difference calculation for the activated features
330           for (const auto index : added[i])
331           {
332             const IndexType offset = kHalfDimensions * index;
333
334             for (IndexType j = 0; j < kHalfDimensions; ++j)
335               st->accumulator.accumulation[c][0][j] += weights_[offset + j];
336           }
337         }
338   #endif
339       }
340       else
341       {
342         // Refresh the accumulator
343         auto& accumulator = pos.state()->accumulator;
344         accumulator.state[c] = COMPUTED;
345         Features::IndexList active;
346         Features::HalfKP<Features::Side::kFriend>::AppendActiveIndices(pos, c, &active);
347
348   #ifdef VECTOR
349         for (IndexType j = 0; j < kHalfDimensions / kTileHeight; ++j)
350         {
351           auto biasesTile = reinterpret_cast<const vec_t*>(
352               &biases_[j * kTileHeight]);
353           for (IndexType k = 0; k < kNumRegs; ++k)
354             acc[k] = biasesTile[k];
355
356           for (const auto index : active)
357           {
358             const IndexType offset = kHalfDimensions * index + j * kTileHeight;
359             auto column = reinterpret_cast<const vec_t*>(&weights_[offset]);
360
361             for (unsigned k = 0; k < kNumRegs; ++k)
362               acc[k] = vec_add_16(acc[k], column[k]);
363           }
364
365           auto accTile = reinterpret_cast<vec_t*>(
366               &accumulator.accumulation[c][0][j * kTileHeight]);
367           for (unsigned k = 0; k < kNumRegs; k++)
368             vec_store(&accTile[k], acc[k]);
369         }
370
371   #else
372         std::memcpy(accumulator.accumulation[c][0], biases_,
373             kHalfDimensions * sizeof(BiasType));
374
375         for (const auto index : active)
376         {
377           const IndexType offset = kHalfDimensions * index;
378
379           for (IndexType j = 0; j < kHalfDimensions; ++j)
380             accumulator.accumulation[c][0][j] += weights_[offset + j];
381         }
382   #endif
383       }
384
385   #if defined(USE_MMX)
386       _mm_empty();
387   #endif
388     }
389
390     using BiasType = std::int16_t;
391     using WeightType = std::int16_t;
392
393     alignas(kCacheLineSize) BiasType biases_[kHalfDimensions];
394     alignas(kCacheLineSize)
395         WeightType weights_[kHalfDimensions * kInputDimensions];
396   };
397
398 }  // namespace Eval::NNUE
399
400 #endif // #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED