Course contents 04 / 27

04 / 27 · Agents and Environments

Games and Monte Carlo tree search

Search against an opponent and search by sampling: minimax and alpha–beta pruning with its best-case count, Monte Carlo tree search with UCT and UCB1, what the networks of AlphaGo, AlphaZero and MuZero replace in the search, and the link to language-model planning.

On this page 7

Markov decision processes treated the uncertainty of the world as chance: the next state was drawn from a known distribution. In a game, much of what happens next is chosen by another agent whose goal is the opposite of ours, and averaging over its moves would be a mistake. Games also break the other assumption of value iteration, that every state can be visited: chess and Go have far more positions than could ever be listed. This note therefore searches forward from the current position only, first exhaustively with minimax and alpha–beta pruning, then by sampling with Monte Carlo tree search, and finally with neural networks that tell the search where to look and when to stop, as in AlphaGo, AlphaZero and MuZero. The same pattern, a search guided by a learned model, is how language models are made to plan later in the course.

Notation. We consider two-player, zero-sum, deterministic games of perfect information: the players, MAX and MIN, alternate moves, both see the whole position, and one player’s gain is the other’s loss. A position is ss; Terminal(s)\mathrm{Terminal}(s) says whether the game is over, and U(s)U(s) is then its utility for MAX (for example +1+1, 00, −1-1). bb is the branching factor and dd the depth searched. In alpha–beta search, α\alpha is the best value MAX is already guaranteed on the current path and β\beta the best for MIN. In Monte Carlo tree search, N(s)N(s) is the number of visits of a node, N(s,a)N(s, a) that of the child reached by move aa, W(s,a)W(s, a) the total reward credited to it and Xˉ(s,a)=W(s,a)/N(s,a)\bar X(s, a) = W(s, a)/N(s, a) its mean; cc is an exploration constant.

Baseline: the opponent as part of the environment#

The simplest model of an opponent is the one of the previous note: treat its moves as random and maximize the expected outcome. Take the tree of the figure below, where MAX has three moves and MIN then picks one of three replies with the values

(4,7,5),(2,9,6),(8,3,1).(4, 7, 5), \qquad (2, 9, 6), \qquad (8, 3, 1).

If MIN chose at random, the moves would be worth the averages 5.335.33, 5.675.67 and 44, and the second move would look best. An opponent who wants MAX to lose answers it with the leaf worth 2. The first move guarantees 4 whatever MIN does. Against an adversary the right question is not “what happens on average” but “what is the worst reply, and which move makes that worst reply best”. Answering it exactly is minimax; answering it with less computation is the rest of the note.

Minimax#

The minimax value of a position is the utility for MAX when both players play optimally from there on (Russell and Norvig, 2021, chapter 5):

  Minimax(s)={U(s)if Terminal(s),max⁡aMinimax(Result(s,a))if MAX moves in s,min⁡aMinimax(Result(s,a))if MIN moves in s.  \boxed{\; \mathrm{Minimax}(s) = \begin{cases} U(s) & \text{if } \mathrm{Terminal}(s), \\ \max_{a} \mathrm{Minimax}(\mathrm{Result}(s, a)) & \text{if MAX moves in } s, \\ \min_{a} \mathrm{Minimax}(\mathrm{Result}(s, a)) & \text{if MIN moves in } s . \end{cases} \;}

It is the Bellman optimality equation of the previous note with the expectation over chance replaced by a minimum over the opponent’s moves, and with no discount because a game ends. The minimax algorithm computes it by depth-first recursion to the end of the game. It visits every node of the game tree, so for depth mm and branching factor bb it takes time O(bm)O(b^m), and memory O(bm)O(bm) for the current path and its siblings.

Small games can be solved this way. Tic-tac-toe from the empty board has a game tree of 549,946 nodes, and minimax over all of them returns 0: with best play it is a draw. Chess, with about 35 legal moves per position and games of about 80 plies (moves of one player), would need a tree of roughly 3580≈1012335^{80} \approx 10^{123} nodes. Two remedies follow. One prunes the tree without changing the answer; the other stops before the end of the game and estimates the value there.

Alpha–beta pruning#

Many branches of the tree cannot affect the decision at the root. Alpha–beta search passes two bounds down the recursion: α\alpha, the value of the best move MAX has already found on the path to the current node, and β\beta, the same for MIN. A MIN node whose value drops to α\alpha or below can be abandoned, because MAX already has a move at least that good elsewhere and will never let play reach this node; symmetrically, a MAX node is abandoned once its value reaches β\beta.

Figure

Alpha–beta pruning on a tree of depth 2

Alpha–beta pruning on a tree of depth 2A MAX root with three MIN children, each over three leaves: 4, 7, 5; 2, 9, 6; 8, 3, 1. The first MIN node gets the value 4. Below the second, the leaves 9 and 6 are pruned after the leaf 2; below the third, the leaf 1 is pruned after the leaves 8 and 3. The root gets the value 4; 6 of the 9 leaves are evaluated.47541296≤ 2pruned2831≤ 3pruned344MAXMINAlpha–beta pruning on a tree of depth 2A MAX root with three MIN children, each over three leaves: 4, 7, 5; 2, 9, 6; 8, 3, 1. The first MIN node gets the value 4. Below the second, the leaves 9 and 6 are pruned after the leaf 2; below the third, the leaf 1 is pruned after the leaves 8 and 3. The root gets the value 4; 6 of the 9 leaves are evaluated.47541296≤ 2pruned2831≤ 3pruned344MAX
MAX (triangle pointing up) picks the move with the largest value, MIN (pointing down) the smallest. The search goes from left to right and remembers α, the best value MAX can already guarantee. As soon as the value of a MIN node drops to α or below, its remaining leaves cannot change anything: MAX will not go there. 6 of the 9 leaves are evaluated, and the root's value, 4, is the same as full minimax gives.
  1. First MIN node. All three leaves are needed: its value is min⁡(4,7,5)=4\min(4, 7, 5) = 4, and at the root α=4\alpha = 4.
  2. Second MIN node. Its first leaf is 2. Whatever the other two are, MIN can force a value ≤2<α\le 2 < \alpha, so MAX will not play this move: the leaves 9 and 6 are pruned.
  3. Third MIN node. The leaf 8 does not settle it; the next leaf 3 does, since 3<α3 < \alpha: the leaf 1 is pruned.
  4. Root. max⁡(4,≤2,≤3)=4\max(4, {\le}2, {\le}3) = 4: the first move, with the same value as minimax, after evaluating 6 of the 9 leaves.

The pruned values differ from the minimax values of their subtrees, but the root’s value and the chosen move are always the same as with minimax (Knuth and Moore, 1975). How much is pruned depends on the order in which moves are tried. If the best move is always tried first, alpha–beta evaluates exactly

b⌈d/2⌉+b⌊d/2⌋−1b^{\lceil d/2 \rceil} + b^{\lfloor d/2 \rfloor} - 1

leaves of a uniform tree of depth dd (Knuth and Moore, 1975), about 2bd/22 b^{d/2} instead of bdb^d: the effective branching factor drops from bb to b\sqrt b, and in the same time the search goes twice as deep. On uniform trees with random leaf values:

Figure

How many leaves alpha–beta evaluates

How many leaves alpha–beta evaluatesA log scale of the number of leaves evaluated, from 1 to 10⁵, against the depth from 1 to 8 with b = 4. Minimax grows as 4ᵈ, up to 65,536. Alpha–beta with the best ordering grows as 4 to the power d/2, up to 511 leaves. Alpha–beta in random order lies in between, 7287 leaves on average at depth 8.110¹10²10³10⁴10⁵12345678tree depth dleaves evaluatedminimax, bᵈ65,536alpha–beta, random order7,287alpha–beta, best order511How many leaves alpha–beta evaluatesA log scale of the number of leaves evaluated, from 1 to 10⁵, against the depth from 1 to 8 with b = 4. Minimax grows as 4ᵈ, up to 65,536. Alpha–beta with the best ordering grows as 4 to the power d/2, up to 511 leaves. Alpha–beta in random order lies in between, 7287 leaves on average at depth 8.110¹10²10³10⁴10⁵12345678tree depth dleaves evaluatedminimax, bᵈalpha–beta, random orderalpha–beta, best order
Uniform trees with b = 4 moves at every node and leaf values drawn uniformly at random; 10 trees per depth, the same ones for all three methods. All three return the same root value. With perfect move ordering alpha–beta evaluates exactly b^⌈d/2⌉ + b^⌊d/2⌋ − 1 leaves (Knuth and Moore), 511 against 65,536 at depth 8: in the same time it can search twice as deep. In random order it evaluates 7287 leaves on average, an effective branching factor of 3.04 instead of 4.

At depth 8 with b=4b = 4, perfect ordering evaluates 511 leaves against 65,536 for minimax, exactly the formula; random ordering evaluates 7,287 on average, an effective branching factor of 3.043.04. On tic-tac-toe, alpha–beta in the plain left-to-right order of the squares visits 18,297 nodes instead of 549,946. Real programs order moves with cheap heuristics, such as trying captures first or the moves that were best in a previous, shallower search, and come close to the best case.

Cutting off the search. For chess even bd/2b^{d/2} is too much to reach the end of the game. Following Shannon (1950), programs stop at a fixed depth and apply an evaluation function, a heuristic estimate of the minimax value, such as a weighted sum of material and positional features. Deep Blue, which beat the world champion Garry Kasparov in 1997, combined alpha–beta search on special-purpose chess chips with a large evaluation function written and tuned by hand (Campbell, Hoane and Hsu, 2002). The quality of the program rests on the evaluation function, and in Go nobody managed to write a good one: positions have about 250 legal moves, and their value depends on subtle, long-range patterns.

Monte Carlo tree search (MCTS) needs no evaluation function. It estimates the value of a position by Monte Carlo: play the game out from there many times with random moves and average the results. And it builds a search tree that grows towards the moves that look best, so that the averages there are computed with better than random play (Coulom, 2006; Browne et al., 2012). Each iteration has four phases:

Figure

One iteration of Monte Carlo tree search

One iteration of Monte Carlo tree searchA tree: the root with 24 visits; its children A (11 wins of 14), B (1 of 6) and C (0 of 4) with UCB1 scores 1.460, 1.196 and 1.261. A is selected. Under A are A1 (1 of 8), A2 (2 of 5) and the new node A3. From A3 a dashed random playout ends in a win for the player who moved into A. After the update: A3 has 0 of 1, A 12 of 15, the root 25 visits.root: n = 24A11/14B1/6C0/4A11/8A22/5UCB 1.460UCB 1.196UCB 1.2611A3new2random playoutthe player whomoved into A wins30/1→ 12/15→ n = 254w/n: wins and visits of the playerwho made the move into the nodeOne iteration of Monte Carlo tree searchA tree: the root with 24 visits; its children A (11 wins of 14), B (1 of 6) and C (0 of 4) with UCB1 scores 1.460, 1.196 and 1.261. A is selected. Under A are A1 (1 of 8), A2 (2 of 5) and the new node A3. From A3 a dashed random playout ends in a win for the player who moved into A. After the update: A3 has 0 of 1, A 12 of 15, the root 25 visits.root: n = 24A11/14B1/6C0/4A11/8A22/51.4601.1961.2611A3new2random playoutthe player whomoved into A wins30/1→ 12/15→ n = 254w/n: wins and visits of the playerwho made the move into the node
The score w/n of each node is kept for the player who made the move into it, so a parent picks a child by that child's own score. UCB1 = w/n + √2 · √(ln N / n) with N = 24 visits of the parent: for A 0.786 + 0.674 = 1.460, for B 0.167 + 1.029 = 1.196, for C 0 + 1.261 = 1.261. The weak but rarely visited C overtakes B: the exploration bonus grows as a node's visits shrink. During backpropagation the win counts on alternate levels: A (a move of the player at the root) gets a win, A3 (a move of the opponent) a loss.
  1. Selection. From the root, repeatedly move to a child chosen by a selection rule, until a node is reached that still has untried moves (or is terminal).
  2. Expansion. Add one child for an untried move.
  3. Simulation. From the new node, play random moves to the end of the game (a playout or rollout) and note the winner.
  4. Backpropagation. Walk back to the root, adding one visit to every node on the path and the result to the score of every node whose player won.

After the last iteration the program plays the root move with the most visits, which is more robust than the one with the best mean, since a mean based on few visits can be high by chance.

Selection as a bandit problem: UCB1 and UCT#

Choosing a child at each node is a multi-armed bandit problem: each move is an arm with an unknown mean reward, and every pull of one arm is a pull not spent on another. Pulling only the arm with the best mean so far can lock onto a move that was lucky early; pulling uniformly wastes samples on moves already known to be bad. The UCB1 rule (Auer, Cesa-Bianchi and Fischer, 2002) picks the arm with the largest upper confidence bound,

  a⋆=arg⁡max⁡a(Xˉ(s,a)+cln⁡N(s)N(s,a) )  \boxed{\; a^\star = \arg\max_a \Big( \bar X(s, a) + c \sqrt{\frac{\ln N(s)}{N(s, a)}} \,\Big) \;}

with rewards in [0,1][0, 1]. The first term exploits: it prefers moves that have done well. The second explores: it grows slowly with the visits of the parent and shrinks with the visits of the child, so that every move is tried again from time to time, and the less it has been tried the sooner. With c=2c = \sqrt 2, UCB1’s expected regret, the reward lost against always pulling the best arm, grows only logarithmically with the number of pulls (Auer et al., theorem 1), and no rule can do better than logarithmic growth (Lai and Robbins, 1985). UCT (“UCB applied to trees”, Kocsis and Szepesvári, 2006) uses this rule at every node of the tree, where Xˉ(s,a)\bar X(s, a) is the fraction of playouts through the child that were won by the player who moves at ss. Kocsis and Szepesvári prove that the probability of choosing a wrong move at the root goes to zero as the number of iterations grows: UCT converges to the minimax decision.

Worked example. The root has N=24N = 24 visits and three children: A won 11 of 14, B 1 of 6, C 0 of 4. With c=2c = \sqrt 2 and ln⁡24=3.178\ln 24 = 3.178:

A:1114+2⋅3.178/14=0.786+0.674=1.460,B:16+2⋅3.178/6=0.167+1.029=1.196,C:04+2⋅3.178/4=0+1.261=1.261.\begin{aligned} \text{A:}\quad & \tfrac{11}{14} + \sqrt{2 \cdot 3.178 / 14} = 0.786 + 0.674 = 1.460, \\ \text{B:}\quad & \tfrac{1}{6} + \sqrt{2 \cdot 3.178 / 6} = 0.167 + 1.029 = 1.196, \\ \text{C:}\quad & \tfrac{0}{4} + \sqrt{2 \cdot 3.178 / 4} = 0 + 1.261 = 1.261 . \end{aligned}

A is selected. C, with no wins at all, still beats B, because it has been visited less: the bonus is doing its job. The figure continues the iteration: A has an untried move, so a child A3 is added; a random playout from A3 ends with a win for the player who moved into A; A becomes 12 of 15, A3 becomes 0 of 1 (it was the opponent’s move into A3, and the opponent lost), and the root has 25 visits.

On a small game. In Nim with heaps of 1, 3 and 5 objects, a move takes any number of objects from one heap and whoever takes the last object wins. The position is a win for the player to move, and of its 9 moves exactly one wins: taking 3 from the heap of 5, which leaves heaps whose bitwise exclusive or, the nim-sum, is zero. The Code section runs UCT 100 times with different seeds and counts how often the most visited root move is the winning one: 11 times after 10 iterations, 39 after 300, only 24 after 1000, then 94 after 2000 and 100 after 3000. The dip is instructive. Early on, every move looks reasonable because random playouts blunder; as the tree deepens, the search discovers its own bad replies inside the winning subtree, which lower that move’s average for a while; only when the visits at every level concentrate on the best replies does the average approach the minimax value. MCTS converges, but its backed-up values are averages over a policy that is still exploring, and they can mislead on the way.

What the network replaces: AlphaGo, AlphaZero and MuZero#

Plain MCTS spends its samples evenly among moves it has never tried, and it judges a position by random games that resemble real play poorly. Both weaknesses can be fixed by a model that has learned what good moves and good positions look like. The three systems of DeepMind replace one more part of the search each time.

AlphaGo (Silver et al., 2016) added two convolutional networks to MCTS. A policy network, first trained to predict the moves of strong human players on 30 million positions from the KGS Go server (57.0% of expert moves predicted correctly) and then improved by self-play, gives every move a prior probability P(s,a)P(s, a). Selection uses it in a variant of UCB, the PUCT rule:

a⋆=arg⁡max⁡a(Q(s,a)+cpuct P(s,a) N(s)1+N(s,a)),a^\star = \arg\max_a \Big( Q(s, a) + c_{\text{puct}}\, P(s, a)\, \frac{\sqrt{N(s)}}{1 + N(s, a)} \Big),

so that moves the network considers unlikely are hardly explored at all: the prior narrows the breadth of the search. A value network, trained to predict the winner from a position, evaluates leaves and cuts the depth: the leaf value is V(sL)=(1−λ) vθ(sL)+λzLV(s_L) = (1 - \lambda)\, v_\theta(s_L) + \lambda z_L, a mix of the network’s estimate and the outcome zLz_L of one fast rollout, and the mix with λ=0.5\lambda = 0.5 played best. AlphaGo won 494 of 495 games (99.8%) against other Go programs and beat the European champion Fan Hui 5–0 in October 2015, the first win of a program over a human professional on a full-sized board without handicap. It evaluated thousands of times fewer positions than Deep Blue had in chess.

AlphaGo Zero (Silver et al., 2017) and AlphaZero (Silver et al., 2018) removed human games and rollouts. One network computes both outputs, (p,v)=fθ(s)(p, v) = f_\theta(s); MCTS with the PUCT rule evaluates each new leaf by vv alone. Training is by self-play: each move is chosen by a search, the search’s visit counts at the root form a distribution π\pi over moves, and at the end of the game its outcome zz is known. The network is trained to match both,

ℓ(θ)=(z−v)2−π⊤log⁡p+c∥θ∥2,\ell(\theta) = (z - v)^2 - \pi^\top \log p + c \lVert \theta \rVert^2 ,

the squared error of the value and the cross-entropy of the policy against the search, with weight decay. The search acts as a policy improvement operator: its visit counts are a better policy than the network’s prior, the network learns to imitate them, and the next search starts from a better prior. It is policy iteration, with search in the role of the improvement step and a network in the role of the table. In the preprint of AlphaZero (Silver et al., 2017b), each search during training used 800 simulations; the same algorithm and hyperparameters, given only the rules, outperformed the world-champion chess program Stockfish after 4 hours of training and the shogi program Elmo after less than 2, and won the 100-game chess match against Stockfish with 28 wins, 72 draws and no losses at one minute per move. It searched about 80 thousand positions per second against Stockfish’s 70 million: the network made each position examined count for far more.

MuZero (Schrittwieser et al., 2020) removed the rules. AlphaZero still needed a simulator to know which moves are legal and where a move leads. MuZero learns three functions instead: a representation hh that encodes the observations into a hidden state s0s^0, a dynamics function gg that maps a hidden state and an action to a predicted reward and the next hidden state, rk,sk=g(sk−1,ak)r^k, s^k = g(s^{k-1}, a^k), and a prediction function ff that gives a policy and a value, pk,vk=f(sk)p^k, v^k = f(s^k). MCTS runs entirely inside this learned model. The hidden state is not trained to reconstruct the screen or the board, only to predict the quantities the search needs, rewards, values and policies, over K=5K = 5 unrolled steps. With 800 simulations per move in board games and 50 in Atari, MuZero matched AlphaZero in Go, chess and shogi without being told the rules, and set a new state of the art on 57 Atari games at the time of publication (2019). Learned world models of this kind are the subject of Model-based reinforcement learning.

part of the searchplain MCTSAlphaGo (2016)AlphaZero (2017–18)MuZero (2019–20)
which moves to exploreUCB1, all moves alikeprior from a policy networkprior from the networkprior from the network
value of a leafrandom playoutvalue network mixed with a rolloutvalue network onlyvalue from a learned hidden state
where a move leadsthe game’s rulesthe rulesthe rulesa learned dynamics model
training datanonehuman games, then self-playself-play onlyself-play, or the agent’s own experience

Toward planning with language models#

The same decomposition carries over to agents built on language models, where the “game” is a task and a move is a step of reasoning or an action. A language model can play each role of the table above. It can propose candidate next steps, a policy prior that narrows the breadth. It can rate a partial solution, a value estimate that shortens the depth. And it can predict the result of an action, a world model in place of a simulator. Tree of Thoughts (Yao et al., 2023) uses the first two inside breadth-first or depth-first search, as Search and planning described; RAP (Hao et al., 2023) runs MCTS with the model as both the world model and the reward; LATS (Zhou et al., 2024) runs MCTS over the actions of an agent, with the environment’s real feedback and the model’s self-evaluation as values. The lesson of AlphaZero also carries over: more search at decision time buys better decisions, and a search can produce better targets than the model that guides it, which can then be trained on them. Planning with language models develops the first idea, and Reasoning models and test-time compute the second.

What changed#

minimaxalpha–betaMCTS (UCT)AlphaZero
how a position is valuedexact, to the end of the gameexact, or an evaluation function at a cutoffmean of random playoutsa learned value network
which moves are searchedallall that can still mattermore often the good and the uncertain onesthose the learned prior favours
guaranteethe minimax valuethe same value, fewer nodesconverges to minimax as iterations grownone, measured by play
cost on the examples549,946 nodes for tic-tac-toe18,297 nodes; 511 of 65,536 leaves at best2000–3000 iterations for Nim (1, 3, 5)800 simulations per move

Limitations#

  • The assumptions of the game. Minimax and alpha–beta assume two players, zero sum, determinism and perfect information. Chance (backgammon) needs expectations at chance nodes; hidden information (poker) needs reasoning over beliefs and randomized strategies, and different algorithms.
  • Minimax assumes a perfect opponent. Against a weak opponent it can pass up moves that would win in practice; it also says nothing about which of several equally valued moves gives the opponent more chances to err.
  • Evaluation functions are hand-made. Alpha–beta with a cutoff is only as good as its evaluation function, and writing one is the hard part.
  • MCTS values are averages. They converge to minimax only in the limit, can be misled by traps where a single precise reply refutes a move, and, as the Nim example shows, can get worse before they get better.
  • Learned guides cost data and compute. AlphaZero trained on thousands of special-purpose processors; its networks are tied to one game, and it needs a simulator (MuZero a learned one) that can be queried millions of times, which most real tasks do not provide.

What you should remember#

  • Against an adversary, value a move by the opponent’s best reply: the minimax value, a Bellman equation with a minimum over the opponent’s moves.
  • Alpha–beta returns the minimax decision while skipping branches outside the window (α,β)(\alpha, \beta); with perfect ordering it evaluates b⌈d/2⌉+b⌊d/2⌋−1b^{\lceil d/2 \rceil} + b^{\lfloor d/2 \rfloor} - 1 leaves, doubling the reachable depth.
  • MCTS repeats selection, expansion, simulation and backpropagation; UCT selects by UCB1, Xˉ+cln⁡N/n\bar X + c\sqrt{\ln N / n}, trading off exploitation and exploration, and converges to the minimax decision.
  • AlphaGo added a policy prior (breadth) and a value network (depth) to MCTS; AlphaZero dropped human data and rollouts and trained one network on the search’s own visit counts and outcomes; MuZero learned the dynamics too and planned in a learned latent space.
  • A language model can serve as prior, value or world model inside a search, and more search at decision time buys better decisions: the recipe of AlphaZero is the template for planning with language models.

Code#

Minimax and alpha–beta on tic-tac-toe, the worked example of the alpha–beta figure, and MCTS with UCT on Nim, repeated over 100 seeds. NumPy and the standard library only; seeds are fixed, and exact numbers can differ slightly across platforms and library versions. The script runs in under ten seconds.

import math
import numpy as np

# 1. minimax and alpha-beta on tic-tac-toe from the empty board: the value and the number of nodes visited
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] != 0 and b[i] == b[j] == b[k]: return b[i]
    return 0
def minimax(b, player, count):
    count[0] += 1
    w = winner(b)
    if w or 0 not in b: return w                      # +1 if X won, -1 if O won, 0 for a draw
    vals = []
    for m in range(9):
        if b[m] == 0:
            b[m] = player; vals.append(minimax(b, -player, count)); b[m] = 0
    return max(vals) if player == 1 else min(vals)
def alphabeta(b, player, alpha, beta, count):
    count[0] += 1
    w = winner(b)
    if w or 0 not in b: return w
    for m in range(9):
        if b[m] == 0:
            b[m] = player; v = alphabeta(b, -player, alpha, beta, count); b[m] = 0
            if player == 1: alpha = max(alpha, v)
            else: beta = min(beta, v)
            if alpha >= beta: break                      # the opponent will never let play reach here
    return alpha if player == 1 else beta
c1, c2 = [0], [0]
print(minimax([0] * 9, 1, c1), c1[0], alphabeta([0] * 9, 1, -2, 2, c2), c2[0])   # 0 549946 0 18297

# 2. the worked example of the text: a MAX root over three MIN nodes
leaves = [[4, 7, 5], [2, 9, 6], [8, 3, 1]]
seen, v = [], -math.inf
for kids in leaves:
    m = math.inf
    for x in kids:
        seen.append(x); m = min(m, x)
        if m <= v: break                                 # MAX already has something at least this good
    v = max(v, m)
print(v, seen)                                           # 4 [4, 7, 5, 2, 8, 3]

# 3. MCTS with UCT on Nim: heaps (1, 3, 5); a move takes any number from one heap; whoever takes the last object wins
def moves(s): return [(i, k) for i, h in enumerate(s) if h for k in range(1, h + 1)]
def play(s, m): t = list(s); t[m[0]] -= m[1]; return tuple(t)
def nim_sum(s): return int(np.bitwise_xor.reduce(np.array(s)))
class Node:
    def __init__(self, s, parent=None, move=None):
        self.s, self.parent, self.move = s, parent, move
        self.kids, self.untried = [], moves(s)
        self.n, self.w = 0, 0.0                          # visits, and wins of the player who moved into this node
def rollout(s, rng):                                     # random moves to the end; True if the mover into s wins
    turn = 0
    while sum(s):
        ms = moves(s); s = play(s, ms[rng.integers(len(ms))]); turn ^= 1
    return turn == 0                                     # an even number of moves: the mover into s took the last one
def mcts(root_state, iters, rng, evaluate=rollout, c=math.sqrt(2), checkpoints=()):
    root, picks = Node(root_state), {}
    for it in range(1, iters + 1):
        node = root
        while not node.untried and node.kids:            # 1. selection by UCB1
            node = max(node.kids, key=lambda k: k.w / k.n + c * math.sqrt(math.log(node.n) / k.n))
        if node.untried:                                 # 2. expansion
            m = node.untried.pop(rng.integers(len(node.untried)))
            node.kids.append(Node(play(node.s, m), node, m)); node = node.kids[-1]
        mover_won = evaluate(node.s, rng)                # 3. simulation: AlphaZero puts a value network here
        while node:                                      # 4. backpropagation, flipping the point of view
            node.n += 1; node.w += mover_won; mover_won = not mover_won; node = node.parent
        if it in checkpoints: picks[it] = max(root.kids, key=lambda k: k.n).move
    return root, picks
start = (1, 3, 5)
winning = [m for m in moves(start) if nim_sum(play(start, m)) == 0]
print(len(moves(start)), winning)                        # 9 [(2, 3)]: the only winning move takes 3 from the heap of 5

budgets = (10, 30, 100, 300, 1000, 2000, 3000)
def success(evaluate, seeds=100):
    hits = dict.fromkeys(budgets, 0)
    for seed in range(seeds):
        _, picks = mcts(start, max(budgets), np.random.default_rng(seed), evaluate, checkpoints=budgets)
        for b in budgets: hits[b] += picks[b] in winning
    return hits
print(success(rollout))                                  # how many of 100 runs pick the winning move
# {10: 11, 30: 21, 100: 19, 300: 39, 1000: 24, 2000: 94, 3000: 100}
root, _ = mcts(start, 3000, np.random.default_rng(0))
print([(k.move, k.n, round(k.w / k.n, 3)) for k in sorted(root.kids, key=lambda k: -k.n)[:3]])
# [((2, 3), 1814, 0.836), ((2, 2), 273, 0.56), ((1, 1), 236, 0.542)]

Next#

Every method of this section assumed a model of the world: the transition function of search and of MDPs, the rules of the game for minimax and AlphaZero, and, even in MuZero, a stream of experience from which a model could be learned. The next section drops the assumption that the agent knows how the world works. Q-learning and temporal-difference learning estimates the values of the Bellman equations directly from the rewards the agent receives as it acts, one transition at a time.

References#