AI Wiki中文/EN

Tree of thoughts: keep alternatives before committing

思维树

Run rational-arithmetic search and measure when a narrow heuristic beam discards the only useful branch.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The promising-looking branch can be a dead end

Use the numbers 1, 3, 4 and 6 exactly once to make 24 with arithmetic operations. Multiplying 6 by 4 looks promising because it already reaches 24, but the other cards still have to be used. A useful route instead begins with the unremarkable fraction 3/43/4 and eventually divides 6 by 1−3/41-3/4.

Tree of thoughts, or ToT, organizes language-model problem solving as search over partial solutions. Yao and colleagues, section 3, separate four choices: the unit of a thought, generation of candidates, evaluation of partial states, and the search algorithm. “Thought” here names a chosen text unit, not a claim that the system has a human mental state.

The complete experiment uses rational arithmetic, a programmed generator and a deliberately weak heuristic. It demonstrates search and pruning; it does not replace those rules with an unreported language model. Snell and colleagues, section 5.2, provide a related setting where search is guided by learned process-based scores and computation must also be counted.

Exact arithmetic search can lose a valid solution when its beam is too narrow.
Exact arithmetic search can lose a valid solution when its beam is too narrow.

Generation, evaluation and retention are separate operations

For a question xx and a sequence of thought units, a search state can be represented as:

st=(x,z1,…,zt).s_t=(x,z_1,\ldots,z_t).

A unit might be an arithmetic operation, a crossword entry or a paragraph of a plan. Yao’s method chooses the unit for each task. A whole solution may be too large to explore locally; a single token may provide too little context for a useful state evaluation.

For a frontier StS_t, a generator G(s)G(s) proposes extensions:

Ct+1=⋃s∈St{extend⁡(s,z):z∈G(s)}.C_{t+1}=\bigcup_{s\in S_t}\{\operatorname{extend}(s,z):z\in G(s)\}.

The original work considers separately sampled candidates and jointly proposed alternatives. A generator can omit a necessary move even if the search controller is perfect. Duplicate proposals also consume work without increasing coverage.

A bounded breadth-first variant scores candidates with VV and keeps at most bb:

St+1=Top⁡b{s:s∈Ct+1}ranked by V(s).S_{t+1}=\operatorname{Top}_b\{s: s\in C_{t+1}\}\quad\text{ranked by }V(s).

This truncation makes it beam-like. It does not inherit the completeness of an unrestricted finite breadth-first search. Yao also describes depth-first search with value-threshold pruning and backtracking. Backtracking can revisit a parent, but cannot repair every mistaken pruning decision automatically.

Our arithmetic state stores remaining value–expression pairs. Combining two values replaces them with one result. Fractions are exact, and equivalent multisets of remaining values are deduplicated. The heuristic is:

V(s)=−min⁡v∈s∣v−24∣.V(s)=-\min_{v\in s}|v-24|.

It favors having some current value near 24. It ignores whether the remaining cards can be combined legally to finish, so it is not a proof of reachability or an admissible search-cost estimate. In this puzzle the useful calculation is:

61−3/4=61/4=24.\frac{6}{1-3/4}=\frac{6}{1/4}=24.

The intermediate 3/43/4 is far from 24 but enables the solution. A value-based ranking can therefore discard the branch before its usefulness becomes visible.

With mm remaining numbers, the generator considers unordered pairs, then addition, multiplication and both orders of subtraction and division:

Km≤6(m2).K_m\le 6\binom m2.

Zero denominators and duplicate value states reduce this upper bound. Different expression histories with the same remaining values have identical numerical future possibilities in this restricted task. That equivalence need not hold for natural-language states, where provenance and earlier constraints may matter.

At depth TT, with at most bb retained states and at most KK candidates per state, a simple bound is:

candidate generations=O(TbK),frontier storage=O(bK).\text{candidate generations}=O(TbK),\qquad \text{frontier storage}=O(bK).

Sorting up to bKbK candidates adds O(bKlog⁡(bK))O(bK\log(bK)) comparisons per level, and exact rational arithmetic has nonconstant bit costs. Language-model generation and evaluation calls can dominate these bookkeeping costs. Search width alone is not an end-to-end compute budget.

Watch the beam discard the solution

Run the Python program below; it uses only the standard library. Each state retains expressions so that a found solution can be inspected. It never evaluates generated Python code. A separate exhaustive depth-first traversal provides a reachability check for this small puzzle.

"""Original rational-arithmetic search analogue; generator and heuristic are rules, not LMs."""
from fractions import Fraction
from itertools import combinations
import json


def key(state):return tuple(sorted(x[0] for x in state))


def successors(state):
    results={}
    for i,j in combinations(range(len(state)),2):
        a,ea=state[i];b,eb=state[j]
        rest=[x for k,x in enumerate(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})'))
        for item in options:
            out=tuple(sorted(rest+[item],key=lambda x:(x[0],x[1])))
            results.setdefault(key(out),out)
    return list(results.values())


def heuristic(state,target):return -min(abs(x[0]-target) for x in state)


def beam(numbers,width,target=24):
    if (len(numbers)<2 or len(numbers)>5 or any(type(x) is not int for x in numbers)
        or type(width) is not int or width<1):raise ValueError("Two to five integer cards and positive width required")
    frontier=[tuple((Fraction(n),str(n)) for n in numbers)];trace=[];generated=0
    for depth in range(1,len(numbers)):
        candidates={}
        for state in frontier:
            children=successors(state);generated+=len(children)
            for child in children:candidates.setdefault(key(child),child)
        ordered=sorted(candidates.values(),key=lambda s:(-heuristic(s,target),key(s)))
        frontier=ordered[:width]
        trace.append(dict(depth=depth,candidates=len(candidates),retained=len(frontier),generated=generated))
        if not frontier:break
    solution=next((s[0][1] for s in frontier if len(s)==1 and s[0][0]==target),None)
    return dict(width=width,solution=solution,success=solution is not None,generated=generated,trace=trace)


def reachable(numbers,target=24):
    memo=set()
    def dfs(state):
        k=key(state)
        if k in memo:return None
        memo.add(k)
        if len(state)==1:return state[0][1] if state[0][0]==target else None
        for child in successors(state):
            answer=dfs(child)
            if answer is not None:return answer
        return None
    solution=dfs(tuple((Fraction(n),str(n)) for n in numbers))
    return dict(solution=solution,visited=len(memo))


def demo():
    cards=[1,3,4,6]
    return dict(cards=cards,target=24,runs=[beam(cards,w) for w in [1,5,20,100,1000]],
        exhaustive=reachable(cards),known_solution=str(Fraction(6)/(1-Fraction(3,4))),
        needed_intermediate=str(Fraction(3,4)))


if __name__=='__main__':print(json.dumps(demo(),indent=2))

Widths 1, 5 and 20 all fail under the stated heuristic and tie ordering. Width 100 finds (6/(1-(3/4))), after 1,078 per-parent successor states have been generated; width 1 generates 52. Width 1,000 also succeeds, generating 1,806. These counts are actual outputs, not language-model token costs.

The exhaustive traversal finds the same expression after visiting 517 unique value states. Its counter has a different definition from the beam’s generated-successor counter, so the two numbers do not establish a speed comparison. The answer itself can be checked independently with exact fractions and card usage.

The input is restricted to two through five integer cards and positive integer width. Each operation reduces the number of remaining values by one, so four cards require three transitions. This finite bound, not a learned stopping judgment, terminates the example.

A search controller cannot make a weak evaluator infallible

ToT’s modularity helps locate failures: the decomposition may hide a useful move, the generator may never propose it, the evaluator may rank it poorly, or the controller may discard it to meet a budget. Logging only the final answer loses that information.

Wider search can expose more candidates but also spends more work and presents more opportunities to exploit an imperfect score. Snell’s sections 5.1–5.2 distinguish the target predicted by a process scorer and how it is used in search. A score trained as reward-to-go is not automatically a certificate that the current written step is logically valid.

The rational puzzle has an exact specification and small state space. Creative writing and open-ended reasoning have different goals, uncertain evaluations and potentially unbounded branching. The numerical deduplication trick and fixed depth do not transfer automatically. This is a search analogue, not a reproduction of the original paper’s GPT-4 results.

Predict what pruning removes

  1. Why is reaching the intermediate value 24 insufficient in the four-card puzzle?

Answer: All four cards must be used exactly once in one expression. An intermediate 6*4 leaves 1 and 3 unused; reaching the target early does not satisfy the full specification.

  1. What is the operation-count upper bound with four remaining values?

Answer: 6(42)=366\binom42=36 proposed arithmetic results before removing zero divisions and duplicate states. Addition and multiplication use one ordering; subtraction and division use both.

  1. Does failure at width 20 prove the puzzle has no solution?

Answer: No. It proves only that this bounded run did not retain a solution under its generator, heuristic and tie ordering. Width 100 and the independent exhaustive traversal both find one.

  1. Why can the arithmetic program merge equal value multisets, while a text-based system may need to keep separate histories?

Answer: Future allowed arithmetic operations depend only on remaining values, and each retained expression preserves card usage. In text, two superficially similar states may have different premises, provenance or obligations, so merging them may discard relevant information.

Read the four interfaces before adopting the name

Yao’s section 3 and algorithms 1–2 specify generation, evaluation and control. Snell’s sections 5.1–5.2 connect learned scores, aggregation and search cost. Compare systems by those components and their budgets, rather than treating every branching prompt as the same algorithm.

Make a prediction, then check

Does keeping only the highest-scored partial state preserve a solution?

Choose one answer

Learning objectives

  • Separate thought decomposition, generation, evaluation and search control.
  • Reproduce the finite example and state its experimental limits.

Prerequisites & connections

Explore related knowledge →

References

  1. Tree of Thoughts: Deliberate Problem Solving with Large Language Models — v1
    Shunyu Yao; Dian Yu; Jeffrey Zhao; Izhak Shafran; Thomas L. Griffiths; Yuan Cao; Karthik Narasimhan · 2023
  2. Scaling LLM Test-Time Compute Optimally can be More Effective than Scaling Model Parameters — v1
    Charlie Snell; Jaehoon Lee; Kelvin Xu; Aviral Kumar · 2024

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author. Read section3, viewed PDF3/4: thought decomposition, sample/propose generation, value/vote evaluation, bounded BFS and DFS/backtracking. Teaching generator/evaluator are explicit rules, not LM replicas. Viewed PDF5/6/7, sections3.1/3.2,4,5.1/5.2: budget allocation, oracle/model-predicted difficulty, excluded difficulty-estimation cost, two-fold selection, rollout value targets and aggregation/search. No scaling benchmark replicated. Seven paired equations and four explained exercises. Exact Fraction search, card conservation, zero division, beam losses, DFS solution and frontier bounds checked. Generated-successor counts differ from unique DFS visits; no LM experiment.

  • Exact Fraction search, card conservation, zero division, beam losses, DFS solution and frontier bounds checked. Generated-successor counts differ from unique DFS visits; no LM experiment.
  • Four computed SVG variants per topic;11 numeric/geometry tests and36 responsive cases passed. Twelve selected final captures directly viewed. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.