Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
official-stockfish
GitHub Repository: official-stockfish/Stockfish
Path: blob/master/src/uci.cpp
376 views
1
/*
2
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
Copyright (C) 2004-2025 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 "uci.h"
20
21
#include <algorithm>
22
#include <cctype>
23
#include <cmath>
24
#include <cstdint>
25
#include <iterator>
26
#include <optional>
27
#include <sstream>
28
#include <string_view>
29
#include <utility>
30
#include <vector>
31
32
#include "benchmark.h"
33
#include "engine.h"
34
#include "memory.h"
35
#include "movegen.h"
36
#include "position.h"
37
#include "score.h"
38
#include "search.h"
39
#include "types.h"
40
#include "ucioption.h"
41
42
namespace Stockfish {
43
44
constexpr auto BenchmarkCommand = "speedtest";
45
46
constexpr auto StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
47
template<typename... Ts>
48
struct overload: Ts... {
49
using Ts::operator()...;
50
};
51
52
template<typename... Ts>
53
overload(Ts...) -> overload<Ts...>;
54
55
void UCIEngine::print_info_string(std::string_view str) {
56
sync_cout_start();
57
for (auto& line : split(str, "\n"))
58
{
59
if (!is_whitespace(line))
60
{
61
std::cout << "info string " << line << '\n';
62
}
63
}
64
sync_cout_end();
65
}
66
67
UCIEngine::UCIEngine(int argc, char** argv) :
68
engine(argv[0]),
69
cli(argc, argv) {
70
71
engine.get_options().add_info_listener([](const std::optional<std::string>& str) {
72
if (str.has_value())
73
print_info_string(*str);
74
});
75
76
init_search_update_listeners();
77
}
78
79
void UCIEngine::init_search_update_listeners() {
80
engine.set_on_iter([](const auto& i) { on_iter(i); });
81
engine.set_on_update_no_moves([](const auto& i) { on_update_no_moves(i); });
82
engine.set_on_update_full(
83
[this](const auto& i) { on_update_full(i, engine.get_options()["UCI_ShowWDL"]); });
84
engine.set_on_bestmove([](const auto& bm, const auto& p) { on_bestmove(bm, p); });
85
engine.set_on_verify_networks([](const auto& s) { print_info_string(s); });
86
}
87
88
void UCIEngine::loop() {
89
std::string token, cmd;
90
91
for (int i = 1; i < cli.argc; ++i)
92
cmd += std::string(cli.argv[i]) + " ";
93
94
do
95
{
96
if (cli.argc == 1
97
&& !getline(std::cin, cmd)) // Wait for an input or an end-of-file (EOF) indication
98
cmd = "quit";
99
100
std::istringstream is(cmd);
101
102
token.clear(); // Avoid a stale if getline() returns nothing or a blank line
103
is >> std::skipws >> token;
104
105
if (token == "quit" || token == "stop")
106
engine.stop();
107
108
// The GUI sends 'ponderhit' to tell that the user has played the expected move.
109
// So, 'ponderhit' is sent if pondering was done on the same move that the user
110
// has played. The search should continue, but should also switch from pondering
111
// to the normal search.
112
else if (token == "ponderhit")
113
engine.set_ponderhit(false);
114
115
else if (token == "uci")
116
{
117
sync_cout << "id name " << engine_info(true) << "\n"
118
<< engine.get_options() << sync_endl;
119
120
sync_cout << "uciok" << sync_endl;
121
}
122
123
else if (token == "setoption")
124
setoption(is);
125
else if (token == "go")
126
{
127
// send info strings after the go command is sent for old GUIs and python-chess
128
print_info_string(engine.numa_config_information_as_string());
129
print_info_string(engine.thread_allocation_information_as_string());
130
go(is);
131
}
132
else if (token == "position")
133
position(is);
134
else if (token == "ucinewgame")
135
engine.search_clear();
136
else if (token == "isready")
137
sync_cout << "readyok" << sync_endl;
138
139
// Add custom non-UCI commands, mainly for debugging purposes.
140
// These commands must not be used during a search!
141
else if (token == "flip")
142
engine.flip();
143
else if (token == "bench")
144
bench(is);
145
else if (token == BenchmarkCommand)
146
benchmark(is);
147
else if (token == "d")
148
sync_cout << engine.visualize() << sync_endl;
149
else if (token == "eval")
150
engine.trace_eval();
151
else if (token == "compiler")
152
sync_cout << compiler_info() << sync_endl;
153
else if (token == "export_net")
154
{
155
std::pair<std::optional<std::string>, std::string> files[2];
156
157
if (is >> std::skipws >> files[0].second)
158
files[0].first = files[0].second;
159
160
if (is >> std::skipws >> files[1].second)
161
files[1].first = files[1].second;
162
163
engine.save_network(files);
164
}
165
else if (token == "--help" || token == "help" || token == "--license" || token == "license")
166
sync_cout
167
<< "\nStockfish is a powerful chess engine for playing and analyzing."
168
"\nIt is released as free software licensed under the GNU GPLv3 License."
169
"\nStockfish is normally used with a graphical user interface (GUI) and implements"
170
"\nthe Universal Chess Interface (UCI) protocol to communicate with a GUI, an API, etc."
171
"\nFor any further information, visit https://github.com/official-stockfish/Stockfish#readme"
172
"\nor read the corresponding README.md and Copying.txt files distributed along with this program.\n"
173
<< sync_endl;
174
else if (!token.empty() && token[0] != '#')
175
sync_cout << "Unknown command: '" << cmd << "'. Type help for more information."
176
<< sync_endl;
177
178
} while (token != "quit" && cli.argc == 1); // The command-line arguments are one-shot
179
}
180
181
Search::LimitsType UCIEngine::parse_limits(std::istream& is) {
182
Search::LimitsType limits;
183
std::string token;
184
185
limits.startTime = now(); // The search starts as early as possible
186
187
while (is >> token)
188
if (token == "searchmoves") // Needs to be the last command on the line
189
while (is >> token)
190
limits.searchmoves.push_back(to_lower(token));
191
192
else if (token == "wtime")
193
is >> limits.time[WHITE];
194
else if (token == "btime")
195
is >> limits.time[BLACK];
196
else if (token == "winc")
197
is >> limits.inc[WHITE];
198
else if (token == "binc")
199
is >> limits.inc[BLACK];
200
else if (token == "movestogo")
201
is >> limits.movestogo;
202
else if (token == "depth")
203
is >> limits.depth;
204
else if (token == "nodes")
205
is >> limits.nodes;
206
else if (token == "movetime")
207
is >> limits.movetime;
208
else if (token == "mate")
209
is >> limits.mate;
210
else if (token == "perft")
211
is >> limits.perft;
212
else if (token == "infinite")
213
limits.infinite = 1;
214
else if (token == "ponder")
215
limits.ponderMode = true;
216
217
return limits;
218
}
219
220
void UCIEngine::go(std::istringstream& is) {
221
222
Search::LimitsType limits = parse_limits(is);
223
224
if (limits.perft)
225
perft(limits);
226
else
227
engine.go(limits);
228
}
229
230
void UCIEngine::bench(std::istream& args) {
231
std::string token;
232
uint64_t num, nodes = 0, cnt = 1;
233
uint64_t nodesSearched = 0;
234
const auto& options = engine.get_options();
235
236
engine.set_on_update_full([&](const auto& i) {
237
nodesSearched = i.nodes;
238
on_update_full(i, options["UCI_ShowWDL"]);
239
});
240
241
std::vector<std::string> list = Benchmark::setup_bench(engine.fen(), args);
242
243
num = count_if(list.begin(), list.end(),
244
[](const std::string& s) { return s.find("go ") == 0 || s.find("eval") == 0; });
245
246
TimePoint elapsed = now();
247
248
for (const auto& cmd : list)
249
{
250
std::istringstream is(cmd);
251
is >> std::skipws >> token;
252
253
if (token == "go" || token == "eval")
254
{
255
std::cerr << "\nPosition: " << cnt++ << '/' << num << " (" << engine.fen() << ")"
256
<< std::endl;
257
if (token == "go")
258
{
259
Search::LimitsType limits = parse_limits(is);
260
261
if (limits.perft)
262
nodesSearched = perft(limits);
263
else
264
{
265
engine.go(limits);
266
engine.wait_for_search_finished();
267
}
268
269
nodes += nodesSearched;
270
nodesSearched = 0;
271
}
272
else
273
engine.trace_eval();
274
}
275
else if (token == "setoption")
276
setoption(is);
277
else if (token == "position")
278
position(is);
279
else if (token == "ucinewgame")
280
{
281
engine.search_clear(); // search_clear may take a while
282
elapsed = now();
283
}
284
}
285
286
elapsed = now() - elapsed + 1; // Ensure positivity to avoid a 'divide by zero'
287
288
dbg_print();
289
290
std::cerr << "\n===========================" //
291
<< "\nTotal time (ms) : " << elapsed //
292
<< "\nNodes searched : " << nodes //
293
<< "\nNodes/second : " << 1000 * nodes / elapsed << std::endl;
294
295
// reset callback, to not capture a dangling reference to nodesSearched
296
engine.set_on_update_full([&](const auto& i) { on_update_full(i, options["UCI_ShowWDL"]); });
297
}
298
299
void UCIEngine::benchmark(std::istream& args) {
300
// Probably not very important for a test this long, but include for completeness and sanity.
301
static constexpr int NUM_WARMUP_POSITIONS = 3;
302
303
std::string token;
304
uint64_t nodes = 0, cnt = 1;
305
uint64_t nodesSearched = 0;
306
307
engine.set_on_update_full([&](const Engine::InfoFull& i) { nodesSearched = i.nodes; });
308
309
engine.set_on_iter([](const auto&) {});
310
engine.set_on_update_no_moves([](const auto&) {});
311
engine.set_on_bestmove([](const auto&, const auto&) {});
312
engine.set_on_verify_networks([](const auto&) {});
313
314
Benchmark::BenchmarkSetup setup = Benchmark::setup_benchmark(args);
315
316
const int numGoCommands = count_if(setup.commands.begin(), setup.commands.end(),
317
[](const std::string& s) { return s.find("go ") == 0; });
318
319
TimePoint totalTime = 0;
320
321
// Set options once at the start.
322
auto ss = std::istringstream("name Threads value " + std::to_string(setup.threads));
323
setoption(ss);
324
ss = std::istringstream("name Hash value " + std::to_string(setup.ttSize));
325
setoption(ss);
326
ss = std::istringstream("name UCI_Chess960 value false");
327
setoption(ss);
328
329
// Warmup
330
for (const auto& cmd : setup.commands)
331
{
332
std::istringstream is(cmd);
333
is >> std::skipws >> token;
334
335
if (token == "go")
336
{
337
// One new line is produced by the search, so omit it here
338
std::cerr << "\rWarmup position " << cnt++ << '/' << NUM_WARMUP_POSITIONS;
339
340
Search::LimitsType limits = parse_limits(is);
341
342
TimePoint elapsed = now();
343
344
// Run with silenced network verification
345
engine.go(limits);
346
engine.wait_for_search_finished();
347
348
totalTime += now() - elapsed;
349
350
nodes += nodesSearched;
351
nodesSearched = 0;
352
}
353
else if (token == "position")
354
position(is);
355
else if (token == "ucinewgame")
356
{
357
engine.search_clear(); // search_clear may take a while
358
}
359
360
if (cnt > NUM_WARMUP_POSITIONS)
361
break;
362
}
363
364
std::cerr << "\n";
365
366
cnt = 1;
367
nodes = 0;
368
369
int numHashfullReadings = 0;
370
constexpr int hashfullAges[] = {0, 999}; // Only normal hashfull and touched hash.
371
int totalHashfull[std::size(hashfullAges)] = {0};
372
int maxHashfull[std::size(hashfullAges)] = {0};
373
374
auto updateHashfullReadings = [&]() {
375
numHashfullReadings += 1;
376
377
for (int i = 0; i < static_cast<int>(std::size(hashfullAges)); ++i)
378
{
379
const int hashfull = engine.get_hashfull(hashfullAges[i]);
380
maxHashfull[i] = std::max(maxHashfull[i], hashfull);
381
totalHashfull[i] += hashfull;
382
}
383
};
384
385
engine.search_clear(); // search_clear may take a while
386
387
for (const auto& cmd : setup.commands)
388
{
389
std::istringstream is(cmd);
390
is >> std::skipws >> token;
391
392
if (token == "go")
393
{
394
// One new line is produced by the search, so omit it here
395
std::cerr << "\rPosition " << cnt++ << '/' << numGoCommands;
396
397
Search::LimitsType limits = parse_limits(is);
398
399
TimePoint elapsed = now();
400
401
// Run with silenced network verification
402
engine.go(limits);
403
engine.wait_for_search_finished();
404
405
totalTime += now() - elapsed;
406
407
updateHashfullReadings();
408
409
nodes += nodesSearched;
410
nodesSearched = 0;
411
}
412
else if (token == "position")
413
position(is);
414
else if (token == "ucinewgame")
415
{
416
engine.search_clear(); // search_clear may take a while
417
}
418
}
419
420
totalTime = std::max<TimePoint>(totalTime, 1); // Ensure positivity to avoid a 'divide by zero'
421
422
dbg_print();
423
424
std::cerr << "\n";
425
426
static_assert(
427
std::size(hashfullAges) == 2 && hashfullAges[0] == 0 && hashfullAges[1] == 999,
428
"Hardcoded for display. Would complicate the code needlessly in the current state.");
429
430
std::string threadBinding = engine.thread_binding_information_as_string();
431
if (threadBinding.empty())
432
threadBinding = "none";
433
434
// clang-format off
435
436
std::cerr << "==========================="
437
<< "\nVersion : "
438
<< engine_version_info()
439
// "\nCompiled by : "
440
<< compiler_info()
441
<< "Large pages : " << (has_large_pages() ? "yes" : "no")
442
<< "\nUser invocation : " << BenchmarkCommand << " "
443
<< setup.originalInvocation << "\nFilled invocation : " << BenchmarkCommand
444
<< " " << setup.filledInvocation
445
<< "\nAvailable processors : " << engine.get_numa_config_as_string()
446
<< "\nThread count : " << setup.threads
447
<< "\nThread binding : " << threadBinding
448
<< "\nTT size [MiB] : " << setup.ttSize
449
<< "\nHash max, avg [per mille] : "
450
<< "\n single search : " << maxHashfull[0] << ", "
451
<< totalHashfull[0] / numHashfullReadings
452
<< "\n single game : " << maxHashfull[1] << ", "
453
<< totalHashfull[1] / numHashfullReadings
454
<< "\nTotal nodes searched : " << nodes
455
<< "\nTotal search time [s] : " << totalTime / 1000.0
456
<< "\nNodes/second : " << 1000 * nodes / totalTime << std::endl;
457
458
// clang-format on
459
460
init_search_update_listeners();
461
}
462
463
void UCIEngine::setoption(std::istringstream& is) {
464
engine.wait_for_search_finished();
465
engine.get_options().setoption(is);
466
}
467
468
std::uint64_t UCIEngine::perft(const Search::LimitsType& limits) {
469
auto nodes = engine.perft(engine.fen(), limits.perft, engine.get_options()["UCI_Chess960"]);
470
sync_cout << "\nNodes searched: " << nodes << "\n" << sync_endl;
471
return nodes;
472
}
473
474
void UCIEngine::position(std::istringstream& is) {
475
std::string token, fen;
476
477
is >> token;
478
479
if (token == "startpos")
480
{
481
fen = StartFEN;
482
is >> token; // Consume the "moves" token, if any
483
}
484
else if (token == "fen")
485
while (is >> token && token != "moves")
486
fen += token + " ";
487
else
488
return;
489
490
std::vector<std::string> moves;
491
492
while (is >> token)
493
{
494
moves.push_back(token);
495
}
496
497
engine.set_position(fen, moves);
498
}
499
500
namespace {
501
502
struct WinRateParams {
503
double a;
504
double b;
505
};
506
507
WinRateParams win_rate_params(const Position& pos) {
508
509
int material = pos.count<PAWN>() + 3 * pos.count<KNIGHT>() + 3 * pos.count<BISHOP>()
510
+ 5 * pos.count<ROOK>() + 9 * pos.count<QUEEN>();
511
512
// The fitted model only uses data for material counts in [17, 78], and is anchored at count 58.
513
double m = std::clamp(material, 17, 78) / 58.0;
514
515
// Return a = p_a(material) and b = p_b(material), see github.com/official-stockfish/WDL_model
516
constexpr double as[] = {-13.50030198, 40.92780883, -36.82753545, 386.83004070};
517
constexpr double bs[] = {96.53354896, -165.79058388, 90.89679019, 49.29561889};
518
519
double a = (((as[0] * m + as[1]) * m + as[2]) * m) + as[3];
520
double b = (((bs[0] * m + bs[1]) * m + bs[2]) * m) + bs[3];
521
522
return {a, b};
523
}
524
525
// The win rate model is 1 / (1 + exp((a - eval) / b)), where a = p_a(material) and b = p_b(material).
526
// It fits the LTC fishtest statistics rather accurately.
527
int win_rate_model(Value v, const Position& pos) {
528
529
auto [a, b] = win_rate_params(pos);
530
531
// Return the win rate in per mille units, rounded to the nearest integer.
532
return int(0.5 + 1000 / (1 + std::exp((a - double(v)) / b)));
533
}
534
}
535
536
std::string UCIEngine::format_score(const Score& s) {
537
constexpr int TB_CP = 20000;
538
const auto format =
539
overload{[](Score::Mate mate) -> std::string {
540
auto m = (mate.plies > 0 ? (mate.plies + 1) : mate.plies) / 2;
541
return std::string("mate ") + std::to_string(m);
542
},
543
[](Score::Tablebase tb) -> std::string {
544
return std::string("cp ")
545
+ std::to_string((tb.win ? TB_CP - tb.plies : -TB_CP - tb.plies));
546
},
547
[](Score::InternalUnits units) -> std::string {
548
return std::string("cp ") + std::to_string(units.value);
549
}};
550
551
return s.visit(format);
552
}
553
554
// Turns a Value to an integer centipawn number,
555
// without treatment of mate and similar special scores.
556
int UCIEngine::to_cp(Value v, const Position& pos) {
557
558
// In general, the score can be defined via the WDL as
559
// (log(1/L - 1) - log(1/W - 1)) / (log(1/L - 1) + log(1/W - 1)).
560
// Based on our win_rate_model, this simply yields v / a.
561
562
auto [a, b] = win_rate_params(pos);
563
564
return std::round(100 * int(v) / a);
565
}
566
567
std::string UCIEngine::wdl(Value v, const Position& pos) {
568
std::stringstream ss;
569
570
int wdl_w = win_rate_model(v, pos);
571
int wdl_l = win_rate_model(-v, pos);
572
int wdl_d = 1000 - wdl_w - wdl_l;
573
ss << wdl_w << " " << wdl_d << " " << wdl_l;
574
575
return ss.str();
576
}
577
578
std::string UCIEngine::square(Square s) {
579
return std::string{char('a' + file_of(s)), char('1' + rank_of(s))};
580
}
581
582
std::string UCIEngine::move(Move m, bool chess960) {
583
if (m == Move::none())
584
return "(none)";
585
586
if (m == Move::null())
587
return "0000";
588
589
Square from = m.from_sq();
590
Square to = m.to_sq();
591
592
if (m.type_of() == CASTLING && !chess960)
593
to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
594
595
std::string move = square(from) + square(to);
596
597
if (m.type_of() == PROMOTION)
598
move += " pnbrqk"[m.promotion_type()];
599
600
return move;
601
}
602
603
604
std::string UCIEngine::to_lower(std::string str) {
605
std::transform(str.begin(), str.end(), str.begin(), [](auto c) { return std::tolower(c); });
606
607
return str;
608
}
609
610
Move UCIEngine::to_move(const Position& pos, std::string str) {
611
str = to_lower(str);
612
613
for (const auto& m : MoveList<LEGAL>(pos))
614
if (str == move(m, pos.is_chess960()))
615
return m;
616
617
return Move::none();
618
}
619
620
void UCIEngine::on_update_no_moves(const Engine::InfoShort& info) {
621
sync_cout << "info depth " << info.depth << " score " << format_score(info.score) << sync_endl;
622
}
623
624
void UCIEngine::on_update_full(const Engine::InfoFull& info, bool showWDL) {
625
std::stringstream ss;
626
627
ss << "info";
628
ss << " depth " << info.depth //
629
<< " seldepth " << info.selDepth //
630
<< " multipv " << info.multiPV //
631
<< " score " << format_score(info.score); //
632
633
if (!info.bound.empty())
634
ss << " " << info.bound;
635
636
if (showWDL)
637
ss << " wdl " << info.wdl;
638
639
ss << " nodes " << info.nodes //
640
<< " nps " << info.nps //
641
<< " hashfull " << info.hashfull //
642
<< " tbhits " << info.tbHits //
643
<< " time " << info.timeMs //
644
<< " pv " << info.pv; //
645
646
sync_cout << ss.str() << sync_endl;
647
}
648
649
void UCIEngine::on_iter(const Engine::InfoIter& info) {
650
std::stringstream ss;
651
652
ss << "info";
653
ss << " depth " << info.depth //
654
<< " currmove " << info.currmove //
655
<< " currmovenumber " << info.currmovenumber; //
656
657
sync_cout << ss.str() << sync_endl;
658
}
659
660
void UCIEngine::on_bestmove(std::string_view bestmove, std::string_view ponder) {
661
sync_cout << "bestmove " << bestmove;
662
if (!ponder.empty())
663
std::cout << " ponder " << ponder;
664
std::cout << sync_endl;
665
}
666
667
} // namespace Stockfish
668
669