Move A looks great on random games, but one reply refutes it. Flat Monte Carlo spreads 800 random games evenly and picks A. Tree search lets the wins steer the games, puts about 85% of them on the safe move B, and picks B.
Pick a searcher, set the budget, then press Search. Watch where the games go. Then we build, piece by piece, the playout, the bonus, the tree policy, the four phases, the flip, and the networks that AlphaGo, AlphaZero and MuZero added.
You need Monte Carlo (an average of random draws estimates an expectation; see the Monte Carlo lesson) and a little Python. We build the rest from zero.
An illustrative toy. Each reply has a hidden chance that a random game from it ends in our win. A 0.9, 0.9, 0.9, 0.05; B 0.6, 0.6, 0.55, 0.6; C 0.4, 0.5, 0.3, 0.45. With best play the values are A 0.05, B 0.55, C 0.30. The games are random, so each press gives a new run.
Chapter 0
Value a move by finishing the game at random many times, and measure how much to trust the average
It is your move in Go. There are about 250 legal moves, and a game lasts about 150 moves. A full search would visit about 250150, or 10360, positions. And no simple formula says how good a Go position is.
There is a cheap trick. From a candidate move, finish the game with random moves for both sides and record who won. One finished random game is a playout (also called a rollout). One playout is close to noise. The average of many playouts is not.
Each bar is a move's win rate so far. The whisker is its error bar. Press Playout ×1 a few times, then ×50, and watch the bars settle.
Illustrative. Each move has a hidden win chance (0.35, 0.50, 0.62, 0.45). Playouts go round-robin, so each move gets the same share.
Each move keeps two numbers. Call the number of playouts through it the visit count N. Call the number of those playouts that we won the win total W. The move's value estimate is Q.
Q equals W over N.
After each playout, add 1 to N and add the result to W. Divide W by N whenever you want the value Q. You never store the single results.
With made-up results 1, 0, 1, 1, 0, 1, 1, 0, 1, 1: W = 7 and N = 10, so Q = 0.7. One more win gives Q = 8 / 11 = 0.727.
How far can 0.7 be from the truth? Call the true win chance p. Each playout is a coin that lands 1 with chance p. The typical miss of Q is its standard error, SE.
S-E equals the square root of Q times one minus Q, over N.
Multiply Q by one minus Q. Divide by N. Take the square root. Four times the playouts halves SE.
Q = 0.7 and N = 10: SE = √(0.21 / 10) = 0.145. The true rate could be 0.55 or 0.85. With N = 1,000 the same Q has SE = 0.0145.
The failure. Symptom: the best move changes from run to run. Measure: compare the gap between the top two Q values with their SE. Fix: spend more playouts on the moves that are close to the top, not on the clear losers. That fix is the rest of this lesson.
Chapter 1
Add a bonus that is large for rarely tried moves and shrinks as you try them
You have a budget of playouts and five moves. Where should the next playout go? This is the multi-armed bandit problem: several slot machines (arms), each with an unknown payout, and limited pulls. The bandits lesson builds it from zero.
Two simple rules fail. Greedy always pulls the best mean so far, so one unlucky start can bury the true best arm forever. Uniform pulls every arm equally and wastes pulls on clear losers. UCB1 sits between them.
Name the parts first. Call the arm's mean value Q. Call the number of times we pulled this arm n. Call the total pulls at this node N. Call the exploration constant, a number you choose, c.
U-C-B-one equals Q plus c times the square root of the natural log of N, over n.
For each arm, divide ln N by n and take the square root. Multiply by c to get the bonus. Add the bonus to Q. Pull the arm with the highest total.
Q = 0.6, n = 10, N = 100, c = 1.414. ln 100 = 4.605. Divide by 10: 0.4605. The square root is 0.679, so the bonus is 0.960 and UCB1 = 1.560. At n = 100 and N = 1,000, the bonus falls to 0.372.
Why this shape? Hoeffding's inequality says that the mean of n results in 0 to 1 sits within √(ln(1/δ) / (2n)) of the truth, except with chance δ. Choose δ = 1/N4 and the width becomes √(2 ln N / n). That is the bonus with c = √2. So the score is an honest upper end of an interval.
Warm is the mean Q. Purple on top is the bonus. Press Pull best and watch that arm's cap shrink. Then slide c to 0 and see greedy lock in.
Illustrative. The hidden win chances are 0.45, 0.55, 0.70, 0.50 and 0.35. Each arm starts with 2 pulls of seeded results, one of them unlucky for the best arm.
The failure. Symptom: the search keeps pulling one arm, and a better arm sits at two pulls. Measure: print n for every arm after the search. Fix: raise c. If instead every arm has about the same n, c is too high.
Chapter 2
Walk down the tree by picking the highest UCB1 child at each node until you reach the edge
One bandit is one decision. A game is a decision, then a reply, then another decision. So stack the bandits. Each node of the tree treats its children as arms.
Kocsis and Szepesvári named this UCT, UCB applied to trees, in 2006. Start at the root. Score every child with UCB1, using the parent's visit count as N and the child's as n. Step into the winner. Repeat until you reach a node that still has an untried child. This walk is the tree policy.
A child with n = 0 has an infinite bonus. So UCT tries every child once before it repeats one. The same year, Rémi Coulom coined the name Monte Carlo Tree Search for his Go program Crazy Stone.
Each node shows its mean Q and visits n. Press Select and watch the pointer pick the highest score at each level. Then move c and select again.
Illustrative statistics. Each node's Q is from the view of the player who chooses at its parent. Chapter 4 shows how the views flip.
Work the root by hand with c = 1.414. The root has N = 200. Child A has Q = 0.7 and n = 80. Child B has Q = 0.55 and n = 20. ln 200 = 5.298.
B has the lower mean but wins. It has a quarter of A's visits, so its bonus is twice as large. UCT checks B again before it commits to A.
The failure. Symptom: the program plays the move with the best mean after a short search, and it loses. Measure: log both the move UCT selects during search and the move you return. Fix: use UCB1 only inside the search. Return the most visited move at the end (Chapter 5).
Chapter 3
Glue the playout and the tree policy into one loop that grows the tree one node at a time
You now have two parts: a playout that values a position (Chapter 0) and a tree policy that picks where to look (Chapter 2). MCTS runs them in a loop. One pass of the loop is an iteration, also called a simulation.
Repeat until the time runs out. Each iteration adds one node and one result. The tree grows where UCT sends it.
Blue is the select path and the new node. Teal is the random game. Warm is the update going back up. Press One iteration a few times, then Run 50.
An illustrative one-player toy: 3 moves per step, 3 steps deep, a hidden win chance at each end position. Chapter 4 adds an opponent and the flip.
Work one Select step by hand. A node has N = 50 and three children with c = 1.414, and ln 50 = 3.912.
The pointer enters C. Say C's new child plays out a win. Then C goes from 2 wins in 5 visits to 3 in 6, so its Q rises from 0.40 to 0.50. The parent goes to N = 51.
The failure. Symptom: memory runs out after a few seconds. Measure: count the nodes after each iteration. Fix: expand one child per iteration, not every reachable position below the leaf.
Chapter 4
Score every node from the view of the player who moves there, and flip the result at each level
A playout deep in the tree ends in a win for Black. That is good news for every node where Black chose. It is bad news for every node where White chose. One number cannot mean the same thing at both.
The fix is the negamax convention: each node stores results from the view of the player who made the move into it. On the way up, flip the result once per level. Call the result a node adds to its win total v. The parent, one level up, gets v′.
V-prime equals one minus v.
At each node on the path: add 1 to N, add v to W. Then set v to one minus v and step to the parent. Repeat until you pass the root.
A node has W = 6 and N = 10, so Q = 0.6. A win arrives: v = 1. Now W = 7, N = 11, Q = 0.636. The parent gets v′ = 1 − 1 = 0, so its Q goes down.
Warm nodes are our choices. Grey nodes are the opponent's. Press Send win and watch the 1 turn into 0 and back. Then switch the flip off.
Illustrative starting counts. "Win" means a win for the player who moved into the bottom node.
The flip is how the hero finds the refutation. Under move A, the opponent's node runs UCT too. It sees that reply 4 wins for it 95% of the time, so it sends most games there. A's value from our side then sinks toward 0.05. Flat Monte Carlo has no opponent node, so it averages all four replies and reports 0.69.
The failure. Symptom: the search plays into moves that lose to an obvious reply. Measure: check one opponent node by hand. Its Q should be high where we lose. Fix: flip v at every level, or store one result per player and read the mover's entry.
Chapter 5
Let the budget follow the value, stop whenever you must, and return the most visited move
A minimax tree is balanced: every branch goes to the same depth. An MCTS tree is lopsided. UCT keeps entering the good lines, so they grow deep. A bad line gets a few visits, enough to show it is bad, and then the search leaves it.
MCTS is also an anytime algorithm. Each iteration adds one more result. You can stop after any iteration and read off a move. A longer search gives a better move, not a different kind of answer.
Circle size is the visit count. The bars below count root visits per move. Press Run, then Stop at any moment and read the recommendation.
Illustrative toy game: 4 moves per turn, 4 turns deep, two players with the negamax flip. Only the top three levels are drawn.
Which move do you return? Call the visit count of root move a N(a). The returned move is a*.
A-star equals the arg-max over a of N of a.
Look at the root's children. Pick the one with the largest N(a). Ignore the bonus, and do not pick by Q alone.
With made-up counts after 1,600 iterations: N = 1,000, 400, 150 and 50. a* is the first move, with a share of 1,000 / 1,600 = 0.625. It got 1,000 / 50 = 20 times the visits of the worst move.
Why visits and not the mean? A move with 3 visits and 3 wins has Q = 1.0, but its standard error is huge. A move only collects 1,000 visits if UCT kept preferring it, iteration after iteration. Visit count is the vote of the whole search.
The failure. Symptom: now and then the program plays a strange move with a perfect record. Measure: print N and Q for each root move. Fix: return the most visited move, or require a minimum visit count before a move can be chosen.
Chapter 6
Weight the exploration bonus by how much a policy network likes each move
Plain UCT is blind at the start. In Go, every one of about 250 moves gets tried before any move gets a second look. Most of those moves are obviously bad to a strong player.
AlphaGo (Silver et al., 2016) learned two networks. A policy network, first trained on human expert games, gives each move a probability. A value network scores a position without finishing the game. AlphaGo beat Fan Hui 5 to 0 in 2015 and Lee Sedol 4 to 1 in March 2016.
The policy enters the selection rule. Call the policy's probability for a move the prior P. Keep Q, the parent's visits N, the child's visits n, and an exploration constant, here called cpuct.
P-U-C-T equals Q plus c-puct times P times the square root of N, over one plus n.
For each child, multiply c-puct by P and by the square root of N. Divide by one plus n. Add Q. A high-prior move gets a big early bonus, and its visits wear the bonus down.
N = 100, so √N = 10. Move A: Q 0.2, P 0.6, n 10: 0.2 + 1.5 × 0.6 × 10 / 11 = 1.018. Move B: Q 0.3, P 0.05, n 40: 0.3 + 0.75 / 41 = 0.318. Unvisited move C with P 0.6: 0 + 9 / 1 = 9.0, so C is tried first.
Warm is Q. Pink on top is the prior-weighted bonus. The strip under each bar is the prior. Press Visit ×10 with each prior and compare where the visits go.
Illustrative. Six moves with hidden values 0.30, 0.62, 0.35, 0.40, 0.25, 0.45. The learned prior is 0.05, 0.55, 0.10, 0.10, 0.05, 0.15. Each visit returns a noisy value, cpuct = 1.5.
AlphaGo also kept a fast playout. At a new leaf it mixed the value network's score v with one fast playout's result z, half and half (the paper's λ = 0.5). A v of 0.6 and a won playout give 0.8. The rule descends from Rosin's PUCB bandit (2011).
The failure. Symptom: the search never considers a good move the network dislikes. Measure: look for strong moves with a prior near 0 and almost no visits. Fix: add noise to the root priors during training, as AlphaZero did, so every move gets some visits.
Chapter 7
Value a leaf with one network call, then train the network toward the search's visit counts
A random game of chess is a farce. Both sides blunder until a fluke decides it. You need many such games to get a usable value.
AlphaGo Zero (2017) and then AlphaZero (2017, for chess, shogi and Go) removed the playout. At a new leaf, one network call returns a prior P for each move and a value v for the position. The search backs up v. The loop becomes select, expand, evaluate, back up.
Left: the running value of one position. Teal is playouts, pink is a value network. Press Evaluate ×10 with each. Right: slide τ to see the policy target.
Illustrative. The position's true value is 0.62. The toy value network is off by a fixed 0.03 plus small noise. The visit counts 30, 15 and 5 are made-up numbers.
How does the network learn? It plays itself. At each position, call the visit count of root move a N(a), and a temperature you choose τ. The search turns visits into a policy target π(a), and the network's prior is trained toward it.
Pi of a equals N of a to the one over tau, over the sum over b of N of b to the one over tau.
Raise each visit count N(a) to the power one over tau. Divide each by their total. Train the network's prior toward these numbers, and its value toward the game's final result.
Visits 30, 15, 5 and τ = 1: π = 0.60, 0.30, 0.10. With τ = 0.5 square them first: 900, 225, 25, total 1,150, so π = 0.78, 0.20, 0.02.
This is the engine. The search is stronger than the raw network, because it looked ahead. Train the network toward the search, and the next search starts from a better prior. AlphaZero used 800 simulations per move in training. In chess it searched about 80 thousand positions per second, against 70 million for Stockfish.
The failure. Symptom: self-play games repeat the same opening forever and stop improving. Measure: count distinct openings in recent games. Fix: pick training moves in proportion to visits (τ = 1) early in the game, and add noise to the root priors.
Chapter 8
Replace the rules with three networks and plan over imagined steps
AlphaZero needs the rules. To expand a node it must compute the next position exactly. An Atari game or a robot gives you no such rulebook.
MuZero (Schrittwieser et al., 2019) learns what it needs. It has three networks.
| Network | Input | Output |
|---|---|---|
| Representation h | past observations | a hidden state s0 |
| Dynamics g | a hidden state and an action | a predicted reward and the next hidden state |
| Prediction f | a hidden state | a policy prior and a value |
The search runs on hidden states. Expand calls g, evaluate calls f. No real step happens while it plans. Then MuZero plays the first move for real and plans again.
The value target bootstraps. Call the reward at the k-th step after time t ut+k, the discount γ, the number of real steps n, and the search value n steps later νt+n. The target is zt.
Z-t equals the sum over k from one to n of gamma to the k minus one times u at t plus k, plus gamma to the n times nu at t plus n.
Take the next n rewards u. Shrink each by gamma once per step of delay and add them. Then add the search value nu from n steps ahead, shrunk n times. MuZero used n = 10 on Atari.
With made-up values: n = 3, rewards 0, 0, 1, ν = 0.8, γ = 0.997. Rewards: 0.997² × 1 = 0.994. Bootstrap: 0.997³ × 0.8 = 0.793. zt = 1.787.
Each box is a hidden state. Teal dots are rewards, pink is the value at the end. Slide n and watch which terms build the target.
Illustrative rewards 0, 0, 1, 0, 0, 1, 0, 0, 0, 1 and values. γ = 0.997 and n up to 10 are MuZero's Atari settings.
MuZero matched AlphaZero in Go, chess and shogi without the rules. It set a new state of the art on 57 Atari games. It used 800 simulations per move in board games and 50 in Atari.
The failure. Symptom: a plan looks great inside the model and fails in the real game. Measure: compare predicted rewards with observed rewards along real trajectories. Fix: keep the unroll short, and replan after every real step.
Chapter 9
Treat each reasoning step as a move and let a reward model play the role of the playout
A chain of reasoning is a series of decisions. So a set of possible chains is a tree. The four phases carry over.
| Game search | Reasoning search |
|---|---|
| A node is a position | A node is a partial solution |
| Expand adds a legal move | Expand samples a next step from an LLM |
| Simulate plays a random game | A reward model scores the step, or the LLM finishes the solution and a checker grades it |
| Visit counts pick the move | Visit counts or scores pick the path |
A process reward model (PRM) scores each intermediate step, not only the final answer. rStar-Math (Guan et al., 2025) ran MCTS over math steps with such a model. It raised Qwen2.5-Math-7B from 58.8% to 90.0% on the MATH benchmark.
The problem is 17 × 24. Each node is a step with its reward score. Press Expand to run one iteration, or Search to run the budget.
Illustrative. We wrote the steps and the scores by hand. A real system samples steps from an LLM and scores them with a trained reward model. One wrong step (17 × 4 = 58) scores high at first to show how search recovers.
Work one choice with c = 1. A node has N = 20. Step A has a reward score Q = 0.9 and n = 3. Step B has Q = 0.7 and n = 1. ln 20 = 2.996.
B is expanded next. Its one visit leaves a large bonus. For the final answer, a simple partner is self-consistency: sample several full solutions and take the majority. Answers 7, 7, 7, 3, 7 give 7 with 4 of 5 votes, a share of 0.8.
Not every tree search is MCTS. Tree of Thoughts (Yao et al., 2023) used breadth-first and depth-first search over thoughts. AlphaProof (2024) paired a language model with AlphaZero-style search to prove statements in Lean. AB-MCTS chooses at each node whether to widen or deepen. The test-time scaling lesson uses a PUCT-style score to reuse states, and test-time compute frames the budget.
The failure. Symptom: the search finds paths that the reward model loves but whose answers are wrong. Measure: grade a sample of the top paths with an exact checker. Fix: score final answers with a verifier where one exists, and treat the reward model as a prior, not as the truth.
Chapter 10
Keep the terms, the numbers, the checklist and the core code in one place
MCTS values a move by results, not by a formula. UCB1 decides where the next iteration goes. The flip keeps both players honest. The visit count is the answer. Networks replace the random parts: a prior for selection, a value for the playout, a model for the rules.
| Term | What it is | Number to remember |
|---|---|---|
| Q = W / N | mean result of a node | SE = √(Q(1 − Q)/N): 0.145 at Q 0.7, N 10 |
| UCB1 | Q + c√(ln N / n) | c = √2 ≈ 1.41; Q 0.6, n 10, N 100 gives 1.560 |
| UCT | UCB1 at every node (Kocsis and Szepesvári, 2006) | unvisited child first |
| Negamax back up | v′ = 1 − v at each level | W 6, N 10, a win: Q 0.636; parent gets 0 |
| Robust child | return argmax N(a) | 1,000 of 1,600 visits: share 0.625 |
| PUCT | Q + c·P√N/(1 + n) | Q 0.2, P 0.6, n 10, N 100, c 1.5 gives 1.018 |
| AlphaGo leaf value | mix of value net and one fast playout | λ = 0.5 |
| AlphaZero | no playouts; train toward π ∝ N1/τ | 800 simulations per move; 80 thousand positions per second in chess |
| MuZero | plan in a learned model | Atari: n = 10, γ = 0.997, 50 simulations |
| rStar-Math | MCTS over math steps with a process reward model | 7B model: 58.8% to 90.0% on MATH |
pythonimport math, random class Node: def __init__(self, state, parent=None): self.state, self.parent = state, parent self.children, self.untried = [], list(state.moves()) self.N, self.W = 0, 0.0 # W from the view of the player who moved INTO this node def ucb1(ch, N, c=math.sqrt(2)): return ch.W / ch.N + c * math.sqrt(math.log(N) / ch.N) def mcts(root_state, iters): root = Node(root_state) for _ in range(iters): node = root while not node.untried and node.children: # 1. select node = max(node.children, key=lambda ch: ucb1(ch, node.N)) if node.untried: # 2. expand one child m = node.untried.pop(random.randrange(len(node.untried))) node.children.append(Node(node.state.play(m), node)); node = node.children[-1] s = node.state # 3. simulate while not s.over(): s = s.play(random.choice(s.moves())) v = s.result_for(node.state.last_mover()) # 1 win, 0 loss for the player who moved into node while node: # 4. back up with the flip node.N += 1; node.W += v; v = 1 - v; node = node.parent return max(root.children, key=lambda ch: ch.N).state.last_move() # robust child
The state object needs five methods: moves, play, over, result_for and last_mover. For AlphaZero, swap step 3 for one network call and swap ucb1 for PUCT.
Monte Carlo (the family hub) · Bandits and UCB · MDPs · Q-learning · RL algorithms · Model-based RL · Test-time scaling and PUCT · Test-time compute · AB-MCTS
Now press Present or Teach and explain from memory: the four phases, the UCB1 bonus, the flip, and why the answer is the most visited move. Then go back to the hero and run flat Monte Carlo at a budget of 2,000. Say why more games make it more sure of the wrong move.