2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2022 The Stockfish developers (see AUTHORS file)
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.
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.
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/>.
19 // Code for calculating NNUE evaluation function
27 #include "../evaluate.h"
28 #include "../position.h"
33 #include "evaluate_nnue.h"
35 namespace Stockfish::Eval::NNUE {
37 // Input feature converter
38 LargePagePtr<FeatureTransformer> featureTransformer;
40 // Evaluation function
41 AlignedPtr<Network> network[LayerStacks];
43 // Evaluation function file name
45 std::string netDescription;
49 // Initialize the evaluation function parameters
51 void initialize(AlignedPtr<T>& pointer) {
53 pointer.reset(reinterpret_cast<T*>(std_aligned_alloc(alignof(T), sizeof(T))));
54 std::memset(pointer.get(), 0, sizeof(T));
58 void initialize(LargePagePtr<T>& pointer) {
60 static_assert(alignof(T) <= 4096, "aligned_large_pages_alloc() may fail for such a big alignment requirement of T");
61 pointer.reset(reinterpret_cast<T*>(aligned_large_pages_alloc(sizeof(T))));
62 std::memset(pointer.get(), 0, sizeof(T));
65 // Read evaluation function parameters
67 bool read_parameters(std::istream& stream, T& reference) {
70 header = read_little_endian<std::uint32_t>(stream);
71 if (!stream || header != T::get_hash_value()) return false;
72 return reference.read_parameters(stream);
75 // Write evaluation function parameters
77 bool write_parameters(std::ostream& stream, const T& reference) {
79 write_little_endian<std::uint32_t>(stream, T::get_hash_value());
80 return reference.write_parameters(stream);
85 // Initialize the evaluation function parameters
88 Detail::initialize(featureTransformer);
89 for (std::size_t i = 0; i < LayerStacks; ++i)
90 Detail::initialize(network[i]);
93 // Read network header
94 bool read_header(std::istream& stream, std::uint32_t* hashValue, std::string* desc)
96 std::uint32_t version, size;
98 version = read_little_endian<std::uint32_t>(stream);
99 *hashValue = read_little_endian<std::uint32_t>(stream);
100 size = read_little_endian<std::uint32_t>(stream);
101 if (!stream || version != Version) return false;
103 stream.read(&(*desc)[0], size);
104 return !stream.fail();
107 // Write network header
108 bool write_header(std::ostream& stream, std::uint32_t hashValue, const std::string& desc)
110 write_little_endian<std::uint32_t>(stream, Version);
111 write_little_endian<std::uint32_t>(stream, hashValue);
112 write_little_endian<std::uint32_t>(stream, (std::uint32_t)desc.size());
113 stream.write(&desc[0], desc.size());
114 return !stream.fail();
117 // Read network parameters
118 bool read_parameters(std::istream& stream) {
120 std::uint32_t hashValue;
121 if (!read_header(stream, &hashValue, &netDescription)) return false;
122 if (hashValue != HashValue) return false;
123 if (!Detail::read_parameters(stream, *featureTransformer)) return false;
124 for (std::size_t i = 0; i < LayerStacks; ++i)
125 if (!Detail::read_parameters(stream, *(network[i]))) return false;
126 return stream && stream.peek() == std::ios::traits_type::eof();
129 // Write network parameters
130 bool write_parameters(std::ostream& stream) {
132 if (!write_header(stream, HashValue, netDescription)) return false;
133 if (!Detail::write_parameters(stream, *featureTransformer)) return false;
134 for (std::size_t i = 0; i < LayerStacks; ++i)
135 if (!Detail::write_parameters(stream, *(network[i]))) return false;
139 // Evaluation function. Perform differential calculation.
140 Value evaluate(const Position& pos, bool adjusted, int* complexity) {
142 // We manually align the arrays on the stack because with gcc < 9.3
143 // overaligning stack variables with alignas() doesn't work correctly.
145 constexpr uint64_t alignment = CacheLineSize;
146 int delta = 24 - pos.non_pawn_material() / 9560;
148 #if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
149 TransformedFeatureType transformedFeaturesUnaligned[
150 FeatureTransformer::BufferSize + alignment / sizeof(TransformedFeatureType)];
152 auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
155 TransformedFeatureType transformedFeatures[FeatureTransformer::BufferSize];
158 ASSERT_ALIGNED(transformedFeatures, alignment);
160 const int bucket = (pos.count<ALL_PIECES>() - 1) / 4;
161 const auto psqt = featureTransformer->transform(pos, transformedFeatures, bucket);
162 const auto positional = network[bucket]->propagate(transformedFeatures);
165 *complexity = abs(psqt - positional) / OutputScale;
167 // Give more value to positional evaluation when adjusted flag is set
169 return static_cast<Value>(((1024 - delta) * psqt + (1024 + delta) * positional) / (1024 * OutputScale));
171 return static_cast<Value>((psqt + positional) / OutputScale);
174 struct NnueEvalTrace {
175 static_assert(LayerStacks == PSQTBuckets);
177 Value psqt[LayerStacks];
178 Value positional[LayerStacks];
179 std::size_t correctBucket;
182 static NnueEvalTrace trace_evaluate(const Position& pos) {
184 // We manually align the arrays on the stack because with gcc < 9.3
185 // overaligning stack variables with alignas() doesn't work correctly.
187 constexpr uint64_t alignment = CacheLineSize;
189 #if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
190 TransformedFeatureType transformedFeaturesUnaligned[
191 FeatureTransformer::BufferSize + alignment / sizeof(TransformedFeatureType)];
193 auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
196 TransformedFeatureType transformedFeatures[FeatureTransformer::BufferSize];
199 ASSERT_ALIGNED(transformedFeatures, alignment);
202 t.correctBucket = (pos.count<ALL_PIECES>() - 1) / 4;
203 for (IndexType bucket = 0; bucket < LayerStacks; ++bucket) {
204 const auto materialist = featureTransformer->transform(pos, transformedFeatures, bucket);
205 const auto positional = network[bucket]->propagate(transformedFeatures);
207 t.psqt[bucket] = static_cast<Value>( materialist / OutputScale );
208 t.positional[bucket] = static_cast<Value>( positional / OutputScale );
214 static const std::string PieceToChar(" PNBRQK pnbrqk");
217 // format_cp_compact() converts a Value into (centi)pawns and writes it in a buffer.
218 // The buffer must have capacity for at least 5 chars.
219 static void format_cp_compact(Value v, char* buffer) {
221 buffer[0] = (v < 0 ? '-' : v > 0 ? '+' : ' ');
223 int cp = std::abs(100 * v / UCI::NormalizeToPawnValue);
226 buffer[1] = '0' + cp / 10000; cp %= 10000;
227 buffer[2] = '0' + cp / 1000; cp %= 1000;
228 buffer[3] = '0' + cp / 100;
233 buffer[1] = '0' + cp / 1000; cp %= 1000;
234 buffer[2] = '0' + cp / 100; cp %= 100;
236 buffer[4] = '0' + cp / 10;
240 buffer[1] = '0' + cp / 100; cp %= 100;
242 buffer[3] = '0' + cp / 10; cp %= 10;
243 buffer[4] = '0' + cp / 1;
248 // format_cp_aligned_dot() converts a Value into (centi)pawns and writes it in a buffer,
249 // always keeping two decimals. The buffer must have capacity for at least 7 chars.
250 static void format_cp_aligned_dot(Value v, char* buffer) {
252 buffer[0] = (v < 0 ? '-' : v > 0 ? '+' : ' ');
254 double cp = 1.0 * std::abs(int(v)) / UCI::NormalizeToPawnValue;
255 sprintf(&buffer[1], "%6.2f", cp);
259 // trace() returns a string with the value of each piece on a board,
260 // and a table for (PSQT, Layers) values bucket by bucket.
262 std::string trace(Position& pos) {
264 std::stringstream ss;
266 char board[3*8+1][8*8+2];
267 std::memset(board, ' ', sizeof(board));
268 for (int row = 0; row < 3*8+1; ++row)
269 board[row][8*8+1] = '\0';
271 // A lambda to output one box of the board
272 auto writeSquare = [&board](File file, Rank rank, Piece pc, Value value) {
274 const int x = ((int)file) * 8;
275 const int y = (7 - (int)rank) * 3;
276 for (int i = 1; i < 8; ++i)
277 board[y][x+i] = board[y+3][x+i] = '-';
278 for (int i = 1; i < 3; ++i)
279 board[y+i][x] = board[y+i][x+8] = '|';
280 board[y][x] = board[y][x+8] = board[y+3][x+8] = board[y+3][x] = '+';
282 board[y+1][x+4] = PieceToChar[pc];
283 if (value != VALUE_NONE)
284 format_cp_compact(value, &board[y+2][x+2]);
287 // We estimate the value of each piece by doing a differential evaluation from
288 // the current base eval, simulating the removal of the piece from its square.
289 Value base = evaluate(pos);
290 base = pos.side_to_move() == WHITE ? base : -base;
292 for (File f = FILE_A; f <= FILE_H; ++f)
293 for (Rank r = RANK_1; r <= RANK_8; ++r)
295 Square sq = make_square(f, r);
296 Piece pc = pos.piece_on(sq);
297 Value v = VALUE_NONE;
299 if (pc != NO_PIECE && type_of(pc) != KING)
301 auto st = pos.state();
303 pos.remove_piece(sq);
304 st->accumulator.computed[WHITE] = false;
305 st->accumulator.computed[BLACK] = false;
307 Value eval = evaluate(pos);
308 eval = pos.side_to_move() == WHITE ? eval : -eval;
311 pos.put_piece(pc, sq);
312 st->accumulator.computed[WHITE] = false;
313 st->accumulator.computed[BLACK] = false;
316 writeSquare(f, r, pc, v);
319 ss << " NNUE derived piece values:\n";
320 for (int row = 0; row < 3*8+1; ++row)
321 ss << board[row] << '\n';
324 auto t = trace_evaluate(pos);
326 ss << " NNUE network contributions "
327 << (pos.side_to_move() == WHITE ? "(White to move)" : "(Black to move)") << std::endl
328 << "+------------+------------+------------+------------+\n"
329 << "| Bucket | Material | Positional | Total |\n"
330 << "| | (PSQT) | (Layers) | |\n"
331 << "+------------+------------+------------+------------+\n";
333 for (std::size_t bucket = 0; bucket < LayerStacks; ++bucket)
336 std::memset(buffer, '\0', sizeof(buffer));
338 format_cp_aligned_dot(t.psqt[bucket], buffer[0]);
339 format_cp_aligned_dot(t.positional[bucket], buffer[1]);
340 format_cp_aligned_dot(t.psqt[bucket] + t.positional[bucket], buffer[2]);
342 ss << "| " << bucket << " "
343 << " | " << buffer[0] << " "
344 << " | " << buffer[1] << " "
345 << " | " << buffer[2] << " "
347 if (bucket == t.correctBucket)
348 ss << " <-- this bucket is used";
352 ss << "+------------+------------+------------+------------+\n";
358 // Load eval, from a file stream or a memory stream
359 bool load_eval(std::string name, std::istream& stream) {
363 return read_parameters(stream);
366 // Save eval, to a file stream or a memory stream
367 bool save_eval(std::ostream& stream) {
369 if (fileName.empty())
372 return write_parameters(stream);
375 /// Save eval, to a file given by its name
376 bool save_eval(const std::optional<std::string>& filename) {
378 std::string actualFilename;
381 if (filename.has_value())
382 actualFilename = filename.value();
385 if (currentEvalFileName != EvalFileDefaultName)
387 msg = "Failed to export a net. A non-embedded net can only be saved if the filename is specified";
389 sync_cout << msg << sync_endl;
392 actualFilename = EvalFileDefaultName;
395 std::ofstream stream(actualFilename, std::ios_base::binary);
396 bool saved = save_eval(stream);
398 msg = saved ? "Network saved successfully to " + actualFilename
399 : "Failed to export a net";
401 sync_cout << msg << sync_endl;
406 } // namespace Stockfish::Eval::NNUE