Files
Rigby/src/mcts.cpp
T
rektdieandclaude c859163e2c feat: live framed search dashboard for a terminal
The terminal output is now a framed dashboard that is redrawn in place
ten times a second instead of a growing list of lines:

- the root position as a coloured board, with the best move's squares
  highlighted;
- the score, white's expected score as an evaluation bar, depth, playouts,
  speed, time with a progress bar (time or playout limit), tree fill and
  notes on tree reuse and collections;
- the principal variation in SAN with move numbers, wrapped and fading
  with depth;
- the most visited root moves (SAN) with a bar for their share of the
  visits, score and prior;
- a spinner while searching, "done" at the end, and bestmove in SAN.

Each frame moves the cursor back to the top of the previous one and
clears below it; lines the user typed under the dashboard (e.g. stop)
are counted and drawn over. The box adapts to the terminal's width and
height (fewer root moves, then no blank lines, the board only when it
fits). RIGBY_PRETTY=1 forces the dashboard into a pipe.

Checked: UCI output is unchanged (node-limited searches identical to
main, including tree reuse and a stalemate root; time-limited ones
differ only in node counts); go wtime, go infinite + stop and quit
work; the dashboard was driven in a real console, including the redraw,
a reused tree and the switch to UCI, and its colours were checked
rendered to HTML. Search is untouched, so the bench is unchanged.

Bench: 546018

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:30:47 +01:00

568 lines
19 KiB
C++

#include "mcts.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <sstream>
#include "eval.h"
#include "pretty.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;
}
size_t Tree::reroot(u32 new_root) {
if (new_root == root()) return used_;
return compact(new_root, 0);
}
size_t Tree::collect_garbage(double keep_fraction) {
const size_t target = size_t(double(nodes_.size()) * keep_fraction);
return compact(root(), prune_threshold(target));
}
u32 Tree::prune_threshold(size_t target) const {
// A node's children survive a collection with threshold T when the node has
// at least T visits. Visits only shrink going down the tree, so every
// ancestor of such a node survives too, and the size kept for a threshold is
// just the children of all nodes with at least that many visits.
constexpr u32 CAP = 1 << 16;
std::vector<u64> children_by_visits(CAP + 1, 0);
std::vector<u32> stack{root()};
while (!stack.empty()) {
const Node& node = nodes_[stack.back()];
stack.pop_back();
if (!node.first_child) continue;
children_by_visits[std::min(node.visits, CAP)] += node.num_children;
for (u32 i = 0; i < node.num_children; i++) stack.push_back(node.first_child + i);
}
u64 kept = 2; // null slot and root
for (u32 v = CAP; v >= 1; v--) {
if (kept + children_by_visits[v] > target) return v + 1;
kept += children_by_visits[v];
}
return 1;
}
size_t Tree::compact(u32 new_root, u32 min_visits) {
// Every child block that stays, as (old first index, size). Nodes below the
// visit threshold lose their children and become leaves again; they keep
// their visits and Q, and get expanded anew if search comes back to them.
std::vector<std::pair<u32, u32>> blocks;
std::vector<u32> stack{new_root};
while (!stack.empty()) {
const u32 idx = stack.back();
stack.pop_back();
Node& node = nodes_[idx];
if (!node.first_child) continue;
if (idx != new_root && node.visits < min_visits) {
node.first_child = 0;
node.num_children = 0;
node.state = UNEXPANDED;
continue;
}
blocks.emplace_back(node.first_child, node.num_children);
for (u32 i = 0; i < node.num_children; i++) stack.push_back(node.first_child + i);
}
// A block is always allocated after its parent's block, so packing the kept
// blocks in their original order only ever moves them towards the front, and
// never onto a block that has not moved yet. That allows doing it in place.
std::sort(blocks.begin(), blocks.end());
std::vector<u32> dest(blocks.size());
u32 next = 2;
for (size_t i = 0; i < blocks.size(); i++) {
dest[i] = next;
next += blocks[i].second;
}
const auto remap = [&](u32 old_first) -> u32 {
if (!old_first) return 0;
const auto it = std::lower_bound(blocks.begin(), blocks.end(), std::make_pair(old_first, u32(0)));
return dest[size_t(it - blocks.begin())];
};
// The new root's own slot may be overwritten by a moved block, so take it first.
Node new_root_node = nodes_[new_root];
new_root_node.first_child = remap(new_root_node.first_child);
for (size_t i = 0; i < blocks.size(); i++) {
const auto [first, count] = blocks[i];
if (dest[i] != first) std::memmove(&nodes_[dest[i]], &nodes_[first], size_t(count) * sizeof(Node));
for (u32 j = 0; j < count; j++) {
Node& node = nodes_[dest[i] + j];
node.first_child = remap(node.first_child);
}
}
nodes_[root()] = new_root_node;
used_ = next;
return used_ - 1; // everything but the null slot
}
// ---------------------------------------------------------------------------
// 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;
}
size_t Searcher::reuse_tree(const Position& root) {
// The new game history must continue the previous one; the keys after the
// old root are the positions reached by the moves played since.
if (!tree_valid_ || history_.size() < prev_history_.size() ||
!std::equal(prev_history_.begin(), prev_history_.end(), history_.begin()))
return 0;
u32 idx = Tree::root();
Position pos = prev_root_;
for (size_t i = prev_history_.size(); i < history_.size(); i++) {
const Node& node = tree_[idx];
if (node.state != EXPANDED) return 0;
u32 next = 0;
for (u32 c = 0; c < node.num_children && !next; c++) {
Position child = pos;
child.make_move(Move::from_raw(tree_[node.first_child + c].move));
if (child.key == history_[i]) {
next = node.first_child + c;
pos = child;
}
}
if (!next) return 0;
idx = next;
}
// A node that was a draw by repetition or the 50-move rule inside the old
// tree can be a real position to play from now; start such a root afresh.
if (pos.key != root.key || tree_[idx].state != EXPANDED) return 0;
return tree_.reroot(idx);
}
#ifdef RIGBY_VERIFY_TREE
// Debug check: the tree must still describe legal play from the root, and every
// expanded node must have at least one visit more than its children together
// (more when it was evaluated as a leaf while the tree was full).
void Searcher::verify_tree() const {
struct Item {
u32 idx;
Position pos;
};
std::vector<Item> stack{{Tree::root(), root_pos_}};
u64 checked = 0;
while (!stack.empty()) {
const Item item = stack.back();
stack.pop_back();
const Node& node = tree_[item.idx];
checked++;
if (node.state != EXPANDED) continue;
MoveList legal;
generate_legal(item.pos, legal);
u64 child_visits = 0;
bool ok = node.first_child >= 2 && node.first_child + node.num_children <= tree_.used() &&
node.num_children == legal.size();
for (u32 c = 0; ok && c < node.num_children; c++) {
const Node& child = tree_[node.first_child + c];
const Move m = Move::from_raw(child.move);
ok = std::find(legal.begin(), legal.end(), m) != legal.end();
child_visits += child.visits;
Position next = item.pos;
next.make_move(m);
stack.push_back({node.first_child + c, next});
}
// The root is expanded before its first visit, so it may have exactly
// as many visits as its children.
const u64 own_visit = item.idx == Tree::root() ? 0 : 1;
if (!ok || node.visits < child_visits + own_visit) {
std::cerr << "TREE CORRUPT at node " << item.idx << " (" << item.pos.fen() << ") ok=" << ok
<< " visits=" << node.visits << " child_visits=" << child_visits
<< " children=" << int(node.num_children) << " legal=" << legal.size()
<< " first=" << node.first_child << " used=" << tree_.used() << std::endl;
std::abort();
}
}
uci_io::send("info string tree verified: " + std::to_string(checked) + " nodes");
}
#endif
float Searcher::evaluate_leaf(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;
}
return eval::value(pos);
}
bool Searcher::expand(u32 idx, const Position& pos) {
Node& node = tree_[idx];
MoveList moves;
generate_legal(pos, moves);
const u32 first = tree_.alloc(u32(moves.size()));
if (!first) {
// Out of memory: this time the node stays a leaf; the tree is collected
// right after this playout, so the next visit can expand it.
gc_pending_ = true;
return false;
}
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 true;
}
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) {
// Most leaves are only ever visited once, so a first visit just
// evaluates; children (moves, priors, memory) come on the second.
if (node.visits == 0) {
value = evaluate_leaf(idx, pos, depth);
break;
}
if (!expand(idx, pos)) {
value = eval::value(pos);
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";
for (const Move m : principal_variation()) out << ' ' << m.to_uci();
uci_io::send(out.str());
}
std::vector<Move> Searcher::principal_variation() const {
std::vector<Move> pv;
u32 idx = Tree::root();
for (int ply = 0; ply < 64; ply++) {
const u32 c = best_child(idx);
if (!c || !tree_[c].visits) break;
pv.push_back(Move::from_raw(tree_[c].move));
idx = c;
}
return pv;
}
void Searcher::draw_dashboard(bool done) {
const Node& root = tree_[Tree::root()];
const u32 best = best_child(Tree::root());
const i64 ms = elapsed_ms();
pretty::Dashboard d;
d.root = root_pos_;
d.depth = int(iterations_ ? std::max<u64>(1, depth_sum_ / iterations_) : 0);
d.seldepth = seldepth_;
d.playouts = iterations_;
d.nps = ms ? iterations_ * 1000 / u64(ms) : iterations_;
d.ms = ms;
d.time_limit_ms = time_limit_ms_;
d.node_limit = node_limit_;
d.hashfull = int(tree_.used() * 1000 / tree_.capacity());
d.cp = eval::q_to_cp(best && tree_[best].visits ? tree_[best].q : -root.q);
d.pv = principal_variation();
for (u32 i = 0; i < root.num_children; i++) {
const Node& child = tree_[root.first_child + i];
d.moves.push_back({Move::from_raw(child.move), child.visits, eval::q_to_cp(child.q), child.prior()});
}
d.reused = reused_;
d.collections = gc_runs_;
d.done = done;
uci_io::send(live_.draw(d));
}
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();
#ifdef RIGBY_VERIFY_TREE
// Check the previous tree as the last search left it, and again after rerooting.
if (tree_valid_ && history_.size() >= prev_history_.size()) {
root_pos_ = prev_root_;
verify_tree();
root_pos_ = root;
}
#endif
const size_t reused = reuse_tree(root);
if (!reused) tree_.clear();
#ifdef RIGBY_VERIFY_TREE
if (reused) verify_tree();
#endif
if (print && !pretty && reused) uci_io::send("info string reused " + std::to_string(reused) + " nodes");
iterations_ = 0;
depth_sum_ = 0;
seldepth_ = 0;
gc_pending_ = false;
gc_runs_ = 0;
reused_ = reused;
node_limit_ = limits.nodes;
compute_time_limit(limits);
SearchResult result;
MoveList root_moves;
generate_legal(root, root_moves);
if (root_moves.empty()) {
tree_valid_ = false;
if (print && pretty)
uci_io::send(pretty::note(root.in_check() ? "checkmate, no legal moves" : "stalemate, no legal moves"));
else if (print)
uci_io::send("info depth 0 score " + std::string(root.in_check() ? "mate 0" : "cp 0"));
return result;
}
if (print && pretty) live_.begin();
// The root needs its children before the first playout, so that even a
// single playout leaves a move to play.
if (tree_[Tree::root()].state == UNEXPANDED && !expand(Tree::root(), root)) {
tree_.clear();
gc_pending_ = false;
expand(Tree::root(), root);
}
// UCI reports once a second; the dashboard for a human is redrawn in place
// ten times a second.
const i64 info_interval = pretty ? 100 : 1000;
const u64 info_mask = pretty ? 255 : 1023;
i64 next_info = pretty ? 0 : 1000;
do {
playout();
if (gc_pending_) {
tree_.collect_garbage(GC_KEEP_FRACTION);
gc_pending_ = false;
gc_runs_++;
#ifdef RIGBY_VERIFY_TREE
verify_tree();
#endif
}
if (print && (iterations_ & info_mask) == 0) {
const i64 ms = elapsed_ms();
if (ms >= next_info) {
next_info = ms + info_interval;
if (pretty) draw_dashboard(false);
else print_info();
}
}
} while (!should_stop(limits));
if (print && pretty) {
draw_dashboard(true);
} else if (print) {
print_info();
if (gc_runs_) uci_io::send("info string tree collected " + std::to_string(gc_runs_) + " times");
}
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();
tree_valid_ = true;
prev_root_ = root;
prev_history_.assign(history_.begin(), history_.begin() + std::ptrdiff_t(root_history_size_));
return result;
}
} // namespace rigby