◆ AI All-in-One

Level 3 In-Depth AI · Reinforcement Learning

Monte Carlo Tree Search and AlphaGo

How a computer plans by playing out the future. Monte Carlo tree search grows a game tree towards promising moves, and AlphaGo, AlphaZero and MuZero guide it with neural networks trained by self-play.

Level
●●●●● Advanced
Reading
15 min
To learn it well
1.5 hours to read, an afternoon to practise
↗ Plan a path here

Read first

Markov Decision ProcessesNeural Networks

This leads to

—
The full path from zero — 16 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. Vectors
  4. Derivatives and Slopes
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Gradient Descent
  10. Supervised Learning
  11. Reinforcement Learning: The Basics
  12. Linear Regression
  13. The Perceptron
  14. Markov Decision Processes
  15. Logistic Regression
  16. Neural Networks
  17. Monte Carlo Tree Search and AlphaGo

Read them roughly in this order. See it on the concept map →

Why it matters

The agents in Q-Learning and Policy Gradients react. They look at the current state and answer immediately from what they have learned. Strong human players do something else as well: they think ahead. "If I play here, they'll probably answer there, and then I can…". Planning lets an agent handle situations its learned instincts get wrong, by checking the consequences before committing.

Monte Carlo tree search (MCTS) is the most successful general way for a computer to plan in games and other decision problems. It needs no hand-written knowledge of what a good position looks like. It explores the future by simulation and focuses its effort on the moves that look most promising.

Combined with deep neural networks and reinforcement learning, MCTS produced one of AI's landmark moments. In March 2016 DeepMind's AlphaGo beat Lee Sedol, one of the world's strongest Go players, 4 games to 1. Go had long been considered decades out of reach. Its successors, AlphaGo Zero, AlphaZero and MuZero, learned with no human examples at all, then mastered chess and shogi too, and finally did it without even being told the rules. The same "search plus learned intuition" recipe now appears in Model-Based RL and World Models and, in a looser form, in the extra thinking that Reasoning Models and Test-Time Compute do at test time.

The intuition

Imagine choosing a move in a board game you barely know. One honest approach: for each possible move, play it, then finish the game with completely random moves, and see who wins. Repeat many times. A move that wins 70% of its random playouts is probably better than one that wins 30%. Such a random playout is called a rollout. Using random samples to estimate an average is what Monte Carlo means, after the casino.

That works, but it wastes effort. Why spend thousands of playouts on a move that clearly loses? MCTS builds a search tree, a map of the positions it has explored and how often each led to a win. It spends its simulations where they matter most. This is the same exploration–exploitation trade-off as in Multi-Armed Bandits and Exploration. Each node of the tree is a little bandit problem: "which of my moves should I try next?". A move with a high win rate deserves more attention (exploit), and a move that has hardly been tried deserves a look (explore).

Each simulation has four phases:

  1. Selection. Start at the current position (the root). Walk down the tree, at each node picking the child with the best balance of high win rate and few visits.
  2. Expansion. On reaching a node with an untried move, add that move's position to the tree as a new child.
  3. Simulation. From the new node, play out the rest of the game (randomly, in plain MCTS) to get a result.
  4. Backpropagation. Walk back up the path and update each node's statistics, adding one to its visit count and adding the result to its total.
6/10 4/6 2/4 1/2 3/3 1. Selection walk down, picking the child with the best UCB score 6/10 4/6 2/4 1/2 3/3 0/0 2. Expansion add one new child (an untried move) 6/10 4/6 2/4 1/2 3/3 0/0 win game over 3. Simulation play randomly to the end (AlphaZero: ask the value net) 7/11 5/7 2/4 1/2 4/4 1/1 4. Backpropagation add the result to every node on the path numbers in nodes: wins / visits, counted for the player to move at the root
Fig. 1 The four phases of one MCTS simulation. Selection follows the most promising path (orange). Expansion adds one new node. Simulation plays to the end of the game. Backpropagation adds the result to every node on the path.

After thousands of simulations, the tree is deep where the play is critical and shallow elsewhere. The move to play is the root's most-visited child. That is more robust than "highest win rate", because a high rate from three visits may be luck.

Key idea MCTS plans by repeated simulation. Select a path with a bandit rule, expand one new node, simulate to an outcome, back up the result. AlphaGo-style systems replace random choices with a learned policy network (which moves to try) and the random playout with a learned value network (who is winning).

How it works

UCT: a bandit at every node

The selection rule in classic MCTS is UCT (Upper Confidence bounds applied to Trees; Kocsis and Szepesvári, 2006). It is the UCB1 rule from Multi-Armed Bandits and Exploration, applied at every node. From a node visited NN times, choose the child ii that maximises

WiNi+cln⁡NNi\frac{W_i}{N_i} + c \sqrt{\frac{\ln N}{N_i}}

Wi/NiW_i/N_i is child ii's average result (wins count 1, draws ½, losses 0), from the point of view of the player choosing at this node. The second term is an exploration bonus. It is large for rarely visited children and shrinks as they are tried. The constant cc balances the two, and 2≈1.4\sqrt 2 \approx 1.4 is the textbook choice.

In a two-player game, each level of the tree belongs to the other player. So each node's statistics must be counted from the view of the player who chooses there, and a win for one side is a loss for the other. Getting this sign flip wrong is the classic MCTS bug.

Worked example. A node has been visited N=100N = 100 times. Child A: 40 wins in 60 visits. Child B: 5 wins in 10 visits. With c=1.4c = 1.4 and ln⁡100=4.61\ln 100 = 4.61:

  • A: 40/60+1.44.61/60=0.667+0.388=1.05540/60 + 1.4\sqrt{4.61/60} = 0.667 + 0.388 = 1.055
  • B: 5/10+1.44.61/10=0.500+0.951=1.4515/10 + 1.4\sqrt{4.61/10} = 0.500 + 0.951 = 1.451

B is selected. Its win rate is lower, but it has been explored so little that it might be better. As B gets more visits its bonus shrinks, and if its true rate is lower, A takes over again.

Given enough simulations, UCT's estimates converge to the true minimax values of the game. MCTS is also an anytime algorithm: stop it whenever you like and it returns its best answer so far.

AlphaGo (2016): search guided by learned intuition

Go has about 2×101702 \times 10^{170} legal positions and around 250 legal moves per turn, compared with about 35 in chess. Random rollouts in Go are a poor guide to who is winning, and before AlphaGo the best MCTS programs played at a strong amateur level. AlphaGo (Silver et al., Nature, January 2016) added deep convolutional networks (Convolutional Neural Networks) that look at the board as a 19 × 19 image:

  • A policy network, trained by supervised learning to predict expert moves from about 30 million positions from the KGS online Go server. It predicted the expert's move 57% of the time. It was then improved by self-play reinforcement learning with Policy Gradients.
  • A value network, trained to predict the winner from a position, using positions from millions of self-play games.
  • A small, fast rollout policy for quick playouts.

In the search, the policy network's probabilities act as a prior that steers selection towards moves an expert would consider. Leaf positions are evaluated by mixing, half and half, the value network's prediction with the result of a fast rollout. AlphaGo beat the European champion Fan Hui 5–0 in October 2015, and Lee Sedol 4–1 in Seoul in March 2016. Its move 37 in game two, a play on the fifth line that commentators first took for a mistake, became a symbol of machines finding ideas humans had overlooked. Lee's own move 78 in game four, which won him that game, became just as famous.

AlphaGo Zero and AlphaZero: learning from scratch

AlphaGo Zero (Nature, October 2017) threw away the human data and the rollouts. It used one deep residual network with two heads. Given a position ss, it outputs move probabilities p\mathbf{p} and a value vv (the expected outcome). Training is a loop of self-play:

  1. Play games against itself. At each move, run MCTS (1,600 simulations per move in AlphaGo Zero), using the network to guide and evaluate. Play a move sampled in proportion to the root's visit counts π\boldsymbol{\pi}.
  2. Train the network so that its policy head matches the search's visit counts π\boldsymbol{\pi} and its value head predicts the actual game result zz (+1+1 for a win, −1-1 for a loss):
L=(z−v)2−π⊤log⁡p+c ∥θ∥2L = (z - v)^2 - \boldsymbol{\pi}^\top \log \mathbf{p} + c\,\lVert \theta \rVert^2

The first term is a squared error on the value, the second is a cross-entropy pulling the policy towards the search result, and the third is weight decay. 3. Repeat. The improved network makes the search stronger, and the stronger search produces better training targets.

The key insight is that search acts as a policy-improvement operator. MCTS guided by the network plays better than the network alone, so imitating the search's choices makes the network better. This is generalized policy iteration again, with search as the improvement step.

The selection rule became PUCT, which weights the exploration bonus by the network's prior P(s,a)P(s, a):

a=arg⁡max⁡a[Q(s,a)+cpuct P(s,a)∑bN(s,b)1+N(s,a)]a = \arg\max_a \left[ Q(s, a) + c_{\text{puct}}\, P(s, a) \frac{\sqrt{\sum_b N(s, b)}}{1 + N(s, a)} \right]

Q(s,a)Q(s, a) is the mean value of the simulations through move aa, and N(s,a)N(s, a) its visit count. Moves the network likes get explored first, but heavy visiting wears the bonus down. Leaf positions are scored by the value head alone, with no rollouts.

After three days of self-play, AlphaGo Zero beat the version that had defeated Lee Sedol by 100 games to 0. AlphaZero (preprint December 2017, Science December 2018) applied the same algorithm, unchanged apart from the rules, to chess and shogi as well. It beat Stockfish (chess), Elmo (shogi) and AlphaGo Zero (Go).

MuZero: planning without the rules

AlphaZero still needs a perfect simulator. MCTS has to know which position results from each move. MuZero (preprint November 2019, Nature December 2020) removed even that. It learns three functions:

  • Representation hh: encode the current observation into a hidden state.
  • Dynamics gg: given a hidden state and an action, predict the next hidden state and the immediate reward.
  • Prediction ff: from a hidden state, predict the policy and the value.

The search then runs entirely inside this learned model. Crucially, the hidden state is not trained to reconstruct the screen or the board, only to predict what planning needs: rewards, values and policies. MuZero matched AlphaZero at Go, chess and shogi and set a new state of the art on the 57-game Atari benchmark at the time. It is a bridge to Model-Based RL and World Models.

AlphaGo 2015–16 AlphaGo Zero 2017 AlphaZero 2017–18 MuZero 2019–20 Human games? yes: 30 million positions to start none self-play only none self-play only none self-play only Rules given? yes simulator yes simulator yes simulator no learns its own model Networks policy + value + fast rollout policy one ResNet, policy + value heads one ResNet, policy + value heads 3 learned functions encode · step · predict Search leaf value net + rollout mixed 50/50 value net only no rollouts value net only no rollouts in learned latent states Games Go Go Go, chess, shogi Go, chess, shogi + 57 Atari games Headline beat Lee Sedol 4–1 March 2016 beat AlphaGo Lee 100–0 beat Stockfish, Elmo and AlphaGo Zero matched AlphaZero without the rules each step removes something hand-supplied: first human data, then game-specific design, then the rules themselves
Fig. 2 The AlphaGo family. Each generation removed something supplied by humans: first the human game records, then game-specific features and rollouts, then the rules themselves.

In code

A complete MCTS (UCT with random rollouts) for tic-tac-toe in plain Python. The board is a 9-character string, read row by row. Each node stores its visit count N and its total result W, counted for the player who made the move into it.

import math, random

LINES = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
def winner(b):
    for i, j, k in LINES:
        if b[i] != "." and b[i] == b[j] == b[k]: return b[i]
    return "draw" if "." not in b else None
def moves(b): return [i for i, c in enumerate(b) if c == "."]
def play(b, m, p): return b[:m] + p + b[m+1:]
other = {"X": "O", "O": "X"}

class Node:
    def __init__(self, board, player, parent=None, move=None):
        self.board, self.player, self.parent, self.move = board, player, parent, move
        self.children, self.untried = [], moves(board) if winner(board) is None else []
        self.N, self.W = 0, 0.0          # visits, total value (from the view of who moved INTO this node)

def ucb(child, parent_N, c=1.4):         # UCT: exploit (mean value) + explore (bonus)
    return child.W / child.N + c * math.sqrt(math.log(parent_N) / child.N)

def mcts(board, player, n_sims=2000):
    root = Node(board, player)
    for _ in range(n_sims):
        node = root
        while not node.untried and node.children:                 # 1. selection
            node = max(node.children, key=lambda ch: ucb(ch, node.N))
        if node.untried:                                          # 2. expansion
            m = node.untried.pop(random.randrange(len(node.untried)))
            child = Node(play(node.board, m, node.player), other[node.player], node, m)
            node.children.append(child); node = child
        b, p = node.board, node.player                            # 3. simulation (random rollout)
        while winner(b) is None:
            b = play(b, random.choice(moves(b)), p); p = other[p]
        w = winner(b)
        while node is not None:                                   # 4. backpropagation
            mover = other[node.player]                            # the player who made node.move
            node.N += 1
            node.W += 1.0 if w == mover else 0.5 if w == "draw" else 0.0
            node = node.parent
    best = max(root.children, key=lambda ch: ch.N)                # most-visited move
    return best.move, {ch.move: ch.N for ch in root.children}

random.seed(0)
board = "XX." + "OO." + "..."           # X to move: win at 2, or lose to O at 5
move, visits = mcts(board, "X")
print("X plays", move, " visits per move:", dict(sorted(visits.items())))
board = "X.." + ".O." + "..X"           # O to move; one subtle defence needed
move, visits = mcts(board, "O")
print("O plays", move, " visits per move:", dict(sorted(visits.items())))

results = {"X": 0, "O": 0, "draw": 0}   # MCTS (X) against itself (O), 20 games
for game in range(20):
    b, p = "." * 9, "X"
    while winner(b) is None:
        m, _ = mcts(b, p, 1000); b = play(b, m, p); p = other[p]
    results[winner(b)] += 1
print("self-play results:", results)

# X plays 2  visits per move: {2: 1875, 5: 53, 6: 26, 7: 23, 8: 23}
# O plays 3  visits per move: {1: 435, 2: 128, 3: 454, 5: 425, 6: 120, 7: 438}
# self-play results: {'X': 0, 'O': 0, 'draw': 20}

In the first position X can win at once (square 2), and must, because O threatens to win at square 5. MCTS spends 1,875 of its 2,000 simulations on the winning move. The second position is subtler. X holds two opposite corners and O the centre. If O takes a corner, X can set up a double threat and win, so O must play an edge (1, 3, 5 or 7). MCTS discovers this from random playouts alone. It gives each edge about 430–450 visits and each corner only about 120–130. And with 1,000 simulations per move, MCTS playing itself draws all 20 games. That is the perfect-play result for tic-tac-toe.

Nothing in the code knows anything about tic-tac-toe strategy. It only knows the rules (moves, play, winner). AlphaZero's code has the same skeleton. Swap the random rollout for a call to the value network, use network priors in the selection rule, and train the network on the search's own visit counts.

Common pitfalls

  • Sign errors in two-player games. Each node's value must be from the perspective of the player choosing at its parent. If you back up the same number to every node, the search helps the opponent.
  • Choosing the move by win rate instead of visits. A child with 3 wins out of 3 visits looks perfect but means little. Pick the most-visited child, or one that is best on both.
  • Too few simulations. MCTS is only as good as its budget. With 50 simulations it blunders even at tic-tac-toe. Strength grows steadily with more thinking time.
  • Random rollouts that mislead. In games where random play is nothing like good play, such as Go, random playouts give a biased value. That is the reason for AlphaGo's value network.
  • Hidden information and chance. Plain MCTS assumes a deterministic game with perfect information. Card games and dice need extensions, such as sampling the hidden cards or adding chance nodes.

Watch out AlphaZero-style training is extremely compute-hungry. AlphaZero's chess training generated its self-play games on 5,000 first-generation TPUs. Small reproductions (for example on Connect Four) are very instructive, but expect hours of computing even for simple games.

Variations

  • Pure MCTS programs before AlphaGo: Rémi Coulom's Crazy Stone (2006) and later MoGo brought Go programs from weak to strong amateur level and started the MCTS revolution.
  • Open-source successors: Leela Zero (Go) and Leela Chess Zero (chess) reproduced AlphaZero with volunteer computing. KataGo improved the efficiency of self-play training by a large factor.
  • Other uses of MCTS: general game playing, scheduling and combinatorial optimisation. AlphaTensor (2022) searched for faster matrix-multiplication algorithms, and AlphaDev (2023) found faster sorting routines, both with AlphaZero-style search.
  • Imperfect information: poker bots such as Libratus and Pluribus used a different family of methods (counterfactual regret minimisation) with search. Student of Games (2023) unified search across perfect- and imperfect-information games.
  • Search for language models: using a learned value model to guide which reasoning steps to explore is an active research area related to Reasoning Models and Test-Time Compute and tree-of-thoughts prompting.

A bit of history

Game-playing has driven AI since its start. Arthur Samuel's checkers player (1959) learned by self-play, and IBM's Deep Blue beat world chess champion Garry Kasparov in 1997 with brute-force alpha-beta search and a hand-crafted evaluation function. Go resisted that approach, because there are too many moves and good positions are hard to evaluate by rule. In 2006, Rémi Coulom coined the term "Monte Carlo tree search", and Levente Kocsis and Csaba Szepesvári published UCT. Go programs improved rapidly. From around 2014 DeepMind, led by Demis Hassabis, with David Silver heading the AlphaGo project, combined MCTS with deep networks. Then came the matches against Fan Hui (October 2015) and Lee Sedol (March 2016). AlphaGo Master went 60–0 in online games against top professionals at the start of 2017 and beat world number one Ke Jie 3–0 in May 2017. AlphaGo Zero followed in October 2017, AlphaZero in December 2017, and MuZero in 2019. Hassabis shared the 2024 Nobel Prize in Chemistry for AlphaFold, a later DeepMind system, a sign of how far the lab's game-playing roots carried.

Try it

  1. Reduce the self-play budget from 1,000 to 50 simulations per move. Do the games still all end in draws? At what budget do mistakes disappear?
  2. Change the exploration constant c in ucb to 0.1 and to 5. How does the visit distribution in the second test position change?
  3. Replace the random rollout with a slightly smarter one: if the player to move can win immediately, do so. Does MCTS find the right moves with fewer simulations?

Hint for 1: in our runs, 50 simulations per move gave X 11 wins, O 1 and 8 draws out of 20 games, and even 200 simulations left half the games decisive. Weak searches miss the opponent's double threats.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A node has N = 100 visits. Child A: 40 wins in 60 visits. Child B: 5 wins in 10 visits. With UCT and c = 1.4, which is selected and why?

  2. After the search, why does MCTS play the root's most-visited move rather than the one with the highest win rate?

  3. Your MCTS for a two-player game keeps choosing moves that help the opponent. What is the most likely bug?

  4. Why does training AlphaGo Zero's network to match the search's visit counts make it stronger?

  5. What did MuZero remove compared with AlphaZero?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

UCL Course on Reinforcement Learning

David Silver · 2015 · Intermediate · Free

Ten recorded lectures with slides by the lead researcher behind AlphaGo. Covers MDPs, dynamic programming, TD learning, function approximation, policy gradients and planning; follows Sutton & Barto closely.

Video

AlphaGo — The Movie

Google DeepMind · 2017 · Beginner · Free

The award-winning feature documentary about AlphaGo's 2016 match against Lee Sedol. Free on YouTube and gripping even if you don't play Go.

Paper

Bandit Based Monte-Carlo Planning

Levente Kocsis & Csaba Szepesvári · 2006 · Advanced · Paid

Introduced UCT, which applies the UCB1 bandit rule at every node of a search tree. The selection rule at the heart of most MCTS programs.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/rl/alphago-and-mcts.md