Module contents
Stage 4 of 9Advanced 110 min

Network-guided MCTS: PUCT

Replace random rollout with the network: policy supplies priors, value evaluates leaves, and selection uses PUCT. To use the GPU, batch evaluations with virtual loss and parallel searches, and add root Dirichlet noise and the temperature used in self-play.

After this lesson you can

  • Implement PUCT with network priors and value-based leaf evaluation.
  • Implement virtual loss and batched leaf collection for the GPU.
  • Add root Dirichlet noise and temperature in move selection.
  • Compare PUCT with the supervised network against pure UCT with many more simulations.

Before you start

Replace a random game with a learned evaluation

In MCTS with UCT, a new leaf was evaluated by continuing the game with random moves. The previous lesson’s policy-value network offers another option: evaluate the position once, use its policy as actions’ initial priority and its value as an outcome estimate. Search can then concentrate where the network expects good decisions and correct some mistakes through exploration.

The network is not an exact solver. It was trained on endgames from one distribution and can be wrong, especially outside it. Search does not automatically turn a biased estimate into truth either: its result depends on budget, selection, leaf values, and how evaluations are batched. We will therefore compare policies with real data and retain experimental limitations, even if an expected hypothesis fails.

InteractiveWhere each algorithm searches
Board: blue to move
1234567

Blue ● is the player to move; orange × the opponent. Positions come from the external set and have no immediate win.

Visits per root move
  • UCT
  • PUCT
Col. 1 · optimalprior 6.6% · exact +1
UCT30
PUCT57
Col. 2prior 8.0% · exact −1
UCT22
PUCT5
Col. 3 · optimalprior 9.0% · exact +1
UCT14
PUCT10
Col. 4prior 50.0% · exact −1
UCT32
PUCT116
Col. 5 · optimalprior 15.4% · exact +1
UCT75
PUCT5
Col. 6 · fullprior 0.0% · exact ∅
UCT0
PUCT0
Col. 7prior 11.0% · exact −1
UCT27
PUCT7

Each bar is scaled to 200 visits. The prior is network probability at the root; exact outcome uses win +1, draw 0, and loss −1.

Recorded outputs from this lesson's cell: 200 simulations per method, UCT with c=1.4, virtual loss 1.0, initial Q 0, and no root noise. PUCT evaluates the root once separately; its evaluated leaves and terminals sum to the simulations. Equal visits do not equal computation cost. The indicated batch is a maximum: an already reserved leaf can end collection sooner. Network and search do not run in this browser. Two positions with no immediate win were chosen because visits change between batch 1 and 16 at c=1.5; they are exploratory examples, not a representative comparison or proof of general superiority.

Tactical position
1.5
Maximum batch size
UCT selection5 · optimal
PUCT selection4 · not optimal
Network value at root−0.160
Exact position value+1
Evaluated leaves / terminals164 / 36
Additional root evaluations1
Network calls, including root165
Compare UCT and PUCT visits from the same position. Change the controls and observe how prior, exploration, and batch alter budget allocation. Visits correspond to the model or run described in the figure; they are not win probabilities.

From UCT to PUCT

Neural MCTS with PUCT stores per edge prior probability P(s,a)P(s,a), visits N(s,a)N(s,a), and accumulated value W(s,a)W(s,a). Mean value Q(s,a)=W(s,a)/N(s,a)Q(s,a)=W(s,a)/N(s,a) is expressed from the perspective of the player selecting the action at ss. For an unvisited edge, define an initialization convention instead of dividing by zero. A common selection rule is

a∗=arg max⁡a∈A(s)[Q(s,a)+cpuctP(s,a)∑bN(s,b)1+N(s,a)].a^*=\argmax_{a\in A(s)}\left[Q(s,a)+c_{\mathrm{puct}}P(s,a)\frac{\sqrt{\sum_b N(s,b)}}{1+N(s,a)}\right].

The second term is large for a high prior and decreases as the edge receives visits. The prior is not a mathematical bound on quality: it is a learned preference that can be wrong. A small prior delays exploration of a move; if it reaches exactly zero, this expression gives it no positive bonus. If the parent has no visits yet, the numerator is also zero and all unvisited actions tie under this formula. Define that first tie-break or an explicit initialization convention. Do not attribute a preference to the formula that it does not produce in that case.

The lab adopts a specific variant: it uses max⁡(1,∑bN(s,b))\sqrt{\max(1,\sum_b N(s,b))}, sets Q=0Q=0 for an unvisited edge, and breaks ties by column order. Thus the prior influences the first selection. The code exercise uses the above formula without that maximum so you can check the empty-root case; the two conventions should not be mixed when comparing visits.

UCT uses a bonus based on the logarithm of parent visits and needs no learned prior. PUCT replaces that rule with one incorporating the network. Rosin studies bandits with prior information; its PUCB formula and assumptions are not identical to the preceding expression, so its guarantees do not automatically transfer to this implementation. The constant cpuctc_{\mathrm{puct}} depends on value scale, prior calibration, and budget. Comparing two values of that constant requires holding the rest fixed.

At a nonterminal leaf, evaluate the network once: mask and renormalize legal priors, create edges, and backpropagate the scalar value. If the leaf is terminal, exact outcome comes from the rules, not the network. A child following a winning move has outcome −1-1 for the player who would have moved there and +1+1 for the player who just won. As in the preceding lesson, each player change reverses value’s sign on the way back. Confusing the active player’s value with the previous player’s turns a good move into a bad one even if the network is well trained.

Batches and temporary reservations

Batched leaf evaluation collects several positions and passes them together to the network. A GPU can use a batch better than many small calls, but search must decide which leaves to request before knowing their values. While multiple selections read the same tree without updates, they may repeatedly choose the same branch or even the same leaf. Batch size therefore changes not only speed but also decisions about what to explore.

Virtual loss is a temporary reservation making an edge less attractive while evaluation is pending. With QQ from the perspective of the player choosing each edge, the penalty must temporarily worsen that edge for that player. On receiving the result, exactly revert the reservation and add the real visit and value with correct signs. Reservations must also be reverted if inference fails or is canceled. A forgotten penalty contaminates all later selections; an excessive one can force artificial diversification and spend a batch on branches sequential search would not have preferred.

The lab’s first mode collects reservations sequentially in one tree and batches leaves in a network call. This studies pending requests and batches without introducing tree races. A second variant runs independent trees in threads and batches their requests through a common server. No tree is shared between threads, and the experiment does not measure scalability of an implementation that does share one.

A reservation counter is not a completed-simulation counter. If a batch fills only partially because a terminal or already-pending leaf is reached, the experiment must report what was evaluated and how duplicates were treated. In particular, counting copies of one inference as independent observations inflates visits without adding information. Reservations are tested with an invariant: after returning or canceling all requests, temporary state returns to zero and only statistics of actually completed simulations remain.

AlphaGo Zero describes batched leaf evaluation and virtual loss in its methods. That implementation uses minibatches of 8 in its described configuration; this does not demonstrate that 8 is best for our network or GPU. Measure the tradeoff on two axes: completed evaluations or simulations per unit time, and decision quality at fixed budget. Higher throughput can coexist with worse search if simultaneous selections receive stale information.

Explore at the root and choose at the end

Root exploration temporarily modifies priors during self-play. For legal actions, sample η\boldsymbol\eta from a Dirichlet distribution and mix it with the network policy:

P′(s,a)=(1−ε)P(s,a)+εηa.P'(s,a)=(1-\varepsilon)P(s,a)+\varepsilon\eta_a.

Both PP and η\boldsymbol\eta sum to one over legal actions, and the mixture does too if 0≤ε≤10\le\varepsilon\le1. The concentration parameter controls sample shape; its effect also depends on legal-action count. Mixing introduces diversity across games but neither repairs a badly normalized prior nor turns noise into position information. Tournament evaluation disables it to measure the agent’s defined policy without exploration perturbation.

After search, temperature τ>0\tau>0 transforms visits into a distribution proportional to N(s,a)1/τN(s,a)^{1/\tau}. At low temperature, mass concentrates on most-visited actions; as τ→0\tau\to0, a maximum-visit action is selected with a declared tie-break. With positive temperature and all visits zero, the distribution is undefined, so choose a legal action or require at least one simulation. Temperature controls final selection, not QQ‘s value or the initial network policy.

AlphaGo Zero’s methods describe a mixture with ε=0.25\varepsilon=0.25 and concentration 0.030.03 for Go. Those numbers belong to that configuration; action count and distribution differ in Connect 4, so they do not prove an optimal choice here. The same source uses high temperature early in self-play and near-zero later. A reproducible tournament specifies temperature, noise, seeds, and tie-breaking rule; changing any changes the measured agent.

What to measure in a fair comparison

Comparison against UCT needs paired openings and swapped colors, as in the second lesson’s tournament. Distinguish per-move budget from total cost: 200 network evaluations and 5 000 random games do not cost the same. Asking “who plays better under these budgets” does not alone answer which is more efficient per second or compute. A valid comparison records both quantities and an uncertainty interval for outcome.

Position distribution matters too. The previous supervised network was trained on conditioned endgames, so opening performance does not follow from its accuracy there. Measuring against UCT in specific positions tests the system, not a universal claim that PUCT always beats UCT. If the expected result does not appear, show the data, inspect positions, and explain what can be concluded; do not replace the tournament with a hand-built curve.

Lab

This lab reproduces the engine and network from the previous lesson’s current cells and retrains them with the same procedure. It requires no checkpoint or temporary dataset from another lesson. The network is retained during this cell series to evaluate leaves. The training distribution remains limited to 36-move endgames without earlier wins: the tournament’s six-move openings are outside that regime.

[ ]Engine and solver from p12-l03Local GPU
W, H, S = 7, 6, 7
ORDER = (3, 2, 4, 1, 5, 0, 6)
BOTTOM = sum(1 << (c * S) for c in range(W))
BOARD = BOTTOM * ((1 << H) - 1)

def win(p):
    for d in (1, 6, 7, 8):
        pairs = p & (p >> d)
        if pairs & (pairs >> (2 * d)):
            return True
    return False

def move_bit(mask, c):
    legal = (mask + BOTTOM) & BOARD
    return legal & (((1 << H) - 1) << (c * S))

def position(sequence):
    # sequence contiene columnas desde cero y termina antes de ganar.
    current = mask = 0
    for c in sequence:
        if not 0 <= c < W:
            raise ValueError('Columna fuera del tablero')
        b = move_bit(mask, c)
        if not b or win(current | b):
            raise ValueError('Columna llena o partida ya terminada')
        current, mask = current ^ mask, mask | b
    return current, mask

class Solver:
    def __init__(self):
        self.table = {}
        self.nodes = 0

    def search(self, current, mask, alpha, beta):
        self.nodes += 1
        if mask == BOARD:
            return 0
        key = current + mask
        entry = self.table.get(key)
        if entry is not None:
            lower, upper = entry
            if lower == upper:
                return lower
            alpha, beta = max(alpha, lower), min(beta, upper)
            if alpha >= beta:
                return lower if lower >= beta else upper
        a0, b0 = alpha, beta
        best = -2
        for c in ORDER:
            b = move_bit(mask, c)
            if not b:
                continue
            if win(current | b):
                value = 1
            else:
                value = -self.search(current ^ mask, mask | b, -beta, -alpha)
            best = max(best, value)
            alpha = max(alpha, best)
            if alpha >= beta:
                break
        lower, upper = self.table.get(key, (-1, 1))
        if best <= a0:
            upper = min(upper, best)
        elif best >= b0:
            lower = max(lower, best)
        else:
            lower = upper = best
        self.table[key] = (lower, upper)
        return best

    def value(self, current, mask):
        return self.search(current, mask, -2, 2)

    def analyze(self, current, mask):
        values = []
        for c in range(W):
            b = move_bit(mask, c)
            if not b:
                values.append(None)
            elif win(current | b):
                values.append(1)
            else:
                values.append(-self.value(current ^ mask, mask | b))
        return values


import numpy as np
from numba import njit, types
from numba.typed import Dict

@njit
def n_win(p):
    for d in (1, 6, 7, 8):
        pairs = p & (p >> d)
        if pairs & (pairs >> (2*d)):
            return True
    return False

@njit
def n_bit(mask, c):
    return ((mask + BOTTOM) & BOARD) & (63 << (c*7))

@njit
def n_search(p, mask, alpha, beta, table, counter):
    counter[0] += 1
    if mask == BOARD:
        return 0
    key = p + mask
    if key in table:
        entry = table[key]
        lower, upper = entry // 3 - 1, entry % 3 - 1
        if lower == upper:
            return lower
        alpha, beta = max(alpha, lower), min(beta, upper)
        if alpha >= beta:
            return lower if lower >= beta else upper
    a0, b0 = alpha, beta
    best = -2
    for c in (3, 2, 4, 1, 5, 0, 6):
        b = n_bit(mask, c)
        if not b:
            continue
        if n_win(p | b):
            table[key] = 8
            return 1
        value = -n_search(p ^ mask, mask | b, -beta, -alpha, table, counter)
        best = max(best, value)
        alpha = max(alpha, best)
        if alpha >= beta:
            break
    lower, upper = -1, 1
    if key in table:
        entry = table[key]
        lower, upper = entry // 3 - 1, entry % 3 - 1
    if best <= a0:
        upper = min(upper, best)
    elif best >= b0:
        lower = max(lower, best)
    else:
        lower = upper = best
    table[key] = (lower + 1)*3 + upper + 1
    return best

@njit
def n_analyze(p, mask, table, counter):
    result = np.full(7, -2, dtype=np.int64)
    for c in range(7):
        b = n_bit(mask, c)
        if b:
            if n_win(p | b):
                result[c] = 1
            else:
                result[c] = -n_search(p ^ mask, mask | b, -2, 2, table, counter)
    return result

@njit
def n_value(p, mask, table, counter):
    if n_search(p, mask, -1, 0, table, counter) < 0:
        return -1
    if n_search(p, mask, 0, 1, table, counter) >= 1:
        return 1
    return 0
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Reconstruct the supervised networkLocal GPU
"""Experimento de política y valor con el oráculo de la lección actual p12-l01."""
import json
import gc
import math
import os
import random
import re
import time
from pathlib import Path
import numpy as np
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
import torch
from torch import nn
import torch.nn.functional as F

torch.set_num_threads(1)
random.seed(1203)
np.random.seed(1203)
torch.manual_seed(1203)
torch.use_deterministic_algorithms(True)

def reflect(x):
    out = 0
    for c in range(7):
        out |= ((x >> (7*c)) & 127) << (7*(6-c))
    return out

def generate(engine, n=20000):
    from numba import types
    from numba.typed import Dict
    win, bit, analyze = engine['win'], engine['move_bit'], engine['n_analyze']
    table = Dict.empty(key_type=types.int64, value_type=types.int64)
    counter = np.zeros(1, np.int64)
    rng = random.Random(1201)
    records, seen = [], set()
    attempts = 0
    while len(records) < n:
        p = mask = 0
        seq = []
        for _ in range(36):
            legal = [(c, bit(mask, c)) for c in range(7)]
            legal = [(c,b) for c,b in legal if b and not win(p | b)]
            if not legal:
                break
            c, b = rng.choice(legal)
            seq.append(c)
            p, mask = p ^ mask, mask | b
        attempts += 1
        if len(seq) != 36 or p + mask in seen:
            continue
        seen.add(p + mask)
        values = [int(v) for v in analyze(p, mask, table, counter)]
        records.append({'sequence': seq, 'p': p, 'mask': mask, 'values': values})
        if len(records) % 1000 == 0:
            table.clear()
    print('Posiciones etiquetadas:', len(records), 'intentos:', attempts, flush=True)
    return records

def key(record):
    p, mask = record['p'], record['mask']
    return min((p,mask), (reflect(p), reflect(mask)))

def split(records):
    groups = {}
    for row in records:
        groups.setdefault(key(row), []).append(row)
    keys = list(groups)
    random.Random(1203).shuffle(keys)
    cutoff = int(.8 * len(keys))
    train = [row for k in keys[:cutoff] for row in groups[k]]
    test = [row for k in keys[cutoff:] for row in groups[k]]
    assert set(map(key,train)).isdisjoint(set(map(key,test)))
    print('Grupos de posición y reflejo:', len(groups), '; entrenamiento:', len(train), '; prueba:', len(test), flush=True)
    return train,test

def encode(row):
    p, mask = row['p'], row['mask']
    x = np.zeros((2,6,7), dtype=np.float32)
    for c in range(7):
        for r in range(6):
            bit = 1 << (7*c+r)
            x[0,r,c] = bool(p & bit)
            x[1,r,c] = bool((p ^ mask) & bit)
    legal = np.array([v != -2 for v in row['values']])
    if not legal.any():
        raise ValueError('No se puede evaluar un estado terminal sin jugadas legales')
    best = max(v for v in row['values'] if v != -2)
    optimal = np.array([v == best for v in row['values']], dtype=np.float32)
    policy = optimal / optimal.sum()
    return x, legal, policy, np.float32(best)

def tensors(rows):
    z = [encode(row) for row in rows]
    return [torch.tensor(np.stack([x[i] for x in z])) for i in range(4)]

class Block(nn.Module):
    def __init__(self, channels):
        super().__init__()
        self.conv1 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(channels)
        self.conv2 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(channels)
    def forward(self, x):
        y = F.relu(self.bn1(self.conv1(x)))
        return F.relu(x + self.bn2(self.conv2(y)))

class PolicyValue(nn.Module):
    def __init__(self, channels=32, blocks=3):
        super().__init__()
        self.stem = nn.Sequential(nn.Conv2d(2,channels,3,padding=1,bias=False), nn.BatchNorm2d(channels), nn.ReLU())
        self.tower = nn.Sequential(*(Block(channels) for _ in range(blocks)))
        self.policy = nn.Sequential(nn.Conv2d(channels,2,1), nn.ReLU(), nn.Flatten(), nn.Linear(84,7))
        self.value = nn.Sequential(nn.Conv2d(channels,1,1), nn.ReLU(), nn.Flatten(), nn.Linear(42,32), nn.ReLU(), nn.Linear(32,1), nn.Tanh())
    def forward(self,x,legal):
        y = self.tower(self.stem(x))
        logits = self.policy(y).masked_fill(~legal, -1e9)
        return logits, self.value(y).squeeze(-1)


def train_run():
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print('Dispositivo:', device, flush=True)
    eng = {'win': win, 'move_bit': move_bit, 'n_analyze': n_analyze}
    records = generate(eng)
    training, testing = split(records)
    X,L,P,V = tensors(training)
    Xt,Lt,Pt,Vt = tensors(testing)
    model = PolicyValue().to(device)
    print('Parámetros:', sum(p.numel() for p in model.parameters()), flush=True)
    optimizer = torch.optim.AdamW(model.parameters(), lr=0.001, weight_decay=1e-4)
    order_rng = torch.Generator().manual_seed(1203)
    losses = []
    for epoch in range(12):
        model.train()
        order = torch.randperm(len(X), generator=order_rng)
        total = 0
        for ix in order.split(256):
            x,l,p,v = X[ix].to(device), L[ix].to(device), P[ix].to(device), V[ix].to(device)
            # La misma reflexión transforma tablero, legales y objetivo de política.
            flip = (torch.rand(len(ix), generator=order_rng) < .5).to(device)
            x[flip] = x[flip].flip(-1)
            l[flip] = l[flip].flip(-1)
            p[flip] = p[flip].flip(-1)
            logits, value = model(x,l)
            loss = -(p*F.log_softmax(logits,dim=1)).sum(dim=1).mean() + F.mse_loss(value,v)
            optimizer.zero_grad(set_to_none=True)
            loss.backward()
            optimizer.step()
            total += loss.item()*len(ix)
        losses.append(total / len(X))
        print('Época:', epoch+1, 'pérdida:', round(losses[-1],4), flush=True)
    model.eval()
    print('Red supervisada reconstruida con la partición de p12-l03')
    return model, testing

model, heldout = train_run()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next cell reproduces UCT from lesson two. It compiles traversal before loading the separate PUCT implementation. Both represent the same game rule, but use different accumulated-value conventions: UCT stores value per node and PUCT per edge from the player who chose it.

[ ]UCT from the second lessonLocal GPU
"""Laboratorio autocontenido: motor de la celda de p12-l01 y MCTS compilado."""
import math
import json
import random
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import numpy as np
from numba import njit
from scipy.optimize import minimize
from urllib.request import urlopen

# Misma representación, máscara, turnos y convención de p12-l01.
W, H, S = 7, 6, 7
BOTTOM = sum(1 << (c * S) for c in range(W))
BOARD = BOTTOM * ((1 << H) - 1)

@njit
def win(p):
    for d in (1, 6, 7, 8):
        m = p & (p >> d)
        if m & (m >> (2*d)):
            return True
    return False

@njit
def move_bit(mask, c):
    return ((mask + BOTTOM) & BOARD) & (63 << (c*7))

@njit
def rollout(p, mask):
    # Salida desde la perspectiva del jugador activo al comenzar.
    sign = 1
    while mask != BOARD:
        legal = np.empty(7, dtype=np.int64)
        n = 0
        for c in range(7):
            if move_bit(mask, c):
                legal[n] = c
                n += 1
        c = legal[np.random.randint(n)]
        b = move_bit(mask, c)
        if win(p | b):
            return sign
        p, mask = p ^ mask, mask | b
        sign = -sign
    return 0

@njit(nogil=True)
def mcts(p0, mask0, simulations, exploration, seed):
    np.random.seed(seed)
    size = simulations + 1
    children = np.full((size, 7), -1, np.int32)
    pp = np.zeros(size, np.int64)
    mm = np.zeros(size, np.int64)
    parent = np.full(size, -1, np.int32)
    visits = np.zeros(size, np.int32)
    total = np.zeros(size, np.float64)
    terminal = np.full(size, 2, np.int8) # 2 no terminal, -1 perdida, 0 empate
    pp[0], mm[0] = p0, mask0
    count = 1
    for _ in range(simulations):
        i = 0
        while terminal[i] == 2:
            p, mask = pp[i], mm[i]
            unexpanded = np.empty(7, np.int64)
            n = 0
            for c in range(7):
                if move_bit(mask, c) and children[i, c] < 0:
                    unexpanded[n] = c
                    n += 1
            if n:
                c = unexpanded[np.random.randint(n)]
                b = move_bit(mask, c)
                child = count
                count += 1
                children[i, c] = child
                parent[child] = i
                pp[child], mm[child] = p ^ mask, mask | b
                if win(p | b):
                    terminal[child] = -1
                elif mm[child] == BOARD:
                    terminal[child] = 0
                i = child
                break
            best = -1e9
            chosen = -1
            for c in range(7):
                child = children[i, c]
                if child < 0:
                    continue
                # total[child] es valor del jugador del hijo: negar para el padre.
                ucb = -total[child] / visits[child] + exploration * math.sqrt(math.log(visits[i]) / visits[child])
                if ucb > best:
                    best, chosen = ucb, child
            i = chosen
        value = terminal[i] if terminal[i] != 2 else rollout(pp[i], mm[i])
        while i >= 0:
            visits[i] += 1
            total[i] += value
            value = -value
            i = parent[i]
    counts = np.zeros(7, np.int32)
    for c in range(7):
        j = children[0, c]
        if j >= 0:
            counts[c] = visits[j]
    return counts

def position(seq):
    p = mask = 0
    for c in seq:
        b = int(move_bit(mask, c))
        if not b or win(p | b):
            raise ValueError('apertura ilegal o terminal')
        p, mask = p ^ mask, mask | b
    return p, mask

def make_openings(n=24, seed=1202, depth=6):
    r = random.Random(seed)
    result = []
    while len(result) < n:
        p = mask = 0
        seq = []
        for _ in range(depth):
            legal = [c for c in range(W) if move_bit(mask, c) and not win(p | move_bit(mask, c))]
            c = r.choice(legal)
            b = int(move_bit(mask, c))
            p, mask = p ^ mask, mask | b
            seq.append(c)
        result.append(tuple(seq))
    return result

def game(task):
    a, b, seq, seed = task
    p, mask = position(seq)
    move = len(seq)
    while True:
        sims = a if move % 2 == 0 else b
        counts = mcts(p, mask, sims, 1.4, seed + move)
        c = int(np.argmax(counts))
        stone = int(move_bit(mask, c))
        if win(p | stone):
            return 1 if move % 2 == 0 else 0
        if mask | stone == BOARD:
            return 0.5
        p, mask = p ^ mask, mask | stone
        move += 1

def fit_elo(matches, n):
    # Cuasi verosimilitud Elo: empate cuenta media victoria y media derrota.
    # Si el grafo de victorias no es fuertemente conexo el maximo es infinito.
    edges = [set() for _ in range(n)]
    for i, j, y in matches:
        if y > 0:
            edges[i].add(j)
        if y < 1:
            edges[j].add(i)
    for start in range(n):
        reached, pending = {start}, [start]
        while pending:
            for nxt in edges[pending.pop()]:
                if nxt not in reached:
                    reached.add(nxt)
                    pending.append(nxt)
        if len(reached) != n:
            raise ValueError('Elo no identificable: grafo de victorias no conexo')
    scale = math.log(10) / 400
    i = np.array([m[0] for m in matches], dtype=int)
    j = np.array([m[1] for m in matches], dtype=int)
    y = np.array([m[2] for m in matches], dtype=float)
    def loss(x):
        ratings = np.r_[0., x]
        z = scale * (ratings[i] - ratings[j])
        error = 1 / (1 + np.exp(-z)) - y
        grad = np.zeros(n)
        np.add.at(grad, i, error * scale)
        np.add.at(grad, j, -error * scale)
        return np.sum(np.logaddexp(0., z) - y*z), grad[1:]
    fit = minimize(loss, np.zeros(n-1), method='BFGS', jac=True, options={'gtol': 1e-7})
    if not np.isfinite(fit.fun) or np.max(np.abs(fit.x)) > 5000:
        raise ValueError('Elo no finito o mal identificado')
    return np.r_[0., fit.x]

def run_tournament(output_path=None):
    sims = [100, 200, 400, 800, 1600, 3200, 6400, 10000]
    openings = make_openings()
    pairs = [(i, i+1) for i in range(len(sims)-1)] + [(0, len(sims)-1)]
    tasks = []
    meta = []
    for i, j in pairs:
        for k, seq in enumerate(openings):
            for flip in (0, 1):
                a, b = (sims[i], sims[j]) if flip == 0 else (sims[j], sims[i])
                tasks.append((a, b, seq, 100000 + 10000*i + 100*k + flip*50))
                meta.append((i, j, k, flip))
    # Compila antes de arrancar hilos: cada llamada libera el GIL y fija su semilla.
    mcts(0, 0, 1, 1.4, 0)
    with ThreadPoolExecutor(max_workers=2) as pool:
        scores = list(pool.map(game, tasks, chunksize=4))
    records = [(i, j, k, score if flip == 0 else 1-score)
               for (i, j, k, flip), score in zip(meta, scores)]
    if output_path is not None:
        Path(output_path).write_text(json.dumps({'simulations': sims, 'openings': openings,
                                                 'records': records}, separators=(',', ':')),
                                     encoding='utf-8')
    matches = [(i, j, score) for i, j, k, score in records]
    elo = fit_elo(matches, len(sims))
    rng = np.random.default_rng(1202)
    intervals = []
    boots = []
    # Reamostrar bloques de apertura, conservando ambos colores y todos los pares.
    for _ in range(300):
        sample = rng.integers(0, len(openings), size=len(openings))
        boot = [m for k in sample for m in matches_by_opening(records, int(k))]
        try:
            boots.append(fit_elo(boot, len(sims)))
        except ValueError:
            pass
    arr = np.array(boots)
    for i, n in enumerate(sims):
        lo, hi = np.percentile(arr[:, i], [2.5, 97.5])
        intervals.append((n, round(float(elo[i]), 1), round(float(lo), 1), round(float(hi), 1)))
    print('Partidas:', len(matches), '; aperturas:', len(openings), '; bootstrap válido:', len(boots))
    print('Simulaciones, Elo relativo, intervalo:', intervals)
    print('Marcadores por par:', [(sims[i], sims[j], sum(x[3] for x in records if x[0]==i and x[1]==j), sum(1 for x in records if x[0]==i and x[1]==j)) for i,j in pairs])
    return records, intervals

def matches_by_opening(records, k):
    return [(i, j, score) for i, j, kk, score in records if kk == k]

# Compilar antes de definir las operaciones equivalentes de PUCT.
mcts(0, 0, 1, 1.4, 0)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The root is evaluated once before counting 200 simulations. A simulation reaching a terminal is resolved without the network; another reaching a nonterminal leaf contributes a state to a batch. Thus evaluated leaves and terminal simulations sum to 200, and root evaluation is additional. network_calls counts batch calls including the root; one call can contain multiple leaves. The tree does not merge transpositions across branches, and reservation only prevents repeating the same pending node within its batch.

[ ]PUCT with reservations and batched evaluationLocal GPU
"""PUCT para el motor y la red de p12-l01 y p12-l03.

El evaluador recibe [(current, mask), ...] y devuelve logits (B, 7) y valores
(B,), siempre desde la perspectiva del jugador que mueve en cada estado.
"""
from dataclasses import dataclass, field
import math
import numpy as np

W, H, S = 7, 6, 7
BOTTOM = sum(1 << (c * S) for c in range(W))
BOARD = BOTTOM * ((1 << H) - 1)


def win(p):
    for d in (1, 6, 7, 8):
        pairs = p & (p >> d)
        if pairs & (pairs >> (2 * d)):
            return True
    return False


def move_bit(mask, c):
    return ((mask + BOTTOM) & BOARD) & (63 << (c * S))


def encode(states):
    x = np.zeros((len(states), 2, H, W), dtype=np.float32)
    legal = np.zeros((len(states), W), dtype=bool)
    for i, (p, mask) in enumerate(states):
        for c in range(W):
            legal[i, c] = bool(move_bit(mask, c))
            for r in range(H):
                bit = 1 << (S*c + r)
                x[i, 0, r, c] = bool(p & bit)
                x[i, 1, r, c] = bool((p ^ mask) & bit)
    return x, legal


class TorchEvaluator:
    """Adaptador de la clase PolicyValue de p12-l03, con inferencia agrupada."""
    def __init__(self, model, device):
        self.model, self.device = model, device
        self.model.eval()

    def __call__(self, states):
        import torch
        x, legal = encode(states)
        if not legal.any(axis=1).all():
            raise ValueError('La red no evalúa posiciones sin acciones legales')
        with torch.inference_mode():
            logits, values = self.model(torch.from_numpy(x).to(self.device),
                                        torch.from_numpy(legal).to(self.device))
        return logits.cpu().numpy(), values.cpu().numpy()


@dataclass
class Edge:
    prior: float
    visits: int = 0
    total: float = 0.0  # Valor desde el jugador del padre.
    virtual: int = 0
    child: object = None


@dataclass
class Node:
    p: int
    mask: int
    terminal: object = None  # None no terminal, -1 derrota, 0 empate.
    edges: dict = field(default_factory=dict)
    expanded: bool = False
    pending: bool = False


def expand(node, logits):
    """Softmax exclusivamente sobre legales; rechaza salidas no finitas."""
    actions = [c for c in range(W) if move_bit(node.mask, c)]
    if node.terminal is not None or not actions:
        raise ValueError('No se expande un estado terminal')
    logits = np.asarray(logits, dtype=float)
    if logits.shape != (W,) or not np.isfinite(logits[actions]).all():
        raise ValueError('Logits legales inválidos')
    weights = np.exp(logits[actions] - np.max(logits[actions]))
    weights /= weights.sum()
    node.edges = {c: Edge(float(prior)) for c, prior in zip(actions, weights)}
    node.expanded = True


def child_of(node, action):
    edge = node.edges[action]
    if edge.child is None:
        bit = move_bit(node.mask, action)
        mask = node.mask | bit
        terminal = -1 if win(node.p | bit) else (0 if mask == BOARD else None)
        edge.child = Node(node.p ^ node.mask, mask, terminal)
    return edge.child


def select(node, c_puct, virtual_loss):
    # Con cero visitas se usa sqrt(1) para que el prior decida la primera rama.
    parent_visits = sum(e.visits + e.virtual for e in node.edges.values())
    root = math.sqrt(max(1, parent_visits))
    def score(edge):
        n = edge.visits + edge.virtual
        q = (edge.total - virtual_loss * edge.virtual) / n if n else 0.0
        return q + c_puct * edge.prior * root / (1 + n)
    return max(node.edges, key=lambda c: score(node.edges[c]))


def apply_virtual(path):
    for edge in path:
        edge.virtual += 1


def revert_virtual(path):
    for edge in path:
        if edge.virtual <= 0:
            raise AssertionError('Pérdida virtual sin reserva')
        edge.virtual -= 1


def backup(path, leaf_value):
    """Cada arista guarda el valor desde el jugador que la eligió."""
    value = float(leaf_value)
    for edge in reversed(path):
        value = -value
        edge.visits += 1
        edge.total += value


def policy_from_visits(counts, temperature):
    counts = np.asarray(counts, dtype=np.int64)
    if counts.shape != (W,) or np.any(counts < 0) or counts.sum() == 0:
        raise ValueError('Se necesitan visitas no negativas y alguna positiva')
    if not np.isfinite(temperature) or temperature < 0:
        raise ValueError('Temperatura inválida')
    out = np.zeros(W, dtype=float)
    if temperature == 0:
        out[np.argmax(counts)] = 1.0
    else:
        active = counts > 0
        log_weights = np.log(counts[active])
        # Restar antes de dividir evita inf - inf con temperatura muy pequeña.
        with np.errstate(over='ignore'):
            log_weights = (log_weights - log_weights.max()) / temperature
        weights = np.exp(log_weights)
        out[active] = weights / weights.sum()
    return out


def search(p, mask, evaluator, simulations=200, batch_size=16, c_puct=1.5,
           virtual_loss=1.0, noise_fraction=0.0, alpha=0.3, rng=None):
    """Raíz evaluada aparte; cada simulación aumenta una visita de raíz.

    La recolección termina antes de llenar el lote si alcanza una hoja ya
    reservada; así no se cuenta una misma evaluación como varias simulaciones.
    Los terminales se resuelven sin red. No se comparten árboles ni hilos.
    """
    if simulations < 1 or batch_size < 1:
        raise ValueError('Presupuesto y lote deben ser positivos')
    if not all(np.isfinite(x) for x in (c_puct, virtual_loss, noise_fraction)):
        raise ValueError('Parámetros de búsqueda no finitos')
    if c_puct < 0 or virtual_loss < 0 or not 0 <= noise_fraction <= 1:
        raise ValueError('Parámetros de búsqueda inválidos')
    if noise_fraction and (not np.isfinite(alpha) or alpha <= 0):
        raise ValueError('Alpha debe ser positivo')
    if (p & ~mask) or (mask & ~BOARD) or mask == BOARD or win(p) or win(p ^ mask):
        raise ValueError('La raíz debe ser una posición no terminal')
    rng = np.random.default_rng() if rng is None else rng
    root = Node(p, mask)

    def evaluate(nodes):
        logits, values = evaluator([(n.p, n.mask) for n in nodes])
        logits, values = np.asarray(logits), np.asarray(values)
        if logits.shape != (len(nodes), W) or values.shape != (len(nodes),):
            raise ValueError('Dimensiones del evaluador inválidas')
        if not np.isfinite(values).all() or np.any(np.abs(values) > 1):
            raise ValueError('Valores fuera de [-1, 1]')
        for node, row in zip(nodes, logits):
            expand(node, row)
        return values

    evaluate([root])
    if noise_fraction:
        noise = rng.dirichlet(np.full(len(root.edges), alpha))
        for edge, sample in zip(root.edges.values(), noise):
            edge.prior = (1-noise_fraction)*edge.prior + noise_fraction*sample

    done = 0
    while done < simulations:
        queued = []
        try:
            while len(queued) < batch_size and done + len(queued) < simulations:
                node, path = root, []
                while node.expanded:
                    action = select(node, c_puct, virtual_loss)
                    edge = node.edges[action]
                    path.append(edge)
                    node = child_of(node, action)
                if node.terminal is not None:
                    backup(path, node.terminal)
                    done += 1
                elif node.pending:
                    # Liberar las reservas previas antes de volver a seleccionar.
                    break
                else:
                    node.pending = True
                    apply_virtual(path)
                    queued.append((node, path))
            if queued:
                values = evaluate([node for node, _ in queued])
                for (node, path), value in zip(queued, values):
                    revert_virtual(path)
                    node.pending = False
                    backup(path, value)
                    done += 1
                queued.clear()
        finally:
            for node, path in queued:
                revert_virtual(path)
                node.pending = False
    counts = np.zeros(W, dtype=np.int64)
    for action, edge in root.edges.items():
        counts[action] = edge.visits
    return root, counts
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]PUCT controlsLocal GPU

class Uniforme:
    def __init__(self):
        self.calls = 0
    def __call__(self, states):
        self.calls += 1
        return np.zeros((len(states),7)), np.zeros(len(states))

e1, e2 = Edge(.5), Edge(.5)
apply_virtual([e1,e2]); revert_virtual([e1,e2])
assert e1.virtual == e2.virtual == 0
backup([e1,e2], .75)
assert (e1.total,e2.total) == (.75,-.75)
np.testing.assert_allclose(policy_from_visits([0,1,4,0,0,0,0],1),[0,.2,.8,0,0,0,0])
np.testing.assert_array_equal(policy_from_visits([0,1,4,0,0,0,0],0),[0,0,1,0,0,0,0])
uniforme = Uniforme()
root, counts = search(0,0,uniforme,simulations=32,batch_size=8,
                      noise_fraction=.25,alpha=.3,rng=np.random.default_rng(42))
assert counts.sum() == 32
assert abs(sum(e.prior for e in root.edges.values())-1) < 1e-12
assert not np.allclose([e.prior for e in root.edges.values()],np.ones(7)/7)
def check_reservas(node):
    assert not node.pending
    for edge in node.edges.values():
        assert edge.virtual == 0
        if edge.child is not None:
            check_reservas(edge.child)
check_reservas(root)
captured = []
original_apply = apply_virtual
def capturar(path):
    captured.extend(path)
    original_apply(path)
def falla(states):
    if captured:
        raise RuntimeError('fallo de inferencia simulado')
    return np.zeros((len(states),7)), np.zeros(len(states))
globals()['apply_virtual'] = capturar
try:
    try:
        search(0,0,falla,simulations=10,batch_size=4)
        raise AssertionError('La inferencia debió fallar')
    except RuntimeError:
        pass
finally:
    globals()['apply_virtual'] = original_apply
assert captured and all(e.virtual == 0 for e in captured)
print('Control de signos, temperatura, ruido y reversión de reservas: correcto')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The preceding search traverses one tree in a single thread and batches its pending leaves. The next variant runs independent trees in several threads: each retains its own virtual reservations and one server gathers requests from different trees to call the network in batches. No multiple threads modify one tree. Requests wait for a response or error, and the server is closed and joined in a finally block. This lesson’s grid and tournaments continue using the preceding mode to retain the measured protocol.

[ ]Parallel trees and inference serverLocal GPU
"""Varias búsquedas independientes con servidor de inferencia agrupada."""
from concurrent.futures import ThreadPoolExecutor
from queue import Queue, Empty
from threading import Thread, Event, Barrier, get_ident
import numpy as np
import time


class BatchServer:
    def __init__(self, evaluator, max_states=64, max_wait=.005):
        if max_states < 1 or max_wait < 0:
            raise ValueError('Límite de lote o espera inválido')
        self.evaluator = evaluator
        self.max_states = max_states
        self.max_wait = max_wait
        self.queue = Queue()
        self.calls = []
        self.workers = set()
        self.thread = Thread(target=self._serve)
        self.thread.start()

    def __call__(self, states):
        if not states or len(states) > self.max_states:
            raise ValueError('Tamaño de solicitud inválido')
        done, result = Event(), {}
        self.queue.put((list(states), done, result, get_ident()))
        done.wait()
        if 'error' in result:
            raise result['error']
        return result['logits'], result['values']

    def _serve(self):
        pending = None
        while True:
            first = pending if pending is not None else self.queue.get()
            pending = None
            if first is None:
                return
            requests = [first]
            size = len(first[0])
            deadline = time.monotonic() + self.max_wait
            while size < self.max_states:
                remaining = deadline - time.monotonic()
                if remaining <= 0:
                    break
                try:
                    item = self.queue.get(timeout=remaining)
                except Empty:
                    break
                if item is None:
                    pending = None
                    self.queue.put(None)
                    break
                if size + len(item[0]) > self.max_states:
                    pending = item
                    break
                requests.append(item)
                size += len(item[0])
            states = [s for item in requests for s in item[0]]
            self.calls.append((len(requests),len(states)))
            self.workers.update(item[3] for item in requests)
            try:
                logits, values = self.evaluator(states)
                if np.shape(logits) != (len(states),7) or np.shape(values) != (len(states),):
                    raise ValueError('El evaluador devolvió dimensiones incompatibles')
                offset = 0
                for batch, _, result, _ in requests:
                    n = len(batch)
                    result['logits'] = logits[offset:offset+n]
                    result['values'] = values[offset:offset+n]
                    offset += n
            except BaseException as error:
                for _, _, result, _ in requests:
                    result['error'] = error
            finally:
                for _, done, _, _ in requests:
                    done.set()

    def close(self):
        self.queue.put(None)
        self.thread.join()


def parallel_searches(states, evaluator, simulations=40, tree_batch=4, workers=4):
    if not states or workers < 1:
        raise ValueError('Se requiere al menos un estado y un trabajador')
    server = BatchServer(evaluator)
    # Sin barrera las peticiones se agrupan igualmente, pero la primera puede
    # llegar antes de que arranque el resto de trabajadores.
    first_group = min(len(states),workers)
    barrier = Barrier(first_group)
    def one(item):
        i, state = item
        if i < first_group:
            barrier.wait()
        return search(*state,server,simulations=simulations,batch_size=tree_batch)
    try:
        with ThreadPoolExecutor(max_workers=workers) as pool:
            results = list(pool.map(one,enumerate(states)))
    finally:
        server.close()
    return results, server.calls, len(server.workers)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

First compare parallel against sequential mode with a uniform evaluator whose output is exactly known. Check that each search completes its budget, all reservations return to zero, and inference failure propagates without leaving the server blocked. Record how many calls combined requests: this depends on thread scheduling and is not guaranteed every run. Then repeat the control with the real network on four test endgames. Agreement in these examples does not prove any batch always yields the same search: network values may change slightly with batch size and reservations alter exploration order.

[ ]Check parallel searchesLocal GPU
states = [(0,0)]*4
simple = Uniforme()
expected = [search(*s,simple,simulations=40,batch_size=4)[1] for s in states]
parallel, calls, threads_used = parallel_searches(states,simple,simulations=40,tree_batch=4,workers=4)
assert threads_used == 4
for (tree,counts), ref in zip(parallel,expected):
    np.testing.assert_array_equal(counts,ref)
    assert counts.sum() == 40
    check_reservas(tree)
def error_eval(states):
    raise ValueError('error de inferencia de prueba')
try:
    parallel_searches(states,error_eval,simulations=2,workers=4)
    raise AssertionError('Se esperaba el error de inferencia')
except ValueError as error:
    assert str(error) == 'error de inferencia de prueba'
print('Árboles independientes:',len(parallel),'hilos:',threads_used,
      'llamadas que agrupan peticiones:',sum(n > 1 for n,_ in calls))

states = [(row['p'],row['mask']) for row in heldout[:4]]
real_eval = TorchEvaluator(model,next(model.parameters()).device)
expected = [search(*s,real_eval,simulations=40,batch_size=4)[1] for s in states]
parallel, calls, threads_used = parallel_searches(states,real_eval,simulations=40,tree_batch=4,workers=4)
for tree, counts in parallel:
    assert counts.sum() == 40
    check_reservas(tree)
print('Red real: visitas por árbol:',[int(counts.sum()) for _,counts in parallel],
      'vectores iguales al modo secuencial:',sum(np.array_equal(counts,ref) for (_,counts),ref in zip(parallel,expected)),
      'llamadas que agrupan peticiones:',sum(n > 1 for n,_ in calls))
del real_eval
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next cell defines both evaluation protocols and instrumentation. In tournament, no noise is added and the most-visited action is chosen with first-column tie-breaking. The bootstrap interval resamples complete openings with both color assignments. If a proportion is exactly zero or one, Elo transformation produces an infinite endpoint and must be reported as such.

[ ]Evaluation, tournament, and countersLocal GPU
class TrackedEvaluator:
    def __init__(self, evaluator):
        self.evaluator = evaluator
        self.calls = 0
        self.states = 0
    def __call__(self, states):
        self.calls += 1
        self.states += len(states)
        return self.evaluator(states)

def load_test():
    # Misma fuente fija que la evaluación de p12-l02; posiciones más tempranas.
    url = ('https://huggingface.co/datasets/davidquarel/connect4-pons-eval/resolve/'
           '70d868ee534df1e2c6213b22daeae36d4ad73cc5/pons_eval_dataset.json')
    with urlopen(url, timeout=30) as response:
        rows = json.load(response)['positions']
    candidates = [row for row in rows if 26 <= row['depth'] <= 30]
    return random.Random(1204).sample(candidates, 100)

def optimal_move(row, choice):
    scores = row['scores']
    actual = [(s > 0) - (s < 0) if s != -1000 else None for s in scores]
    return actual[choice] == max(x for x in actual if x is not None)

def export_grid(evaluator, rows):
    cases = []
    for i, row in enumerate(rows[:2]):
        seq = [int(c) for c in row['moves']]
        p, mask = position(seq)
        logits, value = evaluator([(p,mask)])
        legal = np.array([bool(move_bit(mask,c)) for c in range(7)])
        soft = np.zeros(7)
        soft[legal] = np.exp(logits[0,legal] - max(logits[0,legal]))
        soft /= soft.sum()
        reference = [None if x == -1000 else (x>0)-(x<0) for x in row['scores']]
        baseline = [int(v) for v in mcts(p,mask,200,1.4,120400+i)]
        grid = []
        for c in (.5,1.,1.5,2.):
            for b in (1,4,8,16):
                tracked = TrackedEvaluator(evaluator)
                _, counts = search(p,mask,tracked,simulations=200,batch_size=b,c_puct=c,virtual_loss=1.)
                leaf_evaluations = tracked.states - 1
                grid.append({'c_puct': c, 'batch_size': b, 'visits': counts.tolist(),
                             'root_evaluations': 1, 'leaf_evaluations': leaf_evaluations,
                             'terminal_simulations': 200 - leaf_evaluations,
                             'network_calls': tracked.calls})
        cases.append({'sequence': seq, 'prior': soft.tolist(), 'value': float(value[0]),
                      'values': reference, 'uct_visits': baseline, 'uct_seed':120400+i,
                      'puct_grid': grid})
    data = {'source': 'dataset Pons de p12-l02, revisado 70d868ee534df1e2c6213b22daeae36d4ad73cc5',
            'simulations':200,'uct_c':1.4,'virtual_loss':1.,'noise_fraction':0.,'cases':cases}
    return data

def compare_positions(evaluator, rows):
    hits = [0,0]
    for i, row in enumerate(rows):
        p, mask = position([int(c) for c in row['moves']])
        _, visits = search(p, mask, evaluator, simulations=200, batch_size=16)
        a = int(np.argmax(visits))
        b = int(np.argmax(mcts(p, mask, 5000, 1.4, 120400+i)))
        hits[0] += optimal_move(row, a)
        hits[1] += optimal_move(row, b)
    print('Aciertos en', len(rows), 'posiciones decisivas: PUCT 200:', hits[0], '; UCT 5000:', hits[1], flush=True)
    return hits

def game(evaluator, seq, puct_first, seed):
    p, mask = position(seq)
    ply = len(seq)
    while True:
        puct_turn = (ply - len(seq)) % 2 == (0 if puct_first else 1)
        if puct_turn:
            _, counts = search(p, mask, evaluator, simulations=200, batch_size=16)
        else:
            counts = mcts(p, mask, 5000, 1.4, seed+ply)
        c = int(np.argmax(counts))
        stone = move_bit(mask, c)
        if win(p | stone):
            return 1.0 if puct_turn else 0.0
        if mask | stone == BOARD:
            return 0.5
        p, mask = p ^ mask, mask | stone
        ply += 1

def bootstrap(matches, seed=1204, repetitions=2000):
    blocks = np.asarray(matches, dtype=float)
    rng = np.random.default_rng(seed)
    samples = np.mean(blocks[rng.integers(0,len(blocks),(repetitions,len(blocks)))], axis=(1,2))
    def elo(score):
        return -math.inf if score <= 0 else math.inf if score >= 1 else 400*math.log10(score/(1-score))
    score = float(blocks.mean())
    lo, hi = np.quantile(samples,[.025,.975])
    return score, (float(lo), float(hi)), elo(score), (elo(float(lo)),elo(float(hi)))

def tournament(evaluator, rows):
    matches = []
    for i,row in enumerate(rows):
        seq = [int(c) for c in row['moves']]
        a = game(evaluator, seq, True, 120400+i*100)
        b = game(evaluator, seq, False, 120450+i*100)
        matches.append((a,b))
        if (i+1)%4 == 0:
            print('Aperturas emparejadas:', i+1, '/', len(rows), flush=True)
    score, score_ci, elo, elo_ci = bootstrap(matches)
    print('Resultados PUCT por apertura:', matches, flush=True)
    print('Puntuacion media:', score, '; IC bootstrap por apertura:', score_ci, flush=True)
    print('Elo relativo UCT:', elo, '; IC bootstrap:', elo_ci, flush=True)
    return matches

def benchmark(evaluator, rows):
    positions = [position([int(c) for c in row['moves']]) for row in rows]
    ratios = {}
    for batch_size in (1,4,8,16,32):
        p,mask = positions[0]
        search(p,mask,evaluator,simulations=200,batch_size=batch_size)
        if torch.cuda.is_available(): torch.cuda.synchronize()
        t = time.perf_counter()
        tracked = TrackedEvaluator(evaluator)
        for p,mask in positions:
            search(p,mask,tracked,simulations=200,batch_size=batch_size)
        if torch.cuda.is_available(): torch.cuda.synchronize()
        rate = len(positions)*200/(time.perf_counter()-t)
        ratios[batch_size] = rate
        leaf_evaluations = tracked.states - len(positions)
        terminal = len(positions)*200 - leaf_evaluations
        print('Lote:', batch_size, 'recorridos/seg:', round(rate,2),
              'evaluaciones de raiz:',len(positions),'de hoja:',leaf_evaluations,
              'terminales:',terminal,'llamadas a red:',tracked.calls,flush=True)
    print('Razon de recorridos/s frente a lote 1:', {b:round(v/ratios[1],3) for b,v in ratios.items()},flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

For the figure, two exploratory cases are explicitly selected from a public decisive-position set: there is no immediate win and visit allocation changes when comparing batches 1 and 16 at the same constant. This selection reveals the mechanism, not frequency or advantage of a batch size. UCT and PUCT each receive 200 simulations in each example; initial policy and value come from the network retrained in this run.

[ ]Select positions for the figureLocal GPU

url = ('https://huggingface.co/datasets/davidquarel/connect4-pons-eval/resolve/'
       '70d868ee534df1e2c6213b22daeae36d4ad73cc5/pons_eval_dataset.json')
with urlopen(url,timeout=30) as response:
    population = json.load(response)['positions']
candidates = [r for r in population if 16 <= r['depth'] <= 26]
random.Random(120405).shuffle(candidates)
evaluator = TorchEvaluator(model, next(model.parameters()).device)
selected = []
examined = 0
for row in candidates:
    p,mask = position([int(c) for c in row['moves']])
    if any(win(p | move_bit(mask,c)) for c in range(7) if move_bit(mask,c)):
        continue
    examined += 1
    _, a = search(p,mask,evaluator,simulations=200,batch_size=1,c_puct=1.5)
    _, b = search(p,mask,evaluator,simulations=200,batch_size=16,c_puct=1.5)
    if not np.array_equal(a,b):
        selected.append(row)
        if len(selected) == 2:
            break
if len(selected) != 2:
    raise RuntimeError('No se encontraron los dos casos exploratorios')
grid = export_grid(evaluator,selected)
print('Casos exploratorios:',len(selected),'estados sin victoria inmediata examinados:',examined)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Figure: position 1 and UCTLocal GPU
case = grid['cases'][0]
print(json.dumps({k:v for k,v in case.items() if k != 'puct_grid'}, separators=(',',':')))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Figure: position 1, constant 1Local GPU
print(json.dumps(grid['cases'][0]['puct_grid'][0:4], separators=(',',':')))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Figure: position 1, constant 2Local GPU
print(json.dumps(grid['cases'][0]['puct_grid'][4:8], separators=(',',':')))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Figure: position 1, constant 3Local GPU
print(json.dumps(grid['cases'][0]['puct_grid'][8:12], separators=(',',':')))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Figure: position 1, constant 4Local GPU
print(json.dumps(grid['cases'][0]['puct_grid'][12:16], separators=(',',':')))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Figure: position 2 and UCTLocal GPU
case = grid['cases'][1]
print(json.dumps({k:v for k,v in case.items() if k != 'puct_grid'}, separators=(',',':')))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Figure: position 2, constant 1Local GPU
print(json.dumps(grid['cases'][1]['puct_grid'][0:4], separators=(',',':')))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Figure: position 2, constant 2Local GPU
print(json.dumps(grid['cases'][1]['puct_grid'][4:8], separators=(',',':')))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Figure: position 2, constant 3Local GPU
print(json.dumps(grid['cases'][1]['puct_grid'][8:12], separators=(',',':')))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Figure: position 2, constant 4Local GPU
print(json.dumps(grid['cases'][1]['puct_grid'][12:16], separators=(',',':')))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

First compare the selected action against external labels on 50 decisive positions at depths 26 to 30. Then play paired games from another 24 positions of that source and, separately, from 24 random six-move openings. Evaluations use no Dirichlet noise. The subsets answer different questions and neither is a random sample of all possible games. Comparing 200 and 5 000 visits measures these agents at those budgets, not equal-compute cost.

[ ]Oracle comparison and decisive-position tournamentLocal GPU
rows = load_test()
hits = compare_positions(evaluator, rows[:50])
matches = tournament(evaluator, rows[50:74])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Tournament from short openingsLocal GPU
openings = make_openings(n=24,seed=1205,depth=6)
short_matches = []
for i,seq in enumerate(openings):
    short_matches.append((game(evaluator,seq,True,120500+i*100),
                          game(evaluator,seq,False,120550+i*100)))
score, interval, elo, elo_interval = bootstrap(short_matches,seed=1205)
print('Resultados PUCT por apertura:',short_matches)
print('Puntuación:',score,'IC:',interval,'Elo:',elo,'IC:',elo_interval)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The following benchmark measures complete searches and counts network calls and states alongside terminals; it is not an isolated GPU inference-time measurement. The root is evaluated separately in each search. CUDA is synchronized at the start and end of timing, and ratios relative to batch one are reported. These figures depend on position mix, terminal count reached, and shared load.

[ ]Batch size and completed workLocal GPU
benchmark(evaluator,rows[74:82])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Release the networkLocal GPU
del evaluator, model
gc.collect()
if torch.cuda.is_available():
    torch.cuda.synchronize()
    clear = getattr(torch._C, '_cuda_clearCublasWorkspaces', None)
    if clear is not None:
        clear()
    torch.cuda.empty_cache()
    print('Memoria CUDA activa del proceso:',torch.cuda.memory_allocated())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In the reference run, PUCT 200 and UCT 5 000 selected an optimal move in 48 and 50 of the 50 decisive positions, respectively. In the tournament from other decisive positions, PUCT scored 41.67%, with an opening-bootstrap interval of approximately [35.42%,47.92%][35.42\%,47.92\%]; the rating model’s equivalent Elo difference was approximately −58-58 with interval [−104,−14][-104,-14]. From short openings it scored 20.83%, with interval approximately [10.42%,32.29%][10.42\%,32.29\%] and Elo −232-232 with interval [−374,−129][-374,-129]. Each tournament has 24 openings and two color assignments per opening. Intervals describe resampling those blocks, not a guarantee across all possible openings.

The project’s expected hypothesis was that PUCT 200 would beat UCT 5 000; it holds in neither tournament. One network and two limited samples do not identify the cause or make the result a universal claim about PUCT. Training positions were conditioned endgames, while the second tournament begins much earlier: an observable distribution difference, but these data do not prove it caused the disadvantage. Expanding openings, seeds, and models and comparing networks trained on different distributions may help investigate.

This run’s benchmark traversed 1 600 simulations per batch size. Depending on batch, 1 463 to 1 487 ended without querying the network and only 113 to 137 additional leaves were evaluated by it, besides eight roots. A traversals-per-second ratio thus mixes selection, terminals, and inference; it cannot be interpreted as pure GPU speedup. Repeat under known load and on positions from other phases before choosing self-play batch size.

Exercises

NumericPrior and exploration
A child has prior 0.3, 5 visits, and mean value 0.1 from the parent's perspective. The parent has 50 total edge visits and c_puct = 1.5. Calculate Q + c_puct P sqrt(N)/(1+n).
QuizAn overly dispersed batch
A very large virtual loss penalizes all reserved edges before resolving the batch. What effect can it have?
QuizAn edge without samples
An implementation assigns Q = 0 to each unvisited edge. What is the correct interpretation?
QuizWhich agent are you measuring?
You used root Dirichlet noise to generate self-play. You want to compare two agents in a reproducible tournament without additional exploration. What do you do?
CodeSelect and revert a reservation
An edge is a dictionary with p, n, w, and pending: prior, completed visits, sum of real values for the parent player, and virtual reservations. Implement select_child(edges, c, penalty), returning the index maximizing Q + cpsqrt(sum(n+pending))/(1+n+pending), with Q = (w-penalty*pending)/(n+pending) if there are visits or reservations and Q = 0 otherwise. Break ties by returning the first index. Implement reserve(path) and revert(path), incrementing and decrementing pending on every path edge respectively; revert rejects a nonexistent reservation. The path does not repeat an edge.
import math

def select_child(edges, c, penalty):
  pass

def reserve(path):
  pass

def revert(path):
  pass
Shift+Enter to run
[ ]PUCT scoreBrowser
import math
print(0.1 + 1.5 * 0.3 * math.sqrt(50) / (1 + 5))

Summary

Key idea
PUCT uses policy as a prior and value as evaluation, but search retains its own statistics. Batching requires reserving and reverting without confusing pending with completed work; resulting strength must be measured against specified opponents and positions.