Monte Carlo Tree Search

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.

Find the move that survives the best reply

800

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

Why You Cannot Look at Every Move

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.

Send playouts under four moves

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.

Say it aloud

Q equals W over N.

Q
Q the move's estimated win rate, from 0 to 1.
W
W the win total: the sum of the playout results, each 1 for a win and 0 for a loss.
N
N the visit count: how many playouts went through this move.
In plain words

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 numbers

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.

Say it aloud

S-E equals the square root of Q times one minus Q, over N.

SE
S-E the standard error: how far Q typically lands from the true win chance p.
√
the square root of it turns a variance back into a distance on the win-rate scale.
Q(1 − Q)
Q times one minus Q the spread of one win-or-loss result. It is largest at Q = 0.5.
N
N the visit count, as above.
In plain words

Multiply Q by one minus Q. Divide by N. Take the square root. Four times the playouts halves SE.

With numbers

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.

The road

  1. UCB1: a bonus that makes rarely tried moves look better.
  2. UCT: run that bonus at every node of a tree.
  3. Four phases: select, expand, simulate, back up. This is the hero's tree search.
  4. Negamax: flip the result for the opponent. It is why the hero finds the refutation.
  5. Anytime: lopsided trees, and why you return the most visited move.
  6. AlphaGo: a learned prior steers the search.
  7. AlphaZero: a value network replaces the playout.
  8. MuZero: search inside a learned model.
  9. Reasoning: the same loop over LLM reasoning steps.
  10. Field guide: numbers, code and links.
A move gets 4 playouts: win, loss, win, win. What is its value estimate, and how much should you trust it?

Chapter 1

Optimism Under Uncertainty: UCB1

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.

Say it aloud

U-C-B-one equals Q plus c times the square root of the natural log of N, over n.

UCB1
U-C-B-one the upper confidence bound: the score we rank arms by. The highest score gets the next pull.
Q
Q the arm's mean result so far, from 0 to 1. This part exploits.
c
c the exploration constant. UCB1 as published uses √2, about 1.41, for results in 0 to 1.
√( )
the square root of the width of a confidence interval grows like a square root.
ln N
the natural log of N N is the total pulls at this node. The log grows slowly, so no arm starves.
n
n the pulls of this arm. A small n gives a large bonus.
In plain words

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.

With numbers

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.

Pull the arm with the tallest bar

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.

1.41

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.

Why does n sit under the square root in the bonus?

Chapter 2

UCT: A Bandit at Every Node

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.

Walk the pointer down the tree

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.

1.41

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.

bonus(A) = 1.414 × √(5.298 / 80) = 1.414 × 0.257 = 0.364, so UCB1(A) = 0.7 + 0.364 = 1.064
bonus(B) = 1.414 × √(5.298 / 20) = 1.414 × 0.515 = 0.728, so UCB1(B) = 0.55 + 0.728 = 1.278

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

A node has N = 200. Child A: Q = 0.7, n = 80. Child B: Q = 0.55, n = 20. With c = 1.414, which child does UCT enter?

Chapter 3

Select, Expand, Simulate, Back Up

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.

  1. 1. Select. From the root, follow UCT down to a node that has an untried move.
  2. 2. Expand. Add one new child for one untried move.
  3. 3. Simulate. From the new child, play one random game to the end. Record 1 for a win, 0 for a loss.
  4. 4. Back up. Walk from the new child to the root. At each node add 1 to N and add the result to W.

Repeat until the time runs out. Each iteration adds one node and one result. The tree grows where UCT sends it.

Step one iteration at a time

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.

A: Q 0.8, n 30: 0.8 + 1.414 × √(3.912 / 30) = 0.8 + 0.511 = 1.311
B: Q 0.6, n 15: 0.6 + 1.414 × √(3.912 / 15) = 0.6 + 0.722 = 1.322
C: Q 0.4, n 5: 0.4 + 1.414 × √(3.912 / 5) = 0.4 + 1.251 = 1.651

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.

In one MCTS iteration, what does the Expand phase do?

Chapter 4

Back Up and Flip for the Opponent

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′.

Say it aloud

V-prime equals one minus v.

v′
v-prime the result passed to the parent, from the other player's view.
1
one a win is 1 and a loss is 0, so one minus a result swaps them. With results of plus 1 and minus 1 you negate instead, so the name is negamax.
v
v the result this node just added to its W, from its own player's view.
In plain words

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.

With numbers

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.

Send a result up the path

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.

A playout returns a win for the player at the bottom node. How does back up handle it in a two-player game?

Chapter 5

Lopsided Trees and the Anytime Answer

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.

Grow the tree, stop it anytime

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.

1,000

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*.

Say it aloud

A-star equals the arg-max over a of N of a.

a*
a-star the move we play after the search: the robust child.
argmaxa
the arg-max over a the root move that makes the next quantity largest.
N(a)
N of a how many iterations went through root move a.
In plain words

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 numbers

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.

After the search, which root move does MCTS most often return?

Chapter 6

AlphaGo: A Learned Prior Steers the Search

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.

Say it aloud

P-U-C-T equals Q plus c-puct times P times the square root of N, over one plus n.

PUCT
P-U-C-T the selection score. The child with the highest score is entered.
Q
Q the child's mean value, 0 until it is visited.
cpuct
c-puct the exploration constant for this rule. Our examples use 1.5.
P
P the prior: the policy network's probability for this move, from 0 to 1.
√N
the square root of N N is the parent's visit count. The bonus floor rises slowly as the parent is visited.
1 + n
one plus n n is the child's visits. The 1 keeps the bonus finite at n = 0.
In plain words

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.

With numbers

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.

Search with and without a prior

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.

In the PUCT score Q + c·P·√N / (1 + n), what does the prior P do?

Chapter 7

AlphaZero: Drop the Playout, Learn from the Search

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.

Evaluate a leaf two ways

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.

1.00

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.

Say it aloud

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.

π(a)
pi of a the policy target: the probability the network should give root move a.
N(a)
N of a the visits root move a got in this search.
1/τ
one over tau the power. τ = 1 keeps visit shares as they are; a small τ sharpens toward the top move.
Σb
the sum over b add the same powered counts over every root move b, so the targets add to 1.
In plain words

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.

With numbers

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.

How does AlphaZero value a newly expanded leaf?

Chapter 8

MuZero: Search Inside a Learned Model

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.

NetworkInputOutput
Representation hpast observationsa hidden state s0
Dynamics ga hidden state and an actiona predicted reward and the next hidden state
Prediction fa hidden statea 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.

Say it aloud

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.

zt
z-t the value target for the position at time t.
Σk=1..n
the sum over k from one to n one term for each of the next n steps.
γk−1
gamma to the k minus one the discount, applied once per step of delay. MuZero used 0.997 on Atari.
ut+k
u at t plus k the reward observed k steps after time t.
γn νt+n
gamma to the n times nu at t plus n the search's value n steps ahead, discounted n times. It stands in for every reward after that.
In plain words

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 numbers

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.

Unroll the learned model

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.

3

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.

What does MuZero learn that AlphaZero is given?

Chapter 9

Reasoning as Search

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 searchReasoning search
A node is a positionA node is a partial solution
Expand adds a legal moveExpand samples a next step from an LLM
Simulate plays a random gameA reward model scores the step, or the LLM finishes the solution and a checker grades it
Visit counts pick the moveVisit 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.

Search over reasoning steps

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.

16

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.

A: 0.9 + 1 × √(2.996 / 3) = 0.9 + 0.999 = 1.899
B: 0.7 + 1 × √(2.996 / 1) = 0.7 + 1.731 = 2.431

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.

How does MCTS map onto LLM reasoning in a system like rStar-Math?

Chapter 10

Field Guide

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.

TermWhat it isNumber to remember
Q = W / Nmean result of a nodeSE = √(Q(1 − Q)/N): 0.145 at Q 0.7, N 10
UCB1Q + c√(ln N / n)c = √2 ≈ 1.41; Q 0.6, n 10, N 100 gives 1.560
UCTUCB1 at every node (Kocsis and Szepesvári, 2006)unvisited child first
Negamax back upv′ = 1 − v at each levelW 6, N 10, a win: Q 0.636; parent gets 0
Robust childreturn argmax N(a)1,000 of 1,600 visits: share 0.625
PUCTQ + c·P√N/(1 + n)Q 0.2, P 0.6, n 10, N 100, c 1.5 gives 1.018
AlphaGo leaf valuemix of value net and one fast playoutλ = 0.5
AlphaZerono playouts; train toward π ∝ N1/τ800 simulations per move; 80 thousand positions per second in chess
MuZeroplan in a learned modelAtari: n = 10, γ = 0.997, 50 simulations
rStar-MathMCTS over math steps with a process reward model7B model: 58.8% to 90.0% on MATH

Checklist before you trust a search

The core in code

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.

Sources

Keep going

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

The takeaway. Play it out at random, let the wins steer where you look next, flip the result for the opponent, and play the move the search visited most.

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.

Monte Carlo Tree Search
The Monte Carlo family · Back to Gleams