☆ Bonus - Gumbel AlphaZero
Learning Objectives
- Use the Gumbel-max and Gumbel-top-k tricks to sample moves without replacement.
- Understand sequential halving, and how it spends a small simulation budget on picking the best move.
- Build the improved policy from completed Q-values, and compare Gumbel and PUCT search.
Our AlphaZero has three weak spots, and all of them get worse the fewer simulations we can afford:
- The training target is coarse. We train the policy towards the visit counts $\pi(a) \propto N(s,a)$. With 16 simulations those are multiples of $1/16$, and any move the search never visited gets a target of exactly 0, however good it is.
- Search can make the policy worse. Nothing guarantees that the visit-count policy is better than the prior it started from. With few simulations, PUCT can pile visits onto a move just because the prior liked it.
- Exploration is a bolt-on. Dirichlet noise works, but its hyperparameters are cargo-culted (see the dropdowns in section 2).
Gumbel AlphaZero (Danihelka, Guez, Schrittwieser & Silver, ICLR 2022) fixes all three by changing only what happens at the root:
- It samples the candidate root moves without replacement using the Gumbel-top-k trick, which replaces Dirichlet noise as the source of exploration.
- It splits the simulation budget between those candidates with sequential halving, a bandit algorithm designed for picking the best arm rather than for balancing exploration and exploitation as UCB does.
- It trains on an improved policy $\pi' = \mathrm{softmax}(\text{logits} + \sigma(\hat q))$ built from the prior and the searched Q-values, rather than on raw visit counts. ($\sigma$ is a rescaling that puts Q-values on the same scale as logits, defined below.) Every legal move gets a sensible target, and the paper proves that $\pi'$ is at least as good as the prior.
Below the root, the search is unchanged: plain PUCT. We'll build the pieces as small exercises, and the
search itself is given, reusing your vectorised Tree kernels. DeepMind's mctx
library has the reference implementation (gumbel_muzero_policy), and our constants follow it.
The Gumbel-max trick
The CDF of the (standard) Gumbel distribution is defined as
Here's a surprising fact. Take any logits $\ell_1, \dots, \ell_n$, and add independent Gumbel noise $g_1, \dots, g_n \sim \mathrm{Gumbel}(0, 1)$ to them. Then for every $i$,
Derivation (optional)
Write $x_a = \ell_a + g_a$, which has CDF $F_a(x) = \exp(-e^{-(x - \ell_a)})$ and density $f_a(x) = e^{-(x-\ell_a)} F_a(x)$. Action $k$ wins if $x_k$ beats every other $x_a$:
It gets better. Suppose we wanted to sample $k \leq n$ outcomes from a categorical distribution over $n$ outcomes without replacement. The naive way to do this would be to repeat the following $k$ times:
- softmax the logits $\ell_1, \dots, \ell_n$
- sample some outcome $i$ from the softmax
- set the corresponding logit $\ell_i := -\infty$.
This works, but it's inherently sequential. As it turns out, we can do this in parallel: The top $k$ of $\ell_a + g_a$ are a sample of $k$ distinct actions without replacement. This is called the Gumbel-top-k trick, and it is how Gumbel AlphaZero chooses which root moves to consider: the likely moves under the prior, with some randomness so that self-play keeps exploring.
PyTorch provides the Gumbel-max trick (a single sample, as a one-hot vector with
hard=True) viagumbel_softmax, but we build our own for clarity.
def rand_gumbel(shape, device) -> Tensor:
"""Standard Gumbel(0, 1) noise of the given shape, by inverting the CDF: g = -log(-log(u))."""
u = t.rand(shape, device=device).clamp(1e-20, 1.0) # avoid log(0)
return -t.log(-t.log(u))
Exercise - implement gumbel_max_sample and gumbel_top_k
Use rand_gumbel to implement both tricks. Don't worry about illegal moves
as their logits will already be set to -inf, so they can never be sampled.
The tests draw a few hundred thousand samples and check the frequencies against the
softmax (and, for top-k, against the without-replacement probabilities $p_i \cdot p_j / (1 - p_i)$ for each
ordered pair).
- You may assume that for
gumbel_max_sample/gumbel_top_kthat there will always be at least one/$k$ legal action(s).
def gumbel_max_sample(logits: Float[Tensor, "B n"]) -> Int[Tensor, "B"]:
"""One sample per row from softmax(logits), using the Gumbel-max trick."""
raise NotImplementedError()
def gumbel_top_k(logits: Float[Tensor, "B n"], k: int) -> Int[Tensor, "B k"]:
"""k distinct indices per row, sampled without replacement from softmax(logits) (in sampling order)."""
raise NotImplementedError()
tests.test_gumbel_max_sample(gumbel_max_sample)
tests.test_gumbel_top_k(gumbel_top_k)
Solution
def gumbel_max_sample(logits: Float[Tensor, "B n"]) -> Int[Tensor, "B"]:
"""One sample per row from softmax(logits), using the Gumbel-max trick."""
noise = rand_gumbel(logits.shape, logits.device)
return (logits + noise).argmax(-1)
def gumbel_top_k(logits: Float[Tensor, "B n"], k: int) -> Int[Tensor, "B k"]:
"""k distinct indices per row, sampled without replacement from softmax(logits) (in sampling order)."""
noise = rand_gumbel(logits.shape, logits.device)
return (logits + noise).topk(k, dim=-1).indices
tests.test_gumbel_max_sample(gumbel_max_sample)
tests.test_gumbel_top_k(gumbel_top_k)
Sequential halving
The problem. At the root we have $n$ simulations to spend on the $L$ legal moves ($L \le 7$ in Connect 4, fewer once columns fill up). Afterwards we play one move, so all that matters is that the move we finally pick is good.
In games with hundreds of moves, like Go, Gumbel AlphaZero first narrows the field to $m \leq L$ candidates with the Gumbel-top-$k$ trick (DeepMind's codebase defaults to $m=16$). The idea is that it's relatively easy to narrow down the best move to one-of-$m$ options, and then focus the search only on that. We only have 7 actions to choose, so we skip this part, and just let $m=7$.
This is a best-arm identification bandit problem. PUCT solves a different one: like UCB, it keeps re-visiting whatever looks best now. That's the right strategy when every visit counts, but with a small budget it can spend nearly all of it on the prior's favourite and learn little about the alternatives.
The idea. Sequential halving runs $\lceil \log_2 L \rceil$ rounds. Each round gives every move still in the running the same number of visits, then drops the worse half. Moves are ranked by the score
After the last round, we play the surviving move with the highest score.
def considered_visit_sequence(m: int, n: int) -> list[int]:
"""Sequential-halving schedule (mctx's `get_sequence_of_considered_visits`): for each of `n`
simulations, the visit count a root move must have to be eligible, with `m` candidate moves."""
if m <= 1:
return list(range(n))
rounds = math.ceil(math.log2(m))
seq, visits, num_considered = [], [0] * m, m
while len(seq) < n:
extra = max(1, n // (rounds * num_considered)) # visits per move this round
for _ in range(extra):
seq.extend(visits[:num_considered])
visits[:num_considered] = [v + 1 for v in visits[:num_considered]]
num_considered = max(2, num_considered // 2) # halve the field
return seq[:n]
def considered_visit_table(max_considered: int, n: int, device) -> Int[Tensor, "8 n"]:
"""Row L is the schedule for a root with L legal moves (row 0 is unused), so a batch of games with
different numbers of legal moves can look up their schedules with one index: `table[num_legal]`."""
rows = [[0] * n] + [considered_visit_sequence(min(max_considered, L), n) for L in range(1, 8)]
return t.tensor(rows, dtype=t.long, device=device)
print("m=4, n=8: ", considered_visit_sequence(4, 8))
print("m=7, n=16:", considered_visit_sequence(7, 16))
Completed Q-values and $\sigma$
The scores and the training target both need a Q-value for every legal root move, including moves the search never visited. Gumbel AlphaZero completes them: an unvisited move gets the root's own value as its guess. For that value it combines two estimates:
- the network's value $v(s)$ of the root position $s$, and
- the search's estimate $\bar Q(s)$: the average Q-value of the moves that were visited, weighted by the
prior,
$$ \bar Q(s) = \frac{\sum_{a' \text{ visited}} p_\theta(a' \mid s)\, Q(s, a')}{\sum_{a' \text{ visited}} p_\theta(a' \mid s)}. $$
The mixed value is their weighted average, where $v(s)$ counts as one visit's worth of evidence and $\bar Q(s)$ counts as $N(s) = \sum_{a'} N(s, a')$ visits' worth (the root's total visit count):
Then $\sigma$ turns $\hat q$ into something on the scale of logits: min-max rescale it to $[0, 1]$ over the legal moves, then multiply by a factor that grows with the search:
sigma is given below.)
The improved policy is then
Exercise - implement completed_q
Implement the formula above, for B roots at once. Q is W / max(N, 1), so it is 0 for unvisited moves.
- Be careful when no move has been visited yet: the weighted average of the visited Q-values is then 0/0,
but it gets multiplied by $N(s) = 0$, so clamp the denominator with
.clamp_min(1e-12)and then the result is just $v(s)$.
def completed_q(
Q: Float[Tensor, "B 7"],
N: Float[Tensor, "B 7"],
prior: Float[Tensor, "B 7"],
value: Float[Tensor, "B"],
) -> Float[Tensor, "B 7"]:
"""Root Q-values with the unvisited moves filled in by the mixed value v_mix.
Args:
Q: (B, 7) root Q-values W / max(N, 1) (0 where unvisited)
N: (B, 7) root visit counts
prior: (B, 7) the network prior p_theta(a | s) at the root s
value: (B,) the network's value of the root position
Returns:
(B, 7) Q where N > 0, else v_mix
"""
raise NotImplementedError()
def sigma(q_hat: Float[Tensor, "B 7"], N: Float[Tensor, "B 7"], legal: Bool[Tensor, "B 7"],
c_visit: float = 50.0, c_scale: float = 0.1) -> Float[Tensor, "B 7"]:
"""Min-max rescale the completed Q-values to [0, 1] over the legal moves, then scale by
(c_visit + max_a N(s, a)) * c_scale, so well-searched Q-values can outweigh the prior logits."""
lo = q_hat.masked_fill(~legal, t.inf).min(-1, keepdim=True).values
hi = q_hat.masked_fill(~legal, -t.inf).max(-1, keepdim=True).values
q01 = (q_hat - lo) / (hi - lo).clamp_min(1e-8)
return (c_visit + N.max(-1, keepdim=True).values) * c_scale * q01
tests.test_completed_q(completed_q)
Solution
def completed_q(
Q: Float[Tensor, "B 7"],
N: Float[Tensor, "B 7"],
prior: Float[Tensor, "B 7"],
value: Float[Tensor, "B"],
) -> Float[Tensor, "B 7"]:
"""Root Q-values with the unvisited moves filled in by the mixed value v_mix.
Args:
Q: (B, 7) root Q-values W / max(N, 1) (0 where unvisited)
N: (B, 7) root visit counts
prior: (B, 7) the network prior p_theta(a | s) at the root s
value: (B,) the network's value of the root position
Returns:
(B, 7) Q where N > 0, else v_mix
"""
visited = N > 0
sum_N = N.sum(-1)
p_visited = (prior * visited).sum(-1)
weighted_q = (prior * Q * visited).sum(-1) / p_visited.clamp_min(1e-12)
v_mix = (value + sum_N * weighted_q) / (sum_N + 1)
return t.where(visited, Q, v_mix.unsqueeze(-1))
def sigma(q_hat: Float[Tensor, "B 7"], N: Float[Tensor, "B 7"], legal: Bool[Tensor, "B 7"],
c_visit: float = 50.0, c_scale: float = 0.1) -> Float[Tensor, "B 7"]:
"""Min-max rescale the completed Q-values to [0, 1] over the legal moves, then scale by
(c_visit + max_a N(s, a)) * c_scale, so well-searched Q-values can outweigh the prior logits."""
lo = q_hat.masked_fill(~legal, t.inf).min(-1, keepdim=True).values
hi = q_hat.masked_fill(~legal, -t.inf).max(-1, keepdim=True).values
q01 = (q_hat - lo) / (hi - lo).clamp_min(1e-8)
return (c_visit + N.max(-1, keepdim=True).values) * c_scale * q01
tests.test_completed_q(completed_q)
Exercise - implement gumbel_root_action and improved_policy
gumbel_root_action is the root's selection rule: per game, the argmax of
gumbel + logits + sigma_q over the moves that are legal and whose visit count equals
considered_visit (set the score of every other move to -inf). The same function picks the move we
finally play: pass the root's largest visit count as considered_visit.
improved_policy is $\pi' = \mathrm{softmax}(\ell + \sigma(\hat q))$, with illegal moves set to probability 0.
def gumbel_root_action(
gumbel: Float[Tensor, "B 7"],
logits: Float[Tensor, "B 7"],
sigma_q: Float[Tensor, "B 7"],
N: Float[Tensor, "B 7"],
legal: Bool[Tensor, "B 7"],
considered_visit: Int[Tensor, "B"],
) -> Int[Tensor, "B"]:
"""Per game: argmax of gumbel + logits + sigma_q over the legal moves with N == considered_visit."""
raise NotImplementedError()
def improved_policy(
logits: Float[Tensor, "B 7"], sigma_q: Float[Tensor, "B 7"], legal: Bool[Tensor, "B 7"]
) -> Float[Tensor, "B 7"]:
"""pi' = softmax(logits + sigma_q) over the legal moves (0 on illegal ones)."""
raise NotImplementedError()
tests.test_gumbel_root_action(gumbel_root_action)
tests.test_improved_policy(improved_policy)
Solution
def gumbel_root_action(
gumbel: Float[Tensor, "B 7"],
logits: Float[Tensor, "B 7"],
sigma_q: Float[Tensor, "B 7"],
N: Float[Tensor, "B 7"],
legal: Bool[Tensor, "B 7"],
considered_visit: Int[Tensor, "B"],
) -> Int[Tensor, "B"]:
"""Per game: argmax of gumbel + logits + sigma_q over the legal moves with N == considered_visit."""
eligible = legal & (N == considered_visit.unsqueeze(-1))
return t.where(eligible, gumbel + logits + sigma_q, -t.inf).argmax(-1)
def improved_policy(
logits: Float[Tensor, "B 7"], sigma_q: Float[Tensor, "B 7"], legal: Bool[Tensor, "B 7"]
) -> Float[Tensor, "B 7"]:
"""pi' = softmax(logits + sigma_q) over the legal moves (0 on illegal ones)."""
return t.softmax(t.where(legal, logits + sigma_q, -t.inf), dim=-1)
tests.test_gumbel_root_action(gumbel_root_action)
tests.test_improved_policy(improved_policy)
The Gumbel search (given)
Here's the full search. It's vec_mcts with three changes at the root:
- Before searching, draw Gumbel noise
gfor each game's root moves, and look up its halving schedule. - Each simulation, the root move is chosen by
gumbel_root_action(with this simulation'sconsidered_visit) instead of PUCT.select_with_root_actionisvec_selectwith one extra line that forces that move at the root. Everything below the root is the same PUCT walk, and expansion, evaluation and backup are your batched kernels, unchanged. - At the end it returns the move to play (the halving winner) and the training target $\pi'$, instead of visit counts.
GumbelAlphaZeroTrainer swaps this search into self-play: it plays the halving winner, and writes
$\pi'$ into the replay buffer as the policy target. Note there's no Dirichlet noise: the Gumbel noise
is the exploration.
def select_with_root_action(tree: Tree, c_puct: float, root_action: Int[Tensor, "B"]) -> tuple[Int[Tensor, "B"], Int[Tensor, "B"]]:
"""`vec_select`, except that at the root each game takes the given `root_action` instead of the PUCT move."""
batch_idx = tree.batch_idx
node = t.zeros_like(batch_idx)
while True:
action = puct_select(tree.N[batch_idx, node], tree.W[batch_idx, node], tree.P[batch_idx, node],
tree.legal[batch_idx, node], c_puct)
action = t.where(node == 0, root_action, action) # the one new line: Gumbel picks the root move
next_node = tree.child[batch_idx, node, action]
can_descend = next_node >= 0
if not can_descend.any():
return node, action
node = t.where(can_descend, next_node, node)
class GumbelMCTS:
"""Gumbel AlphaZero search: Gumbel-top-k + sequential halving at the root, PUCT below it.
`.search(model, root_boards)` returns `(action, pi_improved, root_N)`: the move to play (B,), the
improved policy target (B, 7), and the root visit counts (B, 7)."""
def __init__(self, env, cfg, max_considered: int = 16, c_visit: float = 50.0, c_scale: float = 0.1):
self.env, self.cfg = env, cfg
self.c_visit, self.c_scale = c_visit, c_scale
self.schedule_table = considered_visit_table(max_considered, cfg.sims, env.device)
@t.no_grad()
def search(self, model, root_boards: Board, add_noise: bool = True):
cfg, env = self.cfg, self.env
tree = Tree.alloc(root_boards.shape[0], cfg, env.device)
batch_idx = tree.batch_idx
tree.boards[:, 0] = root_boards
root_value = vec_evaluate(tree, t.zeros_like(batch_idx), model).float() # also sets the root's P, legal
legal = tree.legal[:, 0]
logits = t.where(legal, t.log(tree.P[:, 0].clamp_min(1e-30)), -t.inf) # log-prior = logits up to a constant
g = rand_gumbel(logits.shape, logits.device) if add_noise else t.zeros_like(logits)
schedule = self.schedule_table[legal.sum(-1)] # (B, sims)
def root_sigma():
N = tree.N[:, 0]
q_hat = completed_q(tree.W[:, 0] / N.clamp_min(1), N, tree.P[:, 0], root_value)
return sigma(q_hat, N, legal, self.c_visit, self.c_scale)
for k in range(cfg.sims):
root_action = gumbel_root_action(g, logits, root_sigma(), tree.N[:, 0], legal, schedule[:, k])
node, action = select_with_root_action(tree, cfg.c_puct, root_action)
leaf = vec_expand(tree, node, action, env)
value = vec_evaluate(tree, leaf, model)
vec_backup(tree, leaf, value)
N, sigma_q = tree.N[:, 0], root_sigma()
action = gumbel_root_action(g, logits, sigma_q, N, legal, N.max(-1).values) # the halving winner
return action, improved_policy(logits, sigma_q, legal), N
class GumbelAlphaZeroTrainer(AlphaZeroTrainer):
"""`AlphaZeroTrainer` with Gumbel search in self-play: play the halving winner, train towards pi'."""
def __init__(self, env, cfg, model):
super().__init__(env, cfg, model)
self.gumbel = GumbelMCTS(env, MCTSConfig(sims=cfg.sims, c_puct=cfg.c_puct, max_depth=cfg.max_depth))
@t.no_grad()
def self_play_step(self, boards: Board) -> tuple[Board, Bool[Tensor, "B"]]:
action, pi, _ = self.gumbel.search(self.model, boards)
next_boards, done, reward = self.env.step(boards, action)
self.buffer.write(boards, pi, done, reward)
return next_boards, done
tests.test_gumbel_search(GumbelMCTS)
Experiment - PUCT vs Gumbel with a small search budget
The paper's headline result is that Gumbel AlphaZero keeps learning with very few simulations, where
AlphaZero's visit-count targets break down. The cell below (set SLOW = True to run it) trains both
trainers with the default recipe at 4, 8 and 16 simulations per move, and plots the Pons accuracy after
every generation.
Here's what we got (RTX 5090, final Pons accuracy after the default 8 generations, two seeds each):
| simulations per move | PUCT (AlphaZero) | Gumbel | time per run |
|---|---|---|---|
| 4 | 0.65, 0.66 | 0.83, 0.84 | ~33 s |
| 8 | 0.78, 0.77 | 0.86, 0.87 | ~42 s |
| 16 | 0.86, 0.85 | 0.86, 0.87 | ~62 s |
With 16 simulations the two are about level. But Gumbel with only 4 simulations nearly matches PUCT with 16, in half the time, and with 8 it matches it outright. That's the regime the paper targets: when search is expensive (a big network, or a big game), you want every simulation to count.
Some things to try:
- Full Gumbel MuZero. The paper also replaces PUCT below the root, with a deterministic rule: pick $\arg\max_a \big(\pi'(a \mid s) - N(s, a) / (1 + \sum_{a'} N(s, a'))\big)$, which steers the visit counts towards $\pi'$.
- Evaluation.
GumbelMCTS.search(model, boards, add_noise=False)searches without noise. How does its move accuracy against the solver compare with PUCT's at the same number of simulations? - The constants. How sensitive is training to $c_\text{visit}$ and $c_\text{scale}$, which set how fast searched Q-values take over from the prior?
if SLOW:
def run(trainer_cls, sims, seed=0):
"""Train with the default recipe at `sims` simulations; return Pons accuracy after each generation."""
t.manual_seed(seed)
trainer = trainer_cls(env, AZConfig(sims=sims), Connect4Model(device))
accs, evaluate = [], trainer.evaluate
def evaluate_and_log():
metrics = evaluate()
accs.append(float(metrics["pons/acc"]))
return metrics
trainer.evaluate = evaluate_and_log
trainer.train()
return accs
trainers = {"PUCT (AlphaZero)": AlphaZeroTrainer, "Gumbel": GumbelAlphaZeroTrainer}
curves = {} # (name, sims) -> Pons accuracy after each generation
for sims in [4, 8, 16]:
for name, cls in trainers.items():
curves[name, sims] = run(cls, sims)
print(f"sims={sims:2d} {name:16s}: final Pons accuracy {curves[name, sims][-1]:.3f}")
if SLOW:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 3, figsize=(15, 4.2), sharey=True)
for ax, sims in zip(axes, [4, 8, 16]):
for name in trainers:
accs = curves[name, sims]
ax.plot(range(1, len(accs) + 1), accs, "o-", label=name)
ax.set_xlabel("generation"); ax.set_title(f"{sims} simulations per move"); ax.grid(alpha=0.3)
axes[0].set_ylabel("Pons optimal-move accuracy"); axes[0].legend()
fig.suptitle("PUCT vs Gumbel AlphaZero: training curves"); fig.tight_layout()
Click to see the expected output

Seed 0 on an RTX A4000 (each run took 100-195 s). Final Pons accuracy, PUCT vs Gumbel: 0.68 vs 0.84 at 4 simulations, 0.79 vs 0.85 at 8, and 0.85 vs 0.87 at 16. With 16 simulations PUCT is ahead for the first few generations and Gumbel catches up by generation 4; with 4 or 8, Gumbel pulls away from generation 3 on.