Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
official-stockfish
GitHub Repository: official-stockfish/Stockfish
Path: blob/master/src/nnue/network.cpp
630 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
#include "network.h"
20
21
#include <cstdlib>
22
#include <fstream>
23
#include <iostream>
24
#include <optional>
25
#include <type_traits>
26
#include <vector>
27
28
#define INCBIN_SILENCE_BITCODE_WARNING
29
#include "../incbin/incbin.h"
30
31
#include "../evaluate.h"
32
#include "../misc.h"
33
#include "../position.h"
34
#include "../types.h"
35
#include "nnue_architecture.h"
36
#include "nnue_common.h"
37
#include "nnue_misc.h"
38
39
// Macro to embed the default efficiently updatable neural network (NNUE) file
40
// data in the engine binary (using incbin.h, by Dale Weiler).
41
// This macro invocation will declare the following three variables
42
// const unsigned char gEmbeddedNNUEData[]; // a pointer to the embedded data
43
// const unsigned char *const gEmbeddedNNUEEnd; // a marker to the end
44
// const unsigned int gEmbeddedNNUESize; // the size of the embedded file
45
// Note that this does not work in Microsoft Visual Studio.
46
#if !defined(_MSC_VER) && !defined(NNUE_EMBEDDING_OFF)
47
INCBIN(EmbeddedNNUEBig, EvalFileDefaultNameBig);
48
INCBIN(EmbeddedNNUESmall, EvalFileDefaultNameSmall);
49
#else
50
const unsigned char gEmbeddedNNUEBigData[1] = {0x0};
51
const unsigned char* const gEmbeddedNNUEBigEnd = &gEmbeddedNNUEBigData[1];
52
const unsigned int gEmbeddedNNUEBigSize = 1;
53
const unsigned char gEmbeddedNNUESmallData[1] = {0x0};
54
const unsigned char* const gEmbeddedNNUESmallEnd = &gEmbeddedNNUESmallData[1];
55
const unsigned int gEmbeddedNNUESmallSize = 1;
56
#endif
57
58
namespace {
59
60
struct EmbeddedNNUE {
61
EmbeddedNNUE(const unsigned char* embeddedData,
62
const unsigned char* embeddedEnd,
63
const unsigned int embeddedSize) :
64
data(embeddedData),
65
end(embeddedEnd),
66
size(embeddedSize) {}
67
const unsigned char* data;
68
const unsigned char* end;
69
const unsigned int size;
70
};
71
72
using namespace Stockfish::Eval::NNUE;
73
74
EmbeddedNNUE get_embedded(EmbeddedNNUEType type) {
75
if (type == EmbeddedNNUEType::BIG)
76
return EmbeddedNNUE(gEmbeddedNNUEBigData, gEmbeddedNNUEBigEnd, gEmbeddedNNUEBigSize);
77
else
78
return EmbeddedNNUE(gEmbeddedNNUESmallData, gEmbeddedNNUESmallEnd, gEmbeddedNNUESmallSize);
79
}
80
81
}
82
83
84
namespace Stockfish::Eval::NNUE {
85
86
87
namespace Detail {
88
89
// Read evaluation function parameters
90
template<typename T>
91
bool read_parameters(std::istream& stream, T& reference) {
92
93
std::uint32_t header;
94
header = read_little_endian<std::uint32_t>(stream);
95
if (!stream || header != T::get_hash_value())
96
return false;
97
return reference.read_parameters(stream);
98
}
99
100
// Write evaluation function parameters
101
template<typename T>
102
bool write_parameters(std::ostream& stream, const T& reference) {
103
104
write_little_endian<std::uint32_t>(stream, T::get_hash_value());
105
return reference.write_parameters(stream);
106
}
107
108
} // namespace Detail
109
110
template<typename Arch, typename Transformer>
111
void Network<Arch, Transformer>::load(const std::string& rootDirectory, std::string evalfilePath) {
112
#if defined(DEFAULT_NNUE_DIRECTORY)
113
std::vector<std::string> dirs = {"<internal>", "", rootDirectory,
114
stringify(DEFAULT_NNUE_DIRECTORY)};
115
#else
116
std::vector<std::string> dirs = {"<internal>", "", rootDirectory};
117
#endif
118
119
if (evalfilePath.empty())
120
evalfilePath = evalFile.defaultName;
121
122
for (const auto& directory : dirs)
123
{
124
if (std::string(evalFile.current) != evalfilePath)
125
{
126
if (directory != "<internal>")
127
{
128
load_user_net(directory, evalfilePath);
129
}
130
131
if (directory == "<internal>" && evalfilePath == std::string(evalFile.defaultName))
132
{
133
load_internal();
134
}
135
}
136
}
137
}
138
139
140
template<typename Arch, typename Transformer>
141
bool Network<Arch, Transformer>::save(const std::optional<std::string>& filename) const {
142
std::string actualFilename;
143
std::string msg;
144
145
if (filename.has_value())
146
actualFilename = filename.value();
147
else
148
{
149
if (std::string(evalFile.current) != std::string(evalFile.defaultName))
150
{
151
msg = "Failed to export a net. "
152
"A non-embedded net can only be saved if the filename is specified";
153
154
sync_cout << msg << sync_endl;
155
return false;
156
}
157
158
actualFilename = evalFile.defaultName;
159
}
160
161
std::ofstream stream(actualFilename, std::ios_base::binary);
162
bool saved = save(stream, evalFile.current, evalFile.netDescription);
163
164
msg = saved ? "Network saved successfully to " + actualFilename : "Failed to export a net";
165
166
sync_cout << msg << sync_endl;
167
return saved;
168
}
169
170
171
template<typename Arch, typename Transformer>
172
NetworkOutput
173
Network<Arch, Transformer>::evaluate(const Position& pos,
174
AccumulatorStack& accumulatorStack,
175
AccumulatorCaches::Cache<FTDimensions>& cache) const {
176
177
constexpr uint64_t alignment = CacheLineSize;
178
179
alignas(alignment)
180
TransformedFeatureType transformedFeatures[FeatureTransformer<FTDimensions>::BufferSize];
181
182
ASSERT_ALIGNED(transformedFeatures, alignment);
183
184
const int bucket = (pos.count<ALL_PIECES>() - 1) / 4;
185
const auto psqt =
186
featureTransformer.transform(pos, accumulatorStack, cache, transformedFeatures, bucket);
187
const auto positional = network[bucket].propagate(transformedFeatures);
188
return {static_cast<Value>(psqt / OutputScale), static_cast<Value>(positional / OutputScale)};
189
}
190
191
192
template<typename Arch, typename Transformer>
193
void Network<Arch, Transformer>::verify(std::string evalfilePath,
194
const std::function<void(std::string_view)>& f) const {
195
if (evalfilePath.empty())
196
evalfilePath = evalFile.defaultName;
197
198
if (std::string(evalFile.current) != evalfilePath)
199
{
200
if (f)
201
{
202
std::string msg1 =
203
"Network evaluation parameters compatible with the engine must be available.";
204
std::string msg2 = "The network file " + evalfilePath + " was not loaded successfully.";
205
std::string msg3 = "The UCI option EvalFile might need to specify the full path, "
206
"including the directory name, to the network file.";
207
std::string msg4 = "The default net can be downloaded from: "
208
"https://tests.stockfishchess.org/api/nn/"
209
+ std::string(evalFile.defaultName);
210
std::string msg5 = "The engine will be terminated now.";
211
212
std::string msg = "ERROR: " + msg1 + '\n' + "ERROR: " + msg2 + '\n' + "ERROR: " + msg3
213
+ '\n' + "ERROR: " + msg4 + '\n' + "ERROR: " + msg5 + '\n';
214
215
f(msg);
216
}
217
218
exit(EXIT_FAILURE);
219
}
220
221
if (f)
222
{
223
size_t size = sizeof(featureTransformer) + sizeof(Arch) * LayerStacks;
224
f("NNUE evaluation using " + evalfilePath + " (" + std::to_string(size / (1024 * 1024))
225
+ "MiB, (" + std::to_string(featureTransformer.TotalInputDimensions) + ", "
226
+ std::to_string(network[0].TransformedFeatureDimensions) + ", "
227
+ std::to_string(network[0].FC_0_OUTPUTS) + ", " + std::to_string(network[0].FC_1_OUTPUTS)
228
+ ", 1))");
229
}
230
}
231
232
233
template<typename Arch, typename Transformer>
234
NnueEvalTrace
235
Network<Arch, Transformer>::trace_evaluate(const Position& pos,
236
AccumulatorStack& accumulatorStack,
237
AccumulatorCaches::Cache<FTDimensions>& cache) const {
238
239
constexpr uint64_t alignment = CacheLineSize;
240
241
alignas(alignment)
242
TransformedFeatureType transformedFeatures[FeatureTransformer<FTDimensions>::BufferSize];
243
244
ASSERT_ALIGNED(transformedFeatures, alignment);
245
246
NnueEvalTrace t{};
247
t.correctBucket = (pos.count<ALL_PIECES>() - 1) / 4;
248
for (IndexType bucket = 0; bucket < LayerStacks; ++bucket)
249
{
250
const auto materialist =
251
featureTransformer.transform(pos, accumulatorStack, cache, transformedFeatures, bucket);
252
const auto positional = network[bucket].propagate(transformedFeatures);
253
254
t.psqt[bucket] = static_cast<Value>(materialist / OutputScale);
255
t.positional[bucket] = static_cast<Value>(positional / OutputScale);
256
}
257
258
return t;
259
}
260
261
262
template<typename Arch, typename Transformer>
263
void Network<Arch, Transformer>::load_user_net(const std::string& dir,
264
const std::string& evalfilePath) {
265
std::ifstream stream(dir + evalfilePath, std::ios::binary);
266
auto description = load(stream);
267
268
if (description.has_value())
269
{
270
evalFile.current = evalfilePath;
271
evalFile.netDescription = description.value();
272
}
273
}
274
275
276
template<typename Arch, typename Transformer>
277
void Network<Arch, Transformer>::load_internal() {
278
// C++ way to prepare a buffer for a memory stream
279
class MemoryBuffer: public std::basic_streambuf<char> {
280
public:
281
MemoryBuffer(char* p, size_t n) {
282
setg(p, p, p + n);
283
setp(p, p + n);
284
}
285
};
286
287
const auto embedded = get_embedded(embeddedType);
288
289
MemoryBuffer buffer(const_cast<char*>(reinterpret_cast<const char*>(embedded.data)),
290
size_t(embedded.size));
291
292
std::istream stream(&buffer);
293
auto description = load(stream);
294
295
if (description.has_value())
296
{
297
evalFile.current = evalFile.defaultName;
298
evalFile.netDescription = description.value();
299
}
300
}
301
302
303
template<typename Arch, typename Transformer>
304
void Network<Arch, Transformer>::initialize() {
305
initialized = true;
306
}
307
308
309
template<typename Arch, typename Transformer>
310
bool Network<Arch, Transformer>::save(std::ostream& stream,
311
const std::string& name,
312
const std::string& netDescription) const {
313
if (name.empty() || name == "None")
314
return false;
315
316
return write_parameters(stream, netDescription);
317
}
318
319
320
template<typename Arch, typename Transformer>
321
std::optional<std::string> Network<Arch, Transformer>::load(std::istream& stream) {
322
initialize();
323
std::string description;
324
325
return read_parameters(stream, description) ? std::make_optional(description) : std::nullopt;
326
}
327
328
329
template<typename Arch, typename Transformer>
330
std::size_t Network<Arch, Transformer>::get_content_hash() const {
331
if (!initialized)
332
return 0;
333
334
std::size_t h = 0;
335
hash_combine(h, featureTransformer);
336
for (auto&& layerstack : network)
337
hash_combine(h, layerstack);
338
hash_combine(h, evalFile);
339
hash_combine(h, static_cast<int>(embeddedType));
340
return h;
341
}
342
343
// Read network header
344
template<typename Arch, typename Transformer>
345
bool Network<Arch, Transformer>::read_header(std::istream& stream,
346
std::uint32_t* hashValue,
347
std::string* desc) const {
348
std::uint32_t version, size;
349
350
version = read_little_endian<std::uint32_t>(stream);
351
*hashValue = read_little_endian<std::uint32_t>(stream);
352
size = read_little_endian<std::uint32_t>(stream);
353
if (!stream || version != Version)
354
return false;
355
desc->resize(size);
356
stream.read(&(*desc)[0], size);
357
return !stream.fail();
358
}
359
360
361
// Write network header
362
template<typename Arch, typename Transformer>
363
bool Network<Arch, Transformer>::write_header(std::ostream& stream,
364
std::uint32_t hashValue,
365
const std::string& desc) const {
366
write_little_endian<std::uint32_t>(stream, Version);
367
write_little_endian<std::uint32_t>(stream, hashValue);
368
write_little_endian<std::uint32_t>(stream, std::uint32_t(desc.size()));
369
stream.write(&desc[0], desc.size());
370
return !stream.fail();
371
}
372
373
374
template<typename Arch, typename Transformer>
375
bool Network<Arch, Transformer>::read_parameters(std::istream& stream,
376
std::string& netDescription) {
377
std::uint32_t hashValue;
378
if (!read_header(stream, &hashValue, &netDescription))
379
return false;
380
if (hashValue != Network::hash)
381
return false;
382
if (!Detail::read_parameters(stream, featureTransformer))
383
return false;
384
for (std::size_t i = 0; i < LayerStacks; ++i)
385
{
386
if (!Detail::read_parameters(stream, network[i]))
387
return false;
388
}
389
return stream && stream.peek() == std::ios::traits_type::eof();
390
}
391
392
393
template<typename Arch, typename Transformer>
394
bool Network<Arch, Transformer>::write_parameters(std::ostream& stream,
395
const std::string& netDescription) const {
396
if (!write_header(stream, Network::hash, netDescription))
397
return false;
398
if (!Detail::write_parameters(stream, featureTransformer))
399
return false;
400
for (std::size_t i = 0; i < LayerStacks; ++i)
401
{
402
if (!Detail::write_parameters(stream, network[i]))
403
return false;
404
}
405
return bool(stream);
406
}
407
408
// Explicit template instantiations
409
410
template class Network<NetworkArchitecture<TransformedFeatureDimensionsBig, L2Big, L3Big>,
411
FeatureTransformer<TransformedFeatureDimensionsBig>>;
412
413
template class Network<NetworkArchitecture<TransformedFeatureDimensionsSmall, L2Small, L3Small>,
414
FeatureTransformer<TransformedFeatureDimensionsSmall>>;
415
416
} // namespace Stockfish::Eval::NNUE
417
418