]> git.sesse.net Git - stockfish/blob - src/nnue/evaluate_nnue.cpp
Remove classical evaluation
[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 <fstream>
22 #include <iomanip>
23 #include <iostream>
24 #include <set>
25 #include <sstream>
26 #include <string_view>
27
28 #include "../evaluate.h"
29 #include "../position.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   static 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   static 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   static 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, (std::uint32_t)desc.size());
113     stream.write(&desc[0], desc.size());
114     return !stream.fail();
115   }
116
117   // Read network parameters
118   static 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   static 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   void hint_common_parent_position(const Position& pos) {
140     featureTransformer->hint_common_access(pos);
141   }
142
143   // Evaluation function. Perform differential calculation.
144   Value evaluate(const Position& pos, bool adjusted, int* complexity) {
145
146     // We manually align the arrays on the stack because with gcc < 9.3
147     // overaligning stack variables with alignas() doesn't work correctly.
148
149     constexpr uint64_t alignment = CacheLineSize;
150     constexpr int delta = 24;
151
152 #if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
153     TransformedFeatureType transformedFeaturesUnaligned[
154       FeatureTransformer::BufferSize + alignment / sizeof(TransformedFeatureType)];
155
156     auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
157 #else
158     alignas(alignment)
159       TransformedFeatureType transformedFeatures[FeatureTransformer::BufferSize];
160 #endif
161
162     ASSERT_ALIGNED(transformedFeatures, alignment);
163
164     const int bucket = (pos.count<ALL_PIECES>() - 1) / 4;
165     const auto psqt = featureTransformer->transform(pos, transformedFeatures, bucket);
166     const auto positional = network[bucket]->propagate(transformedFeatures);
167
168     if (complexity)
169         *complexity = abs(psqt - positional) / OutputScale;
170
171     // Give more value to positional evaluation when adjusted flag is set
172     if (adjusted)
173         return static_cast<Value>(((1024 - delta) * psqt + (1024 + delta) * positional) / (1024 * OutputScale));
174     else
175         return static_cast<Value>((psqt + positional) / OutputScale);
176   }
177
178   struct NnueEvalTrace {
179     static_assert(LayerStacks == PSQTBuckets);
180
181     Value psqt[LayerStacks];
182     Value positional[LayerStacks];
183     std::size_t correctBucket;
184   };
185
186   static NnueEvalTrace trace_evaluate(const Position& pos) {
187
188     // We manually align the arrays on the stack because with gcc < 9.3
189     // overaligning stack variables with alignas() doesn't work correctly.
190
191     constexpr uint64_t alignment = CacheLineSize;
192
193 #if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
194     TransformedFeatureType transformedFeaturesUnaligned[
195       FeatureTransformer::BufferSize + alignment / sizeof(TransformedFeatureType)];
196
197     auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
198 #else
199     alignas(alignment)
200       TransformedFeatureType transformedFeatures[FeatureTransformer::BufferSize];
201 #endif
202
203     ASSERT_ALIGNED(transformedFeatures, alignment);
204
205     NnueEvalTrace t{};
206     t.correctBucket = (pos.count<ALL_PIECES>() - 1) / 4;
207     for (IndexType bucket = 0; bucket < LayerStacks; ++bucket) {
208       const auto materialist = featureTransformer->transform(pos, transformedFeatures, bucket);
209       const auto positional = network[bucket]->propagate(transformedFeatures);
210
211       t.psqt[bucket] = static_cast<Value>( materialist / OutputScale );
212       t.positional[bucket] = static_cast<Value>( positional / OutputScale );
213     }
214
215     return t;
216   }
217
218   constexpr std::string_view PieceToChar(" PNBRQK  pnbrqk");
219
220
221   // format_cp_compact() converts a Value into (centi)pawns and writes it in a buffer.
222   // The buffer must have capacity for at least 5 chars.
223   static void format_cp_compact(Value v, char* buffer) {
224
225     buffer[0] = (v < 0 ? '-' : v > 0 ? '+' : ' ');
226
227     int cp = std::abs(100 * v / UCI::NormalizeToPawnValue);
228     if (cp >= 10000)
229     {
230         buffer[1] = '0' + cp / 10000; cp %= 10000;
231         buffer[2] = '0' + cp / 1000; cp %= 1000;
232         buffer[3] = '0' + cp / 100;
233         buffer[4] = ' ';
234     }
235     else if (cp >= 1000)
236     {
237         buffer[1] = '0' + cp / 1000; cp %= 1000;
238         buffer[2] = '0' + cp / 100; cp %= 100;
239         buffer[3] = '.';
240         buffer[4] = '0' + cp / 10;
241     }
242     else
243     {
244         buffer[1] = '0' + cp / 100; cp %= 100;
245         buffer[2] = '.';
246         buffer[3] = '0' + cp / 10; cp %= 10;
247         buffer[4] = '0' + cp / 1;
248     }
249   }
250
251
252   // format_cp_aligned_dot() converts a Value into (centi)pawns, always keeping two decimals.
253   static void format_cp_aligned_dot(Value v, std::stringstream &stream) {
254     const double cp = 1.0 * std::abs(int(v)) / UCI::NormalizeToPawnValue;
255
256     stream << (v < 0 ? '-' : v > 0 ? '+' : ' ')
257            << std::setiosflags(std::ios::fixed)
258            << std::setw(6)
259            << std::setprecision(2)
260            << cp;
261   }
262
263
264   // trace() returns a string with the value of each piece on a board,
265   // and a table for (PSQT, Layers) values bucket by bucket.
266
267   std::string trace(Position& pos) {
268
269     std::stringstream ss;
270
271     char board[3*8+1][8*8+2];
272     std::memset(board, ' ', sizeof(board));
273     for (int row = 0; row < 3*8+1; ++row)
274       board[row][8*8+1] = '\0';
275
276     // A lambda to output one box of the board
277     auto writeSquare = [&board](File file, Rank rank, Piece pc, Value value) {
278
279       const int x = ((int)file) * 8;
280       const int y = (7 - (int)rank) * 3;
281       for (int i = 1; i < 8; ++i)
282          board[y][x+i] = board[y+3][x+i] = '-';
283       for (int i = 1; i < 3; ++i)
284          board[y+i][x] = board[y+i][x+8] = '|';
285       board[y][x] = board[y][x+8] = board[y+3][x+8] = board[y+3][x] = '+';
286       if (pc != NO_PIECE)
287         board[y+1][x+4] = PieceToChar[pc];
288       if (value != VALUE_NONE)
289         format_cp_compact(value, &board[y+2][x+2]);
290     };
291
292     // We estimate the value of each piece by doing a differential evaluation from
293     // the current base eval, simulating the removal of the piece from its square.
294     Value base = evaluate(pos);
295     base = pos.side_to_move() == WHITE ? base : -base;
296
297     for (File f = FILE_A; f <= FILE_H; ++f)
298       for (Rank r = RANK_1; r <= RANK_8; ++r)
299       {
300         Square sq = make_square(f, r);
301         Piece pc = pos.piece_on(sq);
302         Value v = VALUE_NONE;
303
304         if (pc != NO_PIECE && type_of(pc) != KING)
305         {
306           auto st = pos.state();
307
308           pos.remove_piece(sq);
309           st->accumulator.computed[WHITE] = false;
310           st->accumulator.computed[BLACK] = false;
311
312           Value eval = evaluate(pos);
313           eval = pos.side_to_move() == WHITE ? eval : -eval;
314           v = base - eval;
315
316           pos.put_piece(pc, sq);
317           st->accumulator.computed[WHITE] = false;
318           st->accumulator.computed[BLACK] = false;
319         }
320
321         writeSquare(f, r, pc, v);
322       }
323
324     ss << " NNUE derived piece values:\n";
325     for (int row = 0; row < 3*8+1; ++row)
326         ss << board[row] << '\n';
327     ss << '\n';
328
329     auto t = trace_evaluate(pos);
330
331     ss << " NNUE network contributions "
332        << (pos.side_to_move() == WHITE ? "(White to move)" : "(Black to move)") << std::endl
333        << "+------------+------------+------------+------------+\n"
334        << "|   Bucket   |  Material  | Positional |   Total    |\n"
335        << "|            |   (PSQT)   |  (Layers)  |            |\n"
336        << "+------------+------------+------------+------------+\n";
337
338     for (std::size_t bucket = 0; bucket < LayerStacks; ++bucket)
339     {
340       ss <<  "|  " << bucket    << "        ";
341       ss << " |  "; format_cp_aligned_dot(t.psqt[bucket], ss); ss << "  "
342          << " |  "; format_cp_aligned_dot(t.positional[bucket], ss); ss << "  "
343          << " |  "; format_cp_aligned_dot(t.psqt[bucket] + t.positional[bucket], ss); ss << "  "
344          << " |";
345       if (bucket == t.correctBucket)
346           ss << " <-- this bucket is used";
347       ss << '\n';
348     }
349
350     ss << "+------------+------------+------------+------------+\n";
351
352     return ss.str();
353   }
354
355
356   // Load eval, from a file stream or a memory stream
357   bool load_eval(std::string name, std::istream& stream) {
358
359     initialize();
360     fileName = name;
361     return read_parameters(stream);
362   }
363
364   // Save eval, to a file stream or a memory stream
365   bool save_eval(std::ostream& stream) {
366
367     if (fileName.empty())
368       return false;
369
370     return write_parameters(stream);
371   }
372
373   /// Save eval, to a file given by its name
374   bool save_eval(const std::optional<std::string>& filename) {
375
376     std::string actualFilename;
377     std::string msg;
378
379     if (filename.has_value())
380         actualFilename = filename.value();
381     else
382     {
383         if (currentEvalFileName != EvalFileDefaultName)
384         {
385              msg = "Failed to export a net. A non-embedded net can only be saved if the filename is specified";
386
387              sync_cout << msg << sync_endl;
388              return false;
389         }
390         actualFilename = EvalFileDefaultName;
391     }
392
393     std::ofstream stream(actualFilename, std::ios_base::binary);
394     bool saved = save_eval(stream);
395
396     msg = saved ? "Network saved successfully to " + actualFilename
397                 : "Failed to export a net";
398
399     sync_cout << msg << sync_endl;
400     return saved;
401   }
402
403
404 } // namespace Stockfish::Eval::NNUE