]> git.sesse.net Git - stockfish/blob - src/nnue/evaluate_nnue.cpp
Rewrite NNUE evaluation adjustments
[stockfish] / src / nnue / evaluate_nnue.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2021 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 <iostream>
22 #include <set>
23 #include <sstream>
24 #include <iomanip>
25 #include <fstream>
26
27 #include "../evaluate.h"
28 #include "../position.h"
29 #include "../misc.h"
30 #include "../uci.h"
31 #include "../types.h"
32
33 #include "evaluate_nnue.h"
34
35 namespace Stockfish::Eval::NNUE {
36
37   // Input feature converter
38   LargePagePtr<FeatureTransformer> featureTransformer;
39
40   // Evaluation function
41   AlignedPtr<Network> network[LayerStacks];
42
43   // Evaluation function file name
44   std::string fileName;
45   std::string netDescription;
46
47   namespace Detail {
48
49   // Initialize the evaluation function parameters
50   template <typename T>
51   void initialize(AlignedPtr<T>& pointer) {
52
53     pointer.reset(reinterpret_cast<T*>(std_aligned_alloc(alignof(T), sizeof(T))));
54     std::memset(pointer.get(), 0, sizeof(T));
55   }
56
57   template <typename T>
58   void initialize(LargePagePtr<T>& pointer) {
59
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));
63   }
64
65   // Read evaluation function parameters
66   template <typename T>
67   bool read_parameters(std::istream& stream, T& reference) {
68
69     std::uint32_t header;
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);
73   }
74
75   // Write evaluation function parameters
76   template <typename T>
77   bool write_parameters(std::ostream& stream, const T& reference) {
78
79     write_little_endian<std::uint32_t>(stream, T::get_hash_value());
80     return reference.write_parameters(stream);
81   }
82
83   }  // namespace Detail
84
85   // Initialize the evaluation function parameters
86   void initialize() {
87
88     Detail::initialize(featureTransformer);
89     for (std::size_t i = 0; i < LayerStacks; ++i)
90       Detail::initialize(network[i]);
91   }
92
93   // Read network header
94   bool read_header(std::istream& stream, std::uint32_t* hashValue, std::string* desc)
95   {
96     std::uint32_t version, size;
97
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;
102     desc->resize(size);
103     stream.read(&(*desc)[0], size);
104     return !stream.fail();
105   }
106
107   // Write network header
108   bool write_header(std::ostream& stream, std::uint32_t hashValue, const std::string& desc)
109   {
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();
115   }
116
117   // Read network parameters
118   bool read_parameters(std::istream& stream) {
119
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();
127   }
128
129   // Write network parameters
130   bool write_parameters(std::ostream& stream) {
131
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;
136     return (bool)stream;
137   }
138
139   // Evaluation function. Perform differential calculation.
140   Value evaluate(const Position& pos, bool adjusted) {
141
142     // We manually align the arrays on the stack because with gcc < 9.3
143     // overaligning stack variables with alignas() doesn't work correctly.
144
145     constexpr uint64_t alignment = CacheLineSize;
146     int delta = 7;
147
148 #if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
149     TransformedFeatureType transformedFeaturesUnaligned[
150       FeatureTransformer::BufferSize + alignment / sizeof(TransformedFeatureType)];
151     char bufferUnaligned[Network::BufferSize + alignment];
152
153     auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
154     auto* buffer = align_ptr_up<alignment>(&bufferUnaligned[0]);
155 #else
156     alignas(alignment)
157       TransformedFeatureType transformedFeatures[FeatureTransformer::BufferSize];
158     alignas(alignment) char buffer[Network::BufferSize];
159 #endif
160
161     ASSERT_ALIGNED(transformedFeatures, alignment);
162     ASSERT_ALIGNED(buffer, alignment);
163
164     const std::size_t bucket = (pos.count<ALL_PIECES>() - 1) / 4;
165     const auto psqt = featureTransformer->transform(pos, transformedFeatures, bucket);
166     const auto positional = network[bucket]->propagate(transformedFeatures, buffer)[0];
167
168     // Give more value to positional evaluation when material is balanced
169     if (   adjusted
170         && abs(pos.non_pawn_material(WHITE) - pos.non_pawn_material(BLACK)) <= RookValueMg - BishopValueMg)
171       return  static_cast<Value>(((128 - delta) * psqt + (128 + delta) * positional) / 128 / OutputScale);
172     else
173       return static_cast<Value>((psqt + positional) / OutputScale);
174   }
175
176   struct NnueEvalTrace {
177     static_assert(LayerStacks == PSQTBuckets);
178
179     Value psqt[LayerStacks];
180     Value positional[LayerStacks];
181     std::size_t correctBucket;
182   };
183
184   static NnueEvalTrace trace_evaluate(const Position& pos) {
185
186     // We manually align the arrays on the stack because with gcc < 9.3
187     // overaligning stack variables with alignas() doesn't work correctly.
188
189     constexpr uint64_t alignment = CacheLineSize;
190
191 #if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
192     TransformedFeatureType transformedFeaturesUnaligned[
193       FeatureTransformer::BufferSize + alignment / sizeof(TransformedFeatureType)];
194     char bufferUnaligned[Network::BufferSize + alignment];
195
196     auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
197     auto* buffer = align_ptr_up<alignment>(&bufferUnaligned[0]);
198 #else
199     alignas(alignment)
200       TransformedFeatureType transformedFeatures[FeatureTransformer::BufferSize];
201     alignas(alignment) char buffer[Network::BufferSize];
202 #endif
203
204     ASSERT_ALIGNED(transformedFeatures, alignment);
205     ASSERT_ALIGNED(buffer, alignment);
206
207     NnueEvalTrace t{};
208     t.correctBucket = (pos.count<ALL_PIECES>() - 1) / 4;
209     for (std::size_t bucket = 0; bucket < LayerStacks; ++bucket) {
210       const auto psqt = featureTransformer->transform(pos, transformedFeatures, bucket);
211       const auto output = network[bucket]->propagate(transformedFeatures, buffer);
212
213       int materialist = psqt;
214       int positional  = output[0];
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   static const std::string 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(100 * v / PawnValueEg);
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; 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 (centi)pawns and writes it in a buffer,
258   // always keeping two decimals. The buffer must have capacity for at least 7 chars.
259   static void format_cp_aligned_dot(Value v, char* buffer) {
260
261     buffer[0] = (v < 0 ? '-' : v > 0 ? '+' : ' ');
262
263     double cp = 1.0 * std::abs(int(v)) / PawnValueEg;
264     sprintf(&buffer[1], "%6.2f", cp);
265   }
266
267
268   // trace() returns a string with the value of each piece on a board,
269   // and a table for (PSQT, Layers) values bucket by bucket.
270
271   std::string trace(Position& pos) {
272
273     std::stringstream ss;
274
275     char board[3*8+1][8*8+2];
276     std::memset(board, ' ', sizeof(board));
277     for (int row = 0; row < 3*8+1; ++row)
278       board[row][8*8+1] = '\0';
279
280     // A lambda to output one box of the board
281     auto writeSquare = [&board](File file, Rank rank, Piece pc, Value value) {
282
283       const int x = ((int)file) * 8;
284       const int y = (7 - (int)rank) * 3;
285       for (int i = 1; i < 8; ++i)
286          board[y][x+i] = board[y+3][x+i] = '-';
287       for (int i = 1; i < 3; ++i)
288          board[y+i][x] = board[y+i][x+8] = '|';
289       board[y][x] = board[y][x+8] = board[y+3][x+8] = board[y+3][x] = '+';
290       if (pc != NO_PIECE)
291         board[y+1][x+4] = PieceToChar[pc];
292       if (value != VALUE_NONE)
293         format_cp_compact(value, &board[y+2][x+2]);
294     };
295
296     // We estimate the value of each piece by doing a differential evaluation from
297     // the current base eval, simulating the removal of the piece from its square.
298     Value base = evaluate(pos);
299     base = pos.side_to_move() == WHITE ? base : -base;
300
301     for (File f = FILE_A; f <= FILE_H; ++f)
302       for (Rank r = RANK_1; r <= RANK_8; ++r)
303       {
304         Square sq = make_square(f, r);
305         Piece pc = pos.piece_on(sq);
306         Value v = VALUE_NONE;
307
308         if (pc != NO_PIECE && type_of(pc) != KING)
309         {
310           auto st = pos.state();
311
312           pos.remove_piece(sq);
313           st->accumulator.computed[WHITE] = false;
314           st->accumulator.computed[BLACK] = false;
315
316           Value eval = evaluate(pos);
317           eval = pos.side_to_move() == WHITE ? eval : -eval;
318           v = base - eval;
319
320           pos.put_piece(pc, sq);
321           st->accumulator.computed[WHITE] = false;
322           st->accumulator.computed[BLACK] = false;
323         }
324
325         writeSquare(f, r, pc, v);
326       }
327
328     ss << " NNUE derived piece values:\n";
329     for (int row = 0; row < 3*8+1; ++row)
330         ss << board[row] << '\n';
331     ss << '\n';
332
333     auto t = trace_evaluate(pos);
334
335     ss << " NNUE network contributions "
336        << (pos.side_to_move() == WHITE ? "(White to move)" : "(Black to move)") << std::endl
337        << "+------------+------------+------------+------------+\n"
338        << "|   Bucket   |  Material  | Positional |   Total    |\n"
339        << "|            |   (PSQT)   |  (Layers)  |            |\n"
340        << "+------------+------------+------------+------------+\n";
341
342     for (std::size_t bucket = 0; bucket < LayerStacks; ++bucket)
343     {
344       char buffer[3][8];
345       std::memset(buffer, '\0', sizeof(buffer));
346
347       format_cp_aligned_dot(t.psqt[bucket], buffer[0]);
348       format_cp_aligned_dot(t.positional[bucket], buffer[1]);
349       format_cp_aligned_dot(t.psqt[bucket] + t.positional[bucket], buffer[2]);
350
351       ss <<  "|  " << bucket    << "        "
352          << " |  " << buffer[0] << "  "
353          << " |  " << buffer[1] << "  "
354          << " |  " << buffer[2] << "  "
355          << " |";
356       if (bucket == t.correctBucket)
357           ss << " <-- this bucket is used";
358       ss << '\n';
359     }
360
361     ss << "+------------+------------+------------+------------+\n";
362
363     return ss.str();
364   }
365
366
367   // Load eval, from a file stream or a memory stream
368   bool load_eval(std::string name, std::istream& stream) {
369
370     initialize();
371     fileName = name;
372     return read_parameters(stream);
373   }
374
375   // Save eval, to a file stream or a memory stream
376   bool save_eval(std::ostream& stream) {
377
378     if (fileName.empty())
379       return false;
380
381     return write_parameters(stream);
382   }
383
384   /// Save eval, to a file given by its name
385   bool save_eval(const std::optional<std::string>& filename) {
386
387     std::string actualFilename;
388     std::string msg;
389
390     if (filename.has_value())
391         actualFilename = filename.value();
392     else
393     {
394         if (currentEvalFileName != EvalFileDefaultName)
395         {
396              msg = "Failed to export a net. A non-embedded net can only be saved if the filename is specified";
397
398              sync_cout << msg << sync_endl;
399              return false;
400         }
401         actualFilename = EvalFileDefaultName;
402     }
403
404     std::ofstream stream(actualFilename, std::ios_base::binary);
405     bool saved = save_eval(stream);
406
407     msg = saved ? "Network saved successfully to " + actualFilename
408                 : "Failed to export a net";
409
410     sync_cout << msg << sync_endl;
411     return saved;
412   }
413
414
415 } // namespace Stockfish::Eval::NNUE