☆ Bonus - Vectorized AlphaZero MCTS
Learning Objectives
- Understand how we can store trees as tensors in a way that tree search can be performed as parallel operations on the GPU in lock-step.
- Vectorize the selection, expansion, evaluation and backup stages of MCTS.
⚠️ Note: This section is mostly just an engineering task: getting tree updates to run as vectorized
tensor operations. There are no new ideas about MCTS itself; it's just speeding up the
SimulatedBatchedMCTS class you were presented with earlier. Please give feedback on how to improve this section.
Recall that we are implementing root parallelism: B independent games,
each with its own search tree, all stepped forward together.
SimulatedBatchedMCTS already batched the network call. Here we
also batch selection, expansion and backup, so that the entire AlphaZero pipeline
runs entirely on the GPU.
The good news is that you've already written this algorithm. Each function in this section is
essentially a line-by-line translation of its section 2 counterpart. The vec_ prefix marks the
vectorised version of a function.
| section 2 (one game, Python objects) | this section (B games, tensors) |
|---|---|
a tree of Node objects |
a Tree of tensors; a node is an integer slot |
select(root, c_puct) -> (node, action) |
vec_select(tree, c_puct) -> (node, action), each (B,) |
expand(node, action, env) -> child |
vec_expand(tree, node, action, env) -> leaf, (B,) |
evaluate(leaf, model, env) -> value |
vec_evaluate(tree, leaf, model) -> value, (B,) |
backup(leaf, value) |
vec_backup(tree, leaf, value) |
mcts(...) -> root |
vec_mcts(...) -> root visit counts (B, 7) |
So for every exercise, keep the section 2 version open next to it.
Storing a tree as tensors
In section 2 a tree was a web of Node objects. A GPU can't follow Python references, so we store the same tree
as a handful of tensors. This layout is the only new idea here (the rest is the section 2 algorithm, rewritten
for it), so we build it up in four steps. All pictures use one example: a search from the empty board, after 3
simulations.
Step 1: one tensor per attribute, one row per node
Instead of one object per node holding every attribute, keep one tensor per attribute, holding every node. Each node gets a row number, its slot, and its data is that row of each tensor:

Left: each Node holds its own .board and .N. Right: the same data as tensors, one row per slot. The ringed
cell is the orange node's node.N[3], which is now N[1, 3]. Grey rows are free slots: their boards are garbage
(?), but N already starts at 0.
# section 2 # this section
node.N[3] N[slot, 3]
node.board boards[slot]
node.W, node.P, ... W[slot], P[slot], ...
So a node is an integer: its slot. There are no Node objects.
Step 2: slots are handed out in creation order
The root is slot 0. Each new node takes the next free slot, num_nodes:

Each simulation's new node (red ring) goes in slot num_nodes, which then goes up by one. Children are drawn in
action order, so slot 2 (a=2) sits left of slot 1 (a=3).
new = num_nodes
num_nodes += 1
Two consequences:
- A slot says when a node was created, not where it is. Slot 2 is a child of the root; slot 3 is a grandchild. To find a node's place in the tree, follow the pointers (step 3).
- We know the maximum size up front. Each simulation adds at most one node, so
cfg.sims + 1slots always suffice.Tree.allocstatically allocates them once, and they're reused throughout the search: no dynamic allocation, which is part of why this is fast. Slots>= num_nodes(grey) aren't in use yet and mostly hold garbage, shown as?. The exceptions arechild,NandW, which start at-1,0,0: expansion relies on a new node already having no children and no visits.
Step 3: pointers become slot numbers
A node is a slot, so a pointer to a node is a slot too:
child[slot, a]: the slot of the child reached by actiona, or-1if it doesn't exist yet. Shape(nodes, 7).parent[slot]: the parent's slot. The root is its own parent,parent[0] = 0(trick 3 shows why).parent_act[slot]: the action from the parent, sochild[parent[s], parent_act[s]] == s(except at the root).
Following a pointer means reading a number and using it as the next row. Selection walks down through child;
backup walks up through parent:

Blue: selection walks down from the root, here taking action 3 each time: child[0, 3] = 1, then
child[1, 3] = 3, then child[3, 3] = -1, so slot 3 is the leaf. Red: backup walks up from the leaf:
parent[3] = 1 and parent_act[3] = 3 (update N[1, 3]), then parent[1] = 0 and parent_act[1] = 3 (update
N[0, 3]), then stop at the root. ? marks values that are never read: the free slots, and the root's
parent_act. Free rows of child are already -1, which expansion relies on.
node = 0 # walk DOWN from the root
a = pick_action(node) # PUCT
while child[node, a] != -1: # -1: no child, so `node` is the leaf
node = child[node, a]
a = pick_action(node)
v = value # walk UP from the leaf; `value` is from the leaf mover's view
while node != 0:
p, a = parent[node], parent_act[node]
v = -v # negamax: the parent's mover is the other player
N[p, a] += 1
W[p, a] += v
node = p
The exercises do these walks for all games at once. For reference, every Node attribute and where it lives now:
Node attribute |
Tree field (one game) |
example tree |
|---|---|---|
children (dict: action → Node) |
child[slot, action]: child's slot, or -1 |
child[0] = [-1,-1, 2, 1,-1,-1,-1]child[1] = [-1,-1,-1, 3,-1,-1,-1]child[2] = child[3] = [-1]*7 |
parent |
parent[slot] (root: 0, itself) |
[0, 0, 0, 1] |
parent_action |
parent_act[slot] |
[?, 3, 2, 3] |
board |
boards[slot] |
|
is_terminal, terminal_value |
terminal[slot], term_val[slot] |
|
P, legal, N, W (each (7,)) |
P[slot], legal[slot], N[slot], W[slot] |
N[0] = [0, 0, 1, 2, 0, 0, 0]N[1] = [0, 0, 0, 1, 0, 0, 0] |
num_nodes: slots in use = next free slot |
4 |
Step 4: one table per game
For B games, every tensor gets a leading batch dimension: child is (B, nodes, 7), parent is (B, nodes),
num_nodes is (B,). Game b's tree is child[b], parent[b], ...: the tables above. The trees are
independent: slot 2 of game 0 and slot 2 of game 1 are unrelated, and each game has its own num_nodes. Reading
each game's own current node in one operation is trick 1.
Three tricks for running B searches in lockstep
1. Indexing each game's own node: X[batch_idx, node]. The current node is a (B,) tensor node, one slot
per game. To read row node[b] of game b, for every b at once, index with batch_idx = t.arange(B) alongside
it. batch_idx carries no information; it just pairs entry b of node with game b:

node = [3, 0, 2] picks slot 3 of game 0, slot 0 of game 1 and slot 2 of game 2, one row per game (each in
its game's colour). Grey rows are free slots; each game has its own num_nodes.
tree.N[batch_idx, node] # (B, 7): row b is tree.N[b, node[b]]
tree.child[batch_idx, node, a] # (B,): entry b is tree.child[b, node[b], a[b]]
tree.N[batch_idx, node, a] += 1 # adds 1 to tree.N[b, node[b], a[b]] for every b
This is the only indexing pattern in this section, and Tree stores batch_idx for you.
Watch out:
tree.N[:, node]is nottree.N[batch_idx, node](a very common PyTorch mistake). It has shape(B, B, 7), pairing every game with every game's node.
2. No branching per game. In section 2, expand skipped terminal nodes. In lockstep every game runs the same
operations, so every game does the work and t.where(mask, new, old) keeps it only where it applies. A write that
lands where nothing will read it needs no mask at all.
Isn't computing both branches wasteful?
GPUs run threads in groups (called warps, 32 threads on NVIDIA) that share one instruction stream: every thread executes the same instruction, each on its own element. So a warp can't run
if x[i] > 0:
out[i] = f(x[i])
else:
out[i] = g(x[i])
with each thread going its own way. When the threads disagree, the hardware runs both branches, one after the other, and then discards the wrong path after the fact.
y = f(x) # every element computes f...
z = g(x) # ...and every element computes g
out = t.where(x > 0, y, z) # then each element keeps the one it needed
In PyTorch there are two more reasons. A Python if on a tensor value forces a GPU→CPU sync (see below). And a
boolean-mask split like x[x > 0] has a data-dependent shape, which hurts in two ways:
- It's a sync too. The output's length is the number of
Trues, which only the GPU knows. The CPU must wait for the GPU to count them before it can allocate the output and queue the next kernel. - It breaks compilation.
t.compileand CUDA graphs record a fixed sequence of kernels on fixed shapes. A shape that changes every step forces recompiles or falls back to slow, uncompiled code.
t.where keeps every tensor at a fixed (B, ...) shape, so none of this happens.
3. Loops of different lengths. Games stop selection (or backup) at different depths. Rather than track who's
done, we make extra iterations a no-op for finished games.
You'll see how in vec_select and vec_backup.
"Sync-free" code
.item()andbool(tensor)copy a value from GPU to CPU, so the CPU stalls until the GPU catches up. The search loop avoids them: it's allwhere, indexing andargmax, one uninterrupted stream of GPU kernels. The one deliberate exception isvec_select'sif not can_descend.any(): return, which ends the descent once every game has found its leaf. Tree depths vary a lot, so here it is worth paying the cost to sync in exchange for stopping early, rather than always walking the maximum depth.
@dataclass
class Tree:
"""`B` independent search trees (one per game), stored as tensors: the batched version of `Node`.
Nodes are integer slots. Slot 0 is each game's root, and nodes are created at slots 1, 2, 3, ...
in order. Each field is one `Node` attribute, with leading dims `(B, nodes)`, where
`nodes = cfg.sims + 1` (the root plus at most one new node per simulation).
Fields:
batch_idx (B,) long: `arange(B)`, so `X[batch_idx, node]` picks each game's own node.
max_depth int: an upper bound on the depth of any node (used by `vec_backup`).
boards Board of batch shape (B, nodes): `Node.board`.
terminal (B, nodes) bool: `Node.is_terminal`.
term_val (B, nodes) float: `Node.terminal_value` (mover's perspective).
legal (B, nodes, 7) bool: `Node.legal`.
P (B, nodes, 7) float: `Node.P`, the prior.
N (B, nodes, 7) float: `Node.N`, per-edge visit counts.
W (B, nodes, 7) float: `Node.W`, per-edge value sums (mover's perspective).
child (B, nodes, 7) long: `Node.children`: the child's slot per action, or -1 if not expanded.
parent (B, nodes) long: `Node.parent`, as a slot. The root is its own parent (0).
parent_act (B, nodes) long: `Node.parent_action`.
num_nodes (B,) long: slots in use per game, so also the next free slot. Starts at 1 (the root).
"""
batch_idx: Int[Tensor, "B"]
max_depth: int
boards: Board # batch shape (B, nodes)
terminal: Bool[Tensor, "B nodes"]
term_val: Float[Tensor, "B nodes"]
legal: Bool[Tensor, "B nodes 7"]
P: Float[Tensor, "B nodes 7"]
N: Float[Tensor, "B nodes 7"]
W: Float[Tensor, "B nodes 7"]
child: Int[Tensor, "B nodes 7"]
parent: Int[Tensor, "B nodes"]
parent_act: Int[Tensor, "B nodes"]
num_nodes: Int[Tensor, "B"]
@classmethod
def alloc(cls, B: int, cfg: MCTSConfig, device) -> "Tree":
"""An empty tree for each of `B` games: no children anywhere, every count zero, one node (the root)."""
nodes = cfg.sims + 1 # the root, plus at most one new node per simulation
zeros = lambda *shape, dtype=t.float32: t.zeros((B, nodes, *shape), dtype=dtype, device=device)
return cls(
batch_idx=t.arange(B, device=device),
# the k-th simulation creates a node at depth <= k, and no game is longer than cfg.max_depth plies
max_depth=min(cfg.max_depth, cfg.sims),
boards=Board(zeros(3, 6, 7), zeros(dtype=t.bool)),
terminal=zeros(dtype=t.bool),
term_val=zeros(),
legal=zeros(7, dtype=t.bool),
P=zeros(7),
N=zeros(7),
W=zeros(7),
child=t.full((B, nodes, 7), -1, dtype=t.long, device=device),
parent=zeros(dtype=t.long), # all zeros: in particular the root is its own parent
parent_act=zeros(dtype=t.long),
num_nodes=t.ones(B, dtype=t.long, device=device),
)
Exercise - implement masked_softmax_prior
A warm-up. The policy head returns raw logits (B, 7), but some columns are full (illegal). Turn the logits
into a normalised prior P(a) over the legal columns only: set illegal columns to -t.inf so they get
probability 0, then softmax. This is the same computation as in section 2's evaluate, for B boards at once.
def masked_softmax_prior(
logits: Float[Tensor, "B 7"], legal: Bool[Tensor, "B 7"]
) -> Float[Tensor, "B 7"]:
"""Softmax of the policy logits over the legal columns only.
Args:
logits: (B, 7) raw policy-head scores
legal: (B, 7) legal-column mask
Returns:
(B, 7) prior P(a): zero on illegal columns, summing to 1 over the legal ones
"""
raise NotImplementedError()
tests.test_masked_softmax_prior(masked_softmax_prior)
Solution
def masked_softmax_prior(
logits: Float[Tensor, "B 7"], legal: Bool[Tensor, "B 7"]
) -> Float[Tensor, "B 7"]:
"""Softmax of the policy logits over the legal columns only.
Args:
logits: (B, 7) raw policy-head scores
legal: (B, 7) legal-column mask
Returns:
(B, 7) prior P(a): zero on illegal columns, summing to 1 over the legal ones
"""
legal_logits = t.where(legal, logits, -t.inf)
return t.softmax(legal_logits, dim=-1)
tests.test_masked_softmax_prior(masked_softmax_prior)
Exercise - implement puct_select (batched PUCT)
The batched twin of select_child: given one node's statistics for each of the B games, return the
legal action maximising the PUCT score, per game:
select_child body should carry over almost unchanged. The only differences are that every tensor has
a leading (B,) dimension, so the sum and the argmax are over the last dimension, and you return a
(B,) tensor instead of an int. Keep exactly the same formula so the two versions agree exactly.
def puct_select(
node_N: Float[Tensor, "B 7"],
node_W: Float[Tensor, "B 7"],
node_P: Float[Tensor, "B 7"],
node_legal: Bool[Tensor, "B 7"],
c_puct: float,
) -> Int[Tensor, "B"]:
"""Batched PUCT selection: the legal action with the highest PUCT score, per game.
Args:
node_N: (B, 7) per-edge visit counts at each game's current node
node_W: (B, 7) per-edge value sums
node_P: (B, 7) per-edge priors P(a)
node_legal: (B, 7) legal-column mask
c_puct: exploration constant
Returns:
(B,) the chosen action (column index) for each game
"""
raise NotImplementedError()
tests.test_puct_select(puct_select)
Solution
def puct_select(
node_N: Float[Tensor, "B 7"],
node_W: Float[Tensor, "B 7"],
node_P: Float[Tensor, "B 7"],
node_legal: Bool[Tensor, "B 7"],
c_puct: float,
) -> Int[Tensor, "B"]:
"""Batched PUCT selection: the legal action with the highest PUCT score, per game.
Args:
node_N: (B, 7) per-edge visit counts at each game's current node
node_W: (B, 7) per-edge value sums
node_P: (B, 7) per-edge priors P(a)
node_legal: (B, 7) legal-column mask
c_puct: exploration constant
Returns:
(B,) the chosen action (column index) for each game
"""
sumN = node_N.sum(-1, keepdim=True)
Q = node_W / node_N.clamp_min(1.0)
U = c_puct * node_P * t.sqrt(sumN + 1.0) / (1.0 + node_N)
legal_score = t.where(node_legal, Q + U, -t.inf)
return legal_score.argmax(-1)
tests.test_puct_select(puct_select)
Exercise - implement vec_select
Here's section 2's select, written so the batched version lines up with it:
node = root
while True:
a = select_child(node, c_puct)
if node.is_terminal or a not in node.children: # can't go any further
return node, a
node = node.children[a]
(Section 2 returned NULL_ACTION on a terminal node. Here we just return whatever a is: the caller won't use it.)
In the batched version, node is a (B,) tensor of slots, starting at 0 (every game's root). Each
iteration of the loop, for every game at once:
- pick
actionwith yourpuct_select, on each game's own node (tree.N[batch_idx, node], etc.), - look up where that edge leads:
next_node = tree.child[batch_idx, node, action](-1if not expanded), can_descend = next_node >= 0: games that can step down do so (t.where); the others stay where they are.
You don't need a separate node.is_terminal check. A terminal node never gets children (vec_expand
won't give it any), so child is -1 along every action there, and the walk stops on it anyway.
When do we stop? Here's the nice part. Selection doesn't change the tree, so a game that couldn't
descend this iteration recomputes the same action, finds the same -1, and stays put on every later
iteration too. So there's no need to track which games are finished: just loop until no game can
descend (if not can_descend.any()), and return (node, action).
def vec_select(tree: Tree, c_puct: float) -> tuple[Int[Tensor, "B"], Int[Tensor, "B"]]:
"""SELECT for all games at once (the batched `select`): from each root, follow the PUCT-best action
down the tree until that action has no child yet, or the node is terminal.
Returns:
node: (B,) the slot each game stopped at
action: (B,) the PUCT-best action there (the edge to expand; unused if `node` is terminal)
"""
batch_idx = tree.batch_idx
node = t.zeros_like(batch_idx) # every game starts at its root, slot 0
raise NotImplementedError()
tests.test_vec_select(vec_select)
Solution
def vec_select(tree: Tree, c_puct: float) -> tuple[Int[Tensor, "B"], Int[Tensor, "B"]]:
"""SELECT for all games at once (the batched `select`): from each root, follow the PUCT-best action
down the tree until that action has no child yet, or the node is terminal.
Returns:
node: (B,) the slot each game stopped at
action: (B,) the PUCT-best action there (the edge to expand; unused if `node` is terminal)
"""
batch_idx = tree.batch_idx
node = t.zeros_like(batch_idx) # every game starts at its root, slot 0
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)
next_node = tree.child[batch_idx, node, action] # -1 where that edge isn't expanded yet
can_descend = next_node >= 0
if not can_descend.any(): # every game has found its leaf
return node, action
node = t.where(can_descend, next_node, node) # step down; stopped games stay put
tests.test_vec_select(vec_select)
Exercise - implement vec_expand
In section 2, mcts did:
leaf = expand(node, action, env) if not node.is_terminal else node
and expand played action with env.step, created the child node, and linked it to its parent. Do the same,
for all B games at once:
- Play the move. One batched
env.stepon each game's board atnode, playingaction. - Create the new node at each game's next free slot,
new = tree.num_nodes: write itsboards,terminal,term_val(= -reward, as in section 2),parentandparent_act. - Link it in, but only for games whose
nodeis not terminal (call themexpanding): settree.child[batch_idx, node, action]tonew, and add 1 totree.num_nodes. - Return the leaf: the new node for expanding games, or
nodeitself for the others.
What about the games whose node is terminal? Trick 2 from above: let them do steps 1 and 2 anyway. Their
"new node" lands in their next free slot, but since we don't link it in (step 3) or advance num_nodes,
nothing points at it, and the next real expansion simply overwrites it. (env.step on a terminal node's
board is fine too: that board is the auto-reset empty board, so any column is legal.) So only step 3 needs
a mask, and step 4 is one t.where.
Hint: how do I write child only for the expanding games?
Write back the old value for the others: tree.child[batch_idx, node, action] = t.where(expanding, new, tree.child[batch_idx, node, action]).
Careful with tree.num_nodes: read new = tree.num_nodes before you update it, and update it out of place
(tree.num_nodes = tree.num_nodes + ...), so that new still holds the slots you just wrote to.
@t.no_grad()
def vec_expand(tree: Tree, node: Int[Tensor, "B"], action: Int[Tensor, "B"],
env: Connect4Env) -> Int[Tensor, "B"]:
"""EXPAND for all games at once (the batched `expand`): play `action` at each game's `node`, store the
resulting position as a new node in the next free slot, and link it in. Games whose `node` is terminal
don't expand: their new node is written but never linked, so it is ignored and later overwritten.
Args:
tree: the trees (modified in place)
node: (B,) the slot each game's selection stopped at
action: (B,) the action to expand there
env: the Connect4Env
Returns:
leaf: (B,) the new node's slot for games that expanded, else `node` (a terminal node)
"""
batch_idx = tree.batch_idx
raise NotImplementedError()
tests.test_vec_expand(vec_expand)
Solution
@t.no_grad()
def vec_expand(tree: Tree, node: Int[Tensor, "B"], action: Int[Tensor, "B"],
env: Connect4Env) -> Int[Tensor, "B"]:
"""EXPAND for all games at once (the batched `expand`): play `action` at each game's `node`, store the
resulting position as a new node in the next free slot, and link it in. Games whose `node` is terminal
don't expand: their new node is written but never linked, so it is ignored and later overwritten.
Args:
tree: the trees (modified in place)
node: (B,) the slot each game's selection stopped at
action: (B,) the action to expand there
env: the Connect4Env
Returns:
leaf: (B,) the new node's slot for games that expanded, else `node` (a terminal node)
"""
batch_idx = tree.batch_idx
# 1. play the move for every game
next_boards, done, reward = env.step(tree.boards[batch_idx, node], action)
# 2. write the new node into each game's next free slot
new = tree.num_nodes
tree.boards[batch_idx, new] = next_boards # env.step has already flipped red_to_move
tree.terminal[batch_idx, new] = done
tree.term_val[batch_idx, new] = -reward # reward is to the mover; the new node's mover is the opponent
tree.parent[batch_idx, new] = node
tree.parent_act[batch_idx, new] = action
# 3. link it in, only where `node` was not terminal
expanding = ~tree.terminal[batch_idx, node]
tree.child[batch_idx, node, action] = t.where(expanding, new, tree.child[batch_idx, node, action])
tree.num_nodes = tree.num_nodes + expanding.long()
# 4. the leaf is the new node, or the terminal node we stopped on
return t.where(expanding, new, node)
tests.test_vec_expand(vec_expand)
Exercise - implement vec_evaluate
The batched evaluate. In section 2:
if node.is_terminal:
return node.terminal_value
value, logits = model(node.board)
node.legal = ...; node.P = ... # store the prior for when we expand this node later
return value
For all B leaves at once: run the network on every leaf's board in one forward pass, store legal
(use legal_mask_from_obs(boards.obs), or env.legal_action_mask) and the masked_softmax_prior at each leaf,
and return term_val for terminal leaves and the network's value for the rest (t.where).
As in SimulatedBatchedMCTS, terminal leaves go through the network too, and we throw that output away.
That keeps the batch a fixed size B, which is faster than picking out the non-terminal leaves. Writing a
prior to a terminal leaf is harmless, since a terminal node is never expanded.
@t.no_grad()
def vec_evaluate(tree: Tree, leaf: Int[Tensor, "B"], model: nn.Module) -> Float[Tensor, "B"]:
"""EVALUATE for all games at once (the batched `evaluate`): one network forward pass over every game's
leaf. Stores each leaf's legal mask and prior, and returns its value from its mover's perspective.
Args:
tree: the trees (modified in place)
leaf: (B,) the leaf slot for each game
model: the policy-value network
Returns:
(B,) the stored terminal value for terminal leaves, else the network's value
"""
batch_idx = tree.batch_idx
raise NotImplementedError()
tests.test_vec_evaluate(vec_evaluate)
Solution
@t.no_grad()
def vec_evaluate(tree: Tree, leaf: Int[Tensor, "B"], model: nn.Module) -> Float[Tensor, "B"]:
"""EVALUATE for all games at once (the batched `evaluate`): one network forward pass over every game's
leaf. Stores each leaf's legal mask and prior, and returns its value from its mover's perspective.
Args:
tree: the trees (modified in place)
leaf: (B,) the leaf slot for each game
model: the policy-value network
Returns:
(B,) the stored terminal value for terminal leaves, else the network's value
"""
batch_idx = tree.batch_idx
boards = tree.boards[batch_idx, leaf]
value, logits = model(boards) # one forward pass for all B leaves
legal = legal_mask_from_obs(boards.obs)
tree.legal[batch_idx, leaf] = legal
tree.P[batch_idx, leaf] = masked_softmax_prior(logits, legal)
return t.where(tree.terminal[batch_idx, leaf], tree.term_val[batch_idx, leaf], value)
tests.test_vec_evaluate(vec_evaluate)
Exercise - implement vec_backup
Section 2's backup:
v, node = value, leaf
while node.parent is not None: # leaf -> root
v = -v # negamax: flip the sign each step up
node.parent.N[node.parent_action] += 1
node.parent.W[node.parent_action] += v
node = node.parent
The batched version follows tree.parent / tree.parent_act up from each game's leaf in the same way.
The games reach their roots after different numbers of steps, so we take a fixed tree.max_depth steps
(enough for the deepest possible leaf) and make the extra steps a no-op (trick 3):
- The root is its own parent, so once a game reaches slot
0it stays there. - At each step, multiply the update by
below_root = (node != 0).float(): games already at the root add0toNandW. (They still update the root'sparent_actentry, which is never used, by 0.)
Each step is then: read parent and parent_act at each game's node, flip the sign of v, add
below_root to N and below_root * v to W at [batch_idx, parent, action], and move node up to parent.
def vec_backup(tree: Tree, leaf: Int[Tensor, "B"], value: Float[Tensor, "B"]) -> None:
"""BACKUP for all games at once (the batched `backup`): walk from each game's leaf up to its root,
adding a visit and the negamax-signed value to every edge on the way. Updates `tree.N` and
`tree.W` in place.
Args:
tree: the trees (`N` and `W` are modified in place)
leaf: (B,) the slot each game's backup starts from
value: (B,) the leaf's value, from the leaf mover's perspective
"""
batch_idx = tree.batch_idx
node, v = leaf, value
for _ in range(tree.max_depth):
raise NotImplementedError()
tests.test_vec_backup(vec_backup)
Solution
def vec_backup(tree: Tree, leaf: Int[Tensor, "B"], value: Float[Tensor, "B"]) -> None:
"""BACKUP for all games at once (the batched `backup`): walk from each game's leaf up to its root,
adding a visit and the negamax-signed value to every edge on the way. Updates `tree.N` and
`tree.W` in place.
Args:
tree: the trees (`N` and `W` are modified in place)
leaf: (B,) the slot each game's backup starts from
value: (B,) the leaf's value, from the leaf mover's perspective
"""
batch_idx = tree.batch_idx
node, v = leaf, value
for _ in range(tree.max_depth):
below_root = (node != 0).float() # 0 for games that have already reached the root
parent, action = tree.parent[batch_idx, node], tree.parent_act[batch_idx, node]
v = -v # negamax: flip the sign each step up
tree.N[batch_idx, parent, action] += below_root
tree.W[batch_idx, parent, action] += below_root * v
node = parent # the root is its own parent, so rooted games stay put
tests.test_vec_backup(vec_backup)
Exercise - implement vec_mcts
Put it together: this is mcts with each phase swapped for its batched version. The root's
setup is given (it's section 2's evaluate(root) plus the root noise). Fill in the loop: each of the
cfg.sims simulations runs vec_select, vec_expand, vec_evaluate and vec_backup.
Return the root visit counts tree.N[:, 0].
The BatchedMCTS class below is the wrapper the trainer uses. It allocates a fresh Tree for every search.
Optional: compiling. The tree kernels are lots of tiny tensor operations, so the GPU spends much of its
time just launching them. t.compile can fuse them into a few kernels. Set compile_tree=True in
AZConfig (or pass compile=True to BatchedMCTS) to compile puct_select, vec_expand and
vec_backup. The results are identical, just faster. The catch is a one-off compile, paid the first time
each batch size / number of simulations is used, so it's off by default. On an RTX 5090 it makes the training
search (8192 games, 16 simulations) about 1.2x faster after a ~10 s compile. It helps most when kernel launches
dominate: small batches with many simulations (98 games at 64 simulations, as in the Elo bonus) run about 2.4x
faster. Compiled code is cached on disk, so later runs recompile in about a second.
@t.no_grad()
def vec_mcts(tree: Tree, root_boards: Board, model: nn.Module, env: Connect4Env,
cfg: MCTSConfig, add_noise: bool = False) -> Float[Tensor, "B 7"]:
"""Run `cfg.sims` simulations of MCTS for all `B` games at once (the batched `mcts`).
Returns:
(B, 7) the root visit counts N(root, a) for each game
"""
# the root: store its board, evaluate it (sets its prior and legal mask), and optionally add noise
tree.boards[:, 0] = root_boards
vec_evaluate(tree, t.zeros_like(tree.batch_idx), model)
if add_noise:
tree.P[:, 0] = dirichlet_root_noise(tree.P[:, 0], tree.legal[:, 0],
cfg.dirichlet_alpha, cfg.dirichlet_eps)
for _ in range(cfg.sims):
raise NotImplementedError()
return tree.N[:, 0]
def compile_tree_kernels():
"""Optional speed-up: replace the tree kernels (`puct_select`, `vec_expand`, `vec_backup`) with
`t.compile`d versions."""
g = globals()
if g.get("_tree_kernels_compiled"):
return
for name in ("puct_select", "vec_expand", "vec_backup"):
g[name] = t.compile(g[name], dynamic=False)
g["_tree_kernels_compiled"] = True
class BatchedMCTS:
"""Same interface as `SimulatedBatchedMCTS`: hold `env` and `cfg`, then call
`.search(model, root_boards, add_noise)` for the (B, 7) root visit counts. A fresh `Tree` per search.
`compile=True` calls `compile_tree_kernels()` (see above)."""
def __init__(self, env, cfg, compile: bool = False):
self.env, self.cfg = env, cfg
if compile:
compile_tree_kernels()
@t.no_grad()
def search(self, model, root_boards: Board, add_noise: bool = False) -> Float[Tensor, "B 7"]:
tree = Tree.alloc(root_boards.shape[0], self.cfg, self.env.device)
return vec_mcts(tree, root_boards, model, self.env, self.cfg, add_noise)
Solution
@t.no_grad()
def vec_mcts(tree: Tree, root_boards: Board, model: nn.Module, env: Connect4Env,
cfg: MCTSConfig, add_noise: bool = False) -> Float[Tensor, "B 7"]:
"""Run `cfg.sims` simulations of MCTS for all `B` games at once (the batched `mcts`).
Returns:
(B, 7) the root visit counts N(root, a) for each game
"""
# the root: store its board, evaluate it (sets its prior and legal mask), and optionally add noise
tree.boards[:, 0] = root_boards
vec_evaluate(tree, t.zeros_like(tree.batch_idx), model)
if add_noise:
tree.P[:, 0] = dirichlet_root_noise(tree.P[:, 0], tree.legal[:, 0],
cfg.dirichlet_alpha, cfg.dirichlet_eps)
for _ in range(cfg.sims):
node, action = vec_select(tree, cfg.c_puct)
leaf = vec_expand(tree, node, action, env)
value = vec_evaluate(tree, leaf, model)
vec_backup(tree, leaf, value)
return tree.N[:, 0]
def compile_tree_kernels():
"""Optional speed-up: replace the tree kernels (`puct_select`, `vec_expand`, `vec_backup`) with
`t.compile`d versions."""
g = globals()
if g.get("_tree_kernels_compiled"):
return
for name in ("puct_select", "vec_expand", "vec_backup"):
g[name] = t.compile(g[name], dynamic=False)
g["_tree_kernels_compiled"] = True
class BatchedMCTS:
"""Same interface as `SimulatedBatchedMCTS`: hold `env` and `cfg`, then call
`.search(model, root_boards, add_noise)` for the (B, 7) root visit counts. A fresh `Tree` per search.
`compile=True` calls `compile_tree_kernels()` (see above)."""
def __init__(self, env, cfg, compile: bool = False):
self.env, self.cfg = env, cfg
if compile:
compile_tree_kernels()
@t.no_grad()
def search(self, model, root_boards: Board, add_noise: bool = False) -> Float[Tensor, "B 7"]:
tree = Tree.alloc(root_boards.shape[0], self.cfg, self.env.device)
return vec_mcts(tree, root_boards, model, self.env, self.cfg, add_noise)
Look inside a tree
Here are the tensors for two games' trees after 12 simulations, printed one row per slot.
- Game 0 is the diagonal-win position from section 2. Column 4 wins on the spot, so its child (a
terminal node) is created once and then simply revisited: selection stops on the terminal node and
vec_expanddoesn't expand it, so each revisit adds toN(root, 4)without adding a node. (The net is untrained, so the search usually expands several of the other root moves too before it settles on column 4; the exact layout depends on the random initialisation.) - Game 1 starts from the empty board, so after the first 7 simulations have expanded every root move, the search starts going deeper.
Check that you can match the child, parent and parent_act columns against each other. Then check
the visit counts: for a non-terminal node other than the root, N(s, ·).sum() is exactly one less than
the count on the edge leading into it, N(parent, via). Every simulation through that edge carries on
below the node, except the one that created it. (A terminal node's own counts stay at zero: simulations
that reach it stop there.)
small_cfg = MCTSConfig(sims=12, c_puct=1.5)
tree = Tree.alloc(2, small_cfg, device)
demo_model = Connect4Model(device).eval() # an untrained net is fine: we only want to see the tree's layout
vec_mcts(tree, Board.cat([tests.diagonal_win_red(), env.reset(1)]), demo_model, env, small_cfg)
for g in range(2):
print(f"game {g}: {int(tree.num_nodes[g])} nodes in use, root visits N(root, ·) = {tree.N[g, 0].int().tolist()}")
print(f"{'slot':>4} {'parent':>6} {'via':>3} {'terminal':>8} {'child (per column; -1 = none)':<34} N(s, ·)")
for s in range(int(tree.num_nodes[g])):
via = "-" if s == 0 else str(int(tree.parent_act[g, s]))
print(f"{s:>4} {int(tree.parent[g, s]):>6} {via:>3} {bool(tree.terminal[g, s])!s:>8} "
f"{str(tree.child[g, s].tolist()):<34} {tree.N[g, s].int().tolist()}")
print()
The payoff: single ↔ batched equivalence
Because the batched search runs the same algorithm as your single-game version (same PUCT,
same negamax backup, same transitions), with add_noise=False the two must produce exactly
the same visit counts. This is the best possible debugging tool: if your batched version is
wrong, this test tells you immediately.
test_model = Connect4Model(device).eval() # a fresh net, so we don't overwrite your trained `model`
test_cfg = MCTSConfig(sims=64, c_puct=1.5)
batched = BatchedMCTS(env, test_cfg)
tests.test_batched_mcts(lambda boards, add_noise=False: batched.search(test_model, boards, add_noise), test_model)