Advanced MCTS: priors, RAVE, parallelism and imperfect information
The variants that turn MCTS into a competitive engine: PUCT selection with priors, the interface AlphaZero fills with a network, shared RAVE statistics, progressive widening for numerous or continuous actions, MCTS-solver, parallelism with virtual loss, and information-set methods for imperfect-information games.
After this lesson you can
- Implement PUCT selection with priors and batched evaluation as used by AlphaZero.
- Apply RAVE, progressive widening and MCTS-solver, and decide when each helps or hurts.
- Parallelize MCTS with virtual loss and analyze the tradeoff between diversity and fidelity.
- Identify strategy fusion in determinization and apply ISMCTS to imperfect-information games.
- Organize tournaments among variants and estimate their Elo with confidence intervals.
Before you start
From UCT to a competitive engine
The previous lesson’s UCT is a complete algorithm: it converges to the minimax value, needs no evaluation function and fits in a hundred lines. But textbook UCT, with uniform simulations and a single-threaded tree search, plays badly as soon as a game has many moves per position or narrow tactical lines. Every historically successful MCTS program adds pieces, each addressing a specific defect:
| Textbook UCT defect | Fix | Where it became famous |
|---|---|---|
| Explores all moves equally, even when most are known to be bad | PUCT selection with prior | AlphaGo (2016), AlphaZero (2018) |
| Every statistic is learned from scratch at each node | RAVE: share statistics across similar moves | MoGo in 9×9 Go (2007 to 2011) |
| With thousands or infinitely many moves, the tree never passes the first level | Progressive widening | Crazy Stone; continuous MCTS (2011) |
| Forced wins get diluted in averages | MCTS-solver | Lines of Action (2008) |
| One simulation at a time, on one thread | Parallelism with virtual loss and GPU batches | Mango (2008), AlphaGo (2016) |
| Assumes the whole board is visible | ISMCTS: information-set trees | Card games (2012) |
The improvements are substantial. With 3000 simulations per move in 9×9 Go, MoGo’s UCT won 24 % of games against GnuGo 3.7.10; with RAVE and prior knowledge, 69 % (Gelly and Silver, 2011). AlphaZero examines 80 000 positions per second in chess versus Stockfish’s 70 million, yet won their 100-game match without a loss (Silver et al., 2018): the difference comes from a network’s prior and value plugged into the selection formula you will study first.
This lesson takes those pieces in order. For each, you will see what changes in the four phases of MCTS, why it works, when it hurts and what numbers its authors reported. Two labs bring them into code: batched PUCT with virtual loss in Connect 4, with precisely the interface AlphaZero’s network will fill, and a Hex tournament between UCT, RAVE and MCTS-solver with Elo and confidence intervals.
PUCT: explore where the prior points
From contextual bandits to AlphaGo
UCT treats each node as a UCB1 bandit knowing nothing about its arms: until it tries them all it cannot distinguish best from worst. Go has about 250 legal moves per position, most absurd; a human discards nearly all at a glance. In 2011 Christopher Rosin formalized that glance as an episodic contextual bandit: at the start of an episode (search at a node), a predictor assigns each arm a weight , with , and PUCB combines it with UCB as follows:
Here is the number of pulls of the arm, its mean (1 if untried), and the exploration bonus is zero while . The prior enters as an additive penalty proportional to : low-weight arms are heavily penalized initially, and the penalty vanishes as . Rosin proves expected regret is at most , where is the optimal arm’s weight: if the predictor is right, the cost no longer depends on the number of arms as in UCB1’s .
AlphaGo took the idea, but not the formula. Its selection rule, retained by AlphaZero, is a variant in which the prior multiplies the exploration bonus:
Three differences from UCT are worth understanding:
- The bonus grows as , not . PUCT exploration is polynomial: a child with fixed sees its bonus grow as , much faster than UCB1’s . This is a design rule, not a theorem’s consequence: Rosin’s bound applies to PUCB, not this variant.
- An unvisited child has no infinite priority. Its score is , finite. If a move’s prior is , search may never visit it under a realistic budget. This is both the source of PUCT’s power and its danger.
- With the bonus is zero for all. On the first iteration only FPU counts; programs usually expand the root before starting and select initially by prior.
In AlphaGo, and the prior came from a policy network trained on human games; in AlphaZero, from a network trained solely by self-play (studied in AlphaZero). For search the origin of does not matter: it is another parameter of each node’s bandit.
What a prior does
The figure’s root has eight children with known true win probabilities, from to ; the best is . Each simulation selects a child with PUCT and returns a win with that child’s true probability: it is the root of an MCTS whose subtrees were already solved, reduced to a bandit where everything is measurable. The initial prior is misleading: it assigns to , the worst child, and only to .
The figure’s behavior admits a written explanation. Consider the good child, with prior and still unvisited, when dominant child has already received nearly all visits. Their scores are
If FPU equals the root mean, initially around , the first term wins as soon as , that is, after visits: the good child is tried early and, since its true value doubles the leader’s, starts accumulating visits. If FPU is (an unvisited child counts as a loss, as in AlphaZero’s published pseudocode with values in ), an unvisited child has only its bonus and needs , where is the current leader’s value: . With a leader around and , about 280 iterations; with , about 2500. If ‘s first simulation loses (probability ), its stays 0 and visit requires , namely . With pessimistic FPU, the cost of a wrong prior grows as for the undervalued child, so implementations never let a prior be exactly zero unintentionally.
Finding the good child is not enough: for the final move, the most visited child (final move selection), to be correct, must catch up with the visits accumulated while leading. The next cell reproduces the figure’s experiment in Python and measures that handover iteration.
import math, random
q = [0.45, 0.52, 0.40, 0.60, 0.35, 0.50, 0.30, 0.42] # probabilidad real de ganar de cada hijo
MEJOR, K = 3, 8
def prior(nombre):
if nombre == "uniforme":
return [1 / K] * K
if nombre == "acertado": # proporcional a exp(q / 0.05)
w = [math.exp(x / 0.05) for x in q]
return [x / sum(w) for x in w]
p = [0.38 / 6] * K # engañoso: 0.6 en el peor, 0.02 en el mejor
p[6], p[MEJOR] = 0.6, 0.02
return p
def puct_raiz(P, c, T, rnd, fpu="media"):
"""T iteraciones de PUCT en una raíz de bandits de Bernoulli. Devuelve las visitas y la
iteración a partir de la cual el mejor hijo es siempre el más visitado (None si no llega)."""
n, w = [0] * K, [0] * K
ultima_mal = 0
for t in range(1, T + 1):
N = t - 1
q0 = {"media": sum(w) / N if N else 0.5, "derrota": 0.0}[fpu]
r = math.sqrt(N)
punt = [(w[a] / n[a] if n[a] else q0) + c * P[a] * r / (1 + n[a]) for a in range(K)]
a = max(range(K), key=lambda b: (punt[b], P[b])) # con N = 0, desempata el prior
n[a] += 1
w[a] += rnd.random() < q[a]
if any(n[b] >= n[MEJOR] for b in range(K) if b != MEJOR):
ultima_mal = t
return n, (ultima_mal + 1 if ultima_mal < T else None)
T = 3000
for nombre in ("uniforme", "acertado", "engañoso"):
P = prior(nombre)
fila = []
for c in (0.5, 1.5, 4.0):
ts = sorted(puct_raiz(P, c, T, random.Random(s))[1] or math.inf for s in range(15))
fila.append(f"c = {c}: {ts[7]:>5}")
print(f"{nombre:9s} mediana de la iteración de relevo " + " ".join(fila))
n, _ = puct_raiz(prior("engañoso"), 1.5, T, random.Random(0), fpu="derrota")
print("\nengañoso, c = 1.5, FPU = derrota: visitas tras", T, "iteraciones:", n)With the accurate prior, the best child is most visited from the first iteration for any . With the uniform one, the lead changes in tens or around a hundred iterations (medians of 43, 119 and 97 for , and ). With the misleading one, cost runs into thousands: with most seeds see no change by 3000 iterations (the median is infinite), with it occurs around iteration 1698 and with around 1560: when the prior misleads, exploring more helps. The last line shows the pessimistic FPU trap: with and unvisited children counting as losses, gets 3 visits out of 3000, while and , with prior and values and , share almost all; this is the staircase above, with ‘s first simulations lost. No suits every prior: the better the prior, the less exploration is desirable. That is the practical reason AlphaZero adds root noise (next section) and many implementations increase with .
Visits follow a regularized policy
A result explains the blue bars’ shape without simulation. Grill et al. (2020) showed that PUCT approximates the solution of a regularized policy optimization problem,
where is the simplex of distributions over the moves and the value vector. Maximize the expected value of policy without straying too far from the prior, with a leash that loosens as .
Proof
The objective is plus a constant, strictly concave inside the simplex because each is and ; it tends to if any , so its maximum is interior and unique. With multiplier for , the first-order condition is , that is , requiring for . Function is continuous and strictly decreasing on , tends to on the left and at infinity, so there is a unique with . Since each summand is at most 1, for every , giving the stated lower bound.
∎The theorem gives two quantitative facts. For a suboptimal child, with gap , as grows , and
Visits to a bad move grow as , with a constant proportional to its prior and inversely proportional to how bad it is. The prior never stops mattering entirely: it sets residual exploration’s proportions. Grill et al. show the empirical visit distribution follows the regularized objective’s gradient (Proposition 1), and PUCT always selects a move whose visits lag behind (Proposition 2); in the figure the magenta line and blue bar approach one another as grows. The same authors propose using exactly computed instead of visits as the acting policy and network training target (MCTS as regularized policy optimization).
The evaluate interface and Dirichlet noise
MCTS with priors needs two things from each new leaf: its moves’ prior and an estimate of its value. AlphaGo obtained value by mixing the value network with a fast simulation of weight ; AlphaZero drops simulations and uses only the network. For the search algorithm both fit in one function:
It receives a batch of positions because, with a moderately sized network on a GPU, evaluating dozens at once often costs little more than evaluating one: for small batches the fixed cost of launching computation and moving data dominates arithmetic (quantified in latency versus throughput). In this lab a heuristic fills evaluate: the prior counts threats and the value comes from a random simulation. In the AlphaZero project a network with the same signature will fill it, with no other code changes.
Root noise
If the network prior is too confident, PUCT barely looks at moves assigned low probability, and self-play never discovers that some were good. AlphaZero avoids this by perturbing only the root prior in each training search:
with (AlphaGo Zero’s value, inherited by AlphaZero) and , and in chess, shogi and Go, scaled, the paper says, inversely to the approximate number of legal moves in a typical position. The symmetric Dirichlet distribution has uniform mean, with legal moves, so noise does not bias the prior on average: . What controls is its shape: with around 10 (about 35 chess moves times is around 10; 361 Go points times , around 11), the noise concentrates its mass on a few random moves per search instead of distributing uniformly. With the noise would always be uniform ; with nearly all falls on one move.
Noise is used only in self-play searches. In evaluation games AlphaZero chooses the most visited move without noise; during training it samples in proportion to visits.
Lab 1: Batched PUCT with virtual loss in Connect 4
We start with the two-integer Connect 4 from the minimax lesson: actual holds the current player’s pieces and mascara all pieces. The threat prior scores each column: 200 for an immediate win, 60 for blocking an immediate opponent win, otherwise closeness to center plus 3 per new threat created, divided by 20 if it lets the opponent win by playing above. Scores are normalized.
import math, random
import numpy as np
W, H = 7, 6
H1 = H + 1
ABAJO = [1 << (c * H1) for c in range(W)]
ARRIBA = [1 << (H - 1 + c * H1) for c in range(W)]
COLUMNA = [((1 << H) - 1) << (c * H1) for c in range(W)]
FONDO = sum(ABAJO)
TABLERO = FONDO * ((1 << H) - 1)
def alineado(p):
for s in (1, H1, H, H + 2):
m = p & (p >> s)
if m & (m >> (2 * s)):
return True
return False
def amenazas(p, mascara):
"""Casillas vacías donde p completaría cuatro en línea."""
r = (p << 1) & (p << 2) & (p << 3)
for s in (H1, H, H + 2):
q = (p << s) & (p << 2 * s)
r |= q & (p << 3 * s)
r |= q & (p >> s)
q = (p >> s) & (p >> 2 * s)
r |= q & (p << s)
r |= q & (p >> 3 * s)
return r & (TABLERO ^ mascara)
def legales(mascara):
return [c for c in range(W) if not mascara & ARRIBA[c]]
def jugar(actual, mascara, c):
return actual ^ mascara, mascara | (mascara + ABAJO[c])
def desde_cadena(jugadas):
actual = mascara = 0
for ch in jugadas:
actual, mascara = jugar(actual, mascara, int(ch) - 1)
return actual, mascara
CENTRO = [1, 2, 3, 4, 3, 2, 1]
def prior_amenazas(actual, mascara):
"""Prior sobre las 7 columnas para el jugador al turno (0 en las llenas)."""
rival = actual ^ mascara
mias, suyas = amenazas(actual, mascara), amenazas(rival, mascara)
s = [0.0] * W
for c in legales(mascara):
casilla = (mascara + ABAJO[c]) & COLUMNA[c]
encima = (casilla << 1) & COLUMNA[c]
if casilla & mias:
s[c] = 200.0 # gana ya
elif casilla & suyas:
s[c] = 60.0 # tapa una victoria inmediata del rival
else:
nuevas = (amenazas(actual | casilla, mascara | casilla) & ~mias).bit_count()
s[c] = CENTRO[c] + 3.0 * nuevas
if encima & suyas:
s[c] /= 20 # el rival ganaría jugando encima
t = sum(s)
return [x / t for x in s]
def simular(actual, mascara, rnd):
"""Partida aleatoria: 1, 0.5 o 0 para el jugador AL TURNO en la posición de partida."""
yo = True
while True:
cols = legales(mascara)
if not cols:
return 0.5
actual, mascara = jugar(actual, mascara, rnd.choice(cols))
if alineado(actual ^ mascara): # ha ganado el que acaba de mover
return 1.0 if yo else 0.0
yo = not yo
for cadena in ("", "4433", "41424"):
a, m = desde_cadena(cadena)
print(f"tras '{cadena}':", " ".join(f"{p:.3f}" for p in prior_amenazas(a, m)))From the empty board the prior is just a center preference. After 4433, the current player has two bottom pieces in columns 3 and 4, and playing 2 or 5 produces a three open on both sides, which wins: the prior assigns them 0.235 and 0.265 versus less than 0.15 for the rest. After 41424, the opponent has three stacked pieces in column 4 and the prior puts almost all mass on blocking it.
Search follows AlphaZero’s structure. Each batch descends the tree lote times using PUCT; each descent leaves a virtual loss along its path: vl visits adding nothing to , so the next descent in the batch sees that path as if it had lost vl more games. All distinct batch leaves are then evaluated together, expanded with their priors and each descent backpropagated, undoing its virtual loss. With vl = 0 and lote > 1, all batch descents see the same tree, choose the same path and reach the same leaf.
def evaluar_heuristica(estados, rnd):
"""La interfaz de la red: lista de (actual, mascara) -> (priors, valores para el jugador al turno)."""
return [prior_amenazas(a, m) for a, m in estados], [simular(a, m, rnd) for a, m in estados]
class Nodo:
__slots__ = ("actual", "mascara", "P", "hijos", "N", "W", "fin")
def __init__(self, actual, mascara, fin=None):
self.actual, self.mascara = actual, mascara
self.P = None # priors de las 7 columnas; None mientras no se haya evaluado
self.hijos = {} # columna -> Nodo
self.N = 0 # visitas, incluidas las pérdidas virtuales pendientes
self.W = 0.0 # valor acumulado para el jugador que movió hasta aquí
self.fin = fin # None, o el valor para quien movió hasta aquí si es terminal
def hijo(nodo, c):
h = nodo.hijos.get(c)
if h is None:
a, m = jugar(nodo.actual, nodo.mascara, c)
fin = 1.0 if alineado(a ^ m) else (0.5 if m == TABLERO else None)
h = nodo.hijos[c] = Nodo(a, m, fin)
return h
class PUCT:
def __init__(self, evaluar, c_puct=1.5, lote=8, vl=1, alfa=None, eps=0.25, fpu=0.0, semilla=0):
self.evaluar, self.c, self.lote, self.vl = evaluar, c_puct, lote, vl
self.alfa, self.eps, self.fpu = alfa, eps, fpu
self.rnd = random.Random(semilla)
self.gen = np.random.default_rng(semilla)
self.unicas = [] # hojas distintas en cada lote
def elegir(self, nodo):
raiz = math.sqrt(nodo.N)
mejor, ms = None, -1.0
for c in legales(nodo.mascara):
h = nodo.hijos.get(c)
n = h.N if h else 0
s = (h.W / n if n else self.fpu) + self.c * nodo.P[c] * raiz / (1 + n)
if s > ms:
mejor, ms = c, s
return mejor
def buscar(self, actual, mascara, simulaciones):
raiz = Nodo(actual, mascara)
(P,), _ = self.evaluar([(actual, mascara)], self.rnd)
if self.alfa: # ruido de Dirichlet, solo en la raíz
cols = legales(mascara)
eta = self.gen.dirichlet([self.alfa] * len(cols))
P = list(P)
for c, e in zip(cols, eta):
P[c] = (1 - self.eps) * P[c] + self.eps * e
raiz.P = P
hechas = 0
while hechas < simulaciones:
caminos = []
for _ in range(min(self.lote, simulaciones - hechas)):
camino, nodo = [raiz], raiz
while nodo.P is not None and nodo.fin is None: # selección
nodo = hijo(nodo, self.elegir(nodo))
camino.append(nodo)
for x in camino: # pérdida virtual
x.N += self.vl
caminos.append(camino)
hechas += len(caminos)
hojas = [c[-1] for c in caminos]
self.unicas.append(len({id(h) for h in hojas}))
nuevas = list({id(h): h for h in hojas if h.fin is None}.values())
valor = {}
if nuevas: # evaluación por lotes
priors, valores = self.evaluar([(h.actual, h.mascara) for h in nuevas], self.rnd)
for h, p, v in zip(nuevas, priors, valores):
h.P, valor[id(h)] = p, v
for camino in caminos: # retropropagación
hoja = camino[-1]
z = hoja.fin if hoja.fin is not None else 1.0 - valor[id(hoja)]
for x in reversed(camino):
x.N += 1 - self.vl # deshace la pérdida virtual
x.W += z
z = 1.0 - z
return raiz
a, m = desde_cadena("4433")
for lote, vl in [(1, 0), (8, 0), (8, 1), (8, 3)]:
s = PUCT(evaluar_heuristica, lote=lote, vl=vl, semilla=2)
raiz = s.buscar(a, m, 800)
visitas = [raiz.hijos[c].N if c in raiz.hijos else 0 for c in range(W)]
print(f"lote {lote}, vl {vl}: hojas distintas por lote {sum(s.unicas) / len(s.unicas):.2f} visitas {visitas}")The numbers tell the tradeoff’s story. With batch size 1 (sequential search), visits split between columns 2 and 5, both winning. With batch size 8 and no virtual loss, each batch contains only one distinct leaf evaluated eight times with the same value: search does one eighth of the real work, counts each evaluation eight times and ends with 632 of 800 visits in column 4, neither winning column. With vl = 1 the batch averages 5.5 distinct leaves and the distribution again resembles sequential search (388 and 359 visits for columns 2 and 5); increasing to vl = 3, AlphaGo’s value, only raises the average to 5.74.
We still need to check whether the prior helps. The next cell pits search with the threat prior against the same search with a uniform prior, with 100 simulations per move and alternating colors.
def evaluar_uniforme(estados, rnd):
priors = []
for a, m in estados:
cols = legales(m)
priors.append([1 / len(cols) if c in cols else 0.0 for c in range(W)])
return priors, [simular(a, m, rnd) for a, m in estados]
def partida(jugadores, sims):
a, m, turno = 0, 0, 0
while True:
raiz = jugadores[turno].buscar(a, m, sims)
c = max(raiz.hijos, key=lambda k: raiz.hijos[k].N) # jugada final: la más visitada
a, m = jugar(a, m, c)
if alineado(a ^ m):
return turno
if m == TABLERO:
return 0.5
turno ^= 1
puntos, partidas = 0.0, 10
for g in range(partidas):
con = PUCT(evaluar_heuristica, lote=1, vl=0, semilla=100 + g)
sin = PUCT(evaluar_uniforme, lote=1, vl=0, semilla=900 + g)
if g % 2 == 0:
r = partida((con, sin), 100)
puntos += 0.5 if r == 0.5 else 1.0 - r
else:
r = partida((sin, con), 100)
puntos += 0.5 if r == 0.5 else r
print(f"prior de amenazas contra uniforme: {puntos} de {partidas} puntos")The threat prior scores 7.5 points out of 10. Ten games are few: the 95 % Wilson interval for a 0.75 score in 10 games runs from 0.44 to 0.92, compatible with either a small or a crushing advantage. At the end of the lesson you will convert scores like this to Elo with an interval and see how many games are needed for precision.
Finally, Dirichlet noise. The cell shows three draws of the perturbed root prior, with Go’s , chess’s and the one giving for Connect 4’s 7 columns, and the average weight received by column 1, which the threat prior rates low.
a, m = desde_cadena("")
P = np.array(prior_amenazas(a, m))
gen = np.random.default_rng(0)
print("prior sin ruido: ", np.round(P, 3))
for alfa in (0.03, 0.3, 10 / 7):
eta = gen.dirichlet([alfa] * 7, size=20000)
Pn = 0.75 * P + 0.25 * eta
print(f"alfa = {alfa:.2f}: ejemplo", np.round(Pn[0], 3),
f" masa media de la jugada mayor del ruido {eta.max(axis=1).mean():.2f}",
f" P'(col 1): media {Pn[:, 0].mean():.3f}, P(P'(col 1) > 0.15) = {(Pn[:, 0] > 0.15).mean():.2f}")All three rows have the same mean for column 1, , but very different shapes. With the largest noise component gets 89 % of its mass on average: each search gives a random move a huge boost and the others almost nothing, and column 1 exceeds in 14 % of searches. With the largest component averages 33 % and column 1 exceeds only 2 % of the time. For a game with 7 moves, Go’s would be too concentrated; AlphaZero’s rule, inversely proportional to , yields values between 1 and 2.
RAVE: share what simulations learn
All moves as if first
A simulation from node ends with result and contains dozens of moves. UCT uses that result only for edges on the tree path. The AMAF (all moves as first) heuristic uses it for many more: if the player to move at played square at any later point in the simulation, the simulation counts as a sample of the value of playing now.
White and black moves at the same square are different, and if a square is played several times in a simulation (in Go, after a capture), only the first counts. The information gain is orders of magnitude: after a dozen simulations, each move already has several AMAF samples even if never chosen at .
The price is bias. estimates the value of in a mixture of positions after , not at . Gelly and Silver put it plainly: RAVE learns very fast but often gets it wrong because its assumption (a move is worth the same throughout the subtree) fails in tactical fights, where a nearby change can render a move useless or vital. If schedule tends to 0, MC-RAVE’s asymptotic behavior matches UCT and retains its consistency; bias matters only while carries weight.
The schedule
The most-used schedule, MoGo’s “hand-picked” one, has an equivalence parameter :
With it equals : is the number of node simulations at which AMAF and Monte Carlo estimates have equal weight. For , , which tends to 0 as .
Gelly and Silver also derive a principled schedule. If the two estimates are independent, Monte Carlo is unbiased with variance and AMAF has variance and bias , the mixture’s squared error is
which is minimized at . With binomial variances and , in balanced positions (), this becomes
with , and a single parameter, bias , tuned through games. In 9×9 MoGo this schedule gained about 80 Elo over the hand-picked one.
The figure’s data come from the second lab’s large experiment, run with its cells’ code. Two sentences summarize it. With few simulations, AMAF is a much better information source than the Monte Carlo mean: at 16 simulations per move RAVE finds a winning move in more than twice as many positions as UCT. And the mixture must end at : the losing move in the second panel has rising to while its stays at , and without decay () RAVE’s accuracy plateaus below UCT’s as the budget grows.
Why AMAF fits Hex so well
Hex has a structural reason for AMAF to work, which also explains when it stops working. Our lab simulations fill empty squares in random order, alternating colors, and in Hex the winner on a full board depends only on each square’s color, not the order in which they were colored (a full board always has exactly one winner). From node with empty squares, simulation gives the player to move a uniform subset of of them. Conditioning on square being theirs leaves the rest of the subset uniform among squares from the remaining , exactly what playing first and filling the rest produces. Thus during random filling, playing a square now or later makes no difference, and ‘s AMAF value is the value of playing now followed by random play. What AMAF cannot see is that with good subsequent play may be worth much less (or much more) than under random play. That is its bias, which schedule removes as the tree below stops playing randomly.
In games where order matters (captures, moves valuable only at a particular moment, tactical combinations), this equivalence breaks and AMAF bias has no bound. This is the typical mistake of using RAVE where a move’s value depends heavily on timing: in chess, “check with the queen on g7” may win now and lose the queen two moves later, and AMAF statistics mix the two moments.
MoGo’s numbers
In 9×9 Go, with 3000 simulations per move and 2300 games per point against GnuGo 3.7.10 (level 10), MC-RAVE won between 50 % and 60 % depending on , versus 24 % for MCTS without RAVE, peaking at : the AMAF estimator was more reliable than Monte Carlo for several thousand simulations per node. With prior knowledge (initial and values supplied by a local shape value function learned through temporal differences, weighted as 50 simulations), 69 %: a prior like PUCT’s, though injected into values rather than exploration. The advantage persisted with larger budgets: 82 % at 10 000 simulations, 92 % with 10 minutes per game, and 97 % with the minimum squared-error schedule.
Progressive widening: too many moves
UCT expands all children of a node before visiting any twice. With 250 Go moves that greatly delays depth, and with continuous actions (an angle, force, amount to invest) it is impossible: there is no “all children.” Progressive widening limits a node’s child count to an increasing function of its visits:
When crosses the next threshold a child is added: in a game, the next move under a heuristic (Coulom used this in Crazy Stone and Chaslot et al. called it progressive unpruning); with continuous actions, a newly sampled action. UCT or PUCT selection considers only admitted children.
The two parameters play different roles. determines the asymptotic rate: the number of tried actions grows as , so each receives on the order of visits. With near 0 the node keeps a few well-estimated actions, possibly all bad; with near 1 almost every visit introduces an action and none is estimated well, precisely naive UCT’s failure. is the constant: how many actions exist initially, when is small.
Couëtoux et al.’s (2011) double progressive widening applies the same rule to chance nodes. In a stochastic environment with continuous states, each action yields a new state different from all previous ones, and the tree never passes the first level: each state node is visited only once. Couëtoux et al. show naive MCTS thus fails on problems with continuous actions and infinite-support random variables. With DPW, action generates a new state only while ; thereafter it reuses a generated one, selected in proportion to its occurrences, and nodes below start accumulating visits.
import math, random
def f(x): # probabilidad de éxito de la acción x en [0, 1]
return 0.5 + 0.2 * math.exp(-((x - 0.73) / 0.05) ** 2)
def pw(N, k, alfa, c, rnd):
"""Raíz con acciones continuas: UCB entre las admitidas y una acción nueva al cruzar k n^alfa."""
xs, n, w = [], [], []
for t in range(1, N + 1):
if len(xs) < math.ceil(k * t ** alfa):
xs.append(rnd.random()); n.append(0); w.append(0)
lt = math.log(t)
i = max(range(len(xs)), key=lambda j: math.inf if n[j] == 0 else w[j] / n[j] + c * math.sqrt(lt / n[j]))
n[i] += 1
w[i] += rnd.random() < f(xs[i])
mejor = max(range(len(xs)), key=lambda j: n[j])
return 0.7 - f(xs[mejor]), len(xs) # arrepentimiento simple: 0.7 es el máximo de f
N, rep = 1000, 16
for alfa in (0.1, 0.3, 0.5, 0.7, 0.9):
res = [pw(N, 1.0, alfa, 0.5, random.Random(s)) for s in range(rep)]
print(f"alfa = {alfa}: acciones probadas {sum(r[1] for r in res) / rep:6.1f} "
f"arrepentimiento simple medio {sum(r[0] for r in res) / rep:.3f}")Success probability is almost everywhere, rising to at a narrow peak around : a random action lands within of the peak with probability , and distinguishing from using Bernoulli outcomes takes tens of samples per action. With the node tries only 2 actions in 1000 visits and mean simple regret is : it almost never finds the peak. With it tries 502, about two visits per action, and regret returns to : the most visited action is little more than noise. The minimum, , occurs at , with 32 actions of around 30 visits each. The U-shaped curve shows progressive widening’s tradeoff: try new actions versus accurately estimate those already available.
MCTS-solver and transpositions
Proofs instead of means
In sudden-death games (Lines of Action, Hex, chess) some lines have one forced winning move and almost every other move loses. UCT estimates their value by simulation means, and a winning move surrounded by replies that refute it if played badly can have a very low mean for a long time. Winands, Björnsson and Saito (2008) give a Lines of Action example: after 5 seconds MCTS chooses c7xc4, which wins 67.2 % of simulations but is a forced loss in 8 half-moves, instead of f8-f7, scoring 48.2 % and winning in 7. MCTS needs 60 seconds to change its mind; alpha-beta solves it in less than one.
This embeds minimax in MCTS: proofs rise as in negamax, but only through branches search chose to explore. Two details from Winands et al. matter. When a child is proven lost but its siblings are not, a normal is backpropagated, not the proven value: ‘s mean cannot jump to because its player may still choose another child. The final move also changes: node means can jump suddenly when a proof appears, so they choose the secure child, maximizing with , unless a proven win exists, which is played directly. In 1000 games with 5 seconds per move, the Lines of Action program with MCTS-solver beat ordinary MCTS 646.5 to 353.5, 65 % of points.
Transpositions: the tree as a graph
In nearly every game the same position can be reached by different move orders. A transposition table lets those positions share one node, turning the tree into a directed acyclic graph. The advantage is clear: simulations reaching a position by any path contribute to the same statistics. But MCTS backpropagation is designed for trees, and graphs introduce inconsistencies:
- Inconsistent means. If statistics live at nodes and node has two parents, simulations reaching through parent also change the seen by , but not . ’s mean ceases to be the weighted mean of its children’s and formula mixes counters from different populations: can exceed .
- Path-dependent values. With the 50-move rule, threefold repetition or Go’s ko, the “same” position has different value depending on how it was reached; sharing a node mixes different values.
- Cycles. If a game allows repetition the graph can have cycles, and backpropagating through “all parents” never ends.
Common solutions keep statistics on edges , which remain a tree of paths, and use the shared node only to read an aggregate value or prior; Childs, Brodeur and Kocsis (2008) studied treating the UCT tree as a graph that shares information across transpositions. Transpositions are even trickier with MCTS-solver: a proof found along one path applies to all, but only if the position’s value is path-independent.
Parallelizing search
MCTS is inherently sequential: each iteration uses statistics left by the previous one. Chaslot, Winands and van den Herik (2008) compared three ways to break that dependence in Mango, a 13×13 Go program, with two measures: the increase in simulations per second and strength speedup, the time factor the single-threaded program would need to play equally well.
- Leaf parallelism. One thread traverses the tree and, upon reaching a leaf, launches simulations in parallel. Easy to implement, but the simulations start from the same place and provide less information than distinct iterations, and the batch waits for the slowest. With 16 threads: strength speedup 2.4.
- Root parallelism. Each thread builds its own tree, sharing nothing, and root children’s visits are summed at the end. No communication: it scales even on a cluster. With 16 threads: 14.9; with 4, 6.5, more than the thread count, because four independent one-second searches escaped local optima better than one four-second search using Mango’s UCT coefficient.
- Tree parallelism. Threads share a tree protected by locks (one global or one per node). Without more, threads collide: with 16 threads and local locks, 3.3. With virtual loss, 8.5, and the win rate against GNU Go rises from 39.9 % to 49.9 %.
These are AlphaGo’s formulas, with . Its single-machine version used 40 search threads, 48 CPUs and 8 GPUs, and the distributed version 40 threads, 1202 CPUs and 176 GPUs. The paper’s scaling table illustrates diminishing returns: at 2 seconds per move, Elo rose from 2203 with one thread to 2890 with 40 threads and 8 GPUs; distributed with 40 threads reached 3140, and with 64 threads and 280 GPUs, 3168: 28 more Elo for 60 % more hardware.
In network-guided search, tree parallelism combines with the first lab’s batched evaluation: several descents with virtual loss fill a batch, the GPU evaluates it at once, and all are backpropagated. Many open AlphaZero implementations use this design (you will build it in batched neural MCTS). Virtual loss no longer protects against thread races but diversifies the batch.
The figure’s model is deliberately small: 27 leaves, a best child beating the others by only and in minimax value, and 240 evaluations per search, with which sequential UCT chooses the correct child in 78 % of searches. With 4 threads and batching, the curves show three things:
- Without virtual loss, the batch is wasted. Each batch has one distinct leaf (fraction ): one evaluation counted four times. Search actually makes 60 evaluations, not 240, and is correct only 53 % of the time.
- With between 1 and 4, the batch diversifies and search recovers sequential quality: with , 0.83 distinct leaves per batch and 84 % accuracy. Distance from sequential UCT’s average visit distribution drops from to a few hundredths.
- With excessive virtual loss, threads flee the good line. From 5 onward distance rises again (0.06 with ; with 8 threads, from 0.02 to 0.12): descents in a batch spread into branches UCT would not visit, and the tree diverges from sequential search’s. Diversity and fidelity pull in opposite directions.
Turn batching off and with independent random simulations virtual loss 0 hardly hurts (77 % accuracy): four simulations of one leaf still provide information, being four distinct samples. Not so with a deterministic network: that is why virtual loss is essential for GPU batch search.
Imperfect information
Determinization and why it fails
In bridge, poker or mus you cannot see the opponent’s cards. The most direct approach is determinization, or perfect information Monte Carlo (PIMC): sample several assignments of hidden cards compatible with what you know, solve each as a perfect-information game (with alpha-beta or MCTS), and choose the move with the best mean value. Ginsberg’s bridge program GIB used this idea, and determinization has experimental successes in card games. But Frank and Basin (1998) identified two fundamental failures:
- Strategy fusion. In each determinization the search can make a different decision in states indistinguishable to you because they lie in the same information set. It chooses as if it knew what it does not know.
- Non-locality. Some determinizations are virtually impossible in practice because the opponent, who knows where the cards are, would never steer the game there. Solving them separately misses this.
Long et al. (2010) characterized when PIMC works well through three game-tree properties: correlation between nearby leaves (how much the outcome can change at the end), bias toward one player, and the speed at which hidden information is revealed.
A minimal game shows strategy fusion. The opponent has a face-down card, red or black with probability . You have three options: stand and win with probability ; pay to look, seeing and naming the card for reward ; or guess blind, naming a color without seeing it and winning 1 if correct. This is a variant of the figure 1 example from Cowling, Powley and Whitehouse (2012).
With and the best move is looking, worth . Determinization gives it that same value, in both worlds, but scores guessing in each: each world’s tree has its own node after “guess,” and search chooses the correct color at each node. Two different strategies, one per world, fused into a single decision. The mean is and PIMC guesses, worth . Determinization never values information: in each world it already has it.
ISMCTS: information-set trees
Availability correction is not a minor detail: without it, an action legal in few determinizations has a very low visit ratio whenever it appears, gets a huge bonus and search spends its time exploring. The essential difference is step 2: all determinizations share the tree, so in the card game the node after “guess” accumulates simulations from both worlds and its value converges to . SO-ISMCTS does not eliminate all fusion: it treats opponent moves as observable, and Cowling et al. propose variants (SO-ISMCTS with partially observable moves and MO-ISMCTS, one tree per player) for games where they are not.
The paper’s results depend on the game, making them instructive. In Lord of the Rings: The Confrontation, which requires deep search, ISMCTS beats determinization because it does not duplicate work in separate trees. In Phantom (4, 4, 4), generalized tic-tac-toe where opponent pieces are hidden, strategy fusion is especially damaging and ISMCTS also wins. In Dou Di Zhu, a Chinese card game, neither effect matters much, the information-set tree’s branching factor is orders of magnitude larger than a determinization’s, and the two algorithms are even.
Why poker needs other techniques
ISMCTS assumes uniform beliefs over information-set states and seeks a good response, not an equilibrium. In poker both fail: beliefs depend on the opponent’s actions (a large bet suggests good cards, and the opponent knows this and may bluff), and every pure strategy is exploitable, so one must play by mixing with precise probabilities. Cowling et al. acknowledge this: MCTS often fails to find Nash policies in imperfect-information games, and methods such as counterfactual regret minimization are used to approximate equilibria in trees with millions of nodes; you will study it in the reinforcement learning module.
Single-player variants: SP-MCTS and NMCS
A puzzle has no opponent, but MCTS remains useful when the space is huge and no admissible A* heuristic exists. SameGame is the classic benchmark: a 15×15 board with blocks in 5 colors where removing a group of blocks scores points; Schadd et al. estimated from one million random games a mean length of 64.4 moves and mean branching factor of 20.7. Two things differ from two-player games: outcomes are not in and no opponent punishes optimism, so the best game found matters, not the mean.
SP-MCTS (Schadd et al., 2008) modifies selection with a third term rewarding variance:
where sums squared outcomes for child and constant makes lightly explored nodes count as uncertain. It also stores the best score seen at each node and occasionally restarts search with another seed (simple meta-search). With it scored 73 998 points across the 20 standard test positions, versus 72 816 for the previous best program (Billings’s Depth-Budgeted Search, with 2 to 3 hours per position) and 22 354 for IDA*.
Nested Monte Carlo Search (Cazenave, 2009) stores no tree. A level-0 search is a random game; at level , at each step it tries all possible moves, runs a level search from each, plays the move leading to the best game found so far and remembers that game so it is never lost. Each level costs the preceding one multiplied by (moves per step) × (game length), but quality rises quickly with level.
import math, random
rnd = random.Random(3)
CIUD = [(rnd.random(), rnd.random()) for _ in range(14)]
D = [[math.dist(a, b) for b in CIUD] for a in CIUD]
def longitud(ruta):
return sum(D[ruta[i]][ruta[(i + 1) % len(ruta)]] for i in range(len(ruta)))
def aleatoria(prefijo, rnd):
resto = [c for c in range(len(CIUD)) if c not in prefijo]
rnd.shuffle(resto)
return prefijo + resto
def nmcs(prefijo, nivel, rnd):
"""Devuelve la mejor ruta completa encontrada desde el prefijo (puntuación: menor longitud)."""
if nivel == 0 or len(prefijo) == len(CIUD):
return aleatoria(prefijo, rnd)
mejor = None
while len(prefijo) < len(CIUD):
for c in range(len(CIUD)):
if c not in prefijo:
r = nmcs(prefijo + [c], nivel - 1, rnd)
if mejor is None or longitud(r) < longitud(mejor):
mejor = r
prefijo = mejor[:len(prefijo) + 1] # sigue la mejor partida encontrada
return mejor
contador = 0
_aleatoria = aleatoria
def aleatoria(prefijo, rnd): # la misma función, contando partidas de nivel 0
global contador
contador += 1
return _aleatoria(prefijo, rnd)
for nivel in (1, 2):
lon = []
for s in range(3):
contador = 0
lon.append(longitud(nmcs([0], nivel, random.Random(s))))
r = random.Random(nivel)
azar = min(longitud(_aleatoria([0], r)) for _ in range(contador))
print(f"NMCS de nivel {nivel} ({contador} partidas aleatorias por búsqueda): "
+ ", ".join(f"{x:.3f}" for x in lon) + f" mejor de {contador} rutas al azar: {azar:.3f}")A fair comparison uses the same number of random games. Level-1 NMCS plays 91 games per search and finds routes of 4.52 to 5.47, versus 5.75 for the best of 91 random routes. Level 2 plays 3732 and drops to 3.84 to 3.97, while the best of 3732 random routes stays at 4.85: at the same budget nesting is much better than sampling because each level fixes early decisions according to the best continuation found and concentrates random games on remaining decisions. NMCS and descendants hold puzzle records: in disjoint (5D) Morpion Solitaire, NMCS found an 80-line solution (Cazenave, 2009), and Rosin’s (2011) Nested Rollout Policy Adaptation, by the same author as PUCB, which adjusts the simulation policy by gradient ascent at each level, raised it to 82.
Lab 2: MCTS-solver and RAVE in Hex, and an Elo tournament
Hex is a good test bed for both techniques: there are no draws (a full board always has exactly one winner, as David Gale proved in 1979 by relating it to Brouwer’s fixed-point theorem), games are short and forced wins abound in endgames. On our 5×5 board, square is row and column ; player 0 (X) connects top to bottom and player 1 (O) left to right. Each square touches up to six neighbors.
MCTS creates all children on expansion and selects with , with and for unvisited children, so UCT tries all children before repeating. With RAVE, an unvisited child with AMAF statistics uses , and a visited one uses mixture with MoGo’s schedule; means always, pure AMAF. The solver follows the definition’s three rules. Simulations fill empty squares in random order and determine the winner once, on the full board.
import math, random, time
L = 5
NC = L * L
VEC = []
for i in range(NC):
f, c = divmod(i, L)
VEC.append([(f + df) * L + c + dc for df, dc in ((-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0))
if 0 <= f + df < L and 0 <= c + dc < L])
INICIO = ([c for c in range(L)], [f * L for f in range(L)]) # X: fila de arriba; O: columna izquierda
META = (frozenset(range(NC - L, NC)), frozenset(f * L + L - 1 for f in range(L)))
def conecta(tab, j):
"""¿Une el jugador j sus dos lados? Búsqueda en profundidad sobre sus fichas."""
pila = [i for i in INICIO[j] if tab[i] == j]
visto = set(pila)
while pila:
i = pila.pop()
if i in META[j]:
return True
for k in VEC[i]:
if tab[k] == j and k not in visto:
visto.add(k)
pila.append(k)
return False
class NodoH:
__slots__ = ("jugada", "padre", "turno", "hijos", "N", "W", "aN", "aW", "probado")
def __init__(self, jugada, padre, turno):
self.jugada, self.padre, self.turno = jugada, padre, turno # turno: quién mueve en este nodo
self.hijos = None # se crean todos al expandir
self.N, self.W = 0, 0.0 # W: victorias del jugador que movió hasta aquí
self.aN, self.aW = {}, {} # AMAF del jugador al turno: casilla -> simulaciones, victorias
self.probado = 0 # +1 gana quien movió hasta aquí, -1 pierde, 0 sin probar
class MCTSHex:
def __init__(self, c=0.4, rave_k=0, solver=False, semilla=0):
self.c, self.k, self.solver = c, rave_k, solver
self.amaf = bool(rave_k) # registrar AMAF (se puede activar sin usarlo, para medirlo)
self.rnd = random.Random(semilla)
def elegir_hijo(self, nodo):
lnN = math.log(nodo.N + 1)
mejor, ms = None, -1e9
for h in nodo.hijos:
if self.solver:
if h.probado == 1: # jugada ganadora probada
return h
if h.probado == -1: # jugada perdedora probada: no se vuelve a elegir
continue
q = h.W / h.N if h.N else 1.0
if self.k:
an = nodo.aN.get(h.jugada, 0)
if an:
qa = nodo.aW.get(h.jugada, 0) / an
beta = 1.0 if self.k == math.inf else math.sqrt(self.k / (3 * nodo.N + self.k))
q = qa if h.N == 0 else (1 - beta) * q + beta * qa
s = q + self.c * math.sqrt(lnN / (h.N + 1))
if s > ms:
mejor, ms = h, s
return mejor
def iteracion(self, raiz, tab):
tab = tab[:]
nodo, jugadas = raiz, [] # jugadas: (jugador, casilla) del árbol y de la simulación
while nodo.hijos is not None and nodo.probado == 0: # 1. selección
h = self.elegir_hijo(nodo)
tab[h.jugada] = nodo.turno
jugadas.append((nodo.turno, h.jugada))
nodo = h
if nodo.probado == 0: # 2. expansión
if nodo.padre is not None and conecta(tab, 1 - nodo.turno):
nodo.probado = 1 # terminal: acaba de ganar quien movió hasta aquí
else:
nodo.hijos = [NodoH(i, nodo, 1 - nodo.turno) for i in range(NC) if tab[i] < 0]
if nodo.probado != 0: # valor conocido: no hace falta simular
ganador = 1 - nodo.turno if nodo.probado == 1 else nodo.turno
else: # 3. simulación
libres = [i for i in range(NC) if tab[i] < 0]
self.rnd.shuffle(libres) # relleno aleatorio: el tablero lleno tiene un ganador
t = nodo.turno
for i in libres:
tab[i] = t
jugadas.append((t, i))
t = 1 - t
ganador = 0 if conecta(tab, 0) else 1
camino = [] # 4. retropropagación
y = nodo
while y is not None:
camino.append(y)
y = y.padre
camino.reverse()
for d, y in enumerate(camino):
y.N += 1
if ganador != y.turno:
y.W += 1.0
if self.amaf and y.hijos is not None: # AMAF: jugadas posteriores del que mueve en y
gana = ganador == y.turno
for j, i in jugadas[d:]:
if j == y.turno:
y.aN[i] = y.aN.get(i, 0) + 1
if gana:
y.aW[i] = y.aW.get(i, 0) + 1
if self.solver: # 5. las pruebas suben
y = nodo
while y.padre is not None and y.probado != 0:
p = y.padre
if y.probado == 1:
p.probado = -1 # quien mueve en p tiene una jugada ganadora
elif all(h.probado == -1 for h in p.hijos):
p.probado = 1 # todas las jugadas de p pierden
else:
break
y = p
def buscar(self, tab, turno, sims):
raiz = NodoH(None, None, turno)
for _ in range(sims):
self.iteracion(raiz, tab)
if raiz.probado != 0: # solo ocurre con el solver
break
return raiz
def jugada(self, raiz):
if self.solver:
for h in raiz.hijos:
if h.probado == 1:
return h.jugada
vivos = [h for h in raiz.hijos if h.probado != -1] or raiz.hijos
return max(vivos, key=lambda h: h.N).jugada
return max(raiz.hijos, key=lambda h: h.N).jugada
def partida(a, b, sims, rnd_apertura=None):
"""a juega con X (mueve primero). Devuelve el ganador, 0 o 1."""
tab, turno, jug = [-1] * NC, 0, (a, b)
if rnd_apertura is not None: # primera jugada al azar para variar las partidas
tab[rnd_apertura.randrange(NC)] = 0
turno = 1
while True:
i = jug[turno].jugada(jug[turno].buscar(tab, turno, sims))
tab[i] = turno
if conecta(tab, turno):
return turno
turno = 1 - turno
t0 = time.perf_counter()
for nombre, m in (("UCT", MCTSHex(semilla=1)), ("RAVE k=300", MCTSHex(rave_k=300, semilla=1))):
raiz = m.buscar([-1] * NC, 0, 1000)
mejores = sorted(raiz.hijos, key=lambda h: -h.N)[:3]
print(f"{nombre:11s} desde el tablero vacío, 1000 iteraciones: más visitadas",
[(h.jugada, h.N, round(h.W / h.N, 3)) for h in mejores])
print(f"tiempo de las dos búsquedas: {time.perf_counter() - t0:.2f} s")The two 1000-iteration searches take just over a tenth of a second in your browser: this MCTS is fast enough to play tournaments on the page. Notice how little visits concentrate from an empty board: with 25 possible moves and 1000 iterations, the most visited receives 176 visits with UCT and 98 with RAVE, and their values, all between and , are barely distinguishable. Hex openings are hard for such short search; endgames are another story.
The solver in an endgame
The next position comes from a game between two weak searches. X moves (connecting top to bottom) and has only one winning move, square 18; all others lose under perfect play. The cell checks this with exact memoized negamax, then compares UCT and the solver.
POS = "XOXOXXX..X..O..O....OO..."
tab0 = [{"X": 0, "O": 1, ".": -1}[ch] for ch in POS]
def dibujar(tab):
for f in range(L):
print(" " * f + " ".join("X" if tab[f * L + c] == 0 else "O" if tab[f * L + c] == 1 else "." for c in range(L)))
def gana(tab, turno, memo):
"""Negamax exacto con memoria: ¿gana el jugador al turno con juego perfecto?"""
clave = (tuple(tab), turno)
if clave not in memo:
res = False
for i in range(NC):
if tab[i] < 0:
tab[i] = turno
res = conecta(tab, turno) or not gana(tab, 1 - turno, memo)
tab[i] = -1
if res:
break
memo[clave] = res
return memo[clave]
dibujar(tab0)
memo, ganadoras = {}, []
for i in range(NC):
if tab0[i] < 0:
tab0[i] = 0
if conecta(tab0, 0) or not gana(tab0, 1, memo):
ganadoras.append(i)
tab0[i] = -1
print("jugadas ganadoras exactas:", ganadoras, f"({len(memo)} posiciones en memoria)")
for s in range(4):
uct = MCTSHex(semilla=s)
r = uct.buscar(tab0, 0, 300)
nq = {h.jugada: f"{h.N} visitas, Q = {h.W / h.N:.2f}" for h in r.hijos if h.jugada in (14, 18)}
sol = MCTSHex(solver=True, semilla=s)
rs = sol.buscar(tab0, 0, 20000)
print(f"semilla {s}: UCT (300 iteraciones) juega {uct.jugada(r):2d} [14: {nq[14]}; 18: {nq[18]}] "
f"solver: raíz probada tras {rs.N} iteraciones, juega {sol.jugada(rs)}")Exact negamax needs 116 630 positions in memory to confirm only square 18 wins. UCT with 300 iterations plays 14 on three of four seeds, with between and and more visits than 18: it wins most random simulations but loses to correct defense, like c7xc4 in Lines of Action. The solver proves the root win for all seeds after between 2290 and 8251 iterations, and plays 18 with certainty. Note the scale: at 300 iterations the solver has not yet proven the root and would play much like UCT; its value is that once proof arrives, the move no longer depends on noisy means.
A tournament of four variants and their Elo
To compare engines we play games and summarize a match’s outcome in Elo. The underlying Bradley-Terry model assumes each player has strength and beats with probability . Written with ,
A 64 % score corresponds to about 100 Elo difference; 76 % to about 200. With two players the difference’s confidence interval comes from one for proportion (Wilson’s, from proportion intervals), transformed by the monotone formula above. With several, all strengths are estimated simultaneously by maximum likelihood using Hunter’s (2004) minorization-maximization algorithm:
where are wins by and are games between and ; intervals use a bootstrap resampling each pairing’s games. To ensure estimates exist even if someone wins every game, one fictitious drawn game is added to each pairing, as BayesElo does with its prior.
import itertools
VARIANTES = {
"UCT": dict(),
"Solver": dict(solver=True),
"RAVE": dict(rave_k=300),
"RAVE+Solver": dict(rave_k=300, solver=True),
}
NOMBRES = list(VARIANTES)
PARES = list(itertools.combinations(range(4), 2))
def encuentro(i, j, sims, pares_apertura, semilla):
"""Partidas con aperturas al azar, cada apertura dos veces con los colores cambiados.
Devuelve las victorias de i y el número de partidas."""
rnd = random.Random(semilla)
vi = 0
for _ in range(pares_apertura):
ap = rnd.randrange(1 << 30)
for i_es_x in (True, False):
A = MCTSHex(semilla=rnd.randrange(1 << 30), **VARIANTES[NOMBRES[i]])
B = MCTSHex(semilla=rnd.randrange(1 << 30), **VARIANTES[NOMBRES[j]])
w = partida(A, B, sims, random.Random(ap)) if i_es_x else partida(B, A, sims, random.Random(ap))
vi += (w == 0) == i_es_x
return vi, 2 * pares_apertura
SIMS, APERTURAS = 64, 8
resultados = {}
t0 = time.perf_counter()
for (i, j) in PARES[:3]:
resultados[(i, j)] = encuentro(i, j, SIMS, APERTURAS, 17 * i + j)
print(f"{NOMBRES[i]:11s} contra {NOMBRES[j]:11s}: {resultados[(i, j)][0]} de {resultados[(i, j)][1]}")
print(f"{time.perf_counter() - t0:.1f} s")import numpy as np
t0 = time.perf_counter()
for (i, j) in PARES[3:]:
resultados[(i, j)] = encuentro(i, j, SIMS, APERTURAS, 17 * i + j)
print(f"{NOMBRES[i]:11s} contra {NOMBRES[j]:11s}: {resultados[(i, j)][0]} de {resultados[(i, j)][1]}")
def bradley_terry(victorias, partidas, iters=300):
"""victorias[i, j]: veces que i ganó a j. Devuelve el Elo de cada jugador, con el primero en 0."""
n = partidas + partidas.T
g = np.ones(len(n))
w = victorias.sum(axis=1)
for _ in range(iters):
g = w / np.array([sum(n[i, j] / (g[i] + g[j]) for j in range(len(g)) if j != i) for i in range(len(g))])
g /= g[0]
return 400 * np.log10(g)
def tablas(res):
V = np.full((4, 4), 0.5) # la partida ficticia empatada de cada emparejamiento
P = np.zeros((4, 4))
np.fill_diagonal(V, 0)
for (i, j), (vi, n) in res.items():
V[i, j] += vi
V[j, i] += n - vi
P[i, j] = n + 1
return V, P
elo = bradley_terry(*tablas(resultados))
gen = np.random.default_rng(0)
muestras = []
for _ in range(200): # bootstrap paramétrico por emparejamiento,
res_b = {par: (gen.binomial(n, (vi + 0.5) / (n + 1)), n) # con la misma partida ficticia empatada
for par, (vi, n) in resultados.items()}
muestras.append(bradley_terry(*tablas(res_b), iters=100))
lo, hi = np.percentile(muestras, [2.5, 97.5], axis=0)
for k in range(4):
print(f"{NOMBRES[k]:11s} Elo {elo[k]:7.1f} intervalo al 95 %: [{lo[k]:7.1f}, {hi[k]:7.1f}]")
print(f"{time.perf_counter() - t0:.1f} s")UCT’s Elo is 0 by construction: the scale fixes only differences, and we anchor to UCT, so the other intervals are differences relative to it (hence its own ). With 16 games per pairing, the order is expected (RAVE with solver first, then RAVE, solver alone, UCT), but each interval is about 250 Elo wide: solver’s runs from 27 to 275 and overlaps RAVE’s. Deciding whether a 50-Elo improvement is real would require hundreds of games per pairing. That is the large experiment’s job.
The large experiment
With 16 games per pairing intervals are over 200 Elo wide. To refine the numbers and obtain the RAVE figure’s data, we ran the same Hex cell code unchanged in CPython with 4 processes for about 12 minutes. The experiment has three parts:
- Accuracy on solved positions. 300 test positions, generated by letting two weak searches (30 iterations) play 10 to 12 moves from the empty board, solved with
ganaand retained only when the player to move has some but not all winning moves. They average 14.0 empty squares and 4.15 winning moves. For each variant and budget, one search per position; it succeeds if its chosen move wins. - Games against UCT. For each and budget, 100 games (50 random openings, each with both colors) between UCT with RAVE and UCT.
- The four-variant tournament, with 200 games per pairing, at 64 and 256 simulations per move.
# Experimento grande: las funciones de Hex de las celdas anteriores, en un módulo hex_lab.py,
# más gana() de la celda del solver. Tarda unos 12 minutos con 4 procesos.
import math, random, itertools
from multiprocessing import Pool
from hex_lab import MCTSHex, conecta, gana, partida, NC
def ganadoras(tab, turno):
memo, out = {}, []
for i in range(NC):
if tab[i] < 0:
tab[i] = turno
if conecta(tab, turno) or not gana(tab, 1 - turno, memo):
out.append(i)
tab[i] = -1
return out
def una_posicion(semilla):
rnd = random.Random(semilla)
while True:
tab, turno, ok = [-1] * NC, 0, True
for _ in range(rnd.choice((10, 11, 12))):
m = MCTSHex(semilla=rnd.randrange(1 << 30))
i = m.jugada(m.buscar(tab, turno, 30))
tab[i] = turno
if conecta(tab, turno):
ok = False
break
turno = 1 - turno
if ok:
w = ganadoras(tab, turno)
if 0 < len(w) < tab.count(-1):
return tab, turno, w
def acierto(args):
(tab, turno, w), cfg, sims, semilla = args
m = MCTSHex(semilla=semilla, **cfg)
return m.jugada(m.buscar(tab, turno, sims)) in w
def par_de_partidas(args): # una apertura al azar, jugada con los dos colores
cfgA, cfgB, sims, semilla = args
rnd = random.Random(semilla)
ap, pts = rnd.randrange(1 << 30), 0
for a_es_x in (True, False):
A = MCTSHex(semilla=rnd.randrange(1 << 30), **cfgA)
B = MCTSHex(semilla=rnd.randrange(1 << 30), **cfgB)
w = partida(A, B, sims, random.Random(ap)) if a_es_x else partida(B, A, sims, random.Random(ap))
pts += (w == 0) == a_es_x
return pts
if __name__ == "__main__":
cfg = lambda k: {} if k == 0 else dict(rave_k=k)
with Pool(4) as pool:
P = pool.map(una_posicion, range(300))
for k in (0, 30, 300, 3000, math.inf):
print("acierto", k, [sum(pool.map(acierto, [(p, cfg(k), b, 7919 * j + b) for j, p in enumerate(P)]))
for b in (16, 32, 64, 128, 256, 512, 1024, 2048, 4096)])
for k in (30, 300, 3000, math.inf):
print("contra UCT", k, [sum(pool.map(par_de_partidas, [(cfg(k), {}, b, 104729 * b + g) for g in range(50)]))
for b in (25, 50, 100, 200, 400, 800, 1600)])
V = [{}, dict(solver=True), dict(rave_k=300), dict(rave_k=300, solver=True)]
for sims in (64, 256):
print("torneo", sims, {(i, j): sum(pool.map(par_de_partidas, [(V[i], V[j], sims, 1000003 * sims + 101 * i + j + 7 * g)
for g in range(100)]))
for i, j in itertools.combinations(range(4), 2)})
The output, copied verbatim, appears in the next cell, which analyzes it using this lab’s functions: Wilson intervals for percentages and Bradley-Terry with bootstrap for the tournament.
PRESUP = [16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
ACIERTOS = { # de 300 posiciones resueltas
"UCT": [65, 109, 158, 196, 212, 221, 244, 255, 265],
"RAVE k=30": [147, 171, 197, 221, 228, 238, 259, 268, 270],
"RAVE k=300": [157, 193, 218, 233, 244, 251, 261, 269, 275],
"RAVE k=3000": [164, 189, 219, 230, 250, 251, 254, 259, 267],
"AMAF puro": [166, 182, 214, 240, 249, 248, 250, 252, 247],
}
PRESUP_P = [25, 50, 100, 200, 400, 800, 1600]
CONTRA_UCT = { # victorias en 100 partidas
"RAVE k=30": [89, 79, 66, 72, 55, 50, 52],
"RAVE k=300": [99, 95, 86, 78, 68, 56, 57],
"RAVE k=3000": [98, 93, 85, 83, 73, 61, 52],
"AMAF puro": [100, 93, 91, 85, 66, 66, 51],
}
TORNEO = {64: {(0, 1): 77, (0, 2): 18, (0, 3): 29, (1, 2): 37, (1, 3): 26, (2, 3): 92},
256: {(0, 1): 98, (0, 2): 51, (0, 3): 41, (1, 2): 59, (1, 3): 62, (2, 3): 100}}
def wilson(x, n, z=1.959964):
p, d = x / n, 1 + z * z / n
c, h = (p + z * z / (2 * n)) / d, z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
return c - h, c + h
print("acierto (%) " + "".join(f"{b:>6}" for b in PRESUP))
for v, fila in ACIERTOS.items():
print(f"{v:16s}" + "".join(f"{100 * x / 300:6.0f}" for x in fila))
lo, hi = wilson(247, 300)
print(f"AMAF puro con 4096: intervalo al 95 % [{100 * lo:.0f}, {100 * hi:.0f}] %;", end=" ")
lo, hi = wilson(265, 300)
print(f"UCT: [{100 * lo:.0f}, {100 * hi:.0f}] %")
print("\nvictorias contra UCT (%)" + "".join(f"{b:>6}" for b in PRESUP_P))
for v, fila in CONTRA_UCT.items():
print(f"{v:24s}" + "".join(f"{x:6d}" for x in fila))
gen = np.random.default_rng(0)
for sims, d in TORNEO.items():
res = {par: (v, 200) for par, v in d.items()}
elo = bradley_terry(*tablas(res))
muestras = [bradley_terry(*tablas({p: (gen.binomial(n, (vi + 0.5) / (n + 1)), n) for p, (vi, n) in res.items()}), iters=100)
for _ in range(200)]
lo, hi = np.percentile(muestras, [2.5, 97.5], axis=0)
print(f"\ntorneo con {sims} simulaciones, 200 partidas por emparejamiento (UCT = 0):")
for k in range(1, 4):
print(f" {NOMBRES[k]:11s} {round(elo[k]):6d} Elo [{round(lo[k]):5d}, {round(hi[k]):5d}]")Three readings, from less to more subtle:
- RAVE buys strength on small budgets. At 16 simulations UCT chooses a winning move in 22 % of positions and RAVE with in 52 %; against UCT, RAVE wins 99 % of games at 25 simulations. In the tournament RAVE is worth 347 Elo more than UCT at 64 simulations and 188 at 256: the advantage halves when the budget quadruples, as predicted for an estimator accelerating the start and ceasing to matter when data accumulate.
- Pure AMAF plateaus: that is bias. Without decay (), accuracy rises fast to 83 % at 256 simulations and stays there (82 % at 4096, with a 95 % Wilson interval of 78 % to 86 %), while UCT continues to 88 % (84 % to 91 %) and RAVE with to 92 %. With decay comes late and at 4096 simulations RAVE barely beats UCT. AMAF bias exists in Hex, even though fill simulations make it small, and only decay of removes it.
- Games do not see the bias that solved positions see. At 1600 simulations, all RAVE variants win 51 % to 57 % against UCT, including pure AMAF. On a 5×5 board at that budget both players play nearly perfectly and the random opening decides most games; because each opening is played with both colors, the score tends to 50 % even if one engine is better in difficult positions. Solved positions measure more finely than games when both engines are strong.
MCTS-solver, by contrast, adds little here: 73 Elo at 64 simulations (35 to 119) and 32 at 256, with an interval touching zero; added to RAVE, differences from RAVE alone are within noise (their direct match gives 92 and 100 wins out of 200). This matches the earlier endgame: solver needs thousands of iterations to prove a position with 13 empty squares, so with budgets of hundreds it proves things only on the last moves, where UCT also succeeds. In Lines of Action, with 5 seconds per move and long tactical endgames, the gain was 65 % of points (you will translate this into Elo in the exercises); solver’s usefulness grows with the budget and the narrowness of winning lines.
The RAVE figure’s trajectory comes from a 3000-iteration UCT search recording AMAF without using it, on one test position (O to move, with a single winning move, square 13). The displayed move, square 17, is the losing move with the largest final difference between and among the first 80 positions: an extreme case chosen to make bias visible. UCT stops visiting it before iteration 450, with at 70 visits, while its rises from to . The mechanism is bias: as search concentrates on the winning move, O wins most simulations, and any square it eventually occupies in them, such as 17, inherits that win rate in AMAF even though playing it now loses.
Common mistakes
Exercises
propagar(nodo), the MCTS-solver part that raises proofs through the tree. Each Nodo has padre (None at the root), hijos (list) and probado: +1 if the player who moved to the node wins, -1 if they lose, 0 if unproven. It is called just after nodo.probado becomes +1 or -1. Rules: if a child is +1, its parent becomes -1; if all children of a parent are -1, the parent becomes +1; otherwise stop. Keep moving upward while something new is proven.class Nodo:
def __init__(self, padre=None, probado=0):
self.padre, self.hijos, self.probado = padre, [], probado
if padre is not None:
padre.hijos.append(self)
def propagar(nodo):
"""Sube las pruebas desde nodo (cuyo probado acaba de pasar a +1 o -1)."""
# tu código
passStep 1 of 4. What is Guess worth in each determinization solved with perfect information?
Summary
- PUCT chooses . Visits follow Grill et al.’s regularized policy ; a bad child receives on the order of visits, and a wrong prior costs on the order of iterations with pessimistic FPU.
- The
evaluate(lote) → (priors, valores)interface separates search from evaluation. Dirichlet root noise, with and inversely proportional to the move count, ensures exploration in self-play. - RAVE mixes and with : it gains much on small budgets and its bias fades as grows. It works when a move’s value does not depend on timing.
- Progressive widening admits children; double widening does the same for stochastic successors. sets the tradeoff between trying actions and estimating them.
- MCTS-solver propagates proven wins and losses like negamax; transpositions require edge statistics and care with path-dependent values.
- Tree parallelism needs virtual loss to spread simultaneous descents; on GPU it combines with batch evaluation. Root parallelism needs no communication.
- Determinization suffers strategy fusion and non-locality; ISMCTS shares an information-set tree between determinizations, and games requiring mixed strategies such as poker need CFR.