feat: minimal MCTS engine with UCI

Bitboard board with fancy magics and fully legal move generation, checked
by a perft suite. PUCT search over a node arena with FPU reduction and
in-tree draw detection. Hand-written value (eval + quiescence) and
heuristic policy stand in until the network is trained. UCI loop with a
search thread, OpenBench-compatible bench and Makefile.

Bench: 546127

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rektdieandclaude committed 2026-11-15 00:31:20 +01:00
commit d3044c0b88
19 files changed
+1997

No files matched your search

+297
View File
@@ -0,0 +1,297 @@
#include "mcts.h"
#include <algorithm>
#include <cmath>
#include <iostream>
#include <sstream>
#include "eval.h"
#include "uci_io.h"
namespace rigby {
// ---------------------------------------------------------------------------
// Tree
// ---------------------------------------------------------------------------
void Tree::resize_mb(size_t mb) {
const size_t count = std::max<size_t>(mb * 1024 * 1024 / sizeof(Node), 1024);
nodes_.assign(count, Node{});
nodes_.shrink_to_fit();
clear();
}
void Tree::clear() {
used_ = 2; // index 0 is the null child, index 1 is the root
nodes_[root()] = Node{};
}
u32 Tree::alloc(u32 count) {
if (used_ + count > nodes_.size()) return 0;
const u32 idx = u32(used_);
used_ += count;
return idx;
}
// ---------------------------------------------------------------------------
// Searcher
// ---------------------------------------------------------------------------
Searcher::Searcher() { tree_.resize_mb(64); }
i64 Searcher::elapsed_ms() const {
return std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time_).count();
}
void Searcher::compute_time_limit(const SearchLimits& limits) {
time_limit_ms_ = 0;
if (limits.infinite) return;
if (limits.movetime) {
time_limit_ms_ = std::max<i64>(1, limits.movetime - params.move_overhead);
return;
}
const int us = root_pos_.stm;
if (limits.time[us] <= 0) return;
const i64 remaining = std::max<i64>(1, limits.time[us] - params.move_overhead);
const i64 moves_left = limits.movestogo ? std::min(limits.movestogo, 40) : 25;
const i64 target = remaining / moves_left + limits.inc[us] * 3 / 4;
time_limit_ms_ = std::clamp<i64>(target, 1, remaining / 2 + 1);
}
bool Searcher::should_stop(const SearchLimits& limits) const {
if (stop_flag.load(std::memory_order_relaxed)) return true;
if (limits.nodes && iterations_ >= limits.nodes) return true;
if (limits.depth && iterations_) {
// "depth" is the mean playout depth. Solved positions may never get
// there, so a depth limit also carries a generous playout cap.
if (int(depth_sum_ / iterations_) >= limits.depth) return true;
if (iterations_ >= (u64(1000) << std::min(2 * limits.depth, 14))) return true;
}
// The clock is cheap but not free; look at it every 64 playouts.
if (time_limit_ms_ && (iterations_ & 63) == 0 && elapsed_ms() >= time_limit_ms_) return true;
return false;
}
bool Searcher::is_repetition(const Position& pos) const {
// history_.back() is the key of `pos` itself. Any earlier occurrence with the
// same side to move inside the reversible window counts as a draw (two-fold).
const int n = int(history_.size());
for (int back = 4; back <= pos.halfmove && back < n; back += 2)
if (history_[n - 1 - back] == pos.key) return true;
return false;
}
float Searcher::expand(u32 idx, const Position& pos, int depth) {
Node& node = tree_[idx];
MoveList moves;
generate_legal(pos, moves);
if (moves.empty()) {
node.state = pos.in_check() ? TERMINAL_LOSS : TERMINAL_DRAW;
return node.state == TERMINAL_LOSS ? -1.0f : 0.0f;
}
// The root must always produce a move, so it is never declared drawn.
if (depth > 0 && (pos.halfmove >= 100 || pos.insufficient_material() || is_repetition(pos))) {
node.state = TERMINAL_DRAW;
return 0.0f;
}
const u32 first = tree_.alloc(u32(moves.size()));
if (!first) {
// Out of memory: keep the node as a leaf and just evaluate it again.
tree_full_ = true;
return eval::value(pos);
}
float priors[256];
eval::policy(pos, moves, params.policy_temperature, priors);
for (int i = 0; i < moves.size(); i++) {
Node& child = tree_[first + i];
child = Node{};
child.move = moves[i].raw();
child.policy = u16(std::lround(std::clamp(priors[i], 0.0f, 1.0f) * 65535.0f));
}
node.first_child = first;
node.num_children = u8(moves.size());
node.state = EXPANDED;
return eval::value(pos);
}
u32 Searcher::select_child(u32 idx) const {
const Node& node = tree_[idx];
// node.q is from the view of the side that moved into this node, so the side
// to move here sees -q.
const float parent_q = node.visits ? -node.q : 0.0f;
float visited_policy = 0.0f;
for (u32 i = 0; i < node.num_children; i++) {
const Node& child = tree_[node.first_child + i];
if (child.visits) visited_policy += child.prior();
}
const float fpu = parent_q - params.fpu_reduction * std::sqrt(visited_policy);
const float explore = params.cpuct * std::sqrt(float(std::max<u32>(node.visits, 1)));
u32 best = node.first_child;
float best_score = -1e30f;
for (u32 i = 0; i < node.num_children; i++) {
const u32 c = node.first_child + i;
const Node& child = tree_[c];
const float q = child.visits ? child.q : fpu;
const float score = q + explore * child.prior() / float(1 + child.visits);
if (score > best_score) {
best_score = score;
best = c;
}
}
return best;
}
void Searcher::playout() {
Position pos = root_pos_;
history_.resize(root_history_size_);
path_.clear();
u32 idx = Tree::root();
path_.push_back(idx);
int depth = 0;
float value;
for (;;) {
const Node& node = tree_[idx];
if (node.state == TERMINAL_LOSS) {
value = -1.0f;
break;
}
if (node.state == TERMINAL_DRAW) {
value = 0.0f;
break;
}
if (node.state == UNEXPANDED) {
value = expand(idx, pos, depth);
break;
}
idx = select_child(idx);
pos.make_move(Move::from_raw(tree_[idx].move));
history_.push_back(pos.key);
path_.push_back(idx);
depth++;
}
// `value` is from the view of the side to move at the leaf. Each node stores
// the view of the side that moved into it, so flip before every update.
for (size_t i = path_.size(); i-- > 0;) {
value = -value;
Node& node = tree_[path_[i]];
node.visits++;
node.q += (value - node.q) / float(node.visits);
}
iterations_++;
depth_sum_ += u64(depth);
seldepth_ = std::max(seldepth_, depth);
}
u32 Searcher::best_child(u32 idx) const {
const Node& node = tree_[idx];
u32 best = 0;
for (u32 i = 0; i < node.num_children; i++) {
const u32 c = node.first_child + i;
if (!best) {
best = c;
continue;
}
const Node& a = tree_[c];
const Node& b = tree_[best];
// Most visits wins; ties go to the better Q, then to the higher prior.
if (a.visits != b.visits ? a.visits > b.visits : a.visits ? a.q > b.q : a.policy > b.policy) best = c;
}
return best;
}
void Searcher::print_info() const {
const Node& root = tree_[Tree::root()];
const i64 ms = elapsed_ms();
const u32 best = best_child(Tree::root());
std::ostringstream out;
out << "info depth " << (iterations_ ? std::max<u64>(1, depth_sum_ / iterations_) : 0) << " seldepth "
<< seldepth_;
const float q = best && tree_[best].visits ? tree_[best].q : -root.q;
out << " score cp " << eval::q_to_cp(q);
out << " nodes " << iterations_ << " nps " << (ms ? iterations_ * 1000 / u64(ms) : iterations_) << " time " << ms;
out << " hashfull " << (tree_.used() * 1000 / tree_.capacity());
out << " pv";
u32 idx = Tree::root();
for (int ply = 0; ply < 64; ply++) {
const u32 c = best_child(idx);
if (!c || !tree_[c].visits) break;
out << ' ' << Move::from_raw(tree_[c].move).to_uci();
idx = c;
}
uci_io::send(out.str());
}
SearchResult Searcher::search(const Position& root, const std::vector<u64>& history, const SearchLimits& limits,
bool print) {
start_time_ = Clock::now();
root_pos_ = root;
history_ = history;
if (history_.empty() || history_.back() != root.key) history_.push_back(root.key);
root_history_size_ = history_.size();
tree_.clear();
iterations_ = 0;
depth_sum_ = 0;
seldepth_ = 0;
tree_full_ = false;
compute_time_limit(limits);
SearchResult result;
MoveList root_moves;
generate_legal(root, root_moves);
if (root_moves.empty()) {
if (print) uci_io::send("info depth 0 score " + std::string(root.in_check() ? "mate 0" : "cp 0"));
return result;
}
i64 last_info = 0;
// Always run at least one playout so the root gets expanded.
do {
playout();
if (print && (iterations_ & 1023) == 0) {
const i64 ms = elapsed_ms();
if (ms - last_info >= 1000) {
last_info = ms;
print_info();
}
}
} while (!should_stop(limits));
if (print) {
print_info();
if (tree_full_) uci_io::send("info string tree memory full, raise Hash");
}
const u32 best = best_child(Tree::root());
result.best = Move::from_raw(tree_[best].move);
result.nodes = iterations_;
result.tree_positions = iterations_ + depth_sum_;
result.time_ms = elapsed_ms();
return result;
}
} // namespace rigby