2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2021 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, 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) {
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;
147 #if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
148 TransformedFeatureType transformedFeaturesUnaligned[
149 FeatureTransformer::BufferSize + alignment / sizeof(TransformedFeatureType)];
150 char bufferUnaligned[Network::BufferSize + alignment];
152 auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
153 auto* buffer = align_ptr_up<alignment>(&bufferUnaligned[0]);
156 TransformedFeatureType transformedFeatures[FeatureTransformer::BufferSize];
157 alignas(alignment) char buffer[Network::BufferSize];
160 ASSERT_ALIGNED(transformedFeatures, alignment);
161 ASSERT_ALIGNED(buffer, alignment);
163 const std::size_t bucket = (pos.count<ALL_PIECES>() - 1) / 4;
164 const auto psqt = featureTransformer->transform(pos, transformedFeatures, bucket);
165 const auto output = network[bucket]->propagate(transformedFeatures, buffer);
167 int materialist = psqt;
168 int positional = output[0];
170 int delta_npm = abs(pos.non_pawn_material(WHITE) - pos.non_pawn_material(BLACK));
171 int entertainment = (adjusted && delta_npm <= BishopValueMg - KnightValueMg ? 7 : 0);
173 int A = 128 - entertainment;
174 int B = 128 + entertainment;
176 int sum = (A * materialist + B * positional) / 128;
178 return static_cast<Value>( sum / OutputScale );
181 struct NnueEvalTrace {
182 static_assert(LayerStacks == PSQTBuckets);
184 Value psqt[LayerStacks];
185 Value positional[LayerStacks];
186 std::size_t correctBucket;
189 static NnueEvalTrace trace_evaluate(const Position& pos) {
191 // We manually align the arrays on the stack because with gcc < 9.3
192 // overaligning stack variables with alignas() doesn't work correctly.
194 constexpr uint64_t alignment = CacheLineSize;
196 #if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
197 TransformedFeatureType transformedFeaturesUnaligned[
198 FeatureTransformer::BufferSize + alignment / sizeof(TransformedFeatureType)];
199 char bufferUnaligned[Network::BufferSize + alignment];
201 auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
202 auto* buffer = align_ptr_up<alignment>(&bufferUnaligned[0]);
205 TransformedFeatureType transformedFeatures[FeatureTransformer::BufferSize];
206 alignas(alignment) char buffer[Network::BufferSize];
209 ASSERT_ALIGNED(transformedFeatures, alignment);
210 ASSERT_ALIGNED(buffer, alignment);
213 t.correctBucket = (pos.count<ALL_PIECES>() - 1) / 4;
214 for (std::size_t bucket = 0; bucket < LayerStacks; ++bucket) {
215 const auto psqt = featureTransformer->transform(pos, transformedFeatures, bucket);
216 const auto output = network[bucket]->propagate(transformedFeatures, buffer);
218 int materialist = psqt;
219 int positional = output[0];
221 t.psqt[bucket] = static_cast<Value>( materialist / OutputScale );
222 t.positional[bucket] = static_cast<Value>( positional / OutputScale );
228 static const std::string PieceToChar(" PNBRQK pnbrqk");
231 // format_cp_compact() converts a Value into (centi)pawns and writes it in a buffer.
232 // The buffer must have capacity for at least 5 chars.
233 static void format_cp_compact(Value v, char* buffer) {
235 buffer[0] = (v < 0 ? '-' : v > 0 ? '+' : ' ');
237 int cp = std::abs(100 * v / PawnValueEg);
240 buffer[1] = '0' + cp / 10000; cp %= 10000;
241 buffer[2] = '0' + cp / 1000; cp %= 1000;
242 buffer[3] = '0' + cp / 100; cp %= 100;
247 buffer[1] = '0' + cp / 1000; cp %= 1000;
248 buffer[2] = '0' + cp / 100; cp %= 100;
250 buffer[4] = '0' + cp / 10;
254 buffer[1] = '0' + cp / 100; cp %= 100;
256 buffer[3] = '0' + cp / 10; cp %= 10;
257 buffer[4] = '0' + cp / 1;
262 // format_cp_aligned_dot() converts a Value into (centi)pawns and writes it in a buffer,
263 // always keeping two decimals. The buffer must have capacity for at least 7 chars.
264 static void format_cp_aligned_dot(Value v, char* buffer) {
266 buffer[0] = (v < 0 ? '-' : v > 0 ? '+' : ' ');
268 double cp = 1.0 * std::abs(int(v)) / PawnValueEg;
269 sprintf(&buffer[1], "%6.2f", cp);
273 // trace() returns a string with the value of each piece on a board,
274 // and a table for (PSQT, Layers) values bucket by bucket.
276 std::string trace(Position& pos) {
278 std::stringstream ss;
280 char board[3*8+1][8*8+2];
281 std::memset(board, ' ', sizeof(board));
282 for (int row = 0; row < 3*8+1; ++row)
283 board[row][8*8+1] = '\0';
285 // A lambda to output one box of the board
286 auto writeSquare = [&board](File file, Rank rank, Piece pc, Value value) {
288 const int x = ((int)file) * 8;
289 const int y = (7 - (int)rank) * 3;
290 for (int i = 1; i < 8; ++i)
291 board[y][x+i] = board[y+3][x+i] = '-';
292 for (int i = 1; i < 3; ++i)
293 board[y+i][x] = board[y+i][x+8] = '|';
294 board[y][x] = board[y][x+8] = board[y+3][x+8] = board[y+3][x] = '+';
296 board[y+1][x+4] = PieceToChar[pc];
297 if (value != VALUE_NONE)
298 format_cp_compact(value, &board[y+2][x+2]);
301 // We estimate the value of each piece by doing a differential evaluation from
302 // the current base eval, simulating the removal of the piece from its square.
303 Value base = evaluate(pos);
304 base = pos.side_to_move() == WHITE ? base : -base;
306 for (File f = FILE_A; f <= FILE_H; ++f)
307 for (Rank r = RANK_1; r <= RANK_8; ++r)
309 Square sq = make_square(f, r);
310 Piece pc = pos.piece_on(sq);
311 Value v = VALUE_NONE;
313 if (pc != NO_PIECE && type_of(pc) != KING)
315 auto st = pos.state();
317 pos.remove_piece(sq);
318 st->accumulator.computed[WHITE] = false;
319 st->accumulator.computed[BLACK] = false;
321 Value eval = evaluate(pos);
322 eval = pos.side_to_move() == WHITE ? eval : -eval;
325 pos.put_piece(pc, sq);
326 st->accumulator.computed[WHITE] = false;
327 st->accumulator.computed[BLACK] = false;
330 writeSquare(f, r, pc, v);
333 ss << " NNUE derived piece values:\n";
334 for (int row = 0; row < 3*8+1; ++row)
335 ss << board[row] << '\n';
338 auto t = trace_evaluate(pos);
340 ss << " NNUE network contributions "
341 << (pos.side_to_move() == WHITE ? "(White to move)" : "(Black to move)") << std::endl
342 << "+------------+------------+------------+------------+\n"
343 << "| Bucket | Material | Positional | Total |\n"
344 << "| | (PSQT) | (Layers) | |\n"
345 << "+------------+------------+------------+------------+\n";
347 for (std::size_t bucket = 0; bucket < LayerStacks; ++bucket)
350 std::memset(buffer, '\0', sizeof(buffer));
352 format_cp_aligned_dot(t.psqt[bucket], buffer[0]);
353 format_cp_aligned_dot(t.positional[bucket], buffer[1]);
354 format_cp_aligned_dot(t.psqt[bucket] + t.positional[bucket], buffer[2]);
356 ss << "| " << bucket << " "
357 << " | " << buffer[0] << " "
358 << " | " << buffer[1] << " "
359 << " | " << buffer[2] << " "
361 if (bucket == t.correctBucket)
362 ss << " <-- this bucket is used";
366 ss << "+------------+------------+------------+------------+\n";
372 // Load eval, from a file stream or a memory stream
373 bool load_eval(std::string name, std::istream& stream) {
377 return read_parameters(stream);
380 // Save eval, to a file stream or a memory stream
381 bool save_eval(std::ostream& stream) {
383 if (fileName.empty())
386 return write_parameters(stream);
389 /// Save eval, to a file given by its name
390 bool save_eval(const std::optional<std::string>& filename) {
392 std::string actualFilename;
395 if (filename.has_value())
396 actualFilename = filename.value();
399 if (eval_file_loaded != EvalFileDefaultName)
401 msg = "Failed to export a net. A non-embedded net can only be saved if the filename is specified";
403 sync_cout << msg << sync_endl;
406 actualFilename = EvalFileDefaultName;
409 std::ofstream stream(actualFilename, std::ios_base::binary);
410 bool saved = save_eval(stream);
412 msg = saved ? "Network saved successfully to " + actualFilename
413 : "Failed to export a net";
415 sync_cout << msg << sync_endl;
420 } // namespace Stockfish::Eval::NNUE