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