Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
official-stockfish
GitHub Repository: official-stockfish/Stockfish
Path: blob/master/src/nnue/layers/affine_transform.h
637 views
1
/*
2
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
Copyright (C) 2004-2026 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
// Definition of layer AffineTransform of NNUE evaluation function
20
21
#ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED
22
#define NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED
23
24
#include <cstdint>
25
#include <iostream>
26
27
#include "../../memory.h"
28
#include "../nnue_common.h"
29
#include "../simd.h"
30
31
/*
32
This file contains the definition for a fully connected layer (aka affine transform).
33
34
- expected use-case is for when PaddedInputDimensions == 32 and InputDimensions <= 32.
35
- that's why AVX512 is hard to implement
36
- expected use-case is small layers
37
- inputs are processed in chunks of 4, weights are respectively transposed
38
- accumulation happens directly to int32s
39
*/
40
41
namespace Stockfish::Eval::NNUE::Layers {
42
43
#if defined(USE_SSSE3) || defined(USE_NEON_DOTPROD)
44
#define ENABLE_SEQ_OPT
45
#endif
46
47
// Fallback implementation for older/other architectures.
48
// Requires the input to be padded to at least 16 values.
49
#ifndef ENABLE_SEQ_OPT
50
51
template<IndexType InputDimensions, IndexType PaddedInputDimensions, IndexType OutputDimensions>
52
static void affine_transform_non_ssse3(std::int32_t* output,
53
const std::int8_t* weights,
54
const std::int32_t* biases,
55
const std::uint8_t* input) {
56
#if defined(USE_SSE2) || defined(USE_NEON)
57
#if defined(USE_SSE2)
58
// At least a multiple of 16, with SSE2.
59
constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;
60
const __m128i Zeros = _mm_setzero_si128();
61
const auto inputVector = reinterpret_cast<const __m128i*>(input);
62
63
#elif defined(USE_NEON)
64
constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;
65
const auto inputVector = reinterpret_cast<const int8x8_t*>(input);
66
#endif
67
68
for (IndexType i = 0; i < OutputDimensions; ++i)
69
{
70
const IndexType offset = i * PaddedInputDimensions;
71
72
#if defined(USE_SSE2)
73
__m128i sumLo = _mm_cvtsi32_si128(biases[i]);
74
__m128i sumHi = Zeros;
75
const auto row = reinterpret_cast<const __m128i*>(&weights[offset]);
76
for (IndexType j = 0; j < NumChunks; ++j)
77
{
78
__m128i row_j = _mm_load_si128(&row[j]);
79
__m128i input_j = _mm_load_si128(&inputVector[j]);
80
__m128i extendedRowLo = _mm_srai_epi16(_mm_unpacklo_epi8(row_j, row_j), 8);
81
__m128i extendedRowHi = _mm_srai_epi16(_mm_unpackhi_epi8(row_j, row_j), 8);
82
__m128i extendedInputLo = _mm_unpacklo_epi8(input_j, Zeros);
83
__m128i extendedInputHi = _mm_unpackhi_epi8(input_j, Zeros);
84
__m128i productLo = _mm_madd_epi16(extendedRowLo, extendedInputLo);
85
__m128i productHi = _mm_madd_epi16(extendedRowHi, extendedInputHi);
86
sumLo = _mm_add_epi32(sumLo, productLo);
87
sumHi = _mm_add_epi32(sumHi, productHi);
88
}
89
__m128i sum = _mm_add_epi32(sumLo, sumHi);
90
__m128i sumHigh_64 = _mm_shuffle_epi32(sum, _MM_SHUFFLE(1, 0, 3, 2));
91
sum = _mm_add_epi32(sum, sumHigh_64);
92
__m128i sum_second_32 = _mm_shufflelo_epi16(sum, _MM_SHUFFLE(1, 0, 3, 2));
93
sum = _mm_add_epi32(sum, sum_second_32);
94
output[i] = _mm_cvtsi128_si32(sum);
95
96
#elif defined(USE_NEON)
97
98
int32x4_t sum = {biases[i]};
99
const auto row = reinterpret_cast<const SIMD::vec_i8x8_t*>(&weights[offset]);
100
for (IndexType j = 0; j < NumChunks; ++j)
101
{
102
int16x8_t product = vmull_s8(inputVector[j * 2], row[j * 2]);
103
product = vmlal_s8(product, inputVector[j * 2 + 1], row[j * 2 + 1]);
104
sum = vpadalq_s16(sum, product);
105
}
106
output[i] = SIMD::neon_m128_reduce_add_epi32(sum);
107
108
#endif
109
}
110
#else
111
std::memcpy(output, biases, sizeof(std::int32_t) * OutputDimensions);
112
113
// Traverse weights in transpose order to take advantage of input sparsity
114
for (IndexType i = 0; i < InputDimensions; ++i)
115
if (input[i])
116
{
117
const std::int8_t* w = &weights[i];
118
const int in = input[i];
119
for (IndexType j = 0; j < OutputDimensions; ++j)
120
output[j] += w[j * PaddedInputDimensions] * in;
121
}
122
#endif
123
}
124
125
#endif // !ENABLE_SEQ_OPT
126
127
template<IndexType InDims, IndexType OutDims>
128
class AffineTransform {
129
public:
130
// Input/output type
131
using InputType = std::uint8_t;
132
using OutputType = std::int32_t;
133
134
// Number of input/output dimensions
135
static constexpr IndexType InputDimensions = InDims;
136
static constexpr IndexType OutputDimensions = OutDims;
137
138
static constexpr IndexType PaddedInputDimensions =
139
ceil_to_multiple<IndexType>(InputDimensions, MaxSimdWidth);
140
static constexpr IndexType PaddedOutputDimensions =
141
ceil_to_multiple<IndexType>(OutputDimensions, MaxSimdWidth);
142
143
using OutputBuffer = OutputType[PaddedOutputDimensions];
144
145
// Hash value embedded in the evaluation file
146
static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {
147
std::uint32_t hashValue = 0xCC03DAE4u;
148
hashValue += OutputDimensions;
149
hashValue ^= prevHash >> 1;
150
hashValue ^= prevHash << 31;
151
return hashValue;
152
}
153
154
static constexpr IndexType get_weight_index_scrambled(IndexType i) {
155
return (i / 4) % (PaddedInputDimensions / 4) * OutputDimensions * 4
156
+ i / PaddedInputDimensions * 4 + i % 4;
157
}
158
159
static constexpr IndexType get_weight_index(IndexType i) {
160
#ifdef ENABLE_SEQ_OPT
161
return get_weight_index_scrambled(i);
162
#else
163
return i;
164
#endif
165
}
166
167
// Read network parameters
168
bool read_parameters(std::istream& stream) {
169
read_little_endian<BiasType>(stream, biases, OutputDimensions);
170
for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
171
weights[get_weight_index(i)] = read_little_endian<WeightType>(stream);
172
173
return !stream.fail();
174
}
175
176
// Write network parameters
177
bool write_parameters(std::ostream& stream) const {
178
write_little_endian<BiasType>(stream, biases, OutputDimensions);
179
180
for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
181
write_little_endian<WeightType>(stream, weights[get_weight_index(i)]);
182
183
return !stream.fail();
184
}
185
186
std::size_t get_content_hash() const {
187
std::size_t h = 0;
188
hash_combine(h, get_raw_data_hash(biases));
189
hash_combine(h, get_raw_data_hash(weights));
190
hash_combine(h, get_hash_value(0));
191
return h;
192
}
193
194
// Forward propagation
195
void propagate(const InputType* input, OutputType* output) const {
196
197
#ifdef ENABLE_SEQ_OPT
198
199
if constexpr (OutputDimensions > 1)
200
{
201
#if defined(USE_AVX512)
202
using vec_t = __m512i;
203
#define vec_set_32 _mm512_set1_epi32
204
#define vec_add_dpbusd_32 SIMD::m512_add_dpbusd_epi32
205
#elif defined(USE_AVX2)
206
using vec_t = __m256i;
207
#define vec_set_32 _mm256_set1_epi32
208
#define vec_add_dpbusd_32 SIMD::m256_add_dpbusd_epi32
209
#elif defined(USE_SSSE3)
210
using vec_t = __m128i;
211
#define vec_set_32 _mm_set1_epi32
212
#define vec_add_dpbusd_32 SIMD::m128_add_dpbusd_epi32
213
#elif defined(USE_NEON_DOTPROD)
214
using vec_t = int32x4_t;
215
#define vec_set_32 vdupq_n_s32
216
#define vec_add_dpbusd_32(acc, a, b) \
217
SIMD::dotprod_m128_add_dpbusd_epi32(acc, vreinterpretq_s8_s32(a), \
218
vreinterpretq_s8_s32(b))
219
#endif
220
221
static constexpr IndexType OutputSimdWidth = sizeof(vec_t) / sizeof(OutputType);
222
223
static_assert(OutputDimensions % OutputSimdWidth == 0);
224
225
constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 8) / 4;
226
constexpr IndexType NumRegs = OutputDimensions / OutputSimdWidth;
227
228
const vec_t* biasvec = reinterpret_cast<const vec_t*>(biases);
229
vec_t acc[NumRegs];
230
for (IndexType k = 0; k < NumRegs; ++k)
231
acc[k] = biasvec[k];
232
233
for (IndexType i = 0; i < NumChunks; ++i)
234
{
235
const vec_t in0 =
236
vec_set_32(load_as<std::int32_t>(input + i * sizeof(std::int32_t)));
237
const auto col0 =
238
reinterpret_cast<const vec_t*>(&weights[i * OutputDimensions * 4]);
239
240
for (IndexType k = 0; k < NumRegs; ++k)
241
vec_add_dpbusd_32(acc[k], in0, col0[k]);
242
}
243
244
vec_t* outptr = reinterpret_cast<vec_t*>(output);
245
for (IndexType k = 0; k < NumRegs; ++k)
246
outptr[k] = acc[k];
247
248
#undef vec_set_32
249
#undef vec_add_dpbusd_32
250
}
251
else if constexpr (OutputDimensions == 1)
252
{
253
// We cannot use AVX512 for the last layer because there are only 32 inputs
254
// and the buffer is not padded to 64 elements.
255
#if defined(USE_AVX2)
256
using vec_t = __m256i;
257
#define vec_setzero() _mm256_setzero_si256()
258
#define vec_add_dpbusd_32 SIMD::m256_add_dpbusd_epi32
259
#define vec_hadd SIMD::m256_hadd
260
#elif defined(USE_SSSE3)
261
using vec_t = __m128i;
262
#define vec_setzero() _mm_setzero_si128()
263
#define vec_add_dpbusd_32 SIMD::m128_add_dpbusd_epi32
264
#define vec_hadd SIMD::m128_hadd
265
#elif defined(USE_NEON_DOTPROD)
266
using vec_t = int32x4_t;
267
#define vec_setzero() vdupq_n_s32(0)
268
#define vec_add_dpbusd_32(acc, a, b) \
269
SIMD::dotprod_m128_add_dpbusd_epi32(acc, vreinterpretq_s8_s32(a), \
270
vreinterpretq_s8_s32(b))
271
#define vec_hadd SIMD::neon_m128_hadd
272
#endif
273
274
const auto inputVector = reinterpret_cast<const vec_t*>(input);
275
276
static constexpr IndexType InputSimdWidth = sizeof(vec_t) / sizeof(InputType);
277
278
static_assert(PaddedInputDimensions % InputSimdWidth == 0);
279
280
constexpr IndexType NumChunks = PaddedInputDimensions / InputSimdWidth;
281
vec_t sum0 = vec_setzero();
282
const auto row0 = reinterpret_cast<const vec_t*>(&weights[0]);
283
284
for (int j = 0; j < int(NumChunks); ++j)
285
{
286
const vec_t in = inputVector[j];
287
vec_add_dpbusd_32(sum0, in, row0[j]);
288
}
289
output[0] = vec_hadd(sum0, biases[0]);
290
291
#undef vec_setzero
292
#undef vec_add_dpbusd_32
293
#undef vec_hadd
294
}
295
#else
296
// Use old implementation for the other architectures.
297
affine_transform_non_ssse3<InputDimensions, PaddedInputDimensions, OutputDimensions>(
298
output, weights, biases, input);
299
#endif
300
}
301
302
private:
303
using BiasType = OutputType;
304
using WeightType = std::int8_t;
305
306
alignas(CacheLineSize) BiasType biases[OutputDimensions];
307
alignas(CacheLineSize) WeightType weights[OutputDimensions * PaddedInputDimensions];
308
};
309
310
} // namespace Stockfish::Eval::NNUE::Layers
311
312
#endif // #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED
313
314