Files
Rigby/src/mcts.h
T
rektdieandclaude bf62fe185f feat: hard time limit for moves still open at the soft limit
With smart pruning most searches stop early and the clock piles up:
after move 40 of 8+0.08 self-play about 5 s of the 8 s were left. A
diagnostic of 202 searches showed 190 settled early; the 12 that reached
the time limit were the open ones (the best move had a median 50% of the
root visits, and was the best by Q in only 3 of 12).

So reaching the soft limit (the old allocation) is itself the sign of an
open move. Under a game clock such a search now runs on, with smart
pruning measured against a hard limit of min(3 x soft, remaining / 3),
until it settles or reaches that limit. movetime, nodes and infinite are
unchanged (their hard limit is the soft one).

Self-play diagnostic at 8+0.08 (3 games, 80 plies), main -> this:
average time per move 152-156 -> 162-189 ms, longest move about 350 ->
860-1040 ms, clock left after move 40 4.8-5.4 -> 2.4-5.0 s. go movetime
500 still stops at 480 ms; a 300 ms clock uses 6 ms.

The bench is unchanged: it searches by playout count.

Bench: 554375

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

201 lines
6.3 KiB
C++

#pragma once
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <vector>
#include "position.h"
#include "pretty.h"
namespace rigby {
enum NodeState : u8 {
UNEXPANDED = 0,
EXPANDED,
TERMINAL_LOSS, // side to move is checkmated
TERMINAL_DRAW,
};
// 20 bytes. Children of a node sit next to each other in the arena, so a node
// only needs the index of its first child.
struct Node {
u32 first_child = 0;
u32 visits = 0;
float q = 0.0f; // running mean, from the view of the side that played `move`
u16 move = 0;
u16 policy = 0; // prior scaled to 0..65535
u8 num_children = 0;
u8 state = UNEXPANDED;
float prior() const { return float(policy) * (1.0f / 65535.0f); }
};
class Tree {
public:
void resize_mb(size_t mb);
void clear();
// Returns the index of `count` fresh nodes, or 0 when the arena is full.
u32 alloc(u32 count);
// Makes `new_root` the root and packs its subtree to the front of the arena;
// everything else is dropped. Returns the number of nodes kept.
size_t reroot(u32 new_root);
// Frees memory when the arena is full: the least visited parts of the tree
// are cut back to leaves until at most `keep_fraction` of it is in use.
size_t collect_garbage(double keep_fraction);
Node& operator[](u32 idx) { return nodes_[idx]; }
const Node& operator[](u32 idx) const { return nodes_[idx]; }
static constexpr u32 root() { return 1; }
size_t used() const { return used_; }
size_t capacity() const { return nodes_.size(); }
private:
std::vector<Node> nodes_;
size_t used_ = 0;
// Keeps the subtree of `new_root`, dropping the children of every node with
// fewer than `min_visits` visits, and packs it to the front in place.
size_t compact(u32 new_root, u32 min_visits);
u32 prune_threshold(size_t target) const;
};
// Butterfly history for MCTS (after Vine, aronpetkovski.com/blog/butterfly-history-mcts):
// every playout scores each move on its path with the playout's result, and
// the score is added to the move's policy logit when a node is expanded.
class ButterflyHistory {
public:
// Value of a move's entry at which it shifts the policy logit by 1.
static constexpr float LOGIT_SCALE = 16384.0f;
void clear() { table_ = {}; }
int get(int stm, Move m) const { return table_[stm][m.from()][m.to()]; }
// `bonus` is the playout's result for the side that played `m`, in
// centipawns. Entries pull towards it and saturate near +-8192.
void update(int stm, Move m, int bonus) {
i16& entry = table_[stm][m.from()][m.to()];
const int v = entry + bonus - entry * std::abs(bonus) / 8192;
entry = i16(std::clamp(v, -32000, 32000));
}
private:
std::array<std::array<std::array<i16, 64>, 64>, 2> table_{};
};
struct SearchLimits {
u64 nodes = 0;
i64 movetime = 0;
i64 time[2] = {0, 0};
i64 inc[2] = {0, 0};
int movestogo = 0;
int depth = 0;
bool infinite = false;
};
struct SearchParams {
float cpuct = 1.60f;
float fpu_reduction = 0.30f;
float policy_temperature = 1.00f;
i64 move_overhead = 20;
};
struct SearchResult {
Move best;
u64 nodes = 0; // playouts
u64 tree_positions = 0; // positions visited across all playouts (bench signature)
i64 time_ms = 0;
};
class Searcher {
public:
SearchParams params;
std::atomic<bool> stop_flag{false};
// Coloured output for a human at a terminal instead of UCI info lines.
bool pretty = false;
Searcher();
void set_hash(size_t mb) {
tree_.resize_mb(mb);
tree_valid_ = false;
}
// Forget the previous tree, e.g. on ucinewgame.
void new_game() {
tree_valid_ = false;
butterfly_.clear();
}
// Synchronous search. `history` holds the keys of every position that led to
// `root`, including the key of `root` itself (for repetition detection).
SearchResult search(const Position& root, const std::vector<u64>& history, const SearchLimits& limits,
bool print_info);
private:
using Clock = std::chrono::steady_clock;
Tree tree_;
// Kept between moves of a game, like the tree.
ButterflyHistory butterfly_;
Position root_pos_;
std::vector<u64> history_;
size_t root_history_size_ = 0;
std::vector<u32> path_;
// The previous search, kept so its tree can be reused.
bool tree_valid_ = false;
Position prev_root_;
std::vector<u64> prev_history_;
Clock::time_point start_time_;
i64 time_limit_ms_ = 0; // soft limit
i64 hard_limit_ms_ = 0;
static constexpr i64 HARD_LIMIT_FACTOR = 3;
// The limit comes from the game clock (not movetime), so stopping early saves time.
bool clock_search_ = false;
std::vector<u32> root_start_visits_;
// Lc0's default: the remaining playouts are divided by this before asking
// whether another root move could still overtake the best one.
static constexpr double SMART_PRUNING_FACTOR = 1.33;
u64 iterations_ = 0;
u64 depth_sum_ = 0;
int seldepth_ = 0;
bool gc_pending_ = false;
int gc_runs_ = 0;
size_t reused_ = 0;
u64 node_limit_ = 0;
pretty::LiveView live_;
// Share of the arena kept after a collection.
static constexpr double GC_KEEP_FRACTION = 0.5;
void playout();
// First visit of a node: settles terminal states, otherwise evaluates.
float evaluate_leaf(u32 idx, const Position& pos, int depth);
// Second visit: creates the children with their priors. False when the
// arena is full (a collection is then scheduled).
bool expand(u32 idx, const Position& pos);
u32 select_child(u32 idx) const;
bool is_repetition(const Position& pos) const;
// Finds the node for `root` in the previous tree and makes it the root.
// Returns the number of nodes kept, 0 when nothing could be reused.
size_t reuse_tree(const Position& root);
#ifdef RIGBY_VERIFY_TREE
void verify_tree() const;
#endif
void compute_time_limit(const SearchLimits& limits);
i64 elapsed_ms() const;
bool should_stop(const SearchLimits& limits) const;
bool best_move_settled(i64 ms, i64 limit_ms) const;
u32 best_child(u32 idx) const;
void print_info() const;
std::vector<Move> principal_variation() const;
void draw_dashboard(bool done);
};
} // namespace rigby