3️⃣ Simulating Vectorized AlphaZero MCTS
Learning Objectives
- Understand how we can restructure the sequential version to batch the
evaluatestage of the MCTS algorithm.- Understand both Root Parallelization and Tree Parallelization, how they work, and why Root Parallelization is suited for implementing in PyTorch.
- Build a simulated version of Root Parallelization that uses the sequential version as the backend.
Your single-game MCTS is correct but slow: one network call per simulation, on a single board. A GPU wants big batches. To train in minutes we need to run hundreds of self-play games at once, with every per-simulation network call batched into one forward pass.
Root Parallelism (we do this)

We run batch_size independent games, each with its own search tree. The trees never interact.
(Each worker's root $s_0$ in the figure is its own game's current board, and what gets aggregated is the replay buffer.
This is a variant of what the literature calls root parallelization (Chaslot et al., 2008):
there, several independent trees all search from the same position, and their root visit counts are summed to choose
a single move. We use independent trees too, but give each one a different game.)
We batch them purely for GPU throughput: after all workers have finished selection and expansion,
we collect all the nodes together and do a single forward pass through the network to evaluate all
the leaves in one go. All trees then backup the values to their respective roots.
After the MCTS search is done, from each tree $T_i$ we derive a respective tree policy $\pi_i$, and
we sample an action from each to get a set of batch_size many actions,
and then step all batch_size many environments by one timestep.
During the training phase, we collect data $(z,s, \pi)$ from all of the environment rollouts, and train the actor/critic network according to the loss mentioned earlier:
The fact that all trees share the same network is the only mechanism by which the trees can causally affect each other.
What gives us the sheer speed is that everything runs on the GPU:
- All of the trees, as well as the operations on them are written as vectorized operations on the GPU. Each operation (walking down or up the tree, updating nodes) are all performed in lockstep, so there is no need to synchronize between threads. The downside of this approach is the additional complication that not all leaf nodes will be at the same depth, nor do all games run for the same number of steps. We will see how to handle this.
- The environment itself is vectorized, we can easily run many thousands of games in parallel, and the rules for updating
the game state, or checking for a winner, are all written as vectorized PyTorch operations (e.g. the operation of checking for a 4-in-a-row can be written as a convolution using kernels with hardcoded weights, see
game.py)
At no point do we need to copy any data back and forth between the CPU or the GPU, as all the data is generated by interaction with the environment, and for a game like Connect-4, the state space is relatively small, and the length of the games reasonably bounded, so the memory usage is not a concern. Expect somewhere in the range 200k-1M steps per second during self-play, depending on your GPU. The environment on its own can run at tens of millions of steps per second, so the search, not the game rules, is the bottleneck.
Tree Parallelism (too complex for us)

We could have used one shared tree with many workers descending it simultaneously. It can be more sample-efficient as all workers pool their statistics into one tree, whereas classic root parallelization (several trees searching the same position) can be wasteful, as the trees duplicate much of each other's work. But we have a different problem: Several workers running up and down the tree to update nodes leads to node contention: workers may have to wait for a node to be free while another worker is updating it, else we may read out a stale value, or worse, overwrite another worker's updates.
This can be solved with mutexes: when a worker wants to write to a node, it first locks it so no other worker can, reads the value, processes it, and then writes back the new value. With several workers waiting for the same node (e.g. the root node), this can negate the gains one hoped to get from tree parallelism. A second problem is that workers tend to all descend the same most promising path. The standard fix is a virtual loss: a worker temporarily counts its path as visited and lost while its evaluation is pending, which steers the other workers elsewhere. It also means you could hash the board state before expanding to see if the node already exists somewhere else, and then jump there instead. This means your MCTS search is operating over a DAG (directed acyclic graph) instead of a tree, leading to some complications on keeping track of the path from a given leaf to the root node. This is a nightmare to write vectorized on the GPU (trust me, I tried!), you would instead write the tree updating code in highly optimized C++, and then have data shuffled back and forth between the CPU and the GPU when you want to query the network (this was also a nightmare when I tried it).
Tree Parallelism is (to the best of my knowledge) the method that DeepMind used for AlphaZero, but we use root parallelism instead as it's much easier to implement as vectorized code on the GPU, and the speed gains from having everything be on the GPU outweigh the sample-efficiency we'd gain from pooling statistics into a shared tree.
A stepping stone: batch the network, keep the Python trees
Before we rewrite everything as vectorised tensor ops, here's a much gentler version that already captures the two ideas that make root parallelism fast:
We keep B completely independent single-game trees, each driven by section 2's select and
backup; expansion is the class's own (per-game) _expand, and evaluation its batched _vec_evaluate.
Per MCTS simulation we:
- select + expand each tree, sequentially with a plain Python
forloop, collecting one leaf node per tree (pretending they run in parallel); - evaluate all
Bleaves in a single fixed-size forward pass through the network; - backup each tree, again sequentially with a
forloop (pretending they run in parallel).
In principle both loops could be accelerated by dispatching multiple worker processes:
from concurrent.futures import ProcessPoolExecutor
#each piece of data processed individually by `work`
def work(x):
...
return something
data = [1, 2, 3, 4, 5]
with ProcessPoolExecutor() as ex:
results = list(ex.map(work, data))
but the overhead of spawning processes, and copying data CPU <-> GPU would kill us. (Threads would not help here either: the tree walks are pure Python, so the Global Interpreter Lock serialises them anyway.)
Two details bring it closer to the real vectorised search:
- A shared board pool. Rather than every node owning its own
(1,)Board, we keep onepoolBoardof batch shape(B, MAXN)and each node just stores an integerslotpointing into it. The root boards go in once (pool[:, 0] = root_boards); the per-simulation batch is then a single gather out of the pool, with no packing/unpacking. This is exactly the storage scheme of the vectorisedTreebelow. - A fixed-size batch. We push all
Bleaves through the network every simulation, including terminal ones whose value we already know. Re-evaluating a terminal leaf is wasted compute, but a constantB-shaped forward pass every step is both faster on the GPU and faithful to the vectorised search, where the batch shape never changes. This also works better witht.compilefor extra speed.
The gains are minimal (I measured ~1.9x speed-up against the purely sequential version), but it's a good starting point.
class SimulatedBatchedMCTS:
"""Root-parallel MCTS over `B` independent trees, with the network call batched across trees.
A clarity-first stand-in for the vectorised `BatchedMCTS` below, with the **same interface**: hold
an `env` + `cfg`, then call `.search(model, root_boards)`. Every tree is a normal
Python `Node` tree driven by the section 2 `select`/`backup` functions, looped over the batch. The two
things it borrows from the vectorised version are (i) a single board `pool` that every node indexes
by `slot` (so boards never need packing/unpacking), and (ii) a fixed-size forward pass over all
`B` leaves every simulation, terminal leaves included.
Each node stores an integer `slot` instead of its own board: its position lives at
`pool[game, slot]`. (`Node.board` is left as `None` since none of `select`/`backup` read it.)
"""
def __init__(self, env, cfg):
self.env, self.cfg = env, cfg
@t.no_grad()
def _expand(self, pool, num_nodes, game, node, action):
"""Section 2's `expand` function, but the child's board is written into the pool and the child stores its `slot`."""
parent_board = pool[game, node.slot] # one game's board, unbatched
next_board, done, reward = self.env.step(parent_board, action) # done, reward: python scalars
slot = num_nodes[game]
num_nodes[game] += 1
pool[game, slot] = next_board
child = Node(board=None, is_terminal=done, terminal_value=-reward,
parent=node, parent_action=action)
child.slot = slot
node.children[action] = child
return child
@t.no_grad()
def _vec_evaluate(self, model, pool, batch_idx, nodes):
"""Evaluate all `B` leaves in ONE fixed-size forward pass; return one value per node.
Terminal leaves are forwarded too (their board is gathered from the pool like any other) even
though we throw away the network's output and use the value stored at creation. The constant
`B`-shaped batch matches the vectorised search and is faster than a ragged one.
"""
slots = t.tensor([node.slot for node in nodes], device=batch_idx.device)
boards = pool[batch_idx, slots] # (B,) Board, one gather
value, logits = model(boards) # <- one batched call, all B nodes
value, logits = value.float(), logits.float() # keep node stats fp32 even if the net runs in bf16
legal = self.env.legal_action_mask(boards)
P = t.softmax(t.where(legal, logits, -t.inf), dim=-1)
value, legal, P = value.cpu(), legal.cpu(), P.cpu()
values = []
for b, node in enumerate(nodes):
if node.is_terminal:
values.append(node.terminal_value) # value known at creation; net output discarded
else:
node.legal = legal[b]
node.P = P[b]
values.append(float(value[b]))
return values
@t.no_grad()
def search(self, model, root_boards: Board, add_noise: bool = False) -> Float[Tensor, "B 7"]:
"""Run `cfg.sims` simulations of root-parallel MCTS from the (B,) `root_boards`; return (B, 7)
root visit counts. Same signature as `BatchedMCTS.search`, just sequential-over-trees (so much slower)."""
cfg = self.cfg
B, device = root_boards.shape[0], root_boards.obs.device
batch_idx = t.arange(B, device=device)
# Shared board pool: every node just stores a `slot` into this, so we never pack/unpack boards.
# At most one node is added per simulation, so `cfg.sims + 1` slots per game (slot 0 = root)
# can never overflow.
pool = Board(t.zeros((B, cfg.sims + 1, *root_boards.obs.shape[1:]), device=device),
t.zeros((B, cfg.sims + 1), dtype=t.bool, device=device))
pool[:, 0] = root_boards # drop in all root boards at once (slot 0)
num_nodes = [1] * B # next free slot per game
# construct the roots of the trees, each pointing at slot 0 of its game's pool
roots = []
for b in range(B):
node = Node(board=None)
node.slot = 0
roots.append(node)
# evaluate every root in one forward pass to set its P / legal (as section 2 does for its single root)
self._vec_evaluate(model, pool, batch_idx, roots)
if add_noise: # batched Dirichlet noise on the root priors, exactly as `vec_mcts` does it
P = dirichlet_root_noise(t.stack([r.P for r in roots]), t.stack([r.legal for r in roots]),
cfg.dirichlet_alpha, cfg.dirichlet_eps)
for b, root in enumerate(roots):
root.P = P[b]
for _ in range(cfg.sims):
# 1. SELECT + EXPAND each tree sequentially, collecting one leaf per tree
leaves = []
for game, root in enumerate(roots):
node, action = select(root, cfg.c_puct)
leaf = node if node.is_terminal else self._expand(pool, num_nodes, game, node, action)
leaves.append(leaf)
# 2. EVALUATE every leaf in a single, fixed-size forward pass through the network
values = self._vec_evaluate(model, pool, batch_idx, leaves)
# 3. BACKUP each tree sequentially
for leaf, value in zip(leaves, values):
backup(leaf, value)
return t.stack([root.N for root in roots]).to(device) # (B, 7), on the input's device
tests.test_simulated_batched_mcts(SimulatedBatchedMCTS)
Unsurprisingly, this barely helps: the bottleneck is the Python loop over the trees, not the network. Here's the search speed at the defaults (8192 games, 16 simulations per move, RTX A4000), in simulations per second (one env step and one leaf evaluation per tree):
| implementation | simulations / s | speedup |
|---|---|---|
sequential trees, sequential network (section 2's mcts, one game at a time) |
555 | 1× |
sequential trees, batched network (SimulatedBatchedMCTS) |
1,040 | 1.9× |
batched everything (BatchedMCTS) |
234,000 | 420× |
Batching only the network roughly doubles the speed. Vectorising selection, expansion and backup as well turns one 8192-game search from about 2 minutes into about half a second. (The two versions that loop over trees in Python run at the same speed whatever the batch size, so they were timed on 256 games.)
For now, we will take for granted the vectorized implementation of MCTS, which provides
a functionally identical BatchedMCTS.search method as SimulatedBatchedMCTS.search above,
but implemented such that selection, expansion and backup are
also vectorized.
As a bonus at the end you can try implementing the vectorized version yourself.