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