Monte Carlo Tree Search in Python: Beating a Heuristic Without One

Build Monte Carlo tree search in Python and measure it against alpha-beta at the same node count. Four phases, one formula, no evaluation function, and it wins.

Cover Image for Monte Carlo Tree Search in Python: Beating a Heuristic Without One

You're writing a Connect Four player. Listing the legal moves is easy, but choosing one means judging positions whose consequences may appear several turns later. You could learn a strategy from games, as in the Q-learning, deep Q-network and policy-gradient tutorials. Monte Carlo tree search offers another starting point, using the loop that AlphaGo and AlphaZero also build on. From the current position, it plays out possible futures and uses their outcomes to decide where to spend the next part of its search budget.

We build a player that starts a fresh tree each move, using random playouts to spend its search budget. Against a heuristic alpha-beta opponent under roughly matched node counts, win rates are 72% and 88%. Those budgets correspond to depths four and five, letting us compare the extra search effort.

Let's Build It

Open this in Google Colab and run it top to bottom. It builds the four phases, plays Monte Carlo tree search against a hand-written alpha-beta opponent, and prints the score. About two minutes on a CPU.

Open In Colab

import math, random

class Node:
    def __init__(self, state, parent=None, move=None):
        self.state, self.parent, self.move = state, parent, move
        self.children, self.untried = [], state.legal_moves()
        self.visits, self.value = 0, 0.0

    @property
    def q(self):                       # from the point of view of whoever picks this move
        return -self.value / self.visits if self.visits else 0.0

    def uct(self, c):
        return self.q + c * math.sqrt(math.log(self.parent.visits) / self.visits)

def search(state, budget, c=1.4, rng=random.Random(0)):
    root = Node(state)
    for _ in range(budget):
        node = root
        while not node.untried and node.children:              # 1. selection
            node = max(node.children, key=lambda n: n.uct(c))
        if node.untried:                                       # 2. expansion
            move = node.untried.pop(rng.randrange(len(node.untried)))
            node = node.add_child(move)
        result = rollout(node.state, rng)                      # 3. simulation
        while node:                                            # 4. backpropagation
            node.visits += 1
            node.value += result
            result, node = -result, node.parent
    return max(root.children, key=lambda n: n.visits).move

That is the whole algorithm. rollout plays uniformly at random until somebody wins. There is nothing else: no features, no weights, no heuristic.

Four panels showing selection, expansion, simulation and backpropagation on a small search tree

Run it against a depth-4 alpha-beta opponent with a hand-written evaluation function, at roughly the same number of nodes each:

# 30 games, sides swapped every game
# MCTS budget 75      11,492 nodes per game    win rate 0.717
# alpha-beta depth 4  10,208 nodes per game

The opponent is told which patterns on a Connect Four board are good. The search above is told nothing, spends the same, and wins about seven games in ten.

What Just Happened?

The four phases

One rollout does four things, and each is a few lines.

Selection starts at the root and walks down, at every step taking the child with the highest UCT score, until it reaches a node that still has moves nobody has tried.

Expansion takes one of those untried moves and adds a single child for it. This is the only place the tree grows, which is why the tree ends up with exactly one node per rollout and no more.

Simulation plays from that new child to the end of the game, choosing uniformly at random. This is the part that sounds like it cannot possibly work.

Backpropagation walks back up to the root, adding the result to every node on the path and flipping its sign at each step, because the player to move alternates.

UCT, which is UCB1 on a tree

Selection needs a rule for choosing between children, and the rule is a bandit formula. Each child is an arm, pulling it means spending a rollout down that branch, and the reward is whether that branch tends to win:

UCT(child)=WcNc⏟how well it has done+  c ln⁡NpNc⏟how little it has been tried\mathrm{UCT}(child) = \underbrace{\frac{W_c}{N_c}}_{\text{how well it has done}} + \; c\,\underbrace{\sqrt{\frac{\ln N_p}{N_c}}}_{\text{how little it has been tried}}

NcN_c is the child's visit count, NpN_p the parent's, and WcW_c the total result accumulated below the child. The first term is exploitation. The second is exploration: it is large for a child nobody has tried, shrinks as that child is visited, and grows slowly as the parent is visited, so a branch that looked bad early is eventually revisited. Kocsis and Szepesvari's contribution was noticing that UCB1, a solved problem for one-step bandits, still behaves well when the arms are subtrees whose reward distributions are themselves changing.

cc sets the exchange rate. It is measured further down, and the answer is less fussy than the literature's 2\sqrt{2} suggests.

The sign that cost an afternoon

value is accumulated from the point of view of the player to move at that node. The player choosing between the children is that node's parent, who is the other player. So reading a child's value from the chooser's side means negating it, which is the minus sign in q.

Getting this wrong is silent. The search still runs, the tree still grows to exactly the right size, the visit counts still concentrate, and the agent loses every single game to a uniformly random opponent. It took a match against random players to catch it, which is worth building before anything else: an agent that cannot beat random is broken, not weak.

The Comparison, Measured

Everything below is three independent blocks of games with disjoint seeds, reported as the mean and the spread across blocks. Connect Four is a first-player win under perfect play, so every match-up plays half its games from each side.

Against a random opponent, and against itself

Two panels: win rate against budget for two opponents, and the falling value of a fourfold budget advantage

Twenty-five rollouts per move beats a random player 94% of the time and fifty beats it every time. That is the floor, and it is reached almost immediately.

Against a copy of itself the picture is more useful. A budget of 100 against a fixed 100 gives 0.467, which is a fair coin as it should be. Doubling to 200 gives 0.633, and eight times the budget gives 0.900.

The right panel is the part worth keeping. The same fourfold advantage in budget is worth 0.933 at 100 against 25, 0.750 at 400 against 100, and 0.583 at 1,600 against 400. Compute buys strength and buys less of it every time, which is the shape every search method has and the reason AlphaZero's authors spent their effort on the rollout rather than on the budget.

Against alpha-beta at the same number of nodes

The honest version of this comparison is harder to set up than it looks. Matching budgets is not matching work: alpha-beta at a fixed depth expands a number of nodes that depends on how well its move ordering prunes, and MCTS spends nodes on rollouts that get shorter as the board fills. The ratio drifts through a game. So each side counts every position it plays out, the budget is swept, and the figure marks what the opponent spent.

MCTS win rate against nodes spent, for four alpha-beta depths, with each opponent's node cost marked

Read where each curve crosses its own dotted line:

opponentits nodes per gameMCTS budget at that costMCTS nodeswin rate
depth 3~1,650101,2710.233
depth 4~10,0007511,4920.717
depth 5~26,00020028,4130.875
depth 6~140,000900126,8160.800

Two things fall out of that table, and only one of them was expected.

The expected one is that MCTS wins at equal cost against everything from depth 4 up, and by a wider margin as the budget grows. It does this with no evaluation function at all, against an opponent that has one.

The unexpected one is the top row. Against depth 3, at matched nodes, MCTS loses badly: 0.233. Its curve only crosses even at around 2,000 nodes, and below that a shallow exact search is simply better. A few hundred random playouts are not an estimate of anything. The crossover is not a detail, it is the answer to when this method is worth using: MCTS is a way of spending a large budget well, and it has nothing to offer a small one.

The depth-6 row also comes with a caveat. Those games are the most expensive here, so they run at ten games per block, and the spread across blocks reaches 0.094. Treat the 0.800 as "clearly winning" rather than as a precise number.

One control was needed before any of this could be read as a comparison of methods. If a deeper alpha-beta were not a stronger player, the ladder above would measure nothing. Head to head, depth 4 beats depth 3 at 0.800, depth 5 beats depth 4 at 0.600, and depth 6 beats depth 5 at 0.633, so the ladder is real, if with its own diminishing returns.

Going Deeper

The exploration constant

Win rate against the UCT exploration constant, flat between 0.5 and 2.0

Setting c=0c = 0 removes the exploration term and turns selection into pure greed on the current average. That costs 28 points: 0.650 against 0.933. The search still works, because expansion forces every untried move to be tried once, but it commits to whatever looked good first.

Everything from 0.5 to 2.0 is the same within the spread. The commonly quoted 2≈1.41\sqrt{2} \approx 1.41 sits in that range and so does 0.5, and choosing between them on this game is not a thing worth doing. What matters is that the term is there at all.

The shape of the tree

Search trees after 10, 100 and 1,000 rollouts, node size by visit count

Because expansion adds exactly one node per rollout, the tree has exactly budget + 1 nodes: 11 nodes at 10 rollouts, 1,001 at 1,000, 10,001 at 10,000. Depth is the interesting number. It goes 2, 4, 6, 10 across those same budgets, so a thousandfold increase in rollouts buys five times the depth. The tree grows out far faster than it grows down, and it is visibly lopsided: the branches UCT likes get most of the nodes and the rest stay stubs.

That is the difference from alpha-beta in one picture. Alpha-beta explores a uniform depth and prunes what it can prove is irrelevant. MCTS explores a wildly uneven depth and decides what is irrelevant by sampling.

Animation of the search tree growing over 500 rollouts

Anytime, and what that buys

Nothing else in this series returns a usable answer when interrupted. Stop training a network halfway and you have a bad network. Stop MCTS halfway and you have the best move it has found so far, because the answer is just the most-visited child of the root and that is defined from the first rollout onwards.

A Connect Four position, the root visit counts after 1,000 rollouts, and the fraction of runs returning the winning move at each budget

The position on the left has exactly one move that wins by force, and the win does not appear until seven plies deep, so it cannot be found by looking one move ahead. After 1,000 rollouts the search has given that column 859 of its visits and a mean value of +0.428, while the next most-visited column has 47 visits and a mean of -0.064. It is not close.

The right panel is the anytime claim tested rather than asserted, over 60 independent runs at each budget. The fraction returning the winning column climbs from chance at five rollouts to 0.32 at 10, 0.62 at 50, 0.78 at 100 and 1.00 from 500 onwards. The search always returns something, and what it returns is worth steadily more. Five hundred rollouts is about 16 milliseconds of work at the 31,588 rollouts per second this implementation manages, which is the price of solving a seven-ply tactic every time by sampling.

A first draft of this section made the claim from three runs, which all happened to lock on by 50 rollouts. Sixty runs put that budget at 0.62. Three samples is enough to see a shape and not enough to quote a number.

The blunder rate

An agent that wins on average can still be unreliable in ways a win rate hides. To measure that, 400 random reachable positions were solved exactly to a 7-ply horizon, which is a proof rather than a heuristic: a move is a blunder when the position was not lost and the move makes it provably lost. 379 of the 400 positions were not already lost and so had something to throw away.

Blunder rate falling from 17.7% at budget 10 to 1.1% at budget 800

The rate falls from 17.7% at 10 rollouts to 4.7% at 100 and 1.1% at 800, and the last doubling from 400 to 800 buys almost nothing. Uniformly random rollouts converge on the right answer and do so slowly at the end, which is the honest version of the "random playouts work" claim: they work, and the last few percent are expensive.

From here to AlphaZero

Two of the four phases in the code above are placeholders that a stronger system replaces, and this is the whole of the structural difference.

The rollout is replaced by a value network. Instead of playing to the end at random, evaluate the leaf with a network trained to predict the outcome. The blunder-rate curve above is what that fixes: a network's estimate of a position is worth far more than the average of a few hundred coin flips, especially in positions where random play is nothing like real play.

The uniform choice among untried moves is replaced by a policy network prior, which enters the selection formula as an extra term (PUCT rather than UCT) biasing the search toward moves the network considers plausible before any rollout has happened.

What does not change is the loop. Selection, expansion, evaluation, backpropagation, most-visited child. Silver et al. (2017) describe AlphaZero as exactly this search with those two substitutions and self-play to train them, and the visit counts at the root become the training target for the policy. The search in this post is the skeleton that stayed.

Where This Comes From

The method has two 2006 papers behind it, and they answer different halves of the problem.

Coulom (2006) introduced the tree search itself and the name, in the context of computer Go, where an evaluation function good enough for alpha-beta had defeated everyone who tried to write one. His contribution was the idea that a tree could be grown selectively and backed up from random playouts rather than from a static evaluation.

Kocsis and Szepesvari (2006) supplied the selection rule and, more importantly, an argument for it. Their paper treats each node as a bandit problem and applies Auer, Cesa-Bianchi and Fischer's UCB1, then proves that the failure probability at the root converges to zero as the budget grows. The result is stated for a setting whose assumptions do not hold exactly on a game tree, and the paper says so:

The convergence of UCT is not immediate from the analysis of UCB1, since the payoff sequences experienced from the tree's internal nodes are not stationary.

That non-stationarity is the interesting part. A child's average value keeps drifting as its own subtree is explored, so the thing being averaged is moving. The guarantee survives because the drift settles, and the practical consequence is visible in the anytime figure above: the root's choice moves around early and stops moving once the subtree under the eventual winner has been sampled enough.

Browne et al. (2012) is the survey to read next, and it catalogues the variants this post does not build: rollout policies that are better than uniform, RAVE and all-moves-as-first, transposition handling, and the parallelisation schemes.

The reason a heuristic-free method could beat a heuristic-driven one, which is the measurement at the top of this post, is the same reason Go resisted alpha-beta for thirty years. Alpha-beta is only as good as its evaluation function, and writing one is hard, domain-specific work that has to be redone for every new problem. MCTS trades that work for compute. When compute is the cheaper of the two, which since roughly 2006 it usually has been, it wins.

Interactive Tools

  • Bandit Simulator: UCB1 on a flat bandit problem, which is exactly the formula the selection step applies to each node.
  • Q-Learning Visualizer: the other way to act well in a game, by keeping a value for every state instead of searching at decision time.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions