]> git.sesse.net Git - stockfish/blob - src/nnue/evaluate_nnue.cpp
Standardize Comments
[stockfish] / src / nnue / evaluate_nnue.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2023 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 // Code for calculating NNUE evaluation function
20
21 #include "evaluate_nnue.h"
22
23 #include <cmath>
24 #include <cstdlib>
25 #include <cstring>
26 #include <fstream>
27 #include <iomanip>
28 #include <iostream>
29 #include <sstream>
30 #include <string_view>
31
32 #include "../evaluate.h"
33 #include "../misc.h"
34 #include "../position.h"
35 #include "../types.h"
36 #include "../uci.h"
37 #include "nnue_accumulator.h"
38 #include "nnue_common.h"
39
40 namespace Stockfish::Eval::NNUE {
41
42   // Input feature converter
43   LargePagePtr<FeatureTransformer> featureTransformer;
44
45   // Evaluation function
46   AlignedPtr<Network> network[LayerStacks];
47
48   // Evaluation function file name
49   std::string fileName;
50   std::string netDescription;
51
52   namespace Detail {
53
54   // Initialize the evaluation function parameters
55   template <typename T>
56   void initialize(AlignedPtr<T>& pointer) {
57
58     pointer.reset(reinterpret_cast<T*>(std_aligned_alloc(alignof(T), sizeof(T))));
59     std::memset(pointer.get(), 0, sizeof(T));
60   }
61
62   template <typename T>
63   void initialize(LargePagePtr<T>& pointer) {
64
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));
68   }
69
70   // Read evaluation function parameters
71   template <typename T>
72   bool read_parameters(std::istream& stream, T& reference) {
73
74     std::uint32_t header;
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);
78   }
79
80   // Write evaluation function parameters
81   template <typename T>
82   bool write_parameters(std::ostream& stream, const T& reference) {
83
84     write_little_endian<std::uint32_t>(stream, T::get_hash_value());
85     return reference.write_parameters(stream);
86   }
87
88   }  // namespace Detail
89
90
91   // Initialize the evaluation function parameters
92   static void initialize() {
93
94     Detail::initialize(featureTransformer);
95     for (std::size_t i = 0; i < LayerStacks; ++i)
96       Detail::initialize(network[i]);
97   }
98
99   // Read network header
100   static bool read_header(std::istream& stream, std::uint32_t* hashValue, std::string* desc)
101   {
102     std::uint32_t version, size;
103
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;
108     desc->resize(size);
109     stream.read(&(*desc)[0], size);
110     return !stream.fail();
111   }
112
113   // Write network header
114   static bool write_header(std::ostream& stream, std::uint32_t hashValue, const std::string& desc)
115   {
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();
121   }
122
123   // Read network parameters
124   static bool read_parameters(std::istream& stream) {
125
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();
133   }
134
135   // Write network parameters
136   static bool write_parameters(std::ostream& stream) {
137
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;
142     return bool(stream);
143   }
144
145   void hint_common_parent_position(const Position& pos) {
146     featureTransformer->hint_common_access(pos);
147   }
148
149   // Evaluation function. Perform differential calculation.
150   Value evaluate(const Position& pos, bool adjusted, int* complexity) {
151
152     // We manually align the arrays on the stack because with gcc < 9.3
153     // overaligning stack variables with alignas() doesn't work correctly.
154
155     constexpr uint64_t alignment = CacheLineSize;
156     constexpr int delta = 24;
157
158 #if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
159     TransformedFeatureType transformedFeaturesUnaligned[
160       FeatureTransformer::BufferSize + alignment / sizeof(TransformedFeatureType)];
161
162     auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
163 #else
164     alignas(alignment)
165       TransformedFeatureType transformedFeatures[FeatureTransformer::BufferSize];
166 #endif
167
168     ASSERT_ALIGNED(transformedFeatures, alignment);
169
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);
173
174     if (complexity)
175         *complexity = abs(psqt - positional) / OutputScale;
176
177     // Give more value to positional evaluation when adjusted flag is set
178     if (adjusted)
179         return static_cast<Value>(((1024 - delta) * psqt + (1024 + delta) * positional) / (1024 * OutputScale));
180     else
181         return static_cast<Value>((psqt + positional) / OutputScale);
182   }
183
184   struct NnueEvalTrace {
185     static_assert(LayerStacks == PSQTBuckets);
186
187     Value psqt[LayerStacks];
188     Value positional[LayerStacks];
189     std::size_t correctBucket;
190   };
191
192   static NnueEvalTrace trace_evaluate(const Position& pos) {
193
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;
197
198 #if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
199     TransformedFeatureType transformedFeaturesUnaligned[
200       FeatureTransformer::BufferSize + alignment / sizeof(TransformedFeatureType)];
201
202     auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
203 #else
204     alignas(alignment)
205       TransformedFeatureType transformedFeatures[FeatureTransformer::BufferSize];
206 #endif
207
208     ASSERT_ALIGNED(transformedFeatures, alignment);
209
210     NnueEvalTrace t{};
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);
215
216       t.psqt[bucket] = static_cast<Value>( materialist / OutputScale );
217       t.positional[bucket] = static_cast<Value>( positional / OutputScale );
218     }
219
220     return t;
221   }
222
223   constexpr std::string_view PieceToChar(" PNBRQK  pnbrqk");
224
225
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) {
229
230     buffer[0] = (v < 0 ? '-' : v > 0 ? '+' : ' ');
231
232     int cp = std::abs(UCI::to_cp(v));
233     if (cp >= 10000)
234     {
235         buffer[1] = '0' + cp / 10000; cp %= 10000;
236         buffer[2] = '0' + cp / 1000; cp %= 1000;
237         buffer[3] = '0' + cp / 100;
238         buffer[4] = ' ';
239     }
240     else if (cp >= 1000)
241     {
242         buffer[1] = '0' + cp / 1000; cp %= 1000;
243         buffer[2] = '0' + cp / 100; cp %= 100;
244         buffer[3] = '.';
245         buffer[4] = '0' + cp / 10;
246     }
247     else
248     {
249         buffer[1] = '0' + cp / 100; cp %= 100;
250         buffer[2] = '.';
251         buffer[3] = '0' + cp / 10; cp %= 10;
252         buffer[4] = '0' + cp / 1;
253     }
254   }
255
256
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) {
259
260     const double pawns = std::abs(0.01 * UCI::to_cp(v));
261
262     stream << (v < 0 ? '-' : v > 0 ? '+' : ' ')
263            << std::setiosflags(std::ios::fixed)
264            << std::setw(6)
265            << std::setprecision(2)
266            << pawns;
267   }
268
269
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) {
273
274     std::stringstream ss;
275
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';
280
281     // A lambda to output one box of the board
282     auto writeSquare = [&board](File file, Rank rank, Piece pc, Value value) {
283
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] = '+';
291       if (pc != NO_PIECE)
292         board[y+1][x+4] = PieceToChar[pc];
293       if (value != VALUE_NONE)
294         format_cp_compact(value, &board[y+2][x+2]);
295     };
296
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;
301
302     for (File f = FILE_A; f <= FILE_H; ++f)
303       for (Rank r = RANK_1; r <= RANK_8; ++r)
304       {
305         Square sq = make_square(f, r);
306         Piece pc = pos.piece_on(sq);
307         Value v = VALUE_NONE;
308
309         if (pc != NO_PIECE && type_of(pc) != KING)
310         {
311           auto st = pos.state();
312
313           pos.remove_piece(sq);
314           st->accumulator.computed[WHITE] = false;
315           st->accumulator.computed[BLACK] = false;
316
317           Value eval = evaluate(pos);
318           eval = pos.side_to_move() == WHITE ? eval : -eval;
319           v = base - eval;
320
321           pos.put_piece(pc, sq);
322           st->accumulator.computed[WHITE] = false;
323           st->accumulator.computed[BLACK] = false;
324         }
325
326         writeSquare(f, r, pc, v);
327       }
328
329     ss << " NNUE derived piece values:\n";
330     for (int row = 0; row < 3*8+1; ++row)
331         ss << board[row] << '\n';
332     ss << '\n';
333
334     auto t = trace_evaluate(pos);
335
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";
342
343     for (std::size_t bucket = 0; bucket < LayerStacks; ++bucket)
344     {
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 << "  "
349          << " |";
350       if (bucket == t.correctBucket)
351           ss << " <-- this bucket is used";
352       ss << '\n';
353     }
354
355     ss << "+------------+------------+------------+------------+\n";
356
357     return ss.str();
358   }
359
360
361   // Load eval, from a file stream or a memory stream
362   bool load_eval(std::string name, std::istream& stream) {
363
364     initialize();
365     fileName = name;
366     return read_parameters(stream);
367   }
368
369   // Save eval, to a file stream or a memory stream
370   bool save_eval(std::ostream& stream) {
371
372     if (fileName.empty())
373       return false;
374
375     return write_parameters(stream);
376   }
377
378   // Save eval, to a file given by its name
379   bool save_eval(const std::optional<std::string>& filename) {
380
381     std::string actualFilename;
382     std::string msg;
383
384     if (filename.has_value())
385         actualFilename = filename.value();
386     else
387     {
388         if (currentEvalFileName != EvalFileDefaultName)
389         {
390              msg = "Failed to export a net. A non-embedded net can only be saved if the filename is specified";
391
392              sync_cout << msg << sync_endl;
393              return false;
394         }
395         actualFilename = EvalFileDefaultName;
396     }
397
398     std::ofstream stream(actualFilename, std::ios_base::binary);
399     bool saved = save_eval(stream);
400
401     msg = saved ? "Network saved successfully to " + actualFilename
402                 : "Failed to export a net";
403
404     sync_cout << msg << sync_endl;
405     return saved;
406   }
407
408
409 } // namespace Stockfish::Eval::NNUE