Inference-time search: step-level beam search, tree of thoughts and MCTS
Formulate reasoning as search over partial solutions. Implement PRM-guided stepwise beam search, Tree of Thoughts with BFS and DFS, and MCTS with PUCT, then compare them with best-of-N at equal compute on exactly verifiable tasks such as Countdown and the game of 24.
After this lesson you can
- Formulate reasoning search in terms of states, actions, proposal, evaluator, and stopping criterion.
- Implement stepwise beam search and its diverse variant using a PRM evaluator.
- Implement Tree of Thoughts with BFS and backtracking DFS using model self-evaluation.
- Adapt PUCT MCTS to reasoning steps with model probabilities as priors and PRM scores or rollouts as values.
- Compare search methods at equal generated-token budgets and explain their difficulty regimes.
Before you start
- 23Process reward modelStep segmentationStep score aggregationSelf-consistencyExact and executable verifiersCost-accuracy Pareto frontier
- 10Monte Carlo Tree SearchUpper Confidence bounds applied to TreesPUCT selection with priorsBreadth-first searchBacktracking searchLocal beam search
- 21Beam searchLength normalization
- 20Best-of-N sampling
Branch before finishing
Suppose a solution requires four steps and at the second there are two possible continuations. Sampling a complete solution pays for all four steps even if the second made reaching the answer impossible. If you can evaluate a prefix, you have another option: propose several continuations, retain promising ones, and spend the remaining budget on them. The benefit depends on evaluator quality and the search not losing every correct path.
In the reasoning search space, a state contains the problem and prefix, an action adds a step, and the transition concatenates that step. The proposer distributes probability over actions; an evaluator assigns a value or score to a state; a stopping condition recognizes complete answers or stops at the budget. An executable verifier can check the final result for a well-specified task. A learned PRM can score prefixes, but its output is not proof of validity and its behavior can worsen on search-generated prefixes absent from training.
In Game 24, the state can be the multiset of remaining numbers together with the expression that produced each. An action chooses two numbers and an operation, replaces them with the result, and leaves the others untouched. If fractions are allowed, use exact rational arithmetic: a state with a single number equal to 24 is terminal, and the expression must use all four inputs exactly once. An expression yielding 24 with a repeated input is not a solution.
Step-level beams and diversity
Step-level beam search maintains up to prefixes. It proposes steps from each, scores candidates, retains the best , and repeats until completion or maximum depth. Width simultaneously controls diversity, memory, and call count. Unlike token-level beam search, an action here can be a line or complete operation, and evaluation occurs at those boundaries. The step segmenter must match what the evaluator understands.
If all survivors descend from the same prefix, apparent width is misleading: an early mistake eliminates every alternative. A diverse beam divides the population into subtrees or reserves slots per group before selection. Diversity does not guarantee improvement: retaining a bad branch consumes compute. Compare the number of distinct prefixes as well as the number of strings.
For example, if a beam of width four contains four paraphrases of the same initial operation, an error in that operation can hurt all four branches. Reserving two slots for each of two initial operations reduces concentration, but can discard a third variant of a truly promising branch. State representation matters: two different expressions can leave the same multiset of numbers with the same available continuations. Deduplicating that state saves evaluations, provided a valid expression is retained to reconstruct the final answer.
A partial evaluation can also confuse “this state resembles an easy one” with “a solution still exists.” In Game 24, a number close to 24 is not enough if others remain to be used; a more distant state may have an exact combination. An exhaustive checker over four numbers can label viability in this small domain and audit the evaluator. That additional check has a cost and does not transfer unchanged to open problems where viability is not practically decidable.
An ideal case where verification changes the scale
Suppose steps, each proposal independently correct with probability , only a sequence of correct steps can succeed, and a perfect verifier identifies each correct step. Proposing independent alternatives at each level and continuing with a correct one if available has probability
Each level fails only if all its proposals fail; independence lets us multiply level success probabilities. If the maximum of steps is budgeted, even if stopping early when no correct step is found, the method fits that budget. With independent complete solutions, best-of-N with a perfect final verifier has probability . Generating the solutions consumes steps; if stopping on finding a correct one, this is its maximum cost. To match or exceed the first method’s ideal probability, the smallest integer is
if and are positive. The assumptions are strong: a correct step can lead to a dead end, an incorrect step may be recoverable, and successes can be correlated. An imperfect verifier may prune the useful path. Equal generated steps also do not account for evaluator tokens.
The figure counts proposed steps, uses a noisy viability signal, and exactly verifies terminal states. Beam search retains three survivors, diverse beam keeps one per initial group, and MCTS uses uniform prior among children. The simulation does not charge for scoring states or represent generative evaluator token cost. Compare trends within this explicit model; a crossover here does not prove the same result on another task.
Tree of Thoughts
Tree of Thoughts (ToT) generalizes chain of thought by exploring alternative text units and evaluating them before continuing. In Yao and colleagues’ work, those units are operations in Game 24. Their BFS retains the highest-scored states at each depth; their DFS explores a branch and backtracks if evaluation or lack of actions rules it out. “Sure,” “likely,” and “impossible” are evaluator judgments, not mathematical certainties.
The recording contains 18, 3, 1, and 1 nodes in the four cases, respectively. In the last two, the model produced no valid binary operation at the root, and none of the recorded traces reached 24. Self-evaluation produced recognizable “impossible” judgments and responses without a recognizable label; “sure” and “likely” were not recognized in this run. The viewer retains those failures and counts calls and tokens for the traversal performed over the data, even when it finds no solution. The generated tree covers up to five children per node and depth two for expansion; exhaustively checking state viability costs additional compute not included in that counter.
Download the generator, verifier and packager, and complete traces. The ZIP includes the protocol, token IDs, and a manifest; its SHA-256 is 73c23ce501a475f32e5ded532049433b10e825241afec5cb50b61cc756e14fb0. With both scripts in the same folder and SNAPSHOT_15 pointing to the snapshot pinned in the code, you can generate the four cases and verify the tree:
python generate_game24.py --model-path "$SNAPSHOT_15" --output game24_run
python build_game24_graphs.py --run game24_run --output game24_graphs.json
On 100 relatively difficult games from their selection, the paper reports 4% for CoT and 74% for ToT with width five using GPT-4, and 49% for the best of 100 CoT chains. The methods have different costs: the paper’s analysis reports 5.5 thousand output tokens for ToT and 6.7 thousand for the best of 100 CoT in that configuration. These figures belong to that experiment, not a general guarantee that search always wins or a measurement of this machine.
PUCT for reasoning steps
Monte Carlo tree search for reasoning maintains, for each edge, , the sum of values, and their mean . During selection, one PUCT version chooses
The first term exploits previous results and the second favors actions with high prior and few visits. After reaching an unexpanded node, children are generated, a value is obtained from the PRM or a completion, and it is backpropagated along the trajectory. In a single-agent problem, success value propagates with the same sign; alternating signs as in zero-sum games would be incorrect. Define what to do if and if actions tie: the figure uses and stable order.
Scale matters: a constant tuned for values in is not automatically equivalent for values in . A complete line’s prior is also not necessarily comparable to one of a different length; specify how log probabilities are aggregated and duplicates handled. RAP uses a language model as agent and world model in MCTS-based planning. LATS incorporates evaluation, self-reflection, and environmental feedback. rStar-Math combines search and a process preference model, training policy and evaluator in self-evolution rounds: its results are not those of this toy example.
An MCTS rollout is not necessarily a complete solution generated from the root. It can end in a value evaluation for a prefix; if it rolls out to the end, its tokens also consume budget. For each simulation record which node was expanded, what value it received, whether it was terminal, and which visits were updated. Before trusting the result, check the invariant that each edge visit corresponds to a simulation that crossed it. The final decision can be the most visited action or the highest-valued one: specify which, since they need not agree.
Measure full cost
A compute-matched comparison fixes in advance which resources enter the budget. At minimum count proposer input and output tokens, generative evaluator tokens, PRM calls, exact verifier cost, and latency or FLOPs when relevant. Calls can be batched and prefixes share KV cache: equal token counts do not imply equal latency. Report whether the cache is warm, hardware, and batch size.
In Snell and colleagues, beam search outperforms best-of-N at low aggregate generation budgets, but its advantage decreases at larger budgets. In easy groups beam search shows signs of PRM overoptimization; in intermediate groups it exceeds best-of-N, and in the hardest groups neither progresses much. This is an observation from their evaluation, not a universal law. The study estimates search costs using its own generation protocol; adding generative evaluator cost answers a different question and should be explicit.
To compare methods, set the stopping rule before seeing whether each problem is solved. If search consumes a variable number of calls, retain per-problem cost and present its distribution, not just the mean. Curves at equal mean cost can hide expensive cases. Hyperparameter selection on the same test problems also introduces optimism: use validation to choose width, exploration constant, and pruning threshold, and reserve test for final comparison. Resample whole problems and, if possible, repeat generation seeds.
Lab: Countdown with simulated proposals
Here the state is a list of exact fractions and expressions. Each action combines two inputs with addition, subtraction, multiplication, or division by a nonzero number; negative numbers and fractions are allowed. A solution expression must consume all four inputs. The simulated proposer shows legal actions chosen without replacement; a seed fixes their order. The heuristic evaluator favors a remaining number close to 24. It is deliberately imperfect: getting close now does not guarantee the remaining numbers permit completion.
from fractions import Fraction
from itertools import combinations
from random import Random
from math import sqrt
def inicial(numbers):
return tuple((Fraction(n),str(n)) for n in numbers)
def acciones(state):
out = []
for i,j in combinations(range(len(state)),2):
a,ea=state[i]; b,eb=state[j]
remaining=[state[k] for k in range(len(state)) if k not in (i,j)]
options=[(a+b,f'({ea}+{eb})'),(a*b,f'({ea}*{eb})'),
(a-b,f'({ea}-{eb})'),(b-a,f'({eb}-{ea})')]
if b: options.append((a/b,f'({ea}/{eb})'))
if a: options.append((b/a,f'({eb}/{ea})'))
out.extend(tuple(remaining+[(value,expr)]) for value,expr in options)
return out
def terminado(state):
return len(state)==1 and state[0][0]==24
def valor(state):
return 1/(1+min(abs(float(value)-24) for value,_ in state))
class Presupuesto:
def __init__(self,limit,seed):
self.limit=limit; self.used=0; self.evaluated=0; self.checked=0; self.r=Random(seed)
def propone(self,state,m):
choices=acciones(state)
n=min(m,len(choices),self.limit-self.used)
picked=self.r.sample(choices,n)
self.used+=n
return picked
def score(self,state):
self.evaluated+=1
return valor(state)
def verifica(self,state):
if len(state)!=1: return False
self.checked+=1
return terminado(state)
assert terminado(inicial([24]))
assert any(x[0]==Fraction(3,2) for state in acciones(inicial([3,2])) for x in state)The following code counts each proposed action, not each combination enumerated internally to build the legal list. That enumeration is an additional simulator cost. Best-of-N does not score prefixes; it retains a solution only when the terminal checker recognizes it. Beam and DFS score proposals that have not ended in success. Terminal verification and heuristic scoring have separate counters. In the diverse variant, each sub-beam is associated with an initial proposal: selection never replaces a group with two branches from another.
def best_of_n(numbers,limit,seed):
p=Presupuesto(limit,seed)
while p.used+3<=limit:
state=inicial(numbers)
for _ in range(3):
state=p.propone(state,1)[0]
if p.verifica(state): return True,p.used,p.evaluated,p.checked
return False,p.used,p.evaluated,p.checked
def beam_search(numbers,limit,seed,width=3,proposals=3,diverse=False):
p=Presupuesto(limit,seed)
beam=[(inicial(numbers),-1)]
for depth in range(3):
candidates=[]
for state,group in beam:
for j,child in enumerate(p.propone(state,proposals)):
group_id=j if depth==0 else group
if p.verifica(child): return True,p.used,p.evaluated,p.checked
candidates.append((p.score(child),child,group_id))
if not candidates: return False,p.used,p.evaluated,p.checked
candidates.sort(key=lambda x:x[0],reverse=True)
if diverse:
seen=set(); selected=[]
for item in candidates:
if item[2] not in seen: selected.append(item); seen.add(item[2])
candidates=selected
beam=[(state,group) for _,state,group in candidates[:width]]
return False,p.used,p.evaluated,p.checked
def dfs_search(numbers,limit,seed,proposals=3):
p=Presupuesto(limit,seed); stack=[inicial(numbers)]
while stack and p.used<limit:
state=stack.pop()
if len(state)==1: continue
candidates=[]
for child in p.propone(state,proposals):
if p.verifica(child): return True,p.used,p.evaluated,p.checked
candidates.append((p.score(child),child))
candidates.sort(key=lambda x:x[0])
stack.extend(child for _,child in candidates)
return False,p.used,p.evaluated,p.checkedThe next MCTS implementation expands a node with up to three proposals and uses a uniform prior over its children. Intermediate values come from the same heuristic, while a terminal state without a solution has value zero. It visits only children that can still expand; if the proposed tree is exhausted, it stops even if budget remains. Thus it does not confuse selection iterations with new proposals.
class Nodo:
def __init__(self,state):
self.state=state; self.children=None; self.n=0; self.total=0.
def mcts(numbers,limit,seed,proposals=3,c=1.5):
p=Presupuesto(limit,seed); root=Nodo(inicial(numbers))
def disponible(node):
if len(node.state)==1: return False
return node.children is None or any(disponible(x) for x in node.children)
while p.used<limit and disponible(root):
node=root; path=[node]
while node.children is not None:
viable=[x for x in node.children if disponible(x)]
if not viable: break
parent=node; prior=1/len(parent.children)
def ucb(child):
q=child.total/child.n if child.n else 0.
return q+c*prior*sqrt(max(1,parent.n))/(1+child.n)
node=max(viable,key=ucb); path.append(node)
if node.children is not None: break
children=p.propone(node.state,proposals)
node.children=[Nodo(child) for child in children]
for child in children:
if p.verifica(child): return True,p.used,p.evaluated,p.checked
if not children: break
scored=[p.score(child) if len(child)>1 else 0. for child in children]
best=max(range(len(children)),key=lambda i:scored[i])
chosen=node.children[best]; path.append(chosen)
for member in path:
member.n+=1; member.total+=scored[best]
return False,p.used,p.evaluated,p.checkedAll variants receive the same proposal limit and problem set. The beam has fixed width and does not restart: when it completes its tree it leaves remaining budget unused. MCTS can also exhaust its tree and DFS its stack. Therefore identical limits do not mean all consume the same number of proposals; the output reports actual spending. The following comparison is small and does not compare tokens or reproduce an LLM’s PRM or proposer.
cases=[(4,9,10,13),(1,3,4,6),(3,3,8,8),(2,2,6,6),
(1,5,5,5),(2,3,7,9),(1,2,7,7),(4,4,6,8)]
methods={'best-of-N':best_of_n,'haz':beam_search,
'haz diverso':lambda nums,b,s:beam_search(nums,b,s,diverse=True),
'DFS':dfs_search,'MCTS':mcts}
for budget in (24,48,96):
for name,method in methods.items():
rows=[method(case,budget,1000+i) for i,case in enumerate(cases)]
assert all(cost<=budget for _,cost,_,_ in rows)
print(budget,name,'aciertos',sum(ok for ok,_,_,_ in rows),
'propuestas',sum(cost for _,cost,_,_ in rows),
'evaluaciones heurísticas',sum(n for _,_,n,_ in rows),
'verificaciones terminales',sum(n for _,_,_,n in rows))To study a crossover without choosing problems after the fact, generate 100 quadruples and estimate difficulty with four independent best-of-N runs at limit 96. Label “easy” if at least two runs find a solution; the rest are “hard.” Comparison runs use different seeds. This definition depends on a noisy estimator and may group impossible problems with hard ones; it does not assume intrinsic difficulty is known.
from collections import defaultdict
r=Random(27)
cases_100=[tuple(r.randint(1,9) for _ in range(4)) for _ in range(100)]
groups=defaultdict(list)
for i,case in enumerate(cases_100):
pilot=sum(best_of_n(case,96,100000+i*10+j)[0] for j in range(4))
groups['facil' if pilot>=2 else 'dificil'].append((i,case))
print({name:len(items) for name,items in groups.items()})As budget grows we jointly increase width and the number of proposals per state, with for the three depths. The possible number of legal operations can limit spending before reaching . The experiment has only 12 easy-group cases for this seed; a difference of one answer corresponds to more than eight percentage points. Do not confuse it with Snell’s study: this task has a uniform proposer, hand-built evaluator, and exact final verifier.
def ancho(budget):
return max(1,int((-1+sqrt(1+8*budget))/4))
def medir_grupos(budget):
width=ancho(budget)
result={}
for name,items in groups.items():
results=[]
for i,case in items:
bon=best_of_n(case,budget,200000+i)
beam=beam_search(case,budget,200000+i,width=width,proposals=width)
results.append((bon,beam))
result[name]={'n':len(results),'bon':sum(a[0] for a,b in results),
'haz':sum(b[0] for a,b in results),
'coste_bon':sum(a[1] for a,b in results),
'coste_haz':sum(b[1] for a,b in results)}
return result
print('B=24',medir_grupos(24))print('B=192',medir_grupos(192))Local lab: search with model proposals
The local searcher uses Qwen2.5-1.5B-Instruct as proposer, asks for numerical self-evaluation of intermediate states, and checks operations and final expressions with rational arithmetic. It accepts one complete binary equality per line, with an optional bullet or mathematical delimiter; it rejects chained operations rather than extracting an apparently valid substring. The beam and MCTS proposer receives the same formatting instruction. It uses the same Countdown generator and verifier as subsequent lessons. Its three limits are 1024, 2048, and 4096 tokens per problem and method; cost sums input and output of all generation and evaluation calls, plus tokens processed to obtain priors. It does not run a call if its input already exhausts the budget; when little space remains, it limits output.
Save both scripts together, install PyTorch and Transformers with support for your device, and point SNAPSHOT_15 to the snapshot of the revision specified in the code. One problem from the training split checks installation; then run the 100 held-out problems without changing the protocol. The smoke test uses a separate folder and does not replace the campaign.
python search_countdown_model.py --model-path "$SNAPSHOT_15" --output smoke --count 1 --split train --smoke-one-budget
python search_countdown_model.py --model-path "$SNAPSHOT_15" --output countdown_search --count 100
python summarize_model_search.py --run countdown_search --output search_summary.json
Also download the paired summary. Beam search retains up to three states. For PUCT, the same model scores each valid operation using teacher forcing as the first answer line to the same prompt: it averages per-token log probabilities and applies softmax over scored proposals. It uses original logits without the temperature or top-p truncation used to sample proposals. This is a relative preference conditioned on the generated set, not a probability over all legal actions; averaging also prevents expression length from being simply confounded with usefulness. The model’s numeric judgment provides the value; before visits, each child uses its initial evaluation as its estimate. Both the prompt and scored tokens of each operation are charged to the budget, even though the latter were not generated in that call. If the priors and maximum evaluation cost fit, the code batches candidates with padding; otherwise it processes them one at a time. The budget counts logical unpadded tokens, and the log also retains padded batch size. Shared batch time is distributed among candidates to avoid counting it repeatedly. If the budget is insufficient, no more candidates are scored. The log separates calls and synchronized wall time for proposer, evaluator, and prior; device contention affects that time.
Each method can stop before spending the entire limit, so also compare mean tokens actually spent and calls, not just success bars at the same cap. Accuracy is checked on paired problems and difference intervals are resampled by problem. The summary adds Wilson intervals for each proportion as a binomial approximation over problems: if no success is observed, an empirical bootstrap interval can collapse to zero and does not prove the true probability is zero. None of these intervals alone measures variation across model trainings. Generation, operation checks, and seeds are retained so format and pruning failures can be inspected; each split, problem, budget, and method combination uses a distinct seed block.
A local-model run
On the 100 held-out problems, we ran all nine combinations on a 12 GiB RTX 3060 with Qwen2.5-1.5B-Instruct in BF16. Each cell shows percentage solved and, after the slash, mean tokens actually charged per problem; the cap is shared by proposal, self-evaluation, and prior where applicable.
| Token cap | Best-of-N | Beam | MCTS with PUCT |
|---|---|---|---|
| 1024 | 6 % / 977 | 2 % / 615 | 1 % / 706 |
| 2048 | 10 % / 1897 | 11 % / 853 | 5 % / 1177 |
| 4096 | 10 % / 3821 | 12 % / 820 | 21 % / 1625 |
At cap 4096, the observed MCTS minus best-of-N difference was 11 percentage points, with a 95% paired bootstrap interval of [1, 21] points. At 1024 it was −5 [−10, 0] and at 2048 it was −5 [−12, 2]. These intervals concern these problems, not new trainings or all models; three comparisons are shown without multiplicity adjustment. Beam and MCTS can spend much less than the cap when no valid proposals remain; generated format and self-evaluation quality influence results. Seeds differ between budgets, so rows are not nested prefixes of one search and each percentage need not increase.
Plotting the empirical frontier of observed success against mean tokens spent leaves beam at cap 1024 (615, 2%), beam at cap 4096 (820, 12%), and MCTS at cap 4096 (1625, 21%). Other points are dominated in these estimates: another has lower mean cost and greater observed success. This frontier does not incorporate uncertainty in the percentages and may change with other samples or seeds.
The complete summary includes intervals, calls, evaluator and prior token breakdown, and synchronized timings; the latter were measured while the device was shared. The records archive contains all 900 individual results, the protocol, a separate development technical check, and a SHA-256 manifest. The ZIP SHA-256 is 91aca72b80825df384404febfb1c7f71bf9611644d7c9f7403d6d12b425b3e2c. Unpack it and run the preceding summarizer on the folder to reconstruct the table. The development check verifies batched prior and evaluator using a previous train proposal; it does not count as a test problem.
Exercises
Step 1 of 3. What is the probability of at least one correct proposal at a level?
def step_beam_search(propose, score, B, M, max_depth):
pass