2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2023 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
21 #include "evaluate_nnue.h"
30 #include <string_view>
32 #include "../evaluate.h"
34 #include "../position.h"
37 #include "nnue_accumulator.h"
38 #include "nnue_common.h"
40 namespace Stockfish::Eval::NNUE {
42 // Input feature converter
43 LargePagePtr<FeatureTransformer> featureTransformer;
45 // Evaluation function
46 AlignedPtr<Network> network[LayerStacks];
48 // Evaluation function file name
50 std::string netDescription;
54 // Initialize the evaluation function parameters
56 void initialize(AlignedPtr<T>& pointer) {
58 pointer.reset(reinterpret_cast<T*>(std_aligned_alloc(alignof(T), sizeof(T))));
59 std::memset(pointer.get(), 0, sizeof(T));
63 void initialize(LargePagePtr<T>& pointer) {
65 static_assert(alignof(T) <= 4096, "aligned_large_pages_alloc() may fail for such a big alignment requirement of T");
66 pointer.reset(reinterpret_cast<T*>(aligned_large_pages_alloc(sizeof(T))));
67 std::memset(pointer.get(), 0, sizeof(T));
70 // Read evaluation function parameters
72 bool read_parameters(std::istream& stream, T& reference) {
75 header = read_little_endian<std::uint32_t>(stream);
76 if (!stream || header != T::get_hash_value()) return false;
77 return reference.read_parameters(stream);
80 // Write evaluation function parameters
82 bool write_parameters(std::ostream& stream, const T& reference) {
84 write_little_endian<std::uint32_t>(stream, T::get_hash_value());
85 return reference.write_parameters(stream);
91 // Initialize the evaluation function parameters
92 static void initialize() {
94 Detail::initialize(featureTransformer);
95 for (std::size_t i = 0; i < LayerStacks; ++i)
96 Detail::initialize(network[i]);
99 // Read network header
100 static bool read_header(std::istream& stream, std::uint32_t* hashValue, std::string* desc)
102 std::uint32_t version, size;
104 version = read_little_endian<std::uint32_t>(stream);
105 *hashValue = read_little_endian<std::uint32_t>(stream);
106 size = read_little_endian<std::uint32_t>(stream);
107 if (!stream || version != Version) return false;
109 stream.read(&(*desc)[0], size);
110 return !stream.fail();
113 // Write network header
114 static bool write_header(std::ostream& stream, std::uint32_t hashValue, const std::string& desc)
116 write_little_endian<std::uint32_t>(stream, Version);
117 write_little_endian<std::uint32_t>(stream, hashValue);
118 write_little_endian<std::uint32_t>(stream, (std::uint32_t)desc.size());
119 stream.write(&desc[0], desc.size());
120 return !stream.fail();
123 // Read network parameters
124 static bool read_parameters(std::istream& stream) {
126 std::uint32_t hashValue;
127 if (!read_header(stream, &hashValue, &netDescription)) return false;
128 if (hashValue != HashValue) return false;
129 if (!Detail::read_parameters(stream, *featureTransformer)) return false;
130 for (std::size_t i = 0; i < LayerStacks; ++i)
131 if (!Detail::read_parameters(stream, *(network[i]))) return false;
132 return stream && stream.peek() == std::ios::traits_type::eof();
135 // Write network parameters
136 static bool write_parameters(std::ostream& stream) {
138 if (!write_header(stream, HashValue, netDescription)) return false;
139 if (!Detail::write_parameters(stream, *featureTransformer)) return false;
140 for (std::size_t i = 0; i < LayerStacks; ++i)
141 if (!Detail::write_parameters(stream, *(network[i]))) return false;
145 void hint_common_parent_position(const Position& pos) {
146 featureTransformer->hint_common_access(pos);
149 // Evaluation function. Perform differential calculation.
150 Value evaluate(const Position& pos, bool adjusted, int* complexity) {
152 // We manually align the arrays on the stack because with gcc < 9.3
153 // overaligning stack variables with alignas() doesn't work correctly.
155 constexpr uint64_t alignment = CacheLineSize;
156 constexpr int delta = 24;
158 #if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
159 TransformedFeatureType transformedFeaturesUnaligned[
160 FeatureTransformer::BufferSize + alignment / sizeof(TransformedFeatureType)];
162 auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
165 TransformedFeatureType transformedFeatures[FeatureTransformer::BufferSize];
168 ASSERT_ALIGNED(transformedFeatures, alignment);
170 const int bucket = (pos.count<ALL_PIECES>() - 1) / 4;
171 const auto psqt = featureTransformer->transform(pos, transformedFeatures, bucket);
172 const auto positional = network[bucket]->propagate(transformedFeatures);
175 *complexity = abs(psqt - positional) / OutputScale;
177 // Give more value to positional evaluation when adjusted flag is set
179 return static_cast<Value>(((1024 - delta) * psqt + (1024 + delta) * positional) / (1024 * OutputScale));
181 return static_cast<Value>((psqt + positional) / OutputScale);
184 struct NnueEvalTrace {
185 static_assert(LayerStacks == PSQTBuckets);
187 Value psqt[LayerStacks];
188 Value positional[LayerStacks];
189 std::size_t correctBucket;
192 static NnueEvalTrace trace_evaluate(const Position& pos) {
194 // We manually align the arrays on the stack because with gcc < 9.3
195 // overaligning stack variables with alignas() doesn't work correctly.
196 constexpr uint64_t alignment = CacheLineSize;
198 #if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
199 TransformedFeatureType transformedFeaturesUnaligned[
200 FeatureTransformer::BufferSize + alignment / sizeof(TransformedFeatureType)];
202 auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
205 TransformedFeatureType transformedFeatures[FeatureTransformer::BufferSize];
208 ASSERT_ALIGNED(transformedFeatures, alignment);
211 t.correctBucket = (pos.count<ALL_PIECES>() - 1) / 4;
212 for (IndexType bucket = 0; bucket < LayerStacks; ++bucket) {
213 const auto materialist = featureTransformer->transform(pos, transformedFeatures, bucket);
214 const auto positional = network[bucket]->propagate(transformedFeatures);
216 t.psqt[bucket] = static_cast<Value>( materialist / OutputScale );
217 t.positional[bucket] = static_cast<Value>( positional / OutputScale );
223 constexpr std::string_view PieceToChar(" PNBRQK pnbrqk");
226 // format_cp_compact() converts a Value into (centi)pawns and writes it in a buffer.
227 // The buffer must have capacity for at least 5 chars.
228 static void format_cp_compact(Value v, char* buffer) {
230 buffer[0] = (v < 0 ? '-' : v > 0 ? '+' : ' ');
232 int cp = std::abs(UCI::to_cp(v));
235 buffer[1] = '0' + cp / 10000; cp %= 10000;
236 buffer[2] = '0' + cp / 1000; cp %= 1000;
237 buffer[3] = '0' + cp / 100;
242 buffer[1] = '0' + cp / 1000; cp %= 1000;
243 buffer[2] = '0' + cp / 100; cp %= 100;
245 buffer[4] = '0' + cp / 10;
249 buffer[1] = '0' + cp / 100; cp %= 100;
251 buffer[3] = '0' + cp / 10; cp %= 10;
252 buffer[4] = '0' + cp / 1;
257 // format_cp_aligned_dot() converts a Value into pawns, always keeping two decimals
258 static void format_cp_aligned_dot(Value v, std::stringstream &stream) {
260 const double pawns = std::abs(0.01 * UCI::to_cp(v));
262 stream << (v < 0 ? '-' : v > 0 ? '+' : ' ')
263 << std::setiosflags(std::ios::fixed)
265 << std::setprecision(2)
270 // trace() returns a string with the value of each piece on a board,
271 // and a table for (PSQT, Layers) values bucket by bucket.
272 std::string trace(Position& pos) {
274 std::stringstream ss;
276 char board[3*8+1][8*8+2];
277 std::memset(board, ' ', sizeof(board));
278 for (int row = 0; row < 3*8+1; ++row)
279 board[row][8*8+1] = '\0';
281 // A lambda to output one box of the board
282 auto writeSquare = [&board](File file, Rank rank, Piece pc, Value value) {
284 const int x = int(file) * 8;
285 const int y = (7 - int(rank)) * 3;
286 for (int i = 1; i < 8; ++i)
287 board[y][x+i] = board[y+3][x+i] = '-';
288 for (int i = 1; i < 3; ++i)
289 board[y+i][x] = board[y+i][x+8] = '|';
290 board[y][x] = board[y][x+8] = board[y+3][x+8] = board[y+3][x] = '+';
292 board[y+1][x+4] = PieceToChar[pc];
293 if (value != VALUE_NONE)
294 format_cp_compact(value, &board[y+2][x+2]);
297 // We estimate the value of each piece by doing a differential evaluation from
298 // the current base eval, simulating the removal of the piece from its square.
299 Value base = evaluate(pos);
300 base = pos.side_to_move() == WHITE ? base : -base;
302 for (File f = FILE_A; f <= FILE_H; ++f)
303 for (Rank r = RANK_1; r <= RANK_8; ++r)
305 Square sq = make_square(f, r);
306 Piece pc = pos.piece_on(sq);
307 Value v = VALUE_NONE;
309 if (pc != NO_PIECE && type_of(pc) != KING)
311 auto st = pos.state();
313 pos.remove_piece(sq);
314 st->accumulator.computed[WHITE] = false;
315 st->accumulator.computed[BLACK] = false;
317 Value eval = evaluate(pos);
318 eval = pos.side_to_move() == WHITE ? eval : -eval;
321 pos.put_piece(pc, sq);
322 st->accumulator.computed[WHITE] = false;
323 st->accumulator.computed[BLACK] = false;
326 writeSquare(f, r, pc, v);
329 ss << " NNUE derived piece values:\n";
330 for (int row = 0; row < 3*8+1; ++row)
331 ss << board[row] << '\n';
334 auto t = trace_evaluate(pos);
336 ss << " NNUE network contributions "
337 << (pos.side_to_move() == WHITE ? "(White to move)" : "(Black to move)") << std::endl
338 << "+------------+------------+------------+------------+\n"
339 << "| Bucket | Material | Positional | Total |\n"
340 << "| | (PSQT) | (Layers) | |\n"
341 << "+------------+------------+------------+------------+\n";
343 for (std::size_t bucket = 0; bucket < LayerStacks; ++bucket)
345 ss << "| " << bucket << " ";
346 ss << " | "; format_cp_aligned_dot(t.psqt[bucket], ss); ss << " "
347 << " | "; format_cp_aligned_dot(t.positional[bucket], ss); ss << " "
348 << " | "; format_cp_aligned_dot(t.psqt[bucket] + t.positional[bucket], ss); ss << " "
350 if (bucket == t.correctBucket)
351 ss << " <-- this bucket is used";
355 ss << "+------------+------------+------------+------------+\n";
361 // Load eval, from a file stream or a memory stream
362 bool load_eval(std::string name, std::istream& stream) {
366 return read_parameters(stream);
369 // Save eval, to a file stream or a memory stream
370 bool save_eval(std::ostream& stream) {
372 if (fileName.empty())
375 return write_parameters(stream);
378 // Save eval, to a file given by its name
379 bool save_eval(const std::optional<std::string>& filename) {
381 std::string actualFilename;
384 if (filename.has_value())
385 actualFilename = filename.value();
388 if (currentEvalFileName != EvalFileDefaultName)
390 msg = "Failed to export a net. A non-embedded net can only be saved if the filename is specified";
392 sync_cout << msg << sync_endl;
395 actualFilename = EvalFileDefaultName;
398 std::ofstream stream(actualFilename, std::ios_base::binary);
399 bool saved = save_eval(stream);
401 msg = saved ? "Network saved successfully to " + actualFilename
402 : "Failed to export a net";
404 sync_cout << msg << sync_endl;
409 } // namespace Stockfish::Eval::NNUE