Monte Carlo Tree Search
Selective lookahead with a bandit at every node.
Judge each candidate move by the average result of thousands of random games played from it, and in the tic-tac-toe position of this lesson you will pick the center, which only draws, over a corner that wins by force. Monte Carlo tree search repairs this by growing a tree in which every node runs its own bandit, so its averages drift from random-play values toward minimax values. This lesson builds MCTS phase by phase, runs it, reads it as reinforcement learning, and follows it from Go programs to AlphaGo.
What you’ll learn
- Explain why full-width minimax search and flat Monte Carlo evaluation both fail in large games, using a position where random play misjudges the best move.
- Implement the four phases of MCTS (selection, expansion, simulation, backup) with the UCT tree policy.
- Compute UCT scores by hand and predict how the exploration constant shapes the search.
- Interpret MCTS as Monte Carlo control on simulated episodes, and explain how AlphaGo's PUCT rule adds learned priors and values.
From minimax to sampling
In a two-player game with known rules the model is given, and planning means looking ahead through the game tree. Minimax search backs values up the tree: at your turn take the maximum over your moves, at the opponent's the minimum. With legal moves per turn and turns to the end it examines about positions; alpha–beta pruning with perfect move ordering cuts that to roughly . Silver et al. (2016) put chess at , and Go at , . Searching to a fixed depth instead needs an evaluation function for the positions where it stops, and for Go nobody managed to write a good one.
Flat Monte Carlo evaluation needs no evaluation function: play many games from each candidate move with uniformly random moves for both sides, and pick the move with the best average result. Its flaw is what it estimates: the value of a move if everyone plays randomly afterward, not if both sides play well.
Take the position with X in the top middle, O in the bottom-right corner, and X to move. The exact outcome probabilities under random play, and the minimax values, are:
| X plays | X wins | Draw | O wins | Minimax value |
|---|---|---|---|---|
| Center | 66.1% | 5.0% | 28.9% | draw |
| Top-right corner | 63.3% | 0% | 36.7% | X wins |
| Top-left corner | 56.1% | 10.0% | 33.9% | O wins |
With enough random playouts, which move does flat Monte Carlo evaluation choose in this position, scoring a win as 1 and a draw as ½?
- The top-right corner, the only winning move
- The center
- The top-left corner
- It cannot decide: all moves look equal under random play
Show the answer
B. The center
Random play scores the center and the winning corner . The averages converge, but to the wrong quantity: random opponents rarely make the forced blocks that best play requires, so the corner's forcing line earns no extra credit.
The four phases of a simulation
Monte Carlo tree search keeps a tree of the positions it has reached, rooted at the current one, with a visit count and a total reward at every node. Each simulation has four phases:
- Selection. From the root, descend through nodes whose moves have all been tried, choosing a child with the tree policy.
- Expansion. At a node with untried moves, add one new child.
- Simulation. From the new node, play to the end of the game with the rollout policy, here uniformly random moves.
- Backup. Add 1 to and the result to at every node on the path.
Because good moves are selected more often, the tree grows deep along promising lines and stays shallow elsewhere. In a two-player game each node stores rewards from the point of view of the player who moved into it, so maximizing at every level is minimax in disguise.
import math, random
class Node:
def __init__(self, state, parent=None):
self.state, self.parent, self.children = state, parent, {}
self.untried = list(state.legal_moves())
self.N, self.W = 0, 0.0 # visits; total reward of the player who moved INTO this node
def uct_search(root_state, n_simulations, c=1.4):
root = Node(root_state)
for _ in range(n_simulations):
node = root
while not node.untried and node.children: # 1. selection
node = max(node.children.values(),
key=lambda ch: ch.W / ch.N + c * math.sqrt(math.log(node.N) / ch.N))
if node.untried: # 2. expansion
move = node.untried.pop(random.randrange(len(node.untried)))
node.children[move] = Node(node.state.play(move), parent=node)
node = node.children[move]
state = node.state
while not state.is_over(): # 3. simulation
state = state.play(random.choice(state.legal_moves()))
while node is not root: # 4. backup
node.N += 1
node.W += state.score_for(node.state.last_mover()) # 1 win, 0.5 draw, 0 loss
node = node.parent
root.N += 1
return max(root.children, key=lambda m: root.children[m].N) # most-visited moveUCT for any two-player game whose state object offers legal_moves, play, is_over, last_mover and score_for. The search returns the most-visited move, the robust choice: a high average built on few visits is noise, while visits concentrate on moves that stayed good under scrutiny.
Three properties follow from the design. MCTS is anytime: stop it after any number of simulations and it has a best guess, which improves with more. It is asymmetric: computation flows to the moves that matter. And it needs no evaluation function: the random playouts provide values, crude but unbiased for the random-play question they answer, and the tree corrects them where it grows deep.
In reinforcement learning terms (Sutton & Barto, §8.11), MCTS is Monte Carlo control applied to simulated episodes that all start at the current state. The tree stores action values for the states it has expanded, the tree policy is the behavior policy there (a bandit rule instead of -greedy), the rollout policy covers everything outside the tree, and each simulation's return updates the averages along its path. The search is thrown away, or partly reused, after the move is played.
UCT: a bandit at every node
A single bandit with i.i.d. rewards has logarithmic regret under UCB1 (The Regret of UCB, Proved). Inside a tree the rewards are not i.i.d.: a child's average drifts as the search below it improves. Kocsis and Szepesvári extended the analysis to such drifting payoffs and showed that, with enough simulations, UCT's probability of choosing a suboptimal move at the root goes to zero; MCTS in Depth: UCT, PUCT & What Search Optimizes states the conditions and the catches.
The exploration constant sets the character of the search. At it is greedy: a move whose first playouts went badly may never be tried again. As grows, visits spread evenly and the search degenerates into flat Monte Carlo with a shallow tree.
A node has been visited times and its three children have equal to A: , B: , C: . With , which child does UCT select next?
- A, with the middle average
- B, the least visited
- C, with the best average
- All three tie
Show the answer
B. B, the least visited
With : A scores , B scores , C scores . B's average is the lowest, but two visits leave it very uncertain. Even if both of B's playouts had been losses it would score about and still be chosen: two playouts are almost no evidence.
From Go programs to AlphaGo: priors and learned values
AlphaGo (Silver et al., 2016) kept the search and replaced its weakest parts with neural networks. A policy network trained on expert games supplied a prior over moves; a value network estimated the outcome from a position, mixed at the leaves with the result of a fast rollout. The tree policy became PUCT: the prior steers exploration toward moves a strong player would consider. AlphaGo Zero (2017) went further, dropping rollouts altogether, and its successors use the same rule.
Think first PUCT's bonus grows like at the parent and UCT's like . Which explores more in the long run, and why might that suit the root of a search?
PUCT. For a fixed child the bonus keeps growing like , so every move with a positive prior is revisited again and again: a suboptimal move with gap ends up with on the order of visits instead of UCT's . Spending on rival moves is wasteful if you are scored by cumulative reward during the search, but the root is scored only by the quality of its final choice, and extra exploration there buys confidence in that choice. The Fixed Point lesson on PUCT derives the rate and shows what the visit counts are computing.
Key takeaways
- Full-width minimax costs about positions (about with ideal alpha–beta), hopeless for Go's ; flat Monte Carlo needs no evaluation function but estimates random-play values, which can rank a drawing move above a winning one.
- MCTS repeats selection, expansion, simulation and backup; good moves are selected more often, so the tree grows deep where it matters, and the search is anytime and asymmetric.
- UCT runs UCB1 at every node, ; trades greedy collapse against flat sampling, and the most-visited root move is played.
- MCTS is Monte Carlo control on simulated episodes from the current state; AlphaGo added a policy prior (PUCT) and a value network, and AlphaGo Zero dropped rollouts entirely.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Flat Monte Carlo evaluates each move by the average result of uniformly random playouts. As the number of playouts grows, what does each average converge to?
- The move's minimax value
- The expected result of the move when both players continue at random
- The value of the best leaf reachable after the move
- It does not converge
Show the answer
B. The expected result of the move when both players continue at random
By the law of large numbers the average converges to the expectation under the playout policy, here uniformly random play by both sides. That can rank moves differently from best play, as the center and the winning corner show. MCTS's tree turns the averages near the root into estimates under increasingly good play.
What goes wrong with UCT when the exploration constant is set to ?
- The search becomes uniform, like flat Monte Carlo
- It never expands new nodes
- It becomes greedy on current averages, so a move whose first playouts went badly may never be tried again
- It converges faster to the minimax value
Show the answer
C. It becomes greedy on current averages, so a move whose first playouts went badly may never be tried again
Without the bonus, selection always picks the child with the best current average. Averages from a handful of random playouts are very noisy, so a strong move that started unluckily can be abandoned forever. The bonus guarantees that every child keeps being revisited, ever more rarely.
Why does MCTS usually play the most-visited root move rather than the one with the highest average value?
- Visit counts are cheaper to compute
- The highest average is always the most-visited move anyway
- It explores more during the game
- A high average from few visits is noisy, while many visits mean the move kept looking good under repeated scrutiny
Show the answer
D. A high average from few visits is noisy, while many visits mean the move kept looking good under repeated scrutiny
The tree policy keeps sending simulations to moves that hold up, so the visit count integrates the whole history of the search. A rarely visited move can show a lucky high average. AlphaZero likewise turns visit counts, not averages, into its move choice and training target.
In AlphaGo Zero's PUCT rule, what role does the network's prior play?
- It scales each move's exploration bonus, so the search tries moves the policy network rates as plausible first
- It replaces the value estimate
- It decides the final move directly, without search
- It is the probability of winning after the move
Show the answer
A. It scales each move's exploration bonus, so the search tries moves the policy network rates as plausible first
The prior multiplies the bonus , focusing a limited budget on a few promising moves among hundreds of legal ones. As visits accumulate the bonus shrinks and the averaged values take over.
Go deeper
- MCTS in Depth: UCT, PUCT & What Search Optimizes · From UCT’s guarantees to the PUCT rule and MCTS as regularized policy optimization.
- Search as Policy Improvement: AlphaZero · Policy and value networks trained by search, and search improved by networks.
- MuZero: Planning with a Learned Model · Value-equivalent models that plan without predicting observations.
Further reading
- L. Kocsis & C. Szepesvári, "Bandit based Monte-Carlo planning," ECML (2006).
- R. Coulom, "Efficient selectivity and backup operators in Monte-Carlo tree search," Computers and Games (2006; LNCS 4630, 2007).
- C. B. Browne et al., "A survey of Monte Carlo tree search methods," IEEE Transactions on Computational Intelligence and AI in Games 4(1), 1–43 (2012).
- D. Silver et al., "Mastering the game of Go with deep neural networks and tree search," Nature 529, 484–489 (2016).