Files
Rigby/src/uci.cpp
T
rektdieandclaude 1ddb001e0b refactor: rename MCTS to MCGS (src/mcgs.h, src/mcgs.cpp)
Rigby searches a graph since PR #23, so the search files, the banner, the
Makefile header and the README now say MCGS. The README describes the
graph search, reuse, collection and Hash memory as they are now.
Internal names (Tree, RIGBY_VERIFY_TREE) are unchanged.

No behaviour change: zero warnings, bench identical to main twice.

Bench: 608763

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:23:39 +01:00

351 lines
13 KiB
C++

#include "uci.h"
#include <algorithm>
#include <cstdio>
#include <chrono>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include "eval.h"
#include "mcgs.h"
#include "perft.h"
#include "policy.h"
#include "position.h"
#include "pretty.h"
#include "uci_io.h"
namespace rigby {
namespace {
constexpr const char* ENGINE_NAME = "Rigby";
constexpr const char* ENGINE_VERSION = "0.1-dev";
constexpr const char* ENGINE_AUTHOR = "rektdie";
constexpr int DEFAULT_HASH_MB = 64;
constexpr int DEFAULT_BENCH_PLAYOUTS = 5000;
using uci_io::send;
struct Engine {
Position pos;
std::vector<u64> history;
Searcher searcher;
std::thread worker;
Engine() {
pos.set_fen(START_FEN);
history = {pos.key};
searcher.set_hash(DEFAULT_HASH_MB);
}
void stop() {
searcher.stop_flag = true;
if (worker.joinable()) worker.join();
}
};
void print_id() {
send(std::string("id name ") + ENGINE_NAME + " " + ENGINE_VERSION);
send(std::string("id author ") + ENGINE_AUTHOR);
send("option name Hash type spin default " + std::to_string(DEFAULT_HASH_MB) + " min 1 max 65536");
send("option name Threads type spin default 1 min 1 max 1");
send("option name MoveOverhead type spin default 20 min 0 max 5000");
send("option name UCI_Chess960 type check default false");
// A policy network file to use instead of the built-in one (or the move heuristics).
send("option name PolicyFile type string default <empty>");
// Search constants, exposed as integers (x100) so SPSA can tune them.
send("option name CPuct type spin default 160 min 1 max 1000");
send("option name RootCPuct type spin default 233 min 1 max 1000");
send("option name FPUReduction type spin default 30 min 0 max 200");
send("option name PolicyTemp type spin default 100 min 10 max 500");
send("uciok");
}
void set_option(Engine& e, std::istringstream& is) {
std::string token, name, value;
is >> token; // "name"
while (is >> token && token != "value") name += (name.empty() ? "" : " ") + token;
while (is >> token) value += (value.empty() ? "" : " ") + token;
std::string lname = name;
std::transform(lname.begin(), lname.end(), lname.begin(), [](unsigned char c) { return char(std::tolower(c)); });
if (lname == "uci_chess960") {
chess960 = value == "true";
return;
}
if (lname == "policyfile") {
if (!policy::load(value)) send("info string cannot load policy network " + value);
else if (policy::loaded()) send("info string policy network " + std::to_string(policy::hidden()) + " hidden");
else send("info string no policy network, using move heuristics");
return;
}
int v = 0;
try {
v = std::stoi(value);
} catch (...) {
send("info string invalid value for option " + name);
return;
}
if (lname == "hash")
e.searcher.set_hash(size_t(std::clamp(v, 1, 65536)));
else if (lname == "threads")
; // single-threaded for now
else if (lname == "moveoverhead")
e.searcher.params.move_overhead = std::clamp(v, 0, 5000);
else if (lname == "cpuct")
e.searcher.params.cpuct = float(v) / 100.0f;
else if (lname == "rootcpuct")
e.searcher.params.root_cpuct = float(v) / 100.0f;
else if (lname == "fpureduction")
e.searcher.params.fpu_reduction = float(v) / 100.0f;
else if (lname == "policytemp")
e.searcher.params.policy_temperature = float(v) / 100.0f;
else
send("info string unknown option " + name);
}
void set_position(Engine& e, std::istringstream& is) {
std::string token, fen;
is >> token;
if (token == "startpos") {
fen = START_FEN;
} else if (token == "fen") {
while (is >> token && token != "moves") fen += token + " ";
} else {
return;
}
Position pos;
if (!pos.set_fen(fen)) {
send("info string invalid fen: " + fen);
return;
}
e.pos = pos;
e.history = {pos.key};
while (is >> token) {
if (token == "moves") continue;
const Move m = e.pos.parse_uci(token);
if (!m) {
send("info string illegal move: " + token);
break;
}
e.pos.make_move(m);
e.history.push_back(e.pos.key);
}
}
void go(Engine& e, std::istringstream& is) {
SearchLimits limits;
std::string token;
bool limited = false;
while (is >> token) {
if (token == "wtime") is >> limits.time[WHITE], limited = true;
else if (token == "btime") is >> limits.time[BLACK], limited = true;
else if (token == "winc") is >> limits.inc[WHITE];
else if (token == "binc") is >> limits.inc[BLACK];
else if (token == "movestogo") is >> limits.movestogo;
else if (token == "movetime") is >> limits.movetime, limited = true;
else if (token == "nodes") is >> limits.nodes, limited = true;
else if (token == "depth") is >> limits.depth, limited = true;
else if (token == "infinite") limits.infinite = true;
}
if (!limited) limits.infinite = true;
e.stop();
e.searcher.stop_flag = false;
e.worker = std::thread([&e, pos = e.pos, history = e.history, limits] {
const SearchResult result = e.searcher.search(pos, history, limits, true);
send(e.searcher.pretty ? pretty::bestmove(pos, result.best) : "bestmove " + pos.uci(result.best));
});
}
} // namespace
void run_bench(int playouts_per_position) {
static constexpr const char* POSITIONS[] = {
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
"r1bqkb1r/pppp1ppp/2n2n2/4p3/2B1P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 4 4",
"rnbqkb1r/pp1p1ppp/4pn2/2p5/2PP4/2N5/PP2PPPP/R1BQKBNR w KQkq - 0 4",
"r1bq1rk1/ppp2ppp/2np1n2/2b1p3/2B1P3/2NP1N2/PPP2PPP/R1BQ1RK1 w - - 0 7",
"2rq1rk1/pp1bppbp/2np1np1/8/3NP3/1BN1BP2/PPPQ2PP/2KR3R b - - 8 11",
"r2qr1k1/1p1nbppp/p2pbn2/4p3/4P3/1NN1BP2/PPPQ2PP/2KR1B1R w - - 3 12",
"r1b2rk1/2q1bppp/p2ppn2/1p6/3BPP2/2N2B2/PPPQ2PP/R4R1K b - - 2 14",
"3r1rk1/p4pp1/1pq1p2p/2p1Pn2/2P2P2/P2Q2P1/1P4BP/3RR1K1 b - - 0 22",
"6k1/5pp1/1p2p2p/1Pq1Pn2/2P2P2/6P1/4Q1BP/6K1 w - - 1 30",
"8/8/3k4/2p1p3/2P1P3/3K4/8/8 w - - 0 1",
"8/5pk1/6p1/7p/7P/6P1/5PK1/8 w - - 0 40",
"4r1k1/r1q2ppp/ppp2n2/4P3/5Rb1/1N1BQ3/PPP3PP/R5K1 w - - 1 17",
"r3r1k1/2p2ppp/p1p1bn2/8/1q2P3/2NPQN2/PPP3PP/R4RK1 b - - 2 15",
"8/8/8/4k3/8/8/2KR4/8 w - - 0 1",
"6k1/6p1/8/6KQ/1r6/q2b4/8/8 w - - 0 32",
};
Searcher searcher;
SearchLimits limits;
limits.nodes = u64(std::max(playouts_per_position, 1));
// Every playout always counts as one node, so a fixed playout budget would
// give the same total for every build. Instead the bench signature counts
// each position visited in the tree, which moves whenever search changes.
u64 total_nodes = 0;
const auto start = std::chrono::steady_clock::now();
for (const char* fen : POSITIONS) {
Position pos;
if (!pos.set_fen(fen)) {
std::cout << "info string bench: invalid fen " << fen << std::endl;
continue;
}
searcher.stop_flag = false;
const SearchResult r = searcher.search(pos, {pos.key}, limits, false);
total_nodes += r.tree_positions;
}
const auto ms =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
std::cout << total_nodes << " nodes " << (ms ? total_nodes * 1000 / u64(ms) : total_nodes) << " nps" << std::endl;
}
void uci_loop() {
auto engine = std::make_unique<Engine>();
Engine& e = *engine;
// A human at a terminal gets coloured search output until "uci" arrives.
e.searcher.pretty = pretty::init_terminal();
if (e.searcher.pretty) send(pretty::banner(ENGINE_NAME, ENGINE_VERSION, ENGINE_AUTHOR));
std::string line;
while (std::getline(std::cin, line)) {
// The terminal echoed the line under a live dashboard; it redraws over it.
if (e.searcher.pretty) pretty::typed_lines()++;
std::istringstream is(line);
std::string cmd;
is >> cmd;
if (cmd == "uci") {
if (e.searcher.pretty) {
e.stop();
e.searcher.pretty = false;
}
print_id();
} else if (cmd == "isready") {
send("readyok");
} else if (cmd == "ucinewgame") {
e.stop();
e.searcher.new_game();
e.pos.set_fen(START_FEN);
e.history = {e.pos.key};
} else if (cmd == "position") {
e.stop();
set_position(e, is);
} else if (cmd == "go") {
go(e, is);
} else if (cmd == "stop") {
e.stop();
} else if (cmd == "quit") {
break;
} else if (cmd == "setoption") {
e.stop();
set_option(e, is);
} else if (cmd == "d") {
send(e.pos.pretty());
} else if (cmd == "eval") {
send("static " + std::to_string(eval::static_eval(e.pos)) + " cp, qsearch " +
std::to_string(eval::quiescence(e.pos, -30000, 30000, 0)) + " cp (side to move)");
} else if (cmd == "evalfens") {
// Same positions as the trainer's --check, to compare inference
static constexpr const char* FENS[] = {
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b KQkq - 0 1",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R b KQkq - 0 1",
"6k1/5pp1/1p2p2p/1Pq1Pn2/2P2P2/6P1/4Q1BP/6K1 w - - 1 30",
"8/8/3k4/2p1p3/2P1P3/3K4/8/8 w - - 0 1",
"4k3/8/8/8/8/8/8/R3K3 w - - 0 1",
"4k3/8/8/8/8/8/8/R3K3 b - - 0 1",
};
for (const char* fen : FENS) {
Position pos;
pos.set_fen(fen);
char line[160];
std::snprintf(line, sizeof(line), "%6d cp %s", eval::static_eval(pos), fen);
send(line);
}
} else if (cmd == "policyfens") {
// Same positions as the policy trainer's --check, to compare inference
static constexpr const char* FENS[] = {
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R b KQkq - 0 1",
"6k1/5pp1/1p2p2p/1Pq1Pn2/2P2P2/6P1/4Q1BP/6K1 w - - 1 30",
"8/2P2k2/8/8/8/8/5K2/8 w - - 0 1",
};
if (!policy::loaded()) {
send("info string no policy network loaded");
continue;
}
for (const char* fen : FENS) {
Position pos;
pos.set_fen(fen);
MoveList moves;
generate_legal(pos, moves);
float priors[256];
eval::policy(pos, moves, 1.0f, nullptr, priors);
std::vector<std::pair<float, std::string>> lines;
for (int i = 0; i < moves.size(); i++) lines.push_back({priors[i], pos.uci(moves[i])});
std::sort(lines.begin(), lines.end(), [](const auto& a, const auto& b) {
return a.first != b.first ? a.first > b.first : a.second < b.second;
});
send("");
send(fen);
for (const auto& [p, uci] : lines) {
char line[64];
std::snprintf(line, sizeof(line), " %-6s %6.2f%%", uci.c_str(), p * 100.0f);
send(line);
}
}
} else if (cmd == "perft") {
int depth = 5;
is >> depth;
e.stop();
perft_divide(e.pos, depth);
} else if (cmd == "perftsuite") {
int depth = 6;
is >> depth;
e.stop();
perft_suite(depth);
} else if (cmd == "perftfile") {
// perftfile <epd> [max depth]: lines of "<fen> ;D1 <nodes> ;D2 <nodes> ..."
std::string path;
int depth = 6;
is >> path >> depth;
e.stop();
perft_file(path, depth);
} else if (cmd == "bench") {
int playouts = DEFAULT_BENCH_PLAYOUTS;
is >> playouts;
e.stop();
run_bench(playouts);
#ifdef RIGBY_VERIFY_TREE
} else if (cmd == "verify") {
e.stop();
e.searcher.self_test();
#endif
} else if (!cmd.empty()) {
send("info string unknown command: " + cmd);
}
}
e.stop();
}
} // namespace rigby