Sign in

AlphaZero

A game-playing agent that learns only from games against itself: a network proposes moves and judges positions, and a tree search guided by it finds better moves to learn from.

Overview

A strong player does two things: glances at a position and has a feeling for which moves look good and who is winning, then reads ahead to check that feeling. AlphaZero has a network for the glance and a tree search for the reading. The search uses the network to decide which moves deserve attention, and after many simulated lines its move counts are a better guide than the network's first impression. The network is then trained to match those counts and the final result of the game. A better network makes the next search stronger, and the cycle repeats. This template is a small version: tic-tac-toe with a one-hidden-layer network instead of a deep convolutional one.

A short history

David Silver and colleagues at DeepMind built AlphaZero in 2017 and published it in Science in 2018. AlphaGo had beaten Lee Sedol at Go in 2016 using human games and hand-made features. AlphaGo Zero then learned Go from self-play alone, and AlphaZero generalised that one algorithm to chess and shogi as well, defeating the strongest programs of the time in each game given only the rules. The name is not an acronym: Zero refers to starting from zero human knowledge.

How it works

  1. PolicyValueNet.predict takes a position, seen from the side of the player to move, and returns a prior over legal moves and a value between −1-1 and 11.
  2. MCTS.search runs n_simulations descents. Each one walks down the tree by picking, at every node, the child with the highest PUCT score.
  3. At a leaf the network is asked once: its prior creates the leaf's children and its value stands in for playing the game out. A finished game gives the exact result instead.
  4. The value is passed back up the path. Its sign flips at every level, because a position that is good for one player is bad for the other.
  5. AlphaZero.self_play_game plays a full game this way with Dirichlet noise at the root, storing each position with the search's visit distribution and, once the game ends, the outcome for the player who was to move.
  6. train_iteration adds games_per_iteration games to the buffer and takes train_steps_per_iteration Adam steps that pull the policy toward the visit distributions and the value toward the outcomes.
  7. best_action plays the most visited move of a fresh search, or the network's top move when use_search=False.

Watch out for

  • Without the root noise and the sampled opening moves, self-play repeats the same few games, and the network never sees the positions it would need to learn from.
  • The value target is the result of one game, which is noisy. With few games per iteration the value head can fit the noise and mislead the search.
  • The search needs the true rules to step through positions. If the rules are unknown or the environment is random, this method does not apply as written.
  • After ten iterations the network alone beats a random player in about 8 games out of 10 but is not perfect. Judging it against a random opponent hides its remaining mistakes.
  • Too few simulations make the visit counts little more than the prior, so the network is trained toward itself and stops improving.

Use cases

When to use it

Use it for two-player, zero-sum games with perfect information whose rules can be simulated exactly. For another game, replace TicTacToe with a class that offers the same static methods.

In industry

Board games
Chess, shogi and Go engines. The open source Leela Chess Zero project applies the same method and is among the strongest chess engines.
Algorithm discovery
DeepMind's AlphaTensor framed finding faster matrix multiplication methods as a single-player game and searched it with an AlphaZero-style agent.
Combinatorial optimisation research
Problems such as chip layout, scheduling or molecule design are posed as games of sequential moves and searched with a learned policy and value.

Choosing it: what must hold

  • A perfect simulator: the exact rules must be known so the search can try moves and see the result.
  • Discrete actions and a clear final outcome such as win, loss or a score.
  • Very large compute for self-play, since every move of every training game runs a tree search.

When to choose something else

IfUse instead
The rules or dynamics are not known and must be learnedMuZero
You only need the search with a model you already have, without learningThe shared planning lesson: Monte Carlo tree search
There is no opponent or search budget and actions are fewDQN or PPO

Math foundations

  1. The network

    (p,v)=fθ(s)(\mathbf{p}, v) = f_\theta(s)

    One network with two outputs. p\mathbf{p} is a probability for each move and vv is the expected result for the player to move: +1+1 a win, −1-1 a loss, 0 a draw.

  2. Selecting a move inside the tree (PUCT)

    a∗=arg⁡max⁡a[Q(s,a)+cpuct P(s,a) N(s)1+N(s,a)]a^{*} = \arg\max_{a} \left[ Q(s, a) + c_{\text{puct}} \, P(s, a) \, \frac{\sqrt{N(s)}}{1 + N(s, a)} \right]

    The first term is how well the move has done so far. The second is an exploration bonus: large for moves the network likes and that have few visits, shrinking as the move is visited. Early visits follow the prior and later visits follow the results.

  3. Backing up a result

    N(s,a)←N(s,a)+1,W(s,a)←W(s,a)+v,Q(s,a)=W(s,a)N(s,a)N(s, a) \leftarrow N(s, a) + 1, \qquad W(s, a) \leftarrow W(s, a) + v, \qquad Q(s, a) = \frac{W(s, a)}{N(s, a)}

    Every move on the path counts one more visit and adds the leaf's value, with vv replaced by −v-v at each step up. QQ is the average result of all simulations that went through the move.

  4. Noise at the root during self-play

    P(s0,a)←(1−ϵ) pa+ϵ ηa,η∼Dir⁡(α)P(s_0, a) \leftarrow (1 - \epsilon) \, p_a + \epsilon \, \eta_a, \qquad \boldsymbol{\eta} \sim \operatorname{Dir}(\alpha)

    Mixing random noise into the root prior gives every legal move some chance of being searched, even one the network currently dismisses.

  5. The search policy

    π(a∣s0)=N(s0,a)∑bN(s0,b)\pi(a \mid s_0) = \frac{N(s_0, a)}{\sum_{b} N(s_0, b)}

    The share of simulations that started with each move. This is the policy target. It is stronger than p\mathbf{p} because it includes what the search found by reading ahead.

  6. The training loss

    L(θ)=(z−v)2−π⊤log⁡p+c ∥θ∥2L(\theta) = (z - v)^{2} - \boldsymbol{\pi}^{\top} \log \mathbf{p} + c \, \lVert \theta \rVert^{2}

    Squared error pulls the value toward the game's outcome. Cross-entropy pulls the network's policy toward the search policy. The last term keeps the weights small. The template averages the first two over a batch.

Symbols

s,  s0s,\; s_0
a game position, and the root position of a search
fθf_\theta
the policy and value network with weights theta
p,  pa\mathbf{p},\; p_a
the network's prior over moves and its entry for move a
vv
the network's value for the player to move, between -1 and 1
P(s,a)P(s, a)
prior stored on a move in the tree
N(s,a)N(s, a)
number of simulations that took move a from s
N(s)N(s)
visit count of the parent position s
W(s,a),  Q(s,a)W(s, a),\; Q(s, a)
summed and average backed-up value of move a
cpuctc_{\text{puct}}
exploration constant of the selection rule
ϵ,  α\epsilon,\; \alpha
weight and concentration of the root noise
π\boldsymbol{\pi}
the search policy: normalized root visit counts
zz
final game outcome for the player to move: +1, 0 or -1
cc
weight of the L2 penalty

Worked by hand

A node has been visited N(s)=10N(s) = 10 times and cpuct=1.5c_{\text{puct}} = 1.5. Move A has Q=0.2Q = 0.2, prior 0.5 and 6 visits. Move B has Q=0Q = 0, prior 0.3 and 1 visit. Which does the next simulation take?

N(s)=10=3.162\sqrt{N(s)} = \sqrt{10} = 3.162
score(A)=0.2+1.5×0.5×3.1621+6=0.2+0.339=0.539\text{score}(A) = 0.2 + 1.5 \times 0.5 \times \frac{3.162}{1 + 6} = 0.2 + 0.339 = 0.539
score(B)=0+1.5×0.3×3.1621+1=0.712\text{score}(B) = 0 + 1.5 \times 0.3 \times \frac{3.162}{1 + 1} = 0.712

The search takes B, although A has the better average and the higher prior. A has already had six visits, so its bonus has shrunk. This is how the rule spreads visits before it commits.

Visual example

Loading the example.

Try this

  • Clear the tree and press One simulation a few times: the first visits follow the prior into cell 6.
  • Press Run and watch the visits leave cell 6 for cell 5 once the search has seen O's winning reply.
  • Raise c_puct to 4, then lower it to 0.2, and compare how widely the visits are spread.
  • Click an empty cell to play there and search the new position from the other side.

Code sample

from impl import AlphaZero, TicTacToe
from config import AlphaZeroConfig

agent = AlphaZero(AlphaZeroConfig())
losses = agent.train(n_iterations=10)                      # 200 self-play games
print(losses[0], losses[-1])                               # the loss falls
print(agent.play_vs_random(50, use_search=False))          # the network alone, no search
state = TicTacToe.initial_state()
print(agent.best_action(state))                            # move chosen by search
Read the implementation (259 lines)
"""AlphaZero on tic-tac-toe: a policy and value network, PUCT tree search guided by it, and self-play training.

NumPy only, manual backpropagation. This is a small version of the algorithm: the game is tic-tac-toe, the
network is a one-hidden-layer MLP and everything runs in one process.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import AlphaZeroConfig
except ImportError:  # run from the template's own folder
    from config import AlphaZeroConfig

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


class TicTacToe:
    """Game rules. A state is (board, player): board is a tuple of 9 cells in {1, -1, 0}, player is 1 or -1."""

    n_actions = 9
    obs_dim = 18

    @staticmethod
    def initial_state():
        return (0,) * 9, 1

    @staticmethod
    def legal_actions(state) -> list[int]:
        return [i for i, cell in enumerate(state[0]) if cell == 0]

    @staticmethod
    def next_state(state, action: int):
        board, player = state
        if board[action] != 0:
            raise ValueError(f"cell {action} is taken")
        return board[:action] + (player,) + board[action + 1 :], -player

    @staticmethod
    def winner(state) -> int | None:
        """1 or -1 if that player has three in a row, 0 for a draw, None while the game is still open."""
        board = state[0]
        for a, b, c in _LINES:
            if board[a] != 0 and board[a] == board[b] == board[c]:
                return board[a]
        return 0 if all(board) else None

    @staticmethod
    def encode(state) -> np.ndarray:
        """Network input from the point of view of the player to move, shape (18,): own stones, then the opponent's."""
        board = np.array(state[0]) * state[1]
        return np.concatenate([board == 1, board == -1]).astype(float)


class PolicyValueNet:
    """obs (B, 18) -> tanh hidden layer -> policy logits (B, 9) and a tanh value (B,) in [-1, 1]."""

    def __init__(self, config: AlphaZeroConfig, obs_dim: int = 18, n_actions: int = 9) -> None:
        self.config = config
        rng = np.random.default_rng(config.seed)
        h = config.hidden_size
        self.params = [
            rng.normal(0.0, 1.0 / math.sqrt(obs_dim), size=(obs_dim, h)), np.zeros(h),
            rng.normal(0.0, 1.0 / math.sqrt(h), size=(h, n_actions)), np.zeros(n_actions),
            rng.normal(0.0, 1.0 / math.sqrt(h), size=(h, 1)), np.zeros(1),
        ]
        self._m = [np.zeros_like(p) for p in self.params]
        self._v = [np.zeros_like(p) for p in self.params]
        self._t = 0

    def forward(self, obs: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        """Returns (policy logits (B, 9), values (B,))."""
        w1, b1, wp, bp, wv, bv = self.params
        hidden = np.tanh(obs @ w1 + b1)
        return hidden @ wp + bp, np.tanh(hidden @ wv + bv)[:, 0]

    def predict(self, state, legal: list[int]) -> tuple[np.ndarray, float]:
        """Prior over the 9 cells (zero on illegal moves, sums to 1) and the value for the player to move."""
        logits, value = self.forward(TicTacToe.encode(state)[None])
        z = np.full(9, -np.inf)
        z[legal] = logits[0, legal]
        p = np.exp(z - z.max())
        return p / p.sum(), float(value[0])

    def loss_and_grads(self, obs: np.ndarray, target_pi: np.ndarray, target_z: np.ndarray):
        """AlphaZero loss: mean (z - v)^2 - mean pi . log p + l2 * |weights|^2.

        obs (B, 18), target_pi (B, 9) search policies, target_z (B,) game outcomes for the player to move.
        Returns (loss, gradients like params).
        """
        w1, b1, wp, bp, wv, bv = self.params
        hidden = np.tanh(obs @ w1 + b1)
        logits = hidden @ wp + bp
        value = np.tanh(hidden @ wv + bv)[:, 0]
        logits = logits - logits.max(axis=1, keepdims=True)
        log_p = logits - np.log(np.exp(logits).sum(axis=1, keepdims=True))
        n, l2 = len(obs), self.config.l2
        loss = float(((target_z - value) ** 2).mean() - (target_pi * log_p).sum(axis=1).mean())
        loss += l2 * sum(float((w**2).sum()) for w in (w1, wp, wv))
        d_logits = (np.exp(log_p) * target_pi.sum(axis=1, keepdims=True) - target_pi) / n
        d_value = (2.0 * (value - target_z) * (1.0 - value**2) / n)[:, None]
        d_hidden = (d_logits @ wp.T + d_value @ wv.T) * (1.0 - hidden**2)
        grads = [obs.T @ d_hidden + 2 * l2 * w1, d_hidden.sum(axis=0),
                 hidden.T @ d_logits + 2 * l2 * wp, d_logits.sum(axis=0),
                 hidden.T @ d_value + 2 * l2 * wv, d_value.sum(axis=0)]
        return loss, grads

    def train_step(self, obs, target_pi, target_z) -> float:
        """One Adam step on a batch. Returns the loss before the step."""
        loss, grads = self.loss_and_grads(obs, target_pi, target_z)
        self._t += 1
        for p, g, m, v in zip(self.params, grads, self._m, self._v):
            m *= 0.9
            m += 0.1 * g
            v *= 0.999
            v += 0.001 * g * g
            p -= self.config.learning_rate * (m / (1 - 0.9**self._t)) / (np.sqrt(v / (1 - 0.999**self._t)) + 1e-8)
        return loss


class _Node:
    """Search tree node. `value_sum` is from the point of view of the player who moved into this node."""

    __slots__ = ("prior", "visits", "value_sum", "children")

    def __init__(self, prior: float) -> None:
        self.prior, self.visits, self.value_sum = prior, 0, 0.0
        self.children: dict[int, _Node] = {}


class MCTS:
    """PUCT search: pick the child maximizing Q + c_puct * prior * sqrt(parent visits) / (1 + child visits)."""

    def __init__(self, config: AlphaZeroConfig, net: PolicyValueNet, rng: np.random.Generator) -> None:
        self.config, self.net, self.rng = config, net, rng

    def _expand(self, node: _Node, state) -> float:
        """Add the children of `node` with the network's priors. Returns the value for the player to move."""
        legal = TicTacToe.legal_actions(state)
        priors, value = self.net.predict(state, legal)
        for a in legal:
            node.children[a] = _Node(float(priors[a]))
        return value

    def _select(self, node: _Node) -> tuple[int, _Node]:
        scale = self.config.c_puct * math.sqrt(node.visits)
        best, best_score = None, -math.inf
        for action, child in node.children.items():
            q = child.value_sum / child.visits if child.visits else 0.0
            score = q + scale * child.prior / (1 + child.visits)
            if score > best_score:
                best, best_score = (action, child), score
        return best

    def search(self, state, add_noise: bool = False) -> np.ndarray:
        """Run `n_simulations` from `state`. Returns the visit counts of the 9 cells, shape (9,).

        add_noise: mix Dirichlet noise into the root priors (used in self-play to keep exploring).
        """
        c = self.config
        root = _Node(1.0)
        self._expand(root, state)
        if add_noise:
            noise = self.rng.dirichlet([c.dirichlet_alpha] * len(root.children))
            for child, eta in zip(root.children.values(), noise):
                child.prior = (1 - c.dirichlet_eps) * child.prior + c.dirichlet_eps * eta
        root.visits = 1
        for _ in range(c.n_simulations):
            node, s, path = root, state, []
            while node.children:
                action, node = self._select(node)
                s = TicTacToe.next_state(s, action)
                path.append(node)
            won = TicTacToe.winner(s)
            if won is None:
                value = self._expand(node, s)
            else:  # terminal: the player to move has lost if anyone won (the opponent just moved), else a draw
                value = 0.0 if won == 0 else -1.0
            root.visits += 1
            for node in reversed(path):  # each step up changes whose point of view the value is from
                value = -value
                node.visits += 1
                node.value_sum += value
        counts = np.zeros(9)
        for action, child in root.children.items():
            counts[action] = child.visits
        return counts


class AlphaZero:
    """Self-play training loop and the playing agent."""

    def __init__(self, config: AlphaZeroConfig | None = None) -> None:
        self.config = config or AlphaZeroConfig()
        self.rng = np.random.default_rng(self.config.seed)
        self.net = PolicyValueNet(self.config)
        self.mcts = MCTS(self.config, self.net, self.rng)
        self.buffer: list[tuple[np.ndarray, np.ndarray, float]] = []  # (encoded state, search policy, outcome)

    def self_play_game(self) -> list[tuple[np.ndarray, np.ndarray, float]]:
        """Play one game against itself. Returns one (obs, search policy, outcome for the player to move) per move."""
        state, moves, history = TicTacToe.initial_state(), 0, []
        while TicTacToe.winner(state) is None:
            counts = self.mcts.search(state, add_noise=True)
            pi = counts / counts.sum()
            history.append((TicTacToe.encode(state), pi, state[1]))
            if moves < self.config.temperature_moves:
                action = int(self.rng.choice(9, p=pi))  # temperature 1: sample in proportion to visits
            else:
                action = int(counts.argmax())
            state = TicTacToe.next_state(state, action)
            moves += 1
        won = TicTacToe.winner(state)
        return [(obs, pi, float(won * player)) for obs, pi, player in history]

    def train_iteration(self) -> float:
        """One iteration: self-play games into the buffer, then gradient steps on it. Returns the mean loss."""
        c = self.config
        for _ in range(c.games_per_iteration):
            self.buffer.extend(self.self_play_game())
        self.buffer = self.buffer[-c.buffer_size :]
        losses = []
        for _ in range(c.train_steps_per_iteration):
            idx = self.rng.integers(0, len(self.buffer), size=min(c.batch_size, len(self.buffer)))
            obs = np.array([self.buffer[i][0] for i in idx])
            pi = np.array([self.buffer[i][1] for i in idx])
            z = np.array([self.buffer[i][2] for i in idx])
            losses.append(self.net.train_step(obs, pi, z))
        return float(np.mean(losses))

    def train(self, n_iterations: int) -> list[float]:
        """Run `n_iterations` iterations. Returns the mean loss of each."""
        return [self.train_iteration() for _ in range(n_iterations)]

    def best_action(self, state, use_search: bool = True) -> int:
        """Move to play in `state`: the most visited move of a search, or the network's top prior without search."""
        if use_search:
            return int(self.mcts.search(state).argmax())
        return int(self.net.predict(state, TicTacToe.legal_actions(state))[0].argmax())

    def play_vs_random(self, n_games: int, use_search: bool = True, seed: int = 0) -> dict:
        """Play `n_games` against a uniformly random opponent, alternating who starts. Returns win/draw/loss counts."""
        rng = np.random.default_rng(seed)
        result = {"win": 0, "draw": 0, "loss": 0}
        for game in range(n_games):
            me = 1 if game % 2 == 0 else -1
            state = TicTacToe.initial_state()
            while TicTacToe.winner(state) is None:
                if state[1] == me:
                    action = self.best_action(state, use_search)
                else:
                    legal = TicTacToe.legal_actions(state)
                    action = legal[int(rng.integers(len(legal)))]
                state = TicTacToe.next_state(state, action)
            won = TicTacToe.winner(state)
            result["draw" if won == 0 else "win" if won == me else "loss"] += 1
        return result
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
10, run with python3 -m unittest -v

Practice

Create AlphaZero(AlphaZeroConfig()) and record play_vs_random(50, use_search=False) and play_vs_random(50, use_search=True) before training. Call train(n_iterations=10), check that the returned losses fall, and record both results again. Then, on the empty board from TicTacToe.initial_state(), compare the network's prior from agent.net.predict with the counts from agent.mcts.search.

Check on learning

  1. The network is trained toward the search's visit counts, and the search is guided by the network. Why does this loop improve the network instead of just confirming what it already believes?
    A way to think about it

    Ask what information the search has that the network's prior does not. Think about what happens when a line reaches the end of the game.

  2. Why does the backed-up value change sign at every level of the tree? What would the search do if it did not?
    A way to think about it

    Each node stores results from the point of view of the player who moved into it. Imagine both players trying to maximize the same number.

  3. Before training, the agent with search already beats a random player more often than the network alone. Where does that strength come from?
    A way to think about it

    Look at what the search does when a simulation reaches a finished game. Those values do not come from the network.

  4. What would self-play look like with dirichlet_eps set to 0 and temperature_moves set to 0? What would the training buffer contain after 200 games?
    A way to think about it

    With no randomness, follow how the first move of every game is chosen and count how many different games can occur.

  5. Tic-tac-toe is a draw with best play. If training went perfectly, what should the value head output for the empty board, and what should the policy target look like?
    A way to think about it

    Think about which first moves keep the draw. A perfect search may split its visits among several moves that are equally good.