Monte Carlo Tree Search: Sampling and Guided Exploration

CSI 4106 Introduction to Artificial Intelligence

Marcel Turcotte

Version: Nov 29, 2026 19:41

Preamble

Message of the Day

Learning objectives

  • Trace the four stages of Monte Carlo Tree Search (MCTS).
  • Interpret visit counts, accumulated returns, and average returns.
  • Predict a UCT selection and explain its exploration bonus.
  • Distinguish selecting a simulation path from choosing the final move.
  • Explain what finite-budget search does and does not establish.

Motivation

With supervised learning, we learn from labelled examples. Reinforcement learning takes a different approach: learning which actions work well from the rewards they produce. Monte Carlo Tree Search gives us a gentle introduction to this idea. With a simulator of the rules, we can try possible continuations and use their outcomes to choose a move. We will build on familiar tree search and random sampling, without developing the full machinery of reinforcement learning.

Introduction

Monte Carlo Tree Search (MCTS)

Lecture 16 introduced AlphaGo as an example of search in reasoning. Lecture 22 showed why full game-tree search becomes impractical.

Could we estimate a position’s value by playing out a few possible continuations?

Historical Notes

  • 2006: foundational Monte Carlo tree-search and UCT work.
  • 2016: policy and value networks are combined with MCTS in AlphaGo (Silver et al. 2016).

Applications

  • De novo drug design
  • Electronic circuit routing
  • Load monitoring in smart grids
  • Lane keeping and overtaking tasks
  • Motion planning in autonomous driving
  • Even solving the travelling salesman problem

Applications (continued)

  • Chess: adding 400 MCTS simulations raises tournament Elo from 1777 (policy-only) and 1992 (value-only) to 2470 for AlphaZero, and from 2292 (policy-only) and 2418 (value-only) to 2858 for Leela Chess Zero. Ruoss et al. (2024)
  • In reasoning models, Monte Carlo Tree Search guides test-time exploration and reinforcement learning over multi-step reasoning trajectories. (Besta et al. 2025)

Monte Carlo Sampling

A Monte Carlo method uses random samples to estimate a numerical quantity.

How could we estimate the quality of a move without examining every possible continuation?

Four Stages

For each completed simulation:

  1. Selection: follow a path in the stored tree.
  2. Expansion: add an untried continuation when appropriate.
  3. Rollout: simulate further moves to a terminal state.
  4. Backpropagation: update statistics along the selected path.

Definition: Policies and Values

A policy is a rule for choosing an action.

Term Role in our MCTS
Tree policy Guides traversal of the stored tree and determines where expansion occurs.
Rollout policy (default policy) Chooses actions during the temporary continuation beyond the stored tree—randomly here.
Value function Estimates a position’s expected return from a stated player’s perspective.

Algorithm

Any-Time Algorithm

MCTS is a textbook example of an any-time algorithm:

  • It can be interrupted and return its current recommendation.
  • More time ⇒ more simulations ⇒ more evidence for action estimates.
  • It returns its currently recommended move using the simulations completed so far.

Discussion

Like BFS, DFS, and A^\star, MCTS explores a search space incrementally.

  • BFS, DFS, and A^\star select a node from a frontier.
  • MCTS follows a path through its stored tree to determine where to expand next.

Discussion

Both A^\star and MCTS use evaluation criteria to guide search:

  • A^\star combines path cost with an estimated remaining cost.
  • MCTS combines estimated returns from simulations with an exploration bonus.

A heuristic supplies an estimate; a policy specifies how to choose an action.

Discussion

Similar to Simulated Annealing and Genetic Algorithms, MCTS incorporates a mechanism to balance exploration and exploitation.

Discussion

  • MCTS repeatedly revisits its stored tree and updates return estimates using new simulations.
  • A^\star retains best-known path costs and updates them when a cheaper path is discovered; its heuristic remains fixed in our examples.

Discussion

MCTS stores only part of the possible game tree:

  • An explicit tree records positions, parent–child links, visit counts, and accumulated returns.
  • Rollouts explore continuations beyond that tree without retaining those states as tree nodes.

A Four-Iteration Walk-through

Which Score Are We Averaging?

The walkthrough uses numerical returns for one decision-maker, with C=2.

For tic-tac-toe, game.evaluate(state) always returns X’s utility:

Terminal outcome X’s utility
X wins +1
Draw 0
O wins -1

Choosing Which Child to Sample

For a visited child i, UCT uses

\operatorname{UCT}(i)=\overline V_i+C\sqrt{\frac{\ln N}{n_i}}.

  • \overline V_i: mean return from the parent’s perspective;
  • N: parent visits; n_i: child visits;
  • C: exploration scale.

Walk-through

Walk-through

Walk-through

Walk-through (1.1)

Walk-through (1.1)

Walk-through (1.1)

Walk-through (1.2)

Walk-through (1.3)

Walk-through (1.4)

Walk-through (1.End)

Walk-through (2.1)

Walk-through (2.2)

Walk-through (2.3)

Walk-through (2.4)

Walk-through (2.End)

Walk-through (3.1)

Walk-through (3.1)

Walk-through (3.2)

Walk-through (3.2)

Walk-through (3.3)

Walk-through (3.4)

Walk-through (3.End)

Walk-through (4.1)

Walk-through (4.1)

Walk-through (4.2)

Walk-through (4.2)

Walk-through (4.3)

Walk-through (4.4)

Walk-through (4.End)

Walk-through

Summary: Tree Building

Initially, the stored tree has one node, the root S_0.

In the walkthrough, we add its children before the first selection.

MCTS gradually grows this partial tree, revisiting existing nodes and adding descendants as search proceeds.

Summary: Four Stages

  1. Selection: descend through the stored tree using UCT.
  2. Expansion: add an untried legal continuation when possible.
  3. Rollout: sample a continuation, or evaluate a terminal state directly.
  4. Backpropagation: update the visited path’s counts and returns.

Summary: Nodes

Each stored node records its total return and visit count.

Their ratio gives the mean return, used in the selection score.

Visit counts also determine the exploration bonus.

Exploration Can Return to a Neglected Child

\operatorname{UCT}(i)=\overline V_i+C\sqrt{\frac{\ln N}{n_i}}.

  • Hold N fixed: more visits to child i reduce its bonus.
  • Hold n_i fixed: more parent visits increase that child’s bonus.
  • The bonus can outweigh a difference in current means.

Predict: Where Should the Next Simulation Go?

Let N=100 and C=\sqrt2. The means use the parent’s perspective.

Child Visits n_i Mean \overline V_i UCT score
A 90 0.7 ?
B 10 0.5 ?

Which child gets the next simulation? Which action would the visit-first final rule play?

UCT scores are approximately 1.020 for A and 1.460 for B. The next simulation goes to B; the final-action rule chooses A.

C Has Meaning Relative to the Reward Scale

  • Larger C gives the exploration bonus more influence.
  • Smaller C puts more weight on current mean returns.
  • Interpret C relative to the scale of those returns.

Choosing C Under a Fixed Budget

Smaller C may help when… Larger C may help when…
Current estimates are relatively reliable. Early returns are noisy.
Promising actions are easy to distinguish. Alternatives need more investigation.

Could an intermediate value make better use of the available simulations?

An Anytime Recommendation

After a completed simulation, MCTS can return its current recommendation.

  • More simulations supply additional evidence.
  • A particular estimate or move need not improve after every simulation.
  • A finite budget does not establish optimal play.

Epilogue

Summary

  • MCTS grows a stored tree and samples continuations.
  • Visit counts and accumulated returns guide further search.
  • UCT balances current means with an exploration bonus.
  • The score’s perspective and reward scale must be explicit.
  • Final action selection differs from simulation-path selection.
  • More evidence supports a recommendation; it does not prove finite-budget optimality.

Next Lecture

Lecture 24 connects the four stages to code and investigates simulation budgets, exploration, and persistent search.

References

Besta, Maciej, Julia Barth, Eric Schreiber, et al. 2025. Reasoning Language Models: A Blueprint. https://arxiv.org/abs/2501.11223.
Browne, Cameron B., Edward Powley, Daniel Whitehouse, et al. 2012. “A Survey of Monte Carlo Tree Search Methods.” IEEE Transactions on Computational Intelligence and AI in Games 4 (1): 1–43. https://doi.org/10.1109/TCIAIG.2012.2186810.
Chaslot, Guillaume, Sander Bakkes, Istvan Szita, and Pieter Spronck. 2008. “Monte-Carlo Tree Search: a new framework for game AI.” Proceedings of the Fourth AAAI Conference on Artificial Intelligence and Interactive Digital Entertainment (Stanford, California), AIIDE’08, 216–17.
Kemmerling, Marco, Daniel Lütticke, and Robert H. Schmitt. 2024. “Beyond Games: A Systematic Review of Neural Monte Carlo Tree Search Applications.” Applied Intelligence 54 (1): 1020–46. https://doi.org/10.1007/s10489-023-05240-w.
Ruoss, Anian, Grégoire Delétang, Sourabh Medapati, et al. 2024. “Amortized Planning with Large-Scale Transformers: A Case Study on Chess.” Proceedings of the 38th International Conference on Neural Information Processing Systems (Red Hook, NY, USA), NIPS ’24.
Russell, Stuart, and Peter Norvig. 2020. Artificial Intelligence: A Modern Approach. 4th ed. Pearson. http://aima.cs.berkeley.edu/.
Silver, David, Aja Huang, Chris J. Maddison, et al. 2016. “Mastering the game of Go with deep neural networks and tree search.” Nature 529 (7587): 484–89. https://doi.org/10.1038/nature16961.
Świechowski, Maciej, Konrad Godlewski, Bartosz Sawicki, and Jacek Mańdziuk. 2023. “Monte Carlo Tree Search: a review of recent modifications and applications.” Artificial Intelligence Review 56 (3): 2497–562. https://doi.org/10.1007/s10462-022-10228-y.

Appendix

UCB1 and UCT

The multi-armed bandit problem repeatedly chooses among actions with uncertain returns.

  • Exploit: use the best current average.
  • Explore: sample an action whose value is less certain.
  • UCT: apply an upper-confidence-bound rule at successive tree nodes.

Simulated Annealing and the Reward Scale

For a minimization problem, let \Delta E=E_{\text{new}}-E_{\text{old}}.

  • If \Delta E\leq0, accept the candidate.
  • If \Delta E>0, accept with probability

p=\exp(-\Delta E/T).

Two Different Exploration Mechanisms

Simulated annealing MCTS with UCT
One current search trajectory A branching stored search structure
Temperature is explicitly scheduled C can remain fixed
Worsening changes may be accepted Under-sampled actions receive a selection bonus

When Can Exploration Overrule the Larger Mean?

Child 2 is selected instead of child 1 when

\overline V_2+C\sqrt{\frac{\ln N}{n_2}}> \overline V_1+C\sqrt{\frac{\ln N}{n_1}}.

Equivalently,

\overline V_2-\overline V_1> C\left(\sqrt{\frac{\ln N}{n_1}}- \sqrt{\frac{\ln N}{n_2}}\right).

Small and Large C

  • C=0: after initial untried-move expansion, selection is greedy in current means.
  • Large C: visit imbalance has more influence relative to current means.
  • Intermediate values: investigate the trade-off under a stated budget.

Another Win-Count Convention

Plotting Helpers

Code
import math
import random
import numpy as np
import matplotlib.pyplot as plt

Logarithmic Growth

Code
n_values = np.arange(1, 10_001)
plt.figure(figsize=(8, 4))
plt.plot(n_values, np.log(n_values), label=r"$\ln N$")
plt.xlabel("N")
plt.ylabel(r"$\ln N$")
plt.title("The numerator grows slowly; it does not decrease")
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()
plt.close()
print("ln(100), ln(1000), ln(10000):", np.log([100, 1000, 10000]))

ln(100), ln(1000), ln(10000): [4.60517019 6.90775528 9.21034037]

Exploration Bonus for Feasible Visit Counts

Code
def plot_exploration_bonus(max_visits):
    """Plot the bonus where child visits do not exceed parent visits."""
    visits = np.arange(1, max_visits + 1)
    parent_visits, child_visits = np.meshgrid(visits, visits)
    bonus = math.sqrt(2) * np.sqrt(
        np.log(parent_visits) / child_visits
    )
    bonus = np.ma.masked_where(child_visits > parent_visits, bonus)
    fig, ax = plt.subplots(figsize=(7, 4))
    contour = ax.contourf(
        parent_visits, child_visits, bonus, levels=15, cmap="viridis"
    )
    fig.colorbar(contour, ax=ax, label="Exploration bonus")
    ax.set_xlabel("Parent visits N")
    ax.set_ylabel("Child visits n")
    ax.set_title(f"Bonus for 1 ≤ n ≤ N ≤ {max_visits}")
    fig.tight_layout()
    plt.show()
    plt.close(fig)


plot_exploration_bonus(10)

Exploration Bonus at a Larger Scale

Code
plot_exploration_bonus(100)

Numerical Integration

Estimate \int_0^\pi\sin(x)\,dx=2 by averaging sampled function values.

Code
def monte_carlo_integrate_visual_with_sticks(
    f, a, b, n_samples, seed=None, true_value=None
):
    """Show uniform samples and successive Monte Carlo estimates."""
    rng = np.random.default_rng(seed)
    xs = rng.uniform(a, b, size=n_samples)
    ys = f(xs)
    cumulative_avg = np.cumsum(ys) / np.arange(1, n_samples + 1)
    estimates = (b - a) * cumulative_avg

    fig, axes = plt.subplots(1, 2, figsize=(11, 4))
    grid = np.linspace(a, b, 400)
    axes[0].plot(grid, f(grid), color="black", label="f(x)")
    axes[0].vlines(xs, 0, ys, color="gray", alpha=0.3, linewidth=1)
    axes[0].scatter(xs, ys, s=12, color="blue", label="Samples")
    axes[0].set_title("Monte Carlo samples")
    axes[0].set_xlabel("x")
    axes[0].set_ylabel("f(x)")

    axes[1].plot(estimates, label="Monte Carlo estimate")
    if true_value is not None:
        axes[1].axhline(
            true_value, linestyle="--", color="red", label="True value"
        )
    axes[1].set_title("Successive integral estimates")
    axes[1].set_xlabel("Number of samples")
    axes[1].set_ylabel("Estimate")
    for ax in axes:
        ax.grid(True)
        ax.legend()
    fig.tight_layout()
    plt.show()
    plt.close(fig)
    return estimates[-1]


estimate = monte_carlo_integrate_visual_with_sticks(
    np.sin, 0.0, math.pi, 500, seed=123, true_value=2.0
)
print(f"Final estimate: {estimate:.6f}; true value: 2.0")

Final estimate: 1.994396; true value: 2.0

Numerical Integration with More Samples

Code
def monte_carlo_integrate(f, a, b, n_samples, seed=None):
    """Estimate an integral using independent uniform samples."""
    rng = random.Random(seed)
    total = 0.0
    for _ in range(n_samples):
        total += f(rng.uniform(a, b))
    return (b - a) * total / n_samples


for n in (100, 1_000, 10_000, 100_000):
    estimate = monte_carlo_integrate(math.sin, 0.0, math.pi, n, seed=0)
    print(
        f"n = {n:6d}; estimate = {estimate:.6f}; "
        f"absolute error = {abs(2.0 - estimate):.6f}"
    )
n =    100; estimate = 2.080957; absolute error = 0.080957
n =   1000; estimate = 1.992136; absolute error = 0.007864
n =  10000; estimate = 2.007041; absolute error = 0.007041
n = 100000; estimate = 1.996149; absolute error = 0.003851

Marcel Turcotte

[email protected]

School of Electrical Engineering and Computer Science (EECS)

University of Ottawa