Module contents
Lesson 8 of 23Advanced 110 min

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 defectFixWhere it became famous
Explores all moves equally, even when most are known to be badPUCT selection with prior P(s,a)P(s, a)AlphaGo (2016), AlphaZero (2018)
Every statistic is learned from scratch at each nodeRAVE: share statistics across similar movesMoGo in 9×9 Go (2007 to 2011)
With thousands or infinitely many moves, the tree never passes the first levelProgressive wideningCrazy Stone; continuous MCTS (2011)
Forced wins get diluted in averagesMCTS-solverLines of Action (2008)
One simulation at a time, on one threadParallelism with virtual loss and GPU batchesMango (2008), AlphaGo (2016)
Assumes the whole board is visibleISMCTS: information-set treesCard 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 ii a weight Mi>0M_i > 0, with ∑iMi=1\sum_i M_i = 1, and PUCB combines it with UCB as follows:

it=arg max⁡i(xˉi+3log⁡t2si−2Milog⁡tt),i_t = \argmax_i \Big( \bar{x}_i + \sqrt{\tfrac{3\log t}{2 s_i}} - \frac{2}{M_i}\sqrt{\tfrac{\log t}{t}} \Big),

Here sis_i is the number of pulls of the arm, xˉi\bar{x}_i its mean (1 if untried), and the exploration bonus is zero while si=0s_i = 0. The prior enters as an additive penalty proportional to 1/Mi1/M_i: low-weight arms are heavily penalized initially, and the penalty vanishes as log⁡t/t\sqrt{\log t / t}. Rosin proves expected regret is at most 17 1M∗nlog⁡n17\,\frac{1}{M^*}\sqrt{n\log n}, where M∗M^* is the optimal arm’s weight: if the predictor is right, the cost no longer depends on the number of arms KK as in UCB1’s Knlog⁡n\sqrt{Kn\log n}.

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 N\sqrt{N}, not log⁡N\sqrt{\log N}. PUCT exploration is polynomial: a child with fixed N(s,a)N(s, a) sees its bonus grow as N(s)\sqrt{N(s)}, much faster than UCB1’s log⁡N\sqrt{\log N}. 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 QFPU+cpuctPNQ_{\text{FPU}} + c_{\text{puct}} P \sqrt{N}, finite. If a move’s prior is 10−310^{-3}, search may never visit it under a realistic budget. This is both the source of PUCT’s power and its danger.
  • With N(s)=0N(s) = 0 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, cpuct=5c_{\text{puct}} = 5 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 PP 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 0.300.30 to 0.600.60; the best is a4a_4. 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 0.60.6 to a7a_7, the worst child, and only 0.020.02 to a4a_4.

InteractiveThe prior dial
0.000.250.500.751.00a1q 0.45a2q 0.52a3q 0.40a4q 0.60a5q 0.35a6q 0.50a7q 0.30a8q 0.42
  • visit share n/Nn/N
  • prior PP (draggable)
  • πˉ\bar\pi de Grill et al. con los qq reales
Iterations until a4 is most visited, by cpuctc_{\text{puct}} (median and quartiles over 31 seeds; 5000 = not achieved)
Prior PP
1.50
800
Most visited childa2 (q = 0.52)
Visits to a4 / π̄(a4)0.004 / 0.752
a4 becomes most visitediteration 4343
Median with c = 1.40 (31 seeds)1958
a2 still leads: search corrects the prior at 4343 (beyond the current 800).
Blue bars: each child's visit fraction after NN PUCT iterations; orange bars: the draggable prior PP; magenta line: the regularized policy πˉ\bar\pi described below, computed from true values. With the misleading prior, a7a_7 takes the first visits, other children overtake it and a4a_4 can take thousands of iterations to lead (with the initial seed, a2a_2 still leads at 800); the lower chart gives, for each cpuctc_{\text{puct}}, the median and quartiles over 31 seeds of the iteration from which a4a_4 stays most visited. Try the accurate and uniform priors, reduce cpuctc_{\text{puct}} to 0.5 with the misleading one and set unvisited children to ‘loss’.

The figure’s behavior admits a written explanation. Consider the good child, with prior P4=0.02P_4 = 0.02 and still unvisited, when dominant child a7a_7 has already received nearly all NN visits. Their scores are

QFPU+cpuct P4N⏟a4 sin visitasfrente aQ7+cpuct P7N1+n7⏟a7, n7≈N≈Q7+cpuct P7N.\underbrace{Q_{\text{FPU}} + c_{\text{puct}}\, P_4 \sqrt{N}}_{a_4\ \text{sin visitas}} \qquad\text{frente a}\qquad \underbrace{Q_7 + c_{\text{puct}}\, P_7 \frac{\sqrt{N}}{1 + n_7}}_{a_7,\ n_7 \approx N} \approx Q_7 + \frac{c_{\text{puct}}\,P_7}{\sqrt{N}}.

If FPU equals the root mean, initially around Q7≈0.3Q_7 \approx 0.3, the first term wins as soon as P4N≳P7/NP_4\sqrt{N} \gtrsim P_7/\sqrt{N}, that is, after N≳P7/P4=30N \gtrsim P_7/P_4 = 30 visits: the good child is tried early and, since its true value doubles the leader’s, starts accumulating visits. If FPU is 00 (an unvisited child counts as a loss, as in AlphaZero’s published pseudocode with values in [0,1][0, 1]), an unvisited child has only its bonus and needs cpuctP4N≳QLc_{\text{puct}} P_4 \sqrt{N} \gtrsim Q_L, where QLQ_L is the current leader’s value: N≳(QL/cpuctP4)2N \gtrsim (Q_L / c_{\text{puct}} P_4)^2. With a leader around QL≈0.5Q_L \approx 0.5 and cpuct=1.5c_{\text{puct}} = 1.5, about 280 iterations; with cpuct=0.5c_{\text{puct}} = 0.5, about 2500. If a4a_4‘s first simulation loses (probability 0.40.4), its QQ stays 0 and visit nn requires cpuctP4N/n≳QLc_{\text{puct}} P_4\sqrt{N}/n \gtrsim Q_L, namely N≳(n QL/cpuctP4)2N \gtrsim (n\,Q_L/c_{\text{puct}}P_4)^2. With pessimistic FPU, the cost of a wrong prior grows as 1/P21/P^2 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, a4a_4 must catch up with the visits a7a_7 accumulated while leading. The next cell reproduces the figure’s experiment in Python and measures that handover iteration.

[ ]PUCT at the root: the cost of correcting a priorBrowser
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 cpuctc_{\text{puct}}. With the uniform one, the lead changes in tens or around a hundred iterations (medians of 43, 119 and 97 for cpuct=0.5c_{\text{puct}} = 0.5, 1.51.5 and 44). With the misleading one, cost runs into thousands: with cpuct=0.5c_{\text{puct}} = 0.5 most seeds see no change by 3000 iterations (the median is infinite), with 1.51.5 it occurs around iteration 1698 and with 44 around 1560: when the prior misleads, exploring more helps. The last line shows the pessimistic FPU trap: with cpuct=1.5c_{\text{puct}} = 1.5 and unvisited children counting as losses, a4a_4 gets 3 visits out of 3000, while a1a_1 and a2a_2, with prior 0.0630.063 and values 0.450.45 and 0.520.52, share almost all; this is the N≳(nQL/cpuctP4)2N \gtrsim (n Q_L/c_{\text{puct}} P_4)^2 staircase above, with a4a_4‘s first simulations lost. No cpuctc_{\text{puct}} 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 cpuctc_{\text{puct}} with NN.

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,

πˉ=arg max⁡y∈Δ(q⊤y−λN KL⁡(P ∥ y)),λN=cpuctNK+N,\bar\pi = \argmax_{\vb{y} \in \Delta} \Big( \vb{q}\T\vb{y} - \lambda_N\, \KL(P \,\|\, \vb{y}) \Big), \qquad \lambda_N = c_{\text{puct}}\frac{\sqrt{N}}{K + N},

where Δ\Delta is the simplex of distributions over the KK moves and q\vb{q} the value vector. Maximize the expected value of policy y\vb{y} without straying too far from the prior, with a leash λN\lambda_N that loosens as 1/N1/\sqrt{N}.

Proof

The objective is ∑aq(a)y(a)+λ∑aP(a)log⁡y(a)\sum_a q(a)y(a) + \lambda\sum_a P(a)\log y(a) plus a constant, strictly concave inside the simplex because each log⁡y(a)\log y(a) is and P(a)>0P(a) > 0; it tends to −∞-\infty if any y(a)→0y(a) \to 0, so its maximum is interior and unique. With multiplier α\alpha for ∑ay(a)=1\sum_a y(a) = 1, the first-order condition is q(a)+λP(a)/y(a)−α=0q(a) + \lambda P(a)/y(a) - \alpha = 0, that is y(a)=λP(a)/(α−q(a))y(a) = \lambda P(a)/(\alpha - q(a)), requiring α>q(a)\alpha > q(a) for y(a)>0y(a) > 0. Function g(α)=∑aλP(a)/(α−q(a))g(\alpha) = \sum_a \lambda P(a)/(\alpha - q(a)) is continuous and strictly decreasing on (max⁡aq(a),∞)(\max_a q(a), \infty), tends to +∞+\infty on the left and 00 at infinity, so there is a unique α\alpha with g(α)=1g(\alpha) = 1. Since each summand is at most 1, α−q(a)≥λP(a)\alpha - q(a) \ge \lambda P(a) for every aa, giving the stated lower bound.

∎

The theorem gives two quantitative facts. For a suboptimal child, with gap Δa=q∗−q(a)>0\Delta_a = q^* - q(a) > 0, as NN grows λN→0\lambda_N \to 0, α→q∗\alpha \to q^* and

N(s,a)N≈πˉ(a)≈λNP(a)Δa≈cpuctP(a)ΔaN,es decir,N(s,a)≈cpuctP(a)ΔaN.\frac{N(s, a)}{N} \approx \bar\pi(a) \approx \frac{\lambda_N P(a)}{\Delta_a} \approx \frac{c_{\text{puct}} P(a)}{\Delta_a\sqrt{N}}, \qquad\text{es decir,}\qquad N(s, a) \approx \frac{c_{\text{puct}}P(a)}{\Delta_a}\sqrt{N}.

Visits to a bad move grow as N\sqrt{N}, 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 πˉ\bar\pi (Proposition 2); in the figure the magenta line and blue bar approach one another as NN grows. The same authors propose using exactly computed πˉ\bar\pi 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 λ=0.5\lambda = 0.5; AlphaZero drops simulations and uses only the network. For the search algorithm both fit in one function:

evaluate(s1,…,sB)  ⟼  ((P1,v1),…,(PB,vB)),\texttt{evaluate}(s_1, \dots, s_B) \;\longmapsto\; \big( (P_1, v_1), \dots, (P_B, v_B) \big),

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:

P′(s0,a)=(1−ε) P(s0,a)+ε ηa,η∼Dir⁡(α,…,α),P'(s_0, a) = (1 - \eps)\,P(s_0, a) + \eps\,\eta_a, \qquad \boldsymbol{\eta} \sim \operatorname{Dir}(\alpha, \dots, \alpha),

with ε=0.25\eps = 0.25 (AlphaGo Zero’s value, inherited by AlphaZero) and α=0.3\alpha = 0.3, 0.150.15 and 0.030.03 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, E[ηa]=1/L\E[\eta_a] = 1/L with LL legal moves, so noise does not bias the prior on average: E[P′]=(1−ε)P+ε/L\E[P'] = (1 - \eps)P + \eps/L. What α\alpha controls is its shape: with αL\alpha L around 10 (about 35 chess moves times 0.30.3 is around 10; 361 Go points times 0.030.03, around 11), the noise concentrates its mass on a few random moves per search instead of distributing ε\eps uniformly. With α→∞\alpha \to \infty the noise would always be uniform ε/L\eps/L; with α→0\alpha \to 0 nearly all ε\eps 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.

[ ]Connect 4 and a threat priorBrowser
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 WW, 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.

[ ]Batched PUCT with virtual loss and Dirichlet noiseBrowser
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.

[ ]Does the prior help? Threat versus uniform priorBrowser
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 α\alpha, chess’s and the one giving αL=10\alpha L = 10 for Connect 4’s 7 columns, and the average weight received by column 1, which the threat prior rates low.

[ ]Dirichlet noise at the rootBrowser
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, 0.75⋅0.0625+0.25/7≈0.0820.75 \cdot 0.0625 + 0.25/7 \approx 0.082, but very different shapes. With α=0.03\alpha = 0.03 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 0.150.15 in 14 % of searches. With α=10/7\alpha = 10/7 the largest component averages 33 % and column 1 exceeds 0.150.15 only 2 % of the time. For a game with 7 moves, Go’s 0.030.03 would be too concentrated; AlphaZero’s rule, α\alpha inversely proportional to LL, yields values between 1 and 2.

RAVE: share what simulations learn

All moves as if first

A simulation from node ss ends with result zz 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 ss played square aa at any later point in the simulation, the simulation counts as a sample of the value of playing aa 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 ss move already has several AMAF samples even if never chosen at ss.

The price is bias. Q~(s,a)\tilde{Q}(s, a) estimates the value of aa in a mixture of positions after ss, not at ss. 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 β\beta tends to 0, MC-RAVE’s asymptotic behavior matches UCT and retains its consistency; bias matters only while β\beta carries weight.

The β(n)\beta(n) schedule

The most-used schedule, MoGo’s “hand-picked” one, has an equivalence parameter kk:

β(s,a)=k3N(s)+k.\beta(s, a) = \sqrt{\frac{k}{3N(s) + k}}.

With N(s)=kN(s) = k it equals k/4k=1/2\sqrt{k/4k} = 1/2: kk is the number of node simulations at which AMAF and Monte Carlo estimates have equal weight. For N(s)≫kN(s) \gg k, β≈k/3N(s)\beta \approx \sqrt{k/3N(s)}, which tends to 0 as N−1/2N^{-1/2}.

Gelly and Silver also derive a principled schedule. If the two estimates are independent, Monte Carlo is unbiased with variance σ2\sigma^2 and AMAF has variance σ~2\tilde\sigma^2 and bias b~\tilde b, the mixture’s squared error is

e2(β)=(1−β)2σ2+β2(σ~2+b~2),e^2(\beta) = (1 - \beta)^2\sigma^2 + \beta^2\big(\tilde\sigma^2 + \tilde b^2\big),

which is minimized at β=σ2/(σ2+σ~2+b~2)\beta = \sigma^2/(\sigma^2 + \tilde\sigma^2 + \tilde b^2). With binomial variances σ2≈μ(1−μ)/n\sigma^2 \approx \mu(1-\mu)/n and σ~2≈μ(1−μ)/n~\tilde\sigma^2 \approx \mu(1 - \mu)/\tilde{n}, in balanced positions (μ≈1/2\mu \approx 1/2), this becomes

β=n~n+n~+4nn~ b~2,\beta = \frac{\tilde{n}}{n + \tilde{n} + 4 n \tilde{n}\, \tilde{b}^2},

with n=N(s,a)n = N(s, a), n~=N~(s,a)\tilde n = \tilde N(s, a) and a single parameter, bias b~\tilde b, tuned through games. In 9×9 MoGo this schedule gained about 80 Elo over the hand-picked one.

InteractiveWhen to trust AMAF
Schedule β(N)=k/(3N+k)\beta(N) = \sqrt{k/(3N + k)}: AMAF estimate weight
A losing move in a Hex position (cell 17): QQ, Q~\tilde Q and mixture Q⋆Q^\star
  • Q, Monte Carlo
  • AMAF
  • mixture Q*
Accuracy on 300 solved 5×5 Hex positions (winning move selected), with 95% Wilson interval
  • UCT
  • RAVE k = 300
RAVE con k=300k = 300 versus UCT: fraction of wins in 100 games per point
  • draw
  • RAVE versus UCT
Equivalence parameter kk
β at N = 100 and N = 10000.707 and 0.302
Move 17 after 3000 iterations: Q and AMAF0.371 y 0.752
Accuracy at 16 / 4096 simulations (UCT)52 % / 92 % (22 % / 88 %)
Wins versus UCT with 25 / 1600 simulations99 % / 57 %
First panel: the schedule β(N)=k/(3N+k)\beta(N) = \sqrt{k/(3N + k)} for the chosen kk, marked at β=1/2\beta = 1/2 (at N=kN = k). Second: a losing move from a solved 5×5 Hex position: its Monte Carlo QQ (starting at 0 because its first simulation lost), AMAF Q~\tilde{Q} and mixture Q⋆Q^\star as search progresses. The last two panels, from the second lab's large experiment: accuracy on 300 solved positions and RAVE wins against UCT by budget, with 95 % Wilson intervals. Move kk and see which part of each curve changes; try k=∞k = \infty, pure AMAF.

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 QQ: the losing move in the second panel has Q~\tilde Q rising to 0.750.75 while its QQ stays at 0.370.37, and without decay (k=∞k = \infty) 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 ss with mm empty squares, simulation gives the player to move a uniform subset of ⌈m/2⌉\lceil m/2 \rceil of them. Conditioning on square aa being theirs leaves the rest of the subset uniform among ⌈m/2⌉−1\lceil m/2 \rceil - 1 squares from the remaining m−1m - 1, exactly what playing aa first and filling the rest produces. Thus during random filling, playing a square now or later makes no difference, and aa‘s AMAF value is the value of playing aa now followed by random play. What AMAF cannot see is that with good subsequent play aa may be worth much less (or much more) than under random play. That is its bias, which schedule β\beta removes as the tree below ss 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 kk, versus 24 % for MCTS without RAVE, peaking at k≥1000k \ge 1000: the AMAF estimator was more reliable than Monte Carlo for several thousand simulations per node. With prior knowledge (initial QQ and Q~\tilde Q 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:

#hijos(s)≤⌈k N(s)α⌉,k>0, α∈(0,1).\#\text{hijos}(s) \le \big\lceil k\, N(s)^{\alpha} \big\rceil, \qquad k > 0,\ \alpha \in (0, 1).

When N(s)N(s) 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. α\alpha determines the asymptotic rate: the number of tried actions grows as NαN^\alpha, so each receives on the order of N1−αN^{1-\alpha} visits. With α\alpha near 0 the node keeps a few well-estimated actions, possibly all bad; with α\alpha near 1 almost every visit introduces an action and none is estimated well, precisely naive UCT’s failure. kk is the constant: how many actions exist initially, when NN 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 (s,a)(s, a) generates a new state only while #sucesores(s,a)≤⌈k′N(s,a)α′⌉\#\text{sucesores}(s, a) \le \lceil k' N(s, a)^{\alpha'} \rceil; thereafter it reuses a generated one, selected in proportion to its occurrences, and nodes below start accumulating visits.

[ ]Progressive widening in a continuous banditBrowser
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 0.50.5 almost everywhere, rising to 0.70.7 at a narrow peak around x=0.73x = 0.73: a random action lands within 0.050.05 of the peak with probability 0.10.1, and distinguishing 0.70.7 from 0.50.5 using Bernoulli outcomes takes tens of samples per action. With α=0.1\alpha = 0.1 the node tries only 2 actions in 1000 visits and mean simple regret is 0.1670.167: it almost never finds the peak. With α=0.9\alpha = 0.9 it tries 502, about two visits per action, and regret returns to 0.1650.165: the most visited action is little more than noise. The minimum, 0.0500.050, occurs at α=0.5\alpha = 0.5, 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 −1-1 is backpropagated, not the proven value: ss‘s mean cannot jump to −∞-\infty 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 v+A/nv + A/\sqrt{n} with A=1A = 1, 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 tt has two parents, simulations reaching tt through parent s1s_1 also change the Q(t)Q(t) seen by s2s_2, but not N(s2)N(s_2). s2s_2’s mean ceases to be the weighted mean of its children’s and formula log⁡N(s2)/N(t)\sqrt{\log N(s_2)/N(t)} mixes counters from different populations: N(t)N(t) can exceed N(s2)N(s_2).
  • 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 (s,a)(s, a), 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.

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 nn simulations in parallel. Easy to implement, but the nn simulations start from the same place and provide less information than nn 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 nvl=3n_{\text{vl}} = 3. 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.

InteractiveThreads and virtual loss
izq. · 33 %centro · 63 %der. · 3 %bars: true value of each leaf (probability that the root wins)
By virtual loss, with 4 threads (means of 200 searches of 240 evaluations)
  • diversity: distinct leaves / threads
  • quality: chooses central child
  • fidelity: TV distance from sequential UCT
0.0
Threads per batch
batch 30
Distinct leaves in this batch1 of 4
Distinct leaves per batch (mean of 200 searches)1.00 of 4
Chooses central child (sequential UCT)53 % (78 %)
Distance from sequential UCT distribution0.121
All 4 threads reached the same leaf: one evaluation counted 4 times.
A depth-3 tree with 27 leaves of known true value; the best root child under minimax is the middle one. In each batch threads descend one after another with UCT over statistics including previous virtual losses, then all are backpropagated. With virtual loss 0, all four threads follow the same path. The figure starts at batch 30; go back to see the tree built and increase virtual loss to see threads spread. Curves below, averaged over 200 searches of 240 evaluations, show diversity (distinct leaves per batch), quality (searches choosing the middle child), and fidelity: the distance between the root's average visit distribution and sequential UCT's using the same evaluations.

The figure’s model is deliberately small: 27 leaves, a best child beating the others by only 0.040.04 and 0.090.09 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 0.250.25): one evaluation counted four times. Search actually makes 60 evaluations, not 240, and is correct only 53 % of the time.
  • With nvln_{\text{vl}} between 1 and 4, the batch diversifies and search recovers sequential quality: with nvl=2n_{\text{vl}} = 2, 0.83 distinct leaves per batch and 84 % accuracy. Distance from sequential UCT’s average visit distribution drops from 0.120.12 to a few hundredths.
  • With excessive virtual loss, threads flee the good line. From 5 onward distance rises again (0.06 with nvl=6n_{\text{vl}} = 6; 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 1/21/2. You have three options: stand and win with probability pPp_P; pay to look, seeing and naming the card for reward pM<1p_M < 1; 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).

InteractiveStrategy fusion
You (cannot see it)stand0.60wins with 0.60peek0.80peek and succeed: 0.80guess1.00one information setRnames redcorrect 1/2Nnames blackcorrect 1/2true values: stand 0.60 · peek 0.80 · guess 0.50
  • value assigned by determinization
  • node after guessing
Method
0.60
0.80
step 5 of 5
Determinization choosesguess (0.50)
ISMCTS chooses (400 iterations)peek (0.80)
Best actual movepeek (0.80)
But after guessing you do not know which world you came from: there is one information set. A fixed strategy (red or black) succeeds half the time, so guessing is worth 1/2.
The card game's tree. In ‘Determinization’ mode, the animation solves both worlds separately: in each, ‘guess’ is worth 1 because search names the card it knows in that world; averaging gives 1 and selects guessing, worth 1/2 in the real game. In ‘ISMCTS’ mode, the node after ‘guess’ is the same in both worlds because you cannot see the card, and its value converges to 1/2. Run the iterations and move pPp_P and pMp_M: when do the methods agree?

With pP=0.6p_P = 0.6 and pM=0.8p_M = 0.8 the best move is looking, worth 0.80.8. Determinization gives it that same value, 0.80.8 in both worlds, but scores guessing 11 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 1>0.81 > 0.8 and PIMC guesses, worth 1/21/2. 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 1/21/2. 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 nn blocks scores (n−2)2(n - 2)^2 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 [0,1][0, 1] 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:

Xˉ+Cln⁡N(s)N(s′)+∑x2−N(s′) Xˉ2+DN(s′),\bar{X} + C\sqrt{\frac{\ln N(s)}{N(s')}} + \sqrt{\frac{\sum x^2 - N(s')\,\bar{X}^2 + D}{N(s')}},

where ∑x2\sum x^2 sums squared outcomes for child s′s' and constant DD 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 (C,D)=(0.1,32)(C, D) = (0.1, 32) 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 ℓ\ell, at each step it tries all possible moves, runs a level ℓ−1\ell - 1 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.

[ ]Nested Monte Carlo Search on a 14-city traveling salespersonBrowser
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 ii is row ⌊i/5⌋\lfloor i/5 \rfloor and column i mod 5i \bmod 5; 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 Q+cln⁡(N+1)/(n+1)Q + c\sqrt{\ln(N + 1)/(n + 1)}, with c=0.4c = 0.4 and Q=1Q = 1 for unvisited children, so UCT tries all children before repeating. With RAVE, an unvisited child with AMAF statistics uses Q~\tilde Q, and a visited one uses mixture Q⋆Q^\star with MoGo’s schedule; k=∞k = \infty means β=1\beta = 1 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.

[ ]5×5 Hex with UCT, RAVE and MCTS-solverBrowser
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 0.630.63 and 0.670.67, 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.

[ ]MCTS-solver versus UCT in a Hex endgameBrowser
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 QQ between 0.670.67 and 0.690.69 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 ii has strength γi>0\gamma_i > 0 and ii beats jj with probability γi/(γi+γj)\gamma_i/(\gamma_i + \gamma_j). Written with γi=10Ri/400\gamma_i = 10^{R_i/400},

P(i gana a j)=11+10−(Ri−Rj)/400,Ri−Rj=400log⁡10p1−p.\Pr(i \text{ gana a } j) = \frac{1}{1 + 10^{-(R_i - R_j)/400}}, \qquad R_i - R_j = 400\log_{10}\frac{p}{1 - p}.

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 pp (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:

γi←wi∑j≠inij/(γi+γj),\gamma_i \leftarrow \frac{w_i}{\sum_{j \ne i} n_{ij}/(\gamma_i + \gamma_j)},

where wiw_i are wins by ii and nijn_{ij} are games between ii and jj; 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.

[ ]Tournament, first half: three pairingsBrowser
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")
[ ]Tournament, second half, and Elo with intervalsBrowser
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 [0,0][0, 0]). 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:

  1. 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 gana and 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.
  2. Games against UCT. For each kk and budget, 100 games (50 random openings, each with both colors) between UCT with RAVE and UCT.
  3. 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.

[ ]Data from the large experimentBrowser
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 k=300k = 300 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 (k=∞k = \infty), 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 k=300k = 300 to 92 %. With k=3000k = 3000 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 β\beta 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 Q~\tilde Q and QQ among the first 80 positions: an extreme case chosen to make bias visible. UCT stops visiting it before iteration 450, with Q=0.37Q = 0.37 at 70 visits, while its Q~\tilde Q rises from 0.420.42 to 0.750.75. 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

NumericTwo children and a prior
At a node with N(s)=400N(s) = 400 visits and cpuct=1.5c_{\text{puct}} = 1.5, two children have (Q,P,n)=(0.55, 0.10, 30)(Q, P, n) = (0.55,\ 0.10,\ 30) and (0.48, 0.40, 12)(0.48,\ 0.40,\ 12). What is the PUCT score of the selected child?
NumericWhen does the other get a turn?
Continue with the previous exercise's node. Assume the children's QQ values do not change and, while the second child is selected, each iteration adds one visit to it and one to N(s)N(s). How many consecutive visits does the second child receive before PUCT first selects the first?
NumericThe RAVE mixture
At a node with N(s)=100N(s) = 100 simulations, a move has Q=0.40Q = 0.40 (Monte Carlo) and Q~=0.70\tilde{Q} = 0.70 (AMAF). Using MoGo's schedule and k=300k = 300, what is Q⋆Q^\star?
QuizParallelizing with a GPU
Your evaluator is a GPU network taking almost the same time to evaluate 1 position as 32. You want to use that capacity in one search of 800 simulations per move. Which scheme do you choose?
QuizWhich move do you play?
After a PUCT search of 800 simulations, three root children have: A with P=0.70P = 0.70, N=120N = 120, Q=0.41Q = 0.41; B with P=0.08P = 0.08, N=640N = 640, Q=0.58Q = 0.58; C with P=0.02P = 0.02, N=3N = 3, Q=0.90Q = 0.90. Which do you play without noise in an evaluation game?
QuizChoosing k and α
You control a robotic arm with a continuous action (an angle) and a budget of about 2000 root simulations. You use progressive widening with at most ⌈kNα⌉\lceil k N^\alpha \rceil children. Which statement is correct?
NumericMCTS-solver's Elo
In Winands et al.'s (2008) match, MCTS-solver scored 646.5 points out of 1000 against MCTS. What Elo difference corresponds to that score?
CodeBackpropagating proofs
Implement 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
  pass
Shift+Enter to run
ProofA determinization that chooses worse
Prove: There is a single-player imperfect-information game with two equally likely determinizations in which naive determinization (solving each world with perfect information and averaging) prefers a strictly worse move to another available one.
0
A hidden card is red or black with probability 1/2. You choose between Stand, worth p∈(1/2,1)p \in (1/2, 1) in both worlds, and Guess: name a color without seeing the card and win 1 if correct, 0 otherwise.

Step 1 of 4. What is Guess worth in each determinization solved with perfect information?

QuizAvailability correction
In SO-ISMCTS action aa is legal in only 5 % of determinizations. With ordinary UCB1, using total parent visits in bonus ln⁡N(s)/n(a)\sqrt{\ln N(s)/n(a)}, what happens?

Summary

Key idea
Competitive MCTS is UCT plus information it need not learn from scratch: a prior telling it where to look (PUCT), statistics shared across moves (RAVE), a widening rate for huge spaces, exact proofs where means mislead (solver), many simultaneous descents without collisions (virtual loss), and a tree of what you know, not what you do not (ISMCTS).
  • PUCT chooses arg max⁡aQ+cpuctPN/(1+n)\argmax_a Q + c_{\text{puct}} P \sqrt{N}/(1 + n). Visits follow Grill et al.’s regularized policy πˉ=λNP/(α−q)\bar\pi = \lambda_N P/(\alpha - q); a bad child receives on the order of cpuctPN/Δc_{\text{puct}} P \sqrt{N}/\Delta visits, and a wrong prior costs on the order of 1/P21/P^2 iterations with pessimistic FPU.
  • The evaluate(lote) → (priors, valores) interface separates search from evaluation. Dirichlet root noise, with ε=0.25\eps = 0.25 and α\alpha inversely proportional to the move count, ensures exploration in self-play.
  • RAVE mixes QQ and Q~\tilde Q with β=k/(3N+k)\beta = \sqrt{k/(3N + k)}: it gains much on small budgets and its bias fades as NN grows. It works when a move’s value does not depend on timing.
  • Progressive widening admits ⌈kNα⌉\lceil k N^\alpha \rceil children; double widening does the same for stochastic successors. α\alpha 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.