]> git.sesse.net Git - stockfish/blob - src/evaluate.cpp
Fix compilation after recent merge.
[stockfish] / src / evaluate.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 #include "evaluate.h"
20
21 #include <algorithm>
22 #include <cassert>
23 #include <cmath>
24 #include <cstdlib>
25 #include <fstream>
26 #include <iomanip>
27 #include <iostream>
28 #include <sstream>
29 #include <vector>
30
31 #include "incbin/incbin.h"
32 #include "misc.h"
33 #include "nnue/evaluate_nnue.h"
34 #include "position.h"
35 #include "thread.h"
36 #include "types.h"
37 #include "uci.h"
38
39 // Macro to embed the default efficiently updatable neural network (NNUE) file
40 // data in the engine binary (using incbin.h, by Dale Weiler).
41 // This macro invocation will declare the following three variables
42 //     const unsigned char        gEmbeddedNNUEData[];  // a pointer to the embedded data
43 //     const unsigned char *const gEmbeddedNNUEEnd;     // a marker to the end
44 //     const unsigned int         gEmbeddedNNUESize;    // the size of the embedded file
45 // Note that this does not work in Microsoft Visual Studio.
46 #if !defined(_MSC_VER) && !defined(NNUE_EMBEDDING_OFF)
47 INCBIN(EmbeddedNNUE, EvalFileDefaultName);
48 #else
49 const unsigned char        gEmbeddedNNUEData[1] = {0x0};
50 const unsigned char* const gEmbeddedNNUEEnd     = &gEmbeddedNNUEData[1];
51 const unsigned int         gEmbeddedNNUESize    = 1;
52 #endif
53
54
55 namespace Stockfish {
56
57 namespace Eval {
58
59 std::string currentEvalFileName = "None";
60
61 // Tries to load a NNUE network at startup time, or when the engine
62 // receives a UCI command "setoption name EvalFile value nn-[a-z0-9]{12}.nnue"
63 // The name of the NNUE network is always retrieved from the EvalFile option.
64 // We search the given network in three locations: internally (the default
65 // network may be embedded in the binary), in the active working directory and
66 // in the engine directory. Distro packagers may define the DEFAULT_NNUE_DIRECTORY
67 // variable to have the engine search in a special directory in their distro.
68 void NNUE::init() {
69
70     std::string eval_file = std::string(Options["EvalFile"]);
71     if (eval_file.empty())
72         eval_file = EvalFileDefaultName;
73
74 #if defined(DEFAULT_NNUE_DIRECTORY)
75     std::vector<std::string> dirs = {"<internal>", "", CommandLine::binaryDirectory,
76                                      stringify(DEFAULT_NNUE_DIRECTORY)};
77 #else
78     std::vector<std::string> dirs = {"<internal>", "", CommandLine::binaryDirectory};
79 #endif
80
81     for (const std::string& directory : dirs)
82         if (currentEvalFileName != eval_file)
83         {
84             if (directory != "<internal>")
85             {
86                 std::ifstream stream(directory + eval_file, std::ios::binary);
87                 if (NNUE::load_eval(eval_file, stream))
88                     currentEvalFileName = eval_file;
89             }
90
91             if (directory == "<internal>" && eval_file == EvalFileDefaultName)
92             {
93                 // C++ way to prepare a buffer for a memory stream
94                 class MemoryBuffer: public std::basic_streambuf<char> {
95                    public:
96                     MemoryBuffer(char* p, size_t n) {
97                         setg(p, p, p + n);
98                         setp(p, p + n);
99                     }
100                 };
101
102                 MemoryBuffer buffer(
103                   const_cast<char*>(reinterpret_cast<const char*>(gEmbeddedNNUEData)),
104                   size_t(gEmbeddedNNUESize));
105                 (void) gEmbeddedNNUEEnd;  // Silence warning on unused variable
106
107                 std::istream stream(&buffer);
108                 if (NNUE::load_eval(eval_file, stream))
109                     currentEvalFileName = eval_file;
110             }
111         }
112 }
113
114 // Verifies that the last net used was loaded successfully
115 void NNUE::verify() {
116
117     std::string eval_file = std::string(Options["EvalFile"]);
118     if (eval_file.empty())
119         eval_file = EvalFileDefaultName;
120
121     if (currentEvalFileName != eval_file)
122     {
123
124         std::string msg1 =
125           "Network evaluation parameters compatible with the engine must be available.";
126         std::string msg2 = "The network file " + eval_file + " was not loaded successfully.";
127         std::string msg3 = "The UCI option EvalFile might need to specify the full path, "
128                            "including the directory name, to the network file.";
129         std::string msg4 = "The default net can be downloaded from: "
130                            "https://tests.stockfishchess.org/api/nn/"
131                          + std::string(EvalFileDefaultName);
132         std::string msg5 = "The engine will be terminated now.";
133
134         sync_cout << "info string ERROR: " << msg1 << sync_endl;
135         sync_cout << "info string ERROR: " << msg2 << sync_endl;
136         sync_cout << "info string ERROR: " << msg3 << sync_endl;
137         sync_cout << "info string ERROR: " << msg4 << sync_endl;
138         sync_cout << "info string ERROR: " << msg5 << sync_endl;
139
140         exit(EXIT_FAILURE);
141     }
142
143     sync_cout << "info string NNUE evaluation using " << eval_file << sync_endl;
144 }
145 }
146
147
148 // Returns a static, purely materialistic evaluation of the position from
149 // the point of view of the given color. It can be divided by PawnValue to get
150 // an approximation of the material advantage on the board in terms of pawns.
151 Value Eval::simple_eval(const Position& pos, Color c) {
152     return PawnValue * (pos.count<PAWN>(c) - pos.count<PAWN>(~c))
153          + (pos.non_pawn_material(c) - pos.non_pawn_material(~c));
154 }
155
156
157 // Evaluate is the evaluator for the outer world. It returns a static evaluation
158 // of the position from the point of view of the side to move.
159 Value Eval::evaluate(const Position& pos) {
160
161     assert(!pos.checkers());
162
163     Value v;
164     Color stm        = pos.side_to_move();
165     int   shuffling  = pos.rule50_count();
166     int   simpleEval = simple_eval(pos, stm) + (int(pos.key() & 7) - 3);
167
168     bool lazy = std::abs(simpleEval) >= RookValue + KnightValue + 16 * shuffling * shuffling
169                                           + std::abs(pos.this_thread()->bestValue)
170                                           + std::abs(pos.this_thread()->rootSimpleEval);
171
172     if (lazy)
173         v = Value(simpleEval);
174     else
175     {
176         int   nnueComplexity;
177         Value nnue = NNUE::evaluate(pos, true, &nnueComplexity);
178
179         Value optimism = pos.this_thread()->optimism[stm];
180
181         // Blend optimism and eval with nnue complexity and material imbalance
182         optimism += optimism * (nnueComplexity + std::abs(simpleEval - nnue)) / 512;
183         nnue -= nnue * (nnueComplexity + std::abs(simpleEval - nnue)) / 32768;
184
185         int npm = pos.non_pawn_material() / 64;
186         v       = (nnue * (915 + npm + 9 * pos.count<PAWN>()) + optimism * (154 + npm)) / 1024;
187     }
188
189     // Damp down the evaluation linearly when shuffling
190     v = v * (200 - shuffling) / 214;
191
192     // Guarantee evaluation does not hit the tablebase range
193     v = std::clamp(v, VALUE_TB_LOSS_IN_MAX_PLY + 1, VALUE_TB_WIN_IN_MAX_PLY - 1);
194
195     return v;
196 }
197
198 // Like evaluate(), but instead of returning a value, it returns
199 // a string (suitable for outputting to stdout) that contains the detailed
200 // descriptions and values of each evaluation term. Useful for debugging.
201 // Trace scores are from white's point of view
202 std::string Eval::trace(Position& pos) {
203
204     if (pos.checkers())
205         return "Final evaluation: none (in check)";
206
207     // Reset any global variable used in eval
208     pos.this_thread()->bestValue       = VALUE_ZERO;
209     pos.this_thread()->rootSimpleEval  = VALUE_ZERO;
210     pos.this_thread()->optimism[WHITE] = VALUE_ZERO;
211     pos.this_thread()->optimism[BLACK] = VALUE_ZERO;
212
213     std::stringstream ss;
214     ss << std::showpoint << std::noshowpos << std::fixed << std::setprecision(2);
215     ss << '\n' << NNUE::trace(pos) << '\n';
216
217     ss << std::showpoint << std::showpos << std::fixed << std::setprecision(2) << std::setw(15);
218
219     Value v;
220     v = NNUE::evaluate(pos, false);
221     v = pos.side_to_move() == WHITE ? v : -v;
222     ss << "NNUE evaluation        " << 0.01 * UCI::to_cp(v) << " (white side)\n";
223
224     v = evaluate(pos);
225     v = pos.side_to_move() == WHITE ? v : -v;
226     ss << "Final evaluation       " << 0.01 * UCI::to_cp(v) << " (white side)";
227     ss << " [with scaled NNUE, ...]";
228     ss << "\n";
229
230     return ss.str();
231 }
232
233 }  // namespace Stockfish