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