Less compute: Gumbel AlphaZero and KataGo tricks
With limited compute, efficiency matters. Implement Gumbel-top-k root selection and sequential halving, which guarantees policy improvement with very few simulations, and test KataGo techniques such as random simulation limits and auxiliary targets. Compare them in an equal-compute ablation design.
After this lesson you can
- Implement Gumbel-top-k with sequential halving and the improved policy target.
- Implement randomized simulation limits and an auxiliary target.
- Compare variants at equal network evaluation counts across multiple seeds.
- Report each variant’s percentage of optimal moves against compute.
Before you start
Budget is a decision
The neural search from the previous lesson turns a prior policy into a decision using simulations. But with few simulations it does not visit every legal move. No visits do not prove an action is bad: the network may have assigned it a low probability before the tree could examine it. Moreover, normalizing visits assigns zero probability to those actions and trains the network to keep ignoring them.
The question in this lesson is not whether a larger search beats a smaller one. It is what improvement is obtained per network evaluation when two methods receive the same budget. Evaluation against the solver provides an independent reference: a move is optimal if it preserves the position’s best theoretical outcome. A result from one seed does not describe variation across training runs.
This figure has eight actions, 32 simulations, and three rounds. First each action receives one simulation; four remain. Each survivor receives two more; two remain. Each receives eight more and one is chosen. The expenditure is . Illustrative scores use fixed values, so the graph shows the allocation algorithm, not statistical uncertainty or a Connect 4 measurement.
Sampling without replacement
Gumbel root selection adds an independent perturbation to each legal logit and takes the largest. If are independent uniforms on , define . Sorting produces a sample without replacement; the first has the logits’ softmax distribution. Apply a mask before sorting: an illegal action must not enter even if its noise is large.
Proof
If , then is exponential with rate one. Maximizing is equivalent to minimizing . The variable is exponential with rate and the variables remain independent. Therefore, integrating the density of and the probability that the others exceed ,
The transformation is strictly monotone. The continuous density makes ties have probability zero.
∎The property holds for the first action. The following ones, conditioned on those already chosen, follow softmax among those remaining. Thus the top-k set is not obtained by making independent draws and removing duplicates afterward: that procedure uses a variable number of draws and can leave fewer than actions.
import numpy as np
rng = np.random.default_rng(2026)
logits = np.array([0.0, 0.7, -0.3])
u = np.clip(rng.random((100000, len(logits))), 1e-12, 1 - 1e-12)
chosen = np.argmax(logits - np.log(-np.log(u)), axis=1)
observed = np.bincount(chosen, minlength=len(logits)) / len(chosen)
expected = np.exp(logits - logits.max())
expected /= expected.sum()
print('observado:', np.round(observed, 3))
print('softmax: ', np.round(expected, 3))This check is Monte Carlo, not a proof of the theorem. The fixed seed makes it reproducible and observed error changes if you change sample size.
The exponential race form also explains the full order. Once the first action is removed, memorylessness leaves a new race among remaining actions at the same rates. Hence, conditioned on the first result, the probability of the second is proportional to among actions that remain. This property does not say all actions in the top-k set have the same marginal probability: actions with larger logits tend to appear earlier and more often.
In numerical code, the endpoints and produce infinite logarithms. A floating-point generator can return zero, so the uniform is clipped to an interior interval as in the cell. Clipping introduces a negligible numerical difference in this example, but it must be stated when comparing implementations at extreme values. Subtracting the maximum before softmax prevents overflow without changing probabilities; illegal actions must still be excluded from normalization.
Halving and completed values
In best-arm identification, the cost of the final choice matters, not just the sum of rewards during exploration. Sequential halving allocates simulations among active candidates, ranks them, and discards approximately half; it repeats until one remains. If the number of actions is not a power of two or the budget does not divide exactly, specify how remainders are distributed and ties resolved. To preserve a round’s interpretation, allocate visits before eliminating candidates.
Gumbel AlphaZero retains each action’s same noise across rounds and uses a score combining noise, logit, and transformed action value. The original work by Danihelka and collaborators describes the algorithm, assumptions, and value completion. Actual search estimates from simulation returns; the figure’s fixed value isolates the allocation arithmetic.
Keeping the noise matters. If it is redrawn each round, an action can win or lose because of a new random number rather than accumulated evidence, and the described procedure is no longer reproduced. What gets counted also matters: an eliminated action does not lose simulations it already received, even though it gets no more. If the budget is smaller than the number of candidate actions, the algorithm must reduce the considered set or declare a rule for incomplete visits; a table assuming one visit per action cannot spend less than their count.
A policy target needs a distribution over all legal actions. A visited action uses its estimated value; an unvisited one is completed with an estimate derived from state value and observed actions. The original logit is then combined with a transformation of these values and normalized. Thus “unvisited” does not automatically mean “zero probability.” The paper’s improvement guarantee depends on its conditions, including accuracy of the values considered: an approximate network and finite budget do not guarantee that every empirical decision improves.
One way to understand ideal improvement is to fix a state, its legal actions, a positive policy , and exact values . For , define . This policy maximizes expected utility penalized by distance from the prior,
over distributions on those actions. Check the identity by expanding : the expression is , with . Comparing the maximum with yields . The inequality applies to the same exact values and does not prove improvement when they are replaced by erroneous estimates.
The open mctx implementation documents one completion. If , is the root’s predicted value and is the mean of visited values weighted by their renormalized priors, it uses when there are visits; without visits it uses . Each unvisited action receives that value. Subsequent scaling and simulation allocation are algorithm choices, not softmax properties.
import numpy as np
prior = np.array([0.5, 0.3, 0.2])
visits = np.array([3, 1, 0])
q = np.array([0.4, -0.2, 0.0]) # el último cero es un marcador, no una observación
v = 0.1
visited = visits > 0
weighted_q = np.dot(prior[visited], q[visited]) / prior[visited].sum()
mix = (v + visits.sum() * weighted_q) / (1 + visits.sum())
completed = np.where(visited, q, mix)
logits = np.log(prior) + completed
target = np.exp(logits - logits.max())
target /= target.sum()
print('valor mixto:', round(mix, 3))
print('valores completados:', np.round(completed, 3))
print('objetivo ilustrativo:', np.round(target, 3))The third action retains positive mass. The cell uses identity as the transformation to make the calculation visible; it does not present this output as a Gumbel AlphaZero run or a measure of play.
Completion is an estimate, not a hidden observation. In the example, the third action inherits mixed value 0.16; if its true value were much worse or better, the target distribution would differ. Completion avoids treating no visits as certainty of zero value, but does not remove uncertainty about unvisited actions. Evaluate the final algorithm against the solver and keep cases where selection changes: a smoother distribution alone does not prove better decisions.
More value data without pretending every search is deep
KataGo efficiency tricks address an imbalance: value training needs many outcomes, while a useful policy target benefits from deeper search. Wu proposes randomizing the simulation limit: some decisions receive full search and others cheap search. The latter allow more games to finish and yield more value outcomes. In the paper’s protocol only full-search turns are recorded for training; exploration noise is also disabled during cheap searches. Mixing sparse and deep visits without distinguishing them changes policy-target quality.
An auxiliary target predicts an extra signal available in self-play, for example a future move. It must be transformed with the board during symmetry augmentation and must not leak information into evaluation. Adding a head changes parameters, compute, and gradients; an observed improvement alone does not prove which change caused it. In an ablation, compare each intervention separately and in combination, with independent seeds, a fixed evaluation protocol, and the cost of all network evaluations counted.
If search evaluates the root plus 16 simulations, cost is not necessarily 16: count the root too and distinguish terminal leaves, which require no inference. Count actually evaluated states, not batch calls, since one call may contain many positions. To compare learning curves, include both self-play and training evaluations, state whether validation is counted too, and avoid changing the test set to tune hyperparameters.
Equal simulation counts do not imply equal useful forwards either. For example, across four roots with 16 simulations each there are at most 68 evaluated positions including roots; if six leaves are terminal, that search may require only 62. Another search with fewer terminal leaves may spend 68. The first can be padded to 68 by evaluating six root copies, but those six passes provide no information to its decision: identify padding and do not confuse it with productive search. To study efficiency, show measured useful cost of each method and accuracy against it, in addition to any common-ceiling comparison.
Curve checkpoints are saved at discrete times. If you fix a common ceiling and select each run’s latest checkpoint that does not exceed it, actual costs can differ because checkpoints are spaced apart. Publish those figures with the ceiling and do not claim they are identical. Visual interpolation between points may aid reading, but does not create an evaluation of an intermediate checkpoint. An exact-budget test needs a protocol explicitly describing how evaluations are allocated and what happens on reaching a terminal.
Prepare local search
The following lab reuses the az4 package generated by cells in the previous lesson. Run its cells writing engine, network, search, evaluation, and trainer before continuing. The default folder is ~/atlas-lab/p12-l06, or ATLAS_LAB_DIR/p12-l06 if you configured another root. No prior checkpoint is required: this lesson’s runs train new networks.
First write the visit schedule and value completion. The sequence follows the public mctx implementation: its considered visit count restricts eligible actions in each simulation. The effective candidate count does not exceed legal moves. For each node, completion mixes network value with the mean of visited values weighted by their priors; unvisited actions receive that mixture. It is then rescaled and multiplied by a factor increasing with maximum visits.
import math, os, sys
from pathlib import Path
import numpy as np
LAB = Path(os.environ.get('ATLAS_LAB_DIR', Path.home() / 'atlas-lab')).expanduser() / 'p12-l06'
if str(LAB) not in sys.path: sys.path.insert(0, str(LAB))
from az4.engine import FULL, won_np, legal_np, bits_np
def schedule(m, budget):
if m <= 1: return list(range(budget))
rounds = math.ceil(math.log2(m))
sequence, visits, active = [], [0] * m, m
while len(sequence) < budget:
extra = max(1, budget // (rounds * active))
for _ in range(extra):
sequence.extend(visits[:active])
for i in range(active): visits[i] += 1
active = max(2, active // 2)
return sequence[:budget]
def completed(prior, raw, visits, wins, legal):
visited = visits > 0
q = wins / np.maximum(visits, 1)
prob = np.where(visited, prior, 0)
weighted = (prob * q).sum(1) / np.maximum(prob.sum(1), 1e-30)
total = visits.sum(1)
mix = (raw + total * weighted) / (1 + total)
q = np.where(visited, q, mix[:, None])
qmin = np.where(legal, q, np.inf).min(1, keepdims=True)
qmax = np.where(legal, q, -np.inf).max(1, keepdims=True)
return (q - qmin) / np.maximum(qmax - qmin, 1e-8) * (0.1 * (50 + visits.max(1, keepdims=True)))
assert len(schedule(7, 16)) == 16
print('visitas consideradas, 7 candidatas y 16 simulaciones:', schedule(7, 16))npm run lab and open the connection link.Now modify search without changing the Connect 4 engine. At the root combine Gumbel, logit, and completed value; internally select to approximate the improved policy. Each edge keeps value from the choosing player’s perspective and propagation reverses its sign. Normalization subtracts the maximum of the legal logits before exponentiating: subtracting only the maximum value may underflow if priors are very small.
def gumbel_search(evaluate, p, mask, sims=16, rng=None, noise=True, considered=7):
rng = np.random.default_rng(0) if rng is None else rng
p, mask = np.asarray(p, np.int64), np.asarray(mask, np.int64)
G, M = len(p), sims + 1
gi = np.arange(G)
P = np.zeros((G, M, 7), np.float32)
V = np.zeros((G, M), np.float32)
N = np.zeros((G, M, 7), np.float32)
W = np.zeros((G, M, 7), np.float32)
child = np.full((G, M, 7), -1, np.int32)
legal = np.zeros((G, M, 7), bool)
pos, msk = np.zeros((G, M), np.int64), np.zeros((G, M), np.int64)
terminal = np.full((G, M), np.nan, np.float32)
expanded, count = np.zeros((G, M), bool), np.ones(G, np.int64)
pos[:, 0], msk[:, 0] = p, mask
P[:, 0], V[:, 0] = evaluate(p, mask)
legal[:, 0] = legal_np(mask)
expanded[:, 0] = True
prior = P[:, 0].copy()
noise_g = rng.gumbel(size=(G, 7)) if noise else np.zeros((G, 7))
tables = np.array([schedule(k, sims) for k in range(8)])
num = np.minimum(considered, legal[:, 0].sum(1)).astype(int)
for simulation in range(sims):
node = np.zeros(G, np.int64)
path_g, path_n, path_a = [], [], []
g = gi
while len(g):
nd, n = node[g], N[g, node[g]]
q = completed(P[g, nd], V[g, nd], n, W[g, nd], legal[g, nd])
logits = np.where(legal[g, nd], np.log(np.maximum(P[g, nd], 1e-30)) + q, -np.inf)
if not np.isfinite(logits).any(axis=1).all():
raise RuntimeError('nodo sin logits legales finitos')
probs = np.exp(logits - np.max(logits, axis=1, keepdims=True))
probs /= probs.sum(1, keepdims=True)
score = probs - n / (1 + n.sum(1, keepdims=True))
root = nd == 0
if root.any():
gr = g[root]
limit = tables[num[gr], simulation]
root_score = noise_g[gr] + np.log(np.maximum(P[gr, 0], 1e-30)) + q[root]
score[root] = np.where(N[gr, 0] == limit[:, None], root_score, -np.inf)
a = np.where(legal[g, nd], score, -np.inf).argmax(1)
path_g.append(g); path_n.append(nd); path_a.append(a)
ch = child[g, nd, a]
fresh = ch < 0
if fresh.any():
gn, pn, an = g[fresh], nd[fresh], a[fresh]
ix = count[gn]
count[gn] += 1
bit = bits_np(msk[gn, pn], an)
mover = pos[gn, pn] | bit
pos[gn, ix] = pos[gn, pn] ^ msk[gn, pn]
msk[gn, ix] = msk[gn, pn] | bit
terminal[gn, ix] = np.where(won_np(mover), -1., np.where(msk[gn, ix] == FULL, 0., np.nan))
child[gn, pn, an] = ix
ch = ch.copy(); ch[fresh] = ix
node[g] = ch
g = g[expanded[g, ch] & np.isnan(terminal[g, ch])]
value = terminal[gi, node].astype(np.float64)
need = np.isnan(value)
if need.any():
gl, nl = gi[need], node[need]
P[gl, nl], V[gl, nl] = evaluate(pos[gl, nl], msk[gl, nl])
legal[gl, nl] = legal_np(msk[gl, nl])
expanded[gl, nl] = True
value[need] = V[gl, nl]
for gg, nn, aa in zip(reversed(path_g), reversed(path_n), reversed(path_a)):
value[gg] = -value[gg]
N[gg, nn, aa] += 1
W[gg, nn, aa] += value[gg]
visits = N[:, 0]
q = completed(prior, V[:, 0], visits, W[:, 0], legal[:, 0])
z = np.where(legal[:, 0], np.log(np.maximum(prior, 1e-30)) + q, -np.inf)
exp = np.exp(z - np.max(z, axis=1, keepdims=True))
improved = exp / exp.sum(1, keepdims=True)
final = np.where(legal[:, 0] & (visits == visits.max(1, keepdims=True)), z + noise_g, -np.inf).argmax(1)
rootq = W[:, 0].sum(1) / np.maximum(visits.sum(1), 1)
return final, improved, rootq, prior, visits.astype(np.int64)
def uniform(p, mask):
legal = legal_np(mask).astype(np.float32)
return legal / legal.sum(1, keepdims=True), np.zeros(len(p), np.float32)
choice, improved, _, _, visits = gumbel_search(uniform, np.array([0, 0]), np.array([0, 0]), 16)
assert np.all(visits.sum(1) == 16) and np.allclose(improved.sum(1), 1)
print('simulaciones:', visits.sum(1).tolist(), 'políticas normalizadas:', improved.sum(1).round(6).tolist())npm run lab and open the connection link.The preceding test checks budget and normalization at two empty roots. It does not show that search learns or replace the self-play and solver experiment. Unvisited actions may retain probability in improved; the executed action comes from the most visited, with ties broken by Gumbel, prior, and completed value. In perfect-information game evaluation Gumbel noise can be fixed at zero, as in the reference implementation.
Integration changes two parts of self-play: the executed action comes from Gumbel search and the policy target is improved, not the visit distribution. The code retains the rest of the previous trainer to keep architecture, buffer, and updates comparable. Evaluation always uses the same list of positions without noise, and the Gumbel implementation also uses 16 simulations during evaluation.
import inspect
from dataclasses import replace
from az4 import train
from az4.engine import from_moves
from az4.evaluate import solver_eval as puct_eval, build_positions, save_jsonl, load_jsonl
original_selfplay = train.self_play
original_eval = puct_eval
source = inspect.getsource(original_selfplay)
before = ''' visits, rootq, prior = search(evaluate, p, m, cfg.sims, cfg.c_puct, cfg.noise_frac,
cfg.dirichlet_alpha, rng)
pi = visits / visits.sum(1, keepdims=True)'''
after = ''' picks, pi, rootq, prior, visits = gumbel_search(evaluate, p, m, cfg.sims, rng=rng)'''
choice_before = ''' if g['ply'] < cfg.temp_plies:
c = int(rng.choice(W, p=pi[j]))
else:
best = np.flatnonzero(visits[j] == visits[j].max())
c = int(rng.choice(best))'''
choice_after = ''' c = int(picks[j])'''
if before not in source or choice_before not in source:
raise RuntimeError('El contrato de autojuego ha cambiado: revisa la integración')
train.gumbel_search = gumbel_search
exec(compile(source.replace(before, after).replace(choice_before, choice_after),
'autojuego_gumbel', 'exec'), train.__dict__)
gumbel_selfplay = train.self_play
train.self_play = original_selfplay
def gumbel_eval(evaluate, positions, sims, c_puct=1.5, batch=1024):
if sims == 0: return original_eval(evaluate, positions, 0, c_puct, batch)
rows = []
for start in range(0, len(positions), batch):
chunk = positions[start:start + batch]
pm = [from_moves(x['moves']) for x in chunk]
p = np.array([x[0] for x in pm], np.int64)
mask = np.array([x[1] for x in pm], np.int64)
choice, _, _, prior, visits = gumbel_search(evaluate, p, mask, sims=sims, noise=False)
for x, a, pr, vi in zip(chunk, choice, prior, visits):
best = max(v for v in x['values'] if v is not None)
v = x['values'][int(a)]
rows.append({'moves': x['moves'], 'phase': x['phase'], 'ply': x['ply'], 'decisive': x['decisive'],
'choice': int(a), 'optimal': v == best, 'drop': int(best - v),
'policy': [round(float(t), 4) for t in pr], 'visits': [int(t) for t in vi],
'values': x['values'], 'sims': sims})
return rows
# No se activa el antiguo límite de memoria del entrenador histórico.
train.guard = lambda cfg, where: train.rss_gb()
print('contrato de autojuego conectado; aún no se ha iniciado un entrenamiento')npm run lab and open the connection link.Data generation and the four training runs may take much longer than an ordinary cell, so they do not run automatically on page load. The test set has 50 positions per phase, 150 total: it is smaller than in the preceding lesson and its intervals will be wider. Canonical validation and test keys are excluded from the buffer. The two seeds are different training runs, not two restarts of one policy. The az4 inference counter counts positions, not batch calls; also add training examples per generation and keep backward cost separate if comparing FLOPs or total time.
The test set in the run included in this repository was already consulted exploratorily in previous experiments. Its results therefore describe that sample but are not a final blind evaluation. For independent evaluation generate another set with new canonical keys, fix the protocol in advance, and do not use it to select configurations.
DATA = LAB.parent / 'p12-l07' / 'data'
DATA.mkdir(parents=True, exist_ok=True)
validation_file, test_file = DATA / 'validation.jsonl', DATA / 'test.jsonl'
if not validation_file.exists() or not test_file.exists():
rng = np.random.default_rng(841)
validation = build_positions(50, rng)
test = build_positions(50, rng, exclude={x['key'] for x in validation})
save_jsonl(validation, validation_file)
save_jsonl(test, test_file)
else:
validation, test = load_jsonl(validation_file), load_jsonl(test_file)
assert len(validation) == len(test) == 150
assert not ({x['key'] for x in validation} & {x['key'] for x in test})
template = train.PRESETS['corta']
try:
for method in ('puct', 'gumbel'):
train.self_play = original_selfplay if method == 'puct' else gumbel_selfplay
train.solver_eval = original_eval if method == 'puct' else gumbel_eval
for seed in (0, 1):
train.PRESETS['corta'] = replace(template, sims=16, val_sims=16, val_positions=150, seed=seed)
run = DATA.parent / f'{method}-seed{seed}'
train.main(['--preset', 'corta', '--run', str(run), '--data', str(DATA), '--resume'])
finally:
train.self_play, train.solver_eval = original_selfplay, original_eval
train.PRESETS['corta'] = templatenpm run lab and open the connection link.Validation is evaluated and state saved each generation, so an interruption need not restart from scratch. The compute axis and final evaluation must be built from each run’s logs, not by allocating a game’s cost evenly: durations and terminal leaves vary. The evals_cumulative field counts network-evaluated positions during self-play and validation, including initial validation in the first generation, but the previous lab resets that counter on resume and does not log it in the initial row. Before each resume record the saved generation’s count; add it as an offset to new rows and retain previous offsets too. If interruption occurs between saving state and writing its metrics row, the counter is not known exactly: record it as missing, without inventing it. Count optimizer-processed examples separately; that field excludes them, so comparing only games or that counter does not equalize full compute. Keep the test set held out until tuning is complete.
Observed curves
Recorded runs include nine PUCT generations for each seed and five and four Gumbel generations. The graph shows all these points without presenting the preceding cell’s twenty-generation recipe as complete. Each generation uses 400 games, 16 simulations per move, and 300 batches of 512 examples. Points are solver accuracy on the same 150 validation positions; they are not a blind generalization measurement. Initial generations ran on GPU and Gumbel seed 0’s fifth was resumed on CPU: numerical identity across devices is not claimed. On CPU reevaluation of the four generation-4 checkpoints, PUCT seed 0 got 118/150 versus the 119/150 originally recorded on GPU; the other three matched. The curve shows original records and attributes no cause to that discrepancy. Initial state is omitted from the axis because its log does not retain the cost counter.
There is another point comparison of useful search cost, distinct from training. At generation 4, using only inference counters and not accuracy for selection, 142 of the 150 validation positions were selected so all four models spent exactly 1991 useful evaluations. The subsample retains 48 early, 46 middle, and 48 late positions, versus 50 per phase in the original set. PUCT scores were 111 and 118 out of 142 for seeds 0 and 1; Gumbel scores were 117 and 118. Searches were repeated on that subsample, confirming the same decisions and costs. Selection depends on each model’s cost, so the subsample need not represent the initial distribution; nor does it equalize training spend. Two seeds and a conditioned sample do not justify a general conclusion about which algorithm is better.
To prepare the KataGo ablation, explicitly separate search budget and policy-loss mask. The example’s auxiliary head predicts the opponent’s next action when one exists; no action is invented on the final turn. The following sampling and mask are lab components, not results of an already executed ablation.
import numpy as np
def sample_budget(rng, high=16, low=4, probability=0.25):
full = bool(rng.random() < probability)
return (high if full else low), full
def next_action_targets(actions, n_actions=7):
target = np.zeros((len(actions), n_actions), dtype=float)
valid = np.zeros(len(actions), dtype=bool)
for i in range(len(actions) - 1):
target[i, actions[i + 1]] = 1.0
valid[i] = True
return target, valid
aux, valid = next_action_targets([2, 3, 2])
assert valid.tolist() == [True, True, False]
assert aux.argmax(1)[:2].tolist() == [3, 2] and aux[-1].sum() == 0
expected = 0.25 * 16 + 0.75 * 4
print('simulaciones esperadas por decisión:', expected)
print('objetivos auxiliares válidos:', valid.tolist())An experimental variant also retains cheap-search positions for value training, although it masks policy loss on them. This differs from the paper’s protocol and must be identified as such. Choose the budget before each search and save the full flag with the position. The future action must undergo the same symmetry as the state. To measure each component’s contribution, run controls and variants separately with the same accounted total budget; without those runs an observed improvement cannot be attributed to randomization or the auxiliary head.
Executable ablation of both ideas
The following variant implements a factorial comparison: fixed or random budget, with or without auxiliary loss for the opponent’s reply. All variants have the same architecture with an auxiliary head; when unused its loss weight is zero. This keeps layer costs comparable and avoids attributing an architectural difference to the technique. In the random-budget variant, only full-search turns are saved, as in the paper’s protocol. Validation and test positions, and the next position when it supplies an auxiliary label, are excluded from training.
First run the az4 preparation cells and this lesson’s separate datasets. The next cell defines the experiment; the second starts it. The auxiliary head here predicts an action actually played by the opponent, a simplification of the policy-distribution target in the original work. Each generation sets a target of 100,000 self-play inferences and 300 updates of 512 examples in advance; games already started are finished. Since a Connect 4 game has at most 42 turns and each turn with 16 simulations costs at most 17 network evaluations, the final game’s excess is under 714 evaluations, or under 0.714% of the target. Validation evaluates the policy once per position and costs exactly 150 inferences; its results do not use 16-simulation search. The checkpoint is saved per generation with optimizer, buffer, and generators. An interruption mid-phase repeats that phase.
import hashlib, json, os, sys
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from az4 import engine, mcts
from az4.net import PolicyValueNet, Evaluator
from az4.evaluate import load_jsonl, solver_eval, summarize
HERE = LAB.parent / 'p12-l07'
HERE.mkdir(parents=True, exist_ok=True)
class Net(PolicyValueNet):
def __init__(self):
super().__init__(channels=64,blocks=4)
self.aux=nn.Linear(64,7)
def all_heads(self,x,legal):
h=self.tower(self.stem(x))
policy=self.pol(h).masked_fill(~legal,-1e9)
value=self.val(h).squeeze(-1)
return policy,value,self.aux(h.mean((2,3)))
def forward(self,x,legal):
policy,value,_=self.all_heads(x,legal)
return policy,value
def selfplay(evaluate,rng,n_games,variable,excluded):
active=[{'p':0,'mask':0,'hist':[]} for _ in range(n_games)]
rows=[];played=0;fulls=0
while active:
p=np.array([g['p'] for g in active],np.int64)
masks=np.array([g['mask'] for g in active],np.int64)
full=(rng.random(len(active))<.25) if variable else np.ones(len(active),bool)
visits=np.zeros((len(active),7),np.int32)
for mark in (True,False):
ids=np.flatnonzero(full==mark)
if len(ids):
result,_,_=mcts.search(evaluate,p[ids],masks[ids],16 if mark else 4,
1.5,.25 if mark else 0.,1.,rng)
visits[ids]=result
survivors=[]
for i,g in enumerate(active):
pi=visits[i]/visits[i].sum()
if len(g['hist'])<12:a=int(rng.choice(7,p=pi))
else:
best=np.flatnonzero(visits[i]==visits[i].max());a=int(rng.choice(best))
g['hist'].append((g['p'],g['mask'],pi.astype(np.float32),a,bool(full[i])))
g['p'],g['mask'],won=engine.play(g['p'],g['mask'],a)
if won or g['mask']==engine.FULL:
hist=g['hist'];n=len(hist)
for t,(hp,hm,policy,action,is_full) in enumerate(hist):
if not is_full or engine.canonical_key(hp,hm) in excluded:continue
if t+1<n and engine.canonical_key(hist[t+1][0],hist[t+1][1]) in excluded:continue
z=0. if not won else (1. if (n-1-t)%2==0 else -1.)
next_action=hist[t+1][3] if t+1<n else -1
rows.append((hp,hm,policy,z,next_action))
played+=n;fulls+=sum(int(x[4]) for x in hist)
else:survivors.append(g)
active=survivors
return rows,played,fulls
def update(net,opt,replay,rng,device,steps=300,batch=512,aux_weight=0.):
net.train();losses=[]
for _ in range(steps):
rows=[replay[int(i)] for i in rng.integers(len(replay),size=batch)]
p=np.array([x[0] for x in rows],np.int64);mask=np.array([x[1] for x in rows],np.int64)
x=engine.encode_np(p,mask);pi=np.stack([x[2] for x in rows]);z=np.array([x[3] for x in rows],np.float32)
auxiliary=np.array([x[4] for x in rows],np.int64);flip=rng.random(batch)<.5
x=np.where(flip[:,None,None,None],x[...,::-1],x)
pi=np.where(flip[:,None],pi[:,::-1],pi)
auxiliary=np.where(flip & (auxiliary>=0),6-auxiliary,auxiliary)
legal=(x.sum(axis=(1,2))<6)
xt=torch.as_tensor(np.ascontiguousarray(x),dtype=torch.float32,device=device)
lt=torch.as_tensor(np.ascontiguousarray(legal),device=device)
pt=torch.as_tensor(np.ascontiguousarray(pi),device=device)
zt=torch.as_tensor(z,device=device);at=torch.as_tensor(auxiliary,device=device)
logits,value,reply=net.all_heads(xt,lt)
lp=-(pt*F.log_softmax(logits,dim=1)).sum(1).mean();lv=F.mse_loss(value,zt)
valid=at>=0
la=F.cross_entropy(reply[valid],at[valid]) if valid.any() else reply.sum()*0
loss=lp+lv+aux_weight*la
opt.zero_grad(set_to_none=True);loss.backward();torch.nn.utils.clip_grad_norm_(net.parameters(),10.);opt.step()
losses.append([float(lp.detach()),float(lv.detach()),float(la.detach())])
return np.mean(losses,axis=0).tolist()
def run_ablacion(variable,auxiliary,seed,generations=4,search_budget=100000,max_parallel_games=400,
updates=300,batch=512,resume=True,stop_after=None,folder_root='katago-search-budget-runs',val_n=150):
device='cuda' if torch.cuda.is_available() else 'cpu'
torch.backends.cudnn.benchmark=False;torch.backends.cudnn.deterministic=True
torch.manual_seed(seed);rng=np.random.default_rng(seed)
net=Net().to(device);opt=torch.optim.AdamW(net.parameters(),lr=1e-3,weight_decay=1e-4)
evaluate=Evaluator(net,device)
data=LAB.parent/'p12-l07'/'data';all_val=load_jsonl(data/'validation.jsonl');test=load_jsonl(data/'test.jsonl')
excluded={x['key'] for x in all_val+test};val=all_val[:val_n]
name=f'cap{int(variable)}-aux{int(auxiliary)}-seed{seed}'
folder=HERE/folder_root/name;folder.mkdir(parents=True,exist_ok=True)
path=folder/'state.pt';replay=[];records=[];start=1
contract={'variable':variable,'auxiliary':auxiliary,'seed':seed,'search_budget':search_budget,
'max_parallel_games':max_parallel_games,'updates':updates,'batch':batch,'val_n':val_n,
'validation_sha256':hashlib.sha256((data/'validation.jsonl').read_bytes()).hexdigest(),
'test_sha256':hashlib.sha256((data/'test.jsonl').read_bytes()).hexdigest()}
if path.exists():
if not resume:raise FileExistsError(path)
st=torch.load(path,map_location=device,weights_only=False)
if st['contract']!=contract:raise ValueError('Contrato distinto')
net.load_state_dict(st['net']);opt.load_state_dict(st['optimizer']);replay=st['replay'];records=st['records'];start=st['generation']+1
rng.bit_generator.state=st['numpy_rng'];torch.set_rng_state(st['torch_rng'].cpu())
if torch.cuda.is_available() and st['cuda_rng'] is not None:torch.cuda.set_rng_state_all([x.cpu() for x in st['cuda_rng']])
(folder/'metrics.jsonl').write_text(''.join(json.dumps(x)+'\n' for x in records),encoding='utf-8')
for generation in range(start,generations+1):
evaluate.positions=0
net.eval();new=[];played=fulls=games=0
while evaluate.positions<search_budget:
count=max(1,min(max_parallel_games,(search_budget-evaluate.positions)//714))
chunk,plies,full=selfplay(evaluate,rng,count,variable,excluded)
new.extend(chunk);played+=plies;fulls+=full;games+=count
search_cost=evaluate.positions
assert search_budget<=search_cost<search_budget+714
if not new:raise RuntimeError('Sin posiciones de entrenamiento')
replay=(replay+new)[-60000:]
losses=update(net,opt,replay,rng,device,steps=updates,batch=batch,aux_weight=.15 if auxiliary else 0.)
from az4.engine import from_moves
pm=[from_moves(row['moves']) for row in val]
p=np.array([x[0] for x in pm],np.int64);mask=np.array([x[1] for x in pm],np.int64)
prior,_=evaluate(p,mask);picks=prior.argmax(axis=1)
optimal=sum(int(row['values'][int(a)]==max(v for v in row['values'] if v is not None))
for row,a in zip(val,picks))
assert evaluate.positions==search_cost+len(val)
record={'generation':generation,'seed':seed,'variable':variable,'auxiliary':auxiliary,
'games':games,'played_plies':played,'full_plies':fulls,'replay':len(replay),
'policy_loss':losses[0],'value_loss':losses[1],'aux_loss':losses[2],
'val_policy':optimal/len(val),'val_n':len(val),'search_examples':search_cost,
'validation_examples':len(val),'train_examples':updates*batch,
'total_forward_examples':evaluate.positions+updates*batch}
records.append(record)
state={'contract':contract,'generation':generation,'net':net.state_dict(),'optimizer':opt.state_dict(),
'replay':replay,'records':records,'numpy_rng':rng.bit_generator.state,'torch_rng':torch.get_rng_state(),
'cuda_rng':torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None}
tmp=folder/'state.tmp';torch.save(state,tmp);os.replace(tmp,path)
torch.save(net.state_dict(),folder/f'gen_{generation:03d}.pt')
(folder/'metrics.jsonl').write_text(''.join(json.dumps(x)+'\n' for x in records),encoding='utf-8')
print(json.dumps(record),flush=True)
if stop_after is not None and generation>=stop_after:break
npm run lab and open the connection link.for variable in (False, True):
for auxiliary in (False, True):
for seed in (0, 1):
run_ablacion(variable, auxiliary, seed, resume=True)npm run lab and open the connection link.This run may take a long time. The row records actual self-play, validation, and training cost per generation: variants use the same update count and their search costs differ by at most the last complete game. Backward cost must be added or measured separately; equal network example counts do not guarantee equal time or FLOPs. Expected simulation count is not exact inference count because terminal leaves do not always require evaluation. Hyperparameters are selected on validation; held-out test results are calculated after fixing the protocol.
Ablation results
All four combinations were run, with two seeds and four generations per run. Each cell contains the number of optimal moves selected by the policy without search on the same 150 validation positions after each generation. The search column totals actual self-play inferences over four generations; each run added exactly 614,400 training examples and 600 validation inferences. Backward cost is excluded. The first generation of the first six arms ran on CPU and resumed on CUDA; the last two ran entirely on CUDA. Device migration does not guarantee a numerically identical trajectory.
| Limit, auxiliary, seed | Search | Optimal in generations 1 to 4 |
|---|---|---|
| Fixed, no, 0 | 400567 | 103, 108, 110, 112 |
| Fixed, no, 1 | 400275 | 109, 117, 115, 120 |
| Fixed, yes, 0 | 400561 | 106, 107, 102, 112 |
| Fixed, yes, 1 | 400450 | 101, 108, 115, 117 |
| Variable, no, 0 | 400179 | 105, 108, 106, 111 |
| Variable, no, 1 | 400210 | 105, 111, 113, 108 |
| Variable, yes, 0 | 400589 | 108, 119, 114, 106 |
| Variable, yes, 1 | 400406 | 97, 105, 102, 107 |
Self-play inferences ranged from 400,179 to 400,589 per run: maximum deviation from 400,000 was 0.148%. The four generations used equal optimization step and example counts. At the last point, variable limit without auxiliary obtained 111 and 108 correct versus 112 and 120 for fixed limit without auxiliary. No uniform advantage appears in this sample; seed variation, validation split, device migration, and short duration limit the conclusion. This table describes a specific factorial experiment and does not show these techniques work worse in other games or budgets.
Exercises
Step 1 of 3. What distribution does E have?
def halving(root, rounds):
pass