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
PolicyValueNet.predicttakes a position, seen from the side of the player to move, and returns a prior over legal moves and a value between and .MCTS.searchrunsn_simulationsdescents. Each one walks down the tree by picking, at every node, the child with the highest PUCT score.- 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.
- 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.
AlphaZero.self_play_gameplays 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.train_iterationaddsgames_per_iterationgames to the buffer and takestrain_steps_per_iterationAdam steps that pull the policy toward the visit distributions and the value toward the outcomes.best_actionplays the most visited move of a fresh search, or the network's top move whenuse_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
| If | Use instead |
|---|---|
| The rules or dynamics are not known and must be learned | MuZero |
| You only need the search with a model you already have, without learning | The shared planning lesson: Monte Carlo tree search |
| There is no opponent or search budget and actions are few | DQN or PPO |
Math foundations
The network
One network with two outputs. is a probability for each move and is the expected result for the player to move: a win, a loss, 0 a draw.
Selecting a move inside the tree (PUCT)
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.
Backing up a result
Every move on the path counts one more visit and adds the leaf's value, with replaced by at each step up. is the average result of all simulations that went through the move.
Noise at the root during self-play
Mixing random noise into the root prior gives every legal move some chance of being searched, even one the network currently dismisses.
The search policy
The share of simulations that started with each move. This is the policy target. It is stronger than because it includes what the search found by reading ahead.
The training loss
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
- a game position, and the root position of a search
- the policy and value network with weights theta
- the network's prior over moves and its entry for move a
- the network's value for the player to move, between -1 and 1
- prior stored on a move in the tree
- number of simulations that took move a from s
- visit count of the parent position s
- summed and average backed-up value of move a
- exploration constant of the selection rule
- weight and concentration of the root noise
- the search policy: normalized root visit counts
- final game outcome for the player to move: +1, 0 or -1
- weight of the L2 penalty
Worked by hand
A node has been visited times and . Move A has , prior 0.5 and 6 visits. Move B has , prior 0.3 and 1 visit. Which does the next simulation take?
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 searchRead 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
- 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.
- 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.
- 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.
- What would self-play look like with
dirichlet_epsset to 0 andtemperature_movesset 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.
- 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.