]> git.sesse.net Git - stockfish/blob - src/evaluate.cpp
Cleanup includes
[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 using namespace std;
55
56 namespace Stockfish {
57
58 namespace Eval {
59
60   string currentEvalFileName = "None";
61
62   /// NNUE::init() tries to load a NNUE network at startup time, or when the engine
63   /// receives a UCI command "setoption name EvalFile value nn-[a-z0-9]{12}.nnue"
64   /// The name of the NNUE network is always retrieved from the EvalFile option.
65   /// We search the given network in three locations: internally (the default
66   /// network may be embedded in the binary), in the active working directory and
67   /// in the engine directory. Distro packagers may define the DEFAULT_NNUE_DIRECTORY
68   /// variable to have the engine search in a special directory in their distro.
69
70   void NNUE::init() {
71
72     string eval_file = string(Options["EvalFile"]);
73     if (eval_file.empty())
74         eval_file = EvalFileDefaultName;
75
76     #if defined(DEFAULT_NNUE_DIRECTORY)
77     vector<string> dirs = { "<internal>" , "" , CommandLine::binaryDirectory , stringify(DEFAULT_NNUE_DIRECTORY) };
78     #else
79     vector<string> dirs = { "<internal>" , "" , CommandLine::binaryDirectory };
80     #endif
81
82     for (const string& directory : dirs)
83         if (currentEvalFileName != eval_file)
84         {
85             if (directory != "<internal>")
86             {
87                 ifstream stream(directory + eval_file, ios::binary);
88                 if (NNUE::load_eval(eval_file, stream))
89                     currentEvalFileName = eval_file;
90             }
91
92             if (directory == "<internal>" && eval_file == EvalFileDefaultName)
93             {
94                 // C++ way to prepare a buffer for a memory stream
95                 class MemoryBuffer : public basic_streambuf<char> {
96                     public: MemoryBuffer(char* p, size_t n) { setg(p, p, p + n); setp(p, p + n); }
97                 };
98
99                 MemoryBuffer buffer(const_cast<char*>(reinterpret_cast<const char*>(gEmbeddedNNUEData)),
100                                     size_t(gEmbeddedNNUESize));
101                 (void) gEmbeddedNNUEEnd; // Silence warning on unused variable
102
103                 istream stream(&buffer);
104                 if (NNUE::load_eval(eval_file, stream))
105                     currentEvalFileName = eval_file;
106             }
107         }
108   }
109
110   /// NNUE::verify() verifies that the last net used was loaded successfully
111   void NNUE::verify() {
112
113     string eval_file = string(Options["EvalFile"]);
114     if (eval_file.empty())
115         eval_file = EvalFileDefaultName;
116
117     if (currentEvalFileName != eval_file)
118     {
119
120         string msg1 = "Network evaluation parameters compatible with the engine must be available.";
121         string msg2 = "The network file " + eval_file + " was not loaded successfully.";
122         string msg3 = "The UCI option EvalFile might need to specify the full path, including the directory name, to the network file.";
123         string msg4 = "The default net can be downloaded from: https://tests.stockfishchess.org/api/nn/" + std::string(EvalFileDefaultName);
124         string msg5 = "The engine will be terminated now.";
125
126         sync_cout << "info string ERROR: " << msg1 << sync_endl;
127         sync_cout << "info string ERROR: " << msg2 << sync_endl;
128         sync_cout << "info string ERROR: " << msg3 << sync_endl;
129         sync_cout << "info string ERROR: " << msg4 << sync_endl;
130         sync_cout << "info string ERROR: " << msg5 << sync_endl;
131
132         exit(EXIT_FAILURE);
133     }
134
135     sync_cout << "info string NNUE evaluation using " << eval_file << sync_endl;
136   }
137 }
138
139 /// evaluate() is the evaluator for the outer world. It returns a static
140 /// evaluation of the position from the point of view of the side to move.
141
142 Value Eval::evaluate(const Position& pos) {
143
144   assert(!pos.checkers());
145
146   Value v;
147
148   int nnueComplexity;
149   int npm = pos.non_pawn_material() / 64;
150
151   Color stm = pos.side_to_move();
152   Value optimism = pos.this_thread()->optimism[stm];
153
154   Value nnue = NNUE::evaluate(pos, true, &nnueComplexity);
155
156   int material =  pos.non_pawn_material(stm) - pos.non_pawn_material(~stm)
157                 + 126 * (pos.count<PAWN>(stm) - pos.count<PAWN>(~stm));
158
159   // Blend optimism and eval with nnue complexity and material imbalance
160   optimism += optimism * (nnueComplexity + abs(material - nnue)) / 512;
161   nnue     -= nnue     * (nnueComplexity + abs(material - nnue)) / 32768;
162
163   v = (  nnue     * (915 + npm + 9 * pos.count<PAWN>())
164        + optimism * (154 + npm +     pos.count<PAWN>())) / 1024;
165
166   // Damp down the evaluation linearly when shuffling
167   v = v * (200 - pos.rule50_count()) / 214;
168
169   // Guarantee evaluation does not hit the tablebase range
170   v = std::clamp(v, VALUE_TB_LOSS_IN_MAX_PLY + 1, VALUE_TB_WIN_IN_MAX_PLY - 1);
171
172   return v;
173 }
174
175 /// trace() is like evaluate(), but instead of returning a value, it returns
176 /// a string (suitable for outputting to stdout) that contains the detailed
177 /// descriptions and values of each evaluation term. Useful for debugging.
178 /// Trace scores are from white's point of view
179
180 std::string Eval::trace(Position& pos) {
181
182   if (pos.checkers())
183       return "Final evaluation: none (in check)";
184
185   // Reset any global variable used in eval
186   pos.this_thread()->bestValue       = VALUE_ZERO;
187   pos.this_thread()->optimism[WHITE] = VALUE_ZERO;
188   pos.this_thread()->optimism[BLACK] = VALUE_ZERO;
189
190   std::stringstream ss;
191   ss << std::showpoint << std::noshowpos << std::fixed << std::setprecision(2);
192   ss << '\n' << NNUE::trace(pos) << '\n';
193
194   ss << std::showpoint << std::showpos << std::fixed << std::setprecision(2) << std::setw(15);
195
196   Value v;
197   v = NNUE::evaluate(pos, false);
198   v = pos.side_to_move() == WHITE ? v : -v;
199   ss << "NNUE evaluation        " << 0.01 * UCI::to_cp(v) << " (white side)\n";
200
201   v = evaluate(pos);
202   v = pos.side_to_move() == WHITE ? v : -v;
203   ss << "Final evaluation       " << 0.01 * UCI::to_cp(v) << " (white side)";
204   ss << " [with scaled NNUE, ...]";
205   ss << "\n";
206
207   return ss.str();
208 }
209
210 } // namespace Stockfish