Simple Algorithm
Reinforcement Learning · Bootstrapping · 22 min

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 bb legal moves per turn and dd turns to the end it examines about bdb^d positions; alpha–beta pruning with perfect move ordering cuts that to roughly bd/2b^{d/2}. Silver et al. (2016) put chess at b≈35b\approx35, d≈80d\approx80 and Go at b≈250b\approx250, d≈150d\approx150. 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 playsX winsDrawO winsMinimax value
Center66.1%5.0%28.9%draw
Top-right corner63.3%0%36.7%X wins
Top-left corner56.1%10.0%33.9%O wins
Computed exactly by enumerating every random continuation. Three of X's other four moves also lose against best play. The top-right corner wins by force: it threatens the top row, O must block in the top-left corner, which in turn threatens the diagonal, and X's reply in the center blocks it while creating two threats at once.
Check your understanding

With enough random playouts, which move does flat Monte Carlo evaluation choose in this position, scoring a win as 1 and a draw as ½?

  1. The top-right corner, the only winning move
  2. The center
  3. The top-left corner
  4. It cannot decide: all moves look equal under random play
Show the answer

B. The center

Random play scores the center 0.661+0.025=0.6860.661+0.025=0.686 and the winning corner 0.6330.633. 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 NN and a total reward WW at every node. Each simulation has four phases:

  1. Selection. From the root, descend through nodes whose moves have all been tried, choosing a child with the tree policy.
  2. Expansion. At a node with untried moves, add one new child.
  3. Simulation. From the new node, play to the end of the game with the rollout policy, here uniformly random moves.
  4. Backup. Add 1 to NN and the result to WW 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.

python
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 move

UCT 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 ε\varepsilon-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

select the child j maximizingWjNj+c ln⁡NNj\text{select the child } j \text{ maximizing}\qquad\frac{W_j}{N_j}+c\,\sqrt{\frac{\ln N}{N_j}}
UCT (Kocsis & Szepesvári, 2006): every node runs UCB1 over its children, with NN the node's own visit count. The first term exploits the child's average, the second explores children that have had few visits. With rewards in [0,1][0,1], UCB1's own constant is c=2≈1.41c=\sqrt2\approx1.41.

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 cc sets the character of the search. At c=0c=0 it is greedy: a move whose first playouts went badly may never be tried again. As cc grows, visits spread evenly and the search degenerates into flat Monte Carlo with a shallow tree.

Check your understanding

A node has been visited N=20N=20 times and its three children have (Nj,Wj)(N_j,W_j) equal to A: (6,4)(6,4), B: (2,1)(2,1), C: (12,9)(12,9). With c=1.4c=1.4, which child does UCT select next?

  1. A, with the middle average
  2. B, the least visited
  3. C, with the best average
  4. All three tie
Show the answer

B. B, the least visited

With ln⁡20≈3.00\ln20\approx3.00: A scores 0.667+1.43.00/6≈1.660.667+1.4\sqrt{3.00/6}\approx1.66, B scores 0.5+1.43.00/2≈2.210.5+1.4\sqrt{3.00/2}\approx2.21, C scores 0.75+1.43.00/12≈1.450.75+1.4\sqrt{3.00/12}\approx1.45. 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 1.711.71 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 P(s,a)P(s,a) 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.

a⋆=arg max⁡a[ Q(s,a)+cpuct P(s,a) ∑bN(s,b)1+N(s,a) ]a^\star=\argmax_a\Big[\,Q(s,a)+c_{\text{puct}}\,P(s,a)\,\frac{\sqrt{\sum_bN(s,b)}}{1+N(s,a)}\,\Big]
The PUCT rule of AlphaGo Zero. Q(s,a)Q(s,a) averages value-network estimates from the subtree. Compared with UCT, the bonus is shaped by the prior and decays like 1/N(s,a)1/N(s,a) instead of 1/N(s,a)1/\sqrt{N(s,a)}, so with a small budget a move with a tiny prior may never be visited at all.
Think first PUCT's bonus grows like N\sqrt N at the parent and UCT's like ln⁡N\sqrt{\ln N}. 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 N\sqrt N, so every move with a positive prior is revisited again and again: a suboptimal move with gap Δ\Delta ends up with on the order of N\sqrt N visits instead of UCT's ln⁡N\ln N. 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 N\sqrt N rate and shows what the visit counts are computing.

Key takeaways

  • Full-width minimax costs about bdb^d positions (about bd/2b^{d/2} with ideal alpha–beta), hopeless for Go's b≈250b\approx250; 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, Wj/Nj+cln⁡N/NjW_j/N_j+c\sqrt{\ln N/N_j}; cc 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.

Question 1

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?

  1. The move's minimax value
  2. The expected result of the move when both players continue at random
  3. The value of the best leaf reachable after the move
  4. 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.

Question 2

What goes wrong with UCT when the exploration constant is set to c=0c=0?

  1. The search becomes uniform, like flat Monte Carlo
  2. It never expands new nodes
  3. It becomes greedy on current averages, so a move whose first playouts went badly may never be tried again
  4. 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.

Question 3

Why does MCTS usually play the most-visited root move rather than the one with the highest average value?

  1. Visit counts are cheaper to compute
  2. The highest average is always the most-visited move anyway
  3. It explores more during the game
  4. 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.

Question 4

In AlphaGo Zero's PUCT rule, what role does the network's prior P(s,a)P(s,a) play?

  1. It scales each move's exploration bonus, so the search tries moves the policy network rates as plausible first
  2. It replaces the value estimate Q(s,a)Q(s,a)
  3. It decides the final move directly, without search
  4. 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 ∑bN(s,b)/(1+N(s,a))\sqrt{\sum_bN(s,b)}/(1+N(s,a)), focusing a limited budget on a few promising moves among hundreds of legal ones. As visits accumulate the bonus shrinks and the averaged values QQ take over.

Go deeper

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).