MCTS with UCT and Elo measurement
Implement MCTS with UCT and random rollouts and build evaluation infrastructure for the project: tournaments between agents with varied openings, Bradley-Terry Elo fitting with bootstrap intervals, and optimal-move percentage according to the solver. Measure how MCTS strength scales with simulation count.
After this lesson you can
- Implement MCTS with UCB selection, expansion, simulation, and alternating-sign backpropagation.
- Build a tournament system with varied openings and alternating colors.
- Estimate Elo with Bradley-Terry and bootstrap intervals.
- Plot Elo and optimal-move percentage against simulation count.
Before you start
Search without traversing the whole tree
The previous lesson’s exact solver returns the best outcome against perfect play. Its guarantee comes from searching to the end and maintaining valid bounds. To decide with a limited budget we need another tool: a search concentrating simulations where they can change the decision, although its answer is not yet a mathematical proof. This is MCTS, Monte Carlo tree search.
A simulation is a possible game, not a prediction of how a perfect opponent must play. If continuations are chosen randomly, a move may look good because simulated opponents miss a defense. MCTS organizes those samples in a tree and allocates more work to promising options without completely abandoning less-explored ones. This lesson asks two questions: how is work allocated, and how do we know whether more work actually improves play?
Reading the figure requires distinguishing three quantities. Visits say how much work an action received; its mean summarizes observed results in those visits; UCT score adds an exploration incentive. They are not three names for the same probability. At the end of search we usually choose the most-visited action, not the one with the greatest exploration bonus: the bonus allocates the next computation rather than declaring a winning move.
Four phases, two perspectives
MCTS with UCT, an application of Monte Carlo tree search, repeats four operations from a root representing the current position:
- Selection: descend through existing children according to a score combining mean value and exploration.
- Expansion: if a legal move has no child yet, add one and apply the move.
- Simulation: from the new state, play to an outcome with a rollout policy, here uniform over legal actions. If the state is already terminal, use its result directly.
- Backpropagation: increment visits and accumulate the result in nodes along the path.
These phases are not interchangeable. Expansion must not create a child for a full column and simulation must not continue after a win. Each node stores visits and a result sum . Under the previous lesson’s convention, each node’s value belongs to the player who would move there. A child created by the parent’s winning move is terminal and has value for the player who would have moved next. On returning along an edge, the sign changes because the result is zero-sum.
Random rollout estimates the outcome of a particular policy, not minimax. Moreover, a node’s sample distribution changes as the tree policy improves; it is not a fixed sequence of independent games from one distribution. Understand UCT as adaptive allocation and check its decisions against the oracle rather than treating a mean as an ordinary confidence interval for a stationary probability.
The UCT rule and its scale
At a parent node visited times, a child with visits and mean from the parent’s perspective receives the score
The first term exploits what was learned; the second favors little-visited actions. Intuition comes from the UCB1 bandit, although MCTS branch rewards change during search. With , after expanding children selection favors the observed mean and can be trapped by unlucky initial samples. Increasing spends more budget exploring, but no value is universally optimal: its effect depends on reward scale, rollout policy, and budget. Here outcomes are in ; copying a constant calibrated for rewards in changes the balance.
An unvisited action has no mean or valid denominator. The implementation expands it before applying the formula instead of dividing by zero. The logarithm is natural. If means are stored from the child’s turn, as in the lab, the mean used in the formula is . Tie-breaking order and seed are also protocol components: with few trials they can change the tree and final action.
Kocsis and Szepesvári present UCT as bandit-based planning and study its consistency under specific finite-horizon or discount assumptions. That theory does not say doubling simulations grants a fixed amount of Elo in every game or regime. Such a relationship, if shown in a chart, is an observation of an experiment and its interval, not an algebraic property of UCT.
Measure strength without confusing it with the opponent
To compare budgets we play with varied openings and swapped colors. Each opening generates a block of two games: in one agent A moves first from that position, and in the other it moves second. Using identical positions and deterministic agents can repeat the same trajectory many times without gaining information from independent games. Recording opening sequence, seeds, colors, budget, and outcome makes the tournament reproducible and reveals imbalances.
Elo from matches summarizes relative results on a scale. In the binary Bradley-Terry model, with ratings and , the modeled probability that wins is
Only differences matter: adding the same constant to every rating changes no probability. Therefore fix a reference, for example . A tournament scale between agents does not identify their strength against an outside population without shared opponents or another connection between match sets. Elo is not a physical property of a program independent of opponents, openings, and game rules.
With outcomes , log likelihood sums . In the lab we assign to a draw and use the same function as a scoring quasi-likelihood. We do not separately model draw probability: is interpreted as expected score under that approximation, not win probability when draws exist. A three-outcome model such as Davidson introduces an additional draw term and gives parameters another interpretation.
Match-graph connectivity is necessary to compare all agents. With binary data, a finite maximum also requires sufficient directed connectivity of outcomes: if one group only beats another and never loses, the estimated difference can grow without bound. An optimizer returning a large number does not make that separation evidence of a finite Elo. Draws with half score contribute in both directions to quasi-likelihood, but do not make comparisons between disconnected components valid.
Uncertainty and test-set choice
The percentile bootstrap interval resamples observation units and repeats fitting. If the two color-swapped games share an opening, resample the opening block, keeping both: treating them as independent observations would ignore shared initial-board variation. Some resamples may lose connectivity or produce separation; count those failures and report their treatment. An interval obtained by discarding them is conditional on valid resamples, not a universal coverage guarantee.
Optimal-move percentage answers another question. For each test position, the oracle calculates the best weak outcome and every column preserving it. The agent is correct if its column belongs to that set, even if it is not the fastest win. The proportion depends on how positions were chosen: easy endgames, critical positions, and common openings can yield very different percentages. A rise in Elo among one’s own opponents does not replace this measure, and improved accuracy on selected positions does not guarantee better performance against every opponent.
The two numerical exercise operations can be checked without the tournament:
import math
print('UCT:', 0.6 + 1.4 * math.sqrt(math.log(200) / 30))
print('Probabilidad sin empates:', 1 / (1 + 10 ** (-200 / 400)))Lab: MCTS, tournament, and oracle
The engine uses the same bits, turns, and win condition as the previous lesson, but each lesson’s cells have their own environment. We include the pieces needed for the lab to run independently. Search uses an explicit seed per decision and no GPU; the tournament distributes independent games among CPU threads.
Tree nodes are stored in arrays with enough capacity to add at most one node per simulation. Each node’s sum belongs to the player active at that node. terminal=-1 indicates the parent just won, while terminal=0 indicates a draw. Unexpanded nodes are tried before UCT is calculated and the final action is the most visited, breaking ties by first index.
The code compiles complete traversal and simulation with Numba. On Windows, functions in a cell cannot be imported by processes created with spawn: here we distribute games between two threads and compiled traversal releases the GIL. One call is compiled before launching threads; each search sets its own seed. Openings have six legal moves and budgets are swapped across colors. Each of 24 boards contributes one block to each matchup. A draw counts half a point in fitting, not as a binary win.
"""Laboratorio autocontenido: motor de la celda de p12-l01 y MCTS compilado."""
import math
import json
import random
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import numpy as np
from numba import njit
from scipy.optimize import minimize
from urllib.request import urlopen
# Misma representación, máscara, turnos y convención de p12-l01.
W, H, S = 7, 6, 7
BOTTOM = sum(1 << (c * S) for c in range(W))
BOARD = BOTTOM * ((1 << H) - 1)
@njit
def win(p):
for d in (1, 6, 7, 8):
m = p & (p >> d)
if m & (m >> (2*d)):
return True
return False
@njit
def move_bit(mask, c):
return ((mask + BOTTOM) & BOARD) & (63 << (c*7))
@njit
def rollout(p, mask):
# Salida desde la perspectiva del jugador activo al comenzar.
sign = 1
while mask != BOARD:
legal = np.empty(7, dtype=np.int64)
n = 0
for c in range(7):
if move_bit(mask, c):
legal[n] = c
n += 1
c = legal[np.random.randint(n)]
b = move_bit(mask, c)
if win(p | b):
return sign
p, mask = p ^ mask, mask | b
sign = -sign
return 0
@njit(nogil=True)
def mcts(p0, mask0, simulations, exploration, seed):
np.random.seed(seed)
size = simulations + 1
children = np.full((size, 7), -1, np.int32)
pp = np.zeros(size, np.int64)
mm = np.zeros(size, np.int64)
parent = np.full(size, -1, np.int32)
visits = np.zeros(size, np.int32)
total = np.zeros(size, np.float64)
terminal = np.full(size, 2, np.int8) # 2 no terminal, -1 perdida, 0 empate
pp[0], mm[0] = p0, mask0
count = 1
for _ in range(simulations):
i = 0
while terminal[i] == 2:
p, mask = pp[i], mm[i]
unexpanded = np.empty(7, np.int64)
n = 0
for c in range(7):
if move_bit(mask, c) and children[i, c] < 0:
unexpanded[n] = c
n += 1
if n:
c = unexpanded[np.random.randint(n)]
b = move_bit(mask, c)
child = count
count += 1
children[i, c] = child
parent[child] = i
pp[child], mm[child] = p ^ mask, mask | b
if win(p | b):
terminal[child] = -1
elif mm[child] == BOARD:
terminal[child] = 0
i = child
break
best = -1e9
chosen = -1
for c in range(7):
child = children[i, c]
if child < 0:
continue
# total[child] es valor del jugador del hijo: negar para el padre.
ucb = -total[child] / visits[child] + exploration * math.sqrt(math.log(visits[i]) / visits[child])
if ucb > best:
best, chosen = ucb, child
i = chosen
value = terminal[i] if terminal[i] != 2 else rollout(pp[i], mm[i])
while i >= 0:
visits[i] += 1
total[i] += value
value = -value
i = parent[i]
counts = np.zeros(7, np.int32)
for c in range(7):
j = children[0, c]
if j >= 0:
counts[c] = visits[j]
return counts
def position(seq):
p = mask = 0
for c in seq:
b = int(move_bit(mask, c))
if not b or win(p | b):
raise ValueError('apertura ilegal o terminal')
p, mask = p ^ mask, mask | b
return p, mask
def make_openings(n=24, seed=1202, depth=6):
r = random.Random(seed)
result = []
while len(result) < n:
p = mask = 0
seq = []
for _ in range(depth):
legal = [c for c in range(W) if move_bit(mask, c) and not win(p | move_bit(mask, c))]
c = r.choice(legal)
b = int(move_bit(mask, c))
p, mask = p ^ mask, mask | b
seq.append(c)
result.append(tuple(seq))
return result
def game(task):
a, b, seq, seed = task
p, mask = position(seq)
move = len(seq)
while True:
sims = a if move % 2 == 0 else b
counts = mcts(p, mask, sims, 1.4, seed + move)
c = int(np.argmax(counts))
stone = int(move_bit(mask, c))
if win(p | stone):
return 1 if move % 2 == 0 else 0
if mask | stone == BOARD:
return 0.5
p, mask = p ^ mask, mask | stone
move += 1
def fit_elo(matches, n):
# Cuasi verosimilitud Elo: empate cuenta media victoria y media derrota.
# Si el grafo de victorias no es fuertemente conexo el maximo es infinito.
edges = [set() for _ in range(n)]
for i, j, y in matches:
if y > 0:
edges[i].add(j)
if y < 1:
edges[j].add(i)
for start in range(n):
reached, pending = {start}, [start]
while pending:
for nxt in edges[pending.pop()]:
if nxt not in reached:
reached.add(nxt)
pending.append(nxt)
if len(reached) != n:
raise ValueError('Elo no identificable: grafo de victorias no conexo')
scale = math.log(10) / 400
i = np.array([m[0] for m in matches], dtype=int)
j = np.array([m[1] for m in matches], dtype=int)
y = np.array([m[2] for m in matches], dtype=float)
def loss(x):
ratings = np.r_[0., x]
z = scale * (ratings[i] - ratings[j])
error = 1 / (1 + np.exp(-z)) - y
grad = np.zeros(n)
np.add.at(grad, i, error * scale)
np.add.at(grad, j, -error * scale)
return np.sum(np.logaddexp(0., z) - y*z), grad[1:]
fit = minimize(loss, np.zeros(n-1), method='BFGS', jac=True, options={'gtol': 1e-7})
if not np.isfinite(fit.fun) or np.max(np.abs(fit.x)) > 5000:
raise ValueError('Elo no finito o mal identificado')
return np.r_[0., fit.x]
def run_tournament(output_path=None):
sims = [100, 200, 400, 800, 1600, 3200, 6400, 10000]
openings = make_openings()
pairs = [(i, i+1) for i in range(len(sims)-1)] + [(0, len(sims)-1)]
tasks = []
meta = []
for i, j in pairs:
for k, seq in enumerate(openings):
for flip in (0, 1):
a, b = (sims[i], sims[j]) if flip == 0 else (sims[j], sims[i])
tasks.append((a, b, seq, 100000 + 10000*i + 100*k + flip*50))
meta.append((i, j, k, flip))
# Compila antes de arrancar hilos: cada llamada libera el GIL y fija su semilla.
mcts(0, 0, 1, 1.4, 0)
with ThreadPoolExecutor(max_workers=2) as pool:
scores = list(pool.map(game, tasks, chunksize=4))
records = [(i, j, k, score if flip == 0 else 1-score)
for (i, j, k, flip), score in zip(meta, scores)]
if output_path is not None:
Path(output_path).write_text(json.dumps({'simulations': sims, 'openings': openings,
'records': records}, separators=(',', ':')),
encoding='utf-8')
matches = [(i, j, score) for i, j, k, score in records]
elo = fit_elo(matches, len(sims))
rng = np.random.default_rng(1202)
intervals = []
boots = []
# Reamostrar bloques de apertura, conservando ambos colores y todos los pares.
for _ in range(300):
sample = rng.integers(0, len(openings), size=len(openings))
boot = [m for k in sample for m in matches_by_opening(records, int(k))]
try:
boots.append(fit_elo(boot, len(sims)))
except ValueError:
pass
arr = np.array(boots)
for i, n in enumerate(sims):
lo, hi = np.percentile(arr[:, i], [2.5, 97.5])
intervals.append((n, round(float(elo[i]), 1), round(float(lo), 1), round(float(hi), 1)))
print('Partidas:', len(matches), '; aperturas:', len(openings), '; bootstrap válido:', len(boots))
print('Simulaciones, Elo relativo, intervalo:', intervals)
print('Marcadores por par:', [(sims[i], sims[j], sum(x[3] for x in records if x[0]==i and x[1]==j), sum(1 for x in records if x[0]==i and x[1]==j)) for i,j in pairs])
return records, intervals
def matches_by_opening(records, k):
return [(i, j, score) for i, j, kk, score in records if kk == k]npm run lab and open the connection link.We first check fitting with simulated data on a known scale. This control does not demonstrate that the rating model describes Connect 4 outcomes well: it checks that the implementation approximately recovers differences when data do come from the model. The second test requires detecting complete separation, for which no finite maximum exists.
import numpy as np
rng = np.random.default_rng(1202)
truth = [0, 150, 300]
matches = []
for i in range(3):
for j in range(i+1, 3):
p = 1 / (1 + 10 ** ((truth[j] - truth[i]) / 400))
for _ in range(500):
matches.append((i, j, int(rng.random() < p)))
fitted = fit_elo(matches, 3)
print('Elo generador:', truth, '; estimado:', np.round(fitted, 1).tolist())
try:
fit_elo([(0, 1, 1), (0, 1, 1)], 2)
except ValueError:
print('Separacion completa detectada')
else:
raise AssertionError('El estimador no detecta separacion completa')npm run lab and open the connection link.The next experiment compares consecutive budgets and also connects both endpoints. It resamples complete openings, retaining all their games and both colors. Resamples without a finite fit are discarded and the remaining count reported: the interval is conditional on those replicas. For the 100-simulation reference the interval is zero by construction, since its Elo is fixed to zero in every fit; this does not mean absolute strength is known without uncertainty.
records, intervals = run_tournament()npm run lab and open the connection link.For an external criterion, the next cell downloads two revision-pinned datasets. The first is the same mirror of the easy-endgame set used in the previous lesson. The second dataset collects decisive positions with Pascal Pons solver labels per column; 100 positions at depths 16 through 26 are selected with a fixed seed. Both compare only the sign of each action’s outcome, as in the previous lesson’s weak oracle. These are selected samples, not a representative distribution of all positions. 100% accuracy on an easy set does not prove perfect play, and one position’s variation can reverse the order of two budgets.
import json
import random
from urllib.request import urlopen
import numpy as np
def evaluate(chosen, label, sequences_zero_based=False):
print(label, flush=True)
series = []
for budget in (100, 200, 400, 800, 1600, 3200, 6400, 10000):
correct = 0
for i, row in enumerate(chosen):
seq = row['moves'] if sequences_zero_based else row['sequence']
p, mask = position([int(c) if sequences_zero_based else int(c)-1 for c in seq])
counts = mcts(p, mask, budget, 1.4, 120200 + i)
action = int(np.argmax(counts))
scores = row['scores'] if sequences_zero_based else row['analysis']
legal = [(c, (s > 0) - (s < 0)) for c, s in enumerate(scores)
if s is not None and s != -1000]
best = max(v for c, v in legal)
correct += int(dict(legal)[action] == best)
print('Simulaciones:', budget, 'aciertos:', correct, '/', len(chosen), flush=True)
series.append((budget, correct, len(chosen)))
return series
url = ('https://raw.githubusercontent.com/Pietot/Gonnect-4/'
'c82e1f1548c4a64d7ee04911a77cac2438a1f0a2/data/test_easy_end.json')
with urlopen(url, timeout=30) as response:
rows = json.load(response)
chosen = random.Random(1202).sample(rows, 100)
easy = evaluate(chosen, 'Finales faciles de Pons')
url = ('https://huggingface.co/datasets/davidquarel/connect4-pons-eval/resolve/'
'70d868ee534df1e2c6213b22daeae36d4ad73cc5/pons_eval_dataset.json')
with urlopen(url, timeout=30) as response:
rows = json.load(response)['positions']
chosen = random.Random(1202).sample([row for row in rows if 16 <= row['depth'] <= 26], 100)
decisive = evaluate(chosen, 'Muestra de posiciones decisivas entre 16 y 26 jugadas', True)npm run lab and open the connection link.The Elo column depends on the opponent graph and the accuracy column on position selection. Under this protocol, intervals are wide and estimated gains per doubling vary greatly: they do not justify claiming a constant increase. Repeat the tournament with more openings and seeds before attributing significance to small differences. Accuracy describes selected positions; retain seeds and reference set so another run can repeat the comparison.
In this run, fitting gives approximately 76 points for 200 simulations against the 100-simulation reference, with a percentile interval of approximately . For 10 000 simulations it estimates about 459 points, with interval . Both are relative to the same reference agent, whose zero is a fitting constraint. The first interval includes negative differences: with this tournament the point estimate alone does not establish a well-determined advantage over the reference. The second is compatible with a considerable advantage within this opponent and opening set, but does not establish Elo against another population.
Decision comparison reveals another limitation. In easy endgames, the agent gets 99 or 100 of 100 positions right depending on this run’s budget. In selected decisive positions it gets 86 with 100 simulations and 97 with 10 000; with 6 400 it gets 98. The final drop from 98 to 97 does not demonstrate that more search worsens the agent: budgets use random traversals and a finite sample, with no obligation of pointwise monotonicity. Nor does it justify ignoring the drop: to quantify it, repeat seeds and analyze which decisions change by position.
Games and positions are related in different ways. A tournament result depends on a complete sequence of decisions by both agents, their colors, and opening. Solver accuracy is evaluated on fixed positions without continuing a game between the two agents. One metric can therefore improve without the other moving similarly. The decisive set was constructed specifically to contain actions with different outcomes; it is not a random sample of all turns encountered in self-play. The easy set leaves little room to distinguish budgets and is useful for finding serious implementation errors, but has a ceiling effect.
A methodological improvement is to hold out openings for a second evaluation and retain seeds separately. When comparing two budgets on the same positions, record paired correctness, not just two percentages: they may succeed and fail on the same positions, or change decisions on many positions and end with the same percentage. For the tournament, the resampling block retains both color assignments and all matchups for each opening, so uncertainty reflects variation among openings actually used. It does not by itself capture variation from every possible hyperparameter choice or a change in opponent distribution.
The next figure is built directly from the preceding two cells’ results. The horizontal scale is logarithmic to distinguish budget doublings. The Elo band is the opening-block percentile interval; the two accuracy curves use different samples and are not estimates of the same population.
import matplotlib.pyplot as plt
budget, elo, lower, upper = map(np.array, zip(*intervals))
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
axes[0].semilogx(budget, elo, marker='o', label='Elo relativo')
axes[0].fill_between(budget, lower, upper, alpha=0.2, label='IC percentil 95 %')
axes[0].set(xlabel='Simulaciones por jugada', ylabel='Elo relativo a 100')
axes[0].legend()
for label, series in [('Finales fáciles', easy), ('Posiciones decisivas', decisive)]:
x, correct, n = map(np.array, zip(*series))
axes[1].semilogx(x, 100 * correct / n, marker='o', label=label)
axes[1].set(xlabel='Simulaciones por jugada', ylabel='Jugadas óptimas (%)', ylim=(0, 105))
axes[1].legend()
fig.tight_layout()
plt.show()npm run lab and open the connection link.Exercises
import numpy as np
from scipy.optimize import minimize
def fit_elo(results, n):
pass