Course contents 10 / 27

10 / 27 · Language Models as Agents

Chain of thought and reasoning

How writing intermediate steps before answering helps a language model: few-shot and zero-shot chain of thought, the serial computation extra tokens add, self-consistency as a vote over reasoning paths with its exact accuracy, search over thoughts, and how faithful the written reasoning is.

On this page 8

The policy of the previous note reads its context and writes an action in a few tokens. Each of those tokens is computed by a fixed stack of layers. When the right action depends on several steps of computation, say the arithmetic of a word problem or a chain of three facts, the model has only those few forward passes to do all of it before it commits to the first token of the answer. The simplest fix is also the most consequential one in the history of language-model agents: let the model write the intermediate steps first. This note covers chain-of-thought prompting, explains why the written steps add computation and not just words, treats sampling several chains and voting as a way to marginalize over reasoning paths, computes exactly how much the vote helps, places decomposition and tree search on the same line, and summarizes what is known about whether the written chain is the reasoning the model actually did.

Notation. A question xx, a reasoning path rr (a sequence of tokens) and an answer yy read off its end; the model defines pθ(r,y∣x)p_\theta(r, y \mid x). For one question, pp is the probability that one sampled path ends in the correct answer. With nn sampled paths, KK is the number that end correctly and y^n\hat y_n the most frequent answer; An(p)=P(y^n is correct)A_n(p) = P(\hat y_n \text{ is correct}). A transformer has LL layers.

Baseline: answer directly#

The standard prompt of the GPT note shows a few solved examples as question–answer pairs and then the new question. The model must produce the answer immediately. On GSM8K, a benchmark of grade-school word problems that each take two to eight arithmetic steps (Cobbe et al., 2021), PaLM 540B prompted this way with eight examples solved 17.9 % of the test problems (Wei et al., 2022). The model had the facts and the arithmetic; what it lacked was a place to do several dependent steps one after another.

Chain-of-thought prompting#

Few-shot chain of thought (Wei et al., 2022) changes only the examples in the prompt. Each answer is preceded by the steps that lead to it, in plain words:

Q: A shop has 17 pens. It receives 6 boxes of 4 pens and sells 9 pens. How many pens does it have now?
A: The boxes hold 6 × 4 = 24 pens. 17 + 24 = 41 pens. After selling 9, 41 − 9 = 32. The answer is 32.

Shown eight such examples, the model writes its own steps for the new question and ends with The answer is …, which a regular expression extracts. On GSM8K, with eight examples in each condition (Wei et al., 2022, section 3):

modelstandard promptingchain-of-thought prompting
LaMDA 137B6.5 %14.3 %
GPT-3 175B (text-davinci-002)15.6 %46.9 %
PaLM 540B17.9 %56.9 %

The gain grew with scale. Below roughly 100 B parameters the models of the paper wrote fluent but wrong chains, and chain of thought did not help or hurt; the authors described it as an ability that emerges with scale. The paper also separated the ingredients, on GSM8K with LaMDA 137B. Writing only the equation before the answer gave 5.4 %. Writing a row of dots as long as the reasoning, extra tokens with no content, gave 6.4 %. Writing the reasoning after the answer gave 6.1 %. All three stayed near the 6.5 % of standard prompting, against 14.3 % for real reasoning before the answer. The steps help when they are written in words, and when they come before the answer.

Zero-shot chain of thought (Kojima et al., 2022) needs no examples. The prompt is the question followed by Let’s think step by step.; the model writes a chain, and a second prompt appends Therefore, the answer (arabic numerals) is to extract the number. With text-davinci-002, accuracy rose from 10.4 % to 40.7 % on GSM8K and from 17.7 % to 78.7 % on MultiArith, against 48.7 % for eight-example chain of thought on GSM8K with the same model. One sentence recovered most of the effect of hand-written examples. Instruction-tuned models now produce such chains for many questions without being asked, because the demonstrations they were tuned on contain them.

Why intermediate tokens add serial computation#

A transformer computes the distribution of token jj from the tokens before it with LL layers applied one after another. All positions are processed in parallel, and information moves only forward, from earlier positions to later ones, through attention. Without intermediate tokens, the first token of the answer is therefore a function of the question computed by a circuit of depth LL: however wide the model, at most LL dependent steps fit in it.

A generated token changes this. It is the output of a full pass of LL layers at its position, and it re-enters the network at the bottom as an input to every later position. A later token can then build on the result of that whole computation:

serial depth before the answer≈L(direct),≈L (T+1)(after T reasoning tokens).\boxed{ \begin{gathered} \text{serial depth before the answer} \approx L \quad \text{(direct)}, \\ \approx L\,(T + 1) \quad \text{(after } T \text{ reasoning tokens)}. \end{gathered} }

Worked example. A 12-layer model answering directly has 12 layers of sequential computation between the question and the first token of the answer. After 60 tokens of reasoning, the token that starts the answer depends on a chain of 12×61=73212 \times 61 = 732 layer applications. The reasoning tokens act as a scratchpad whose every entry is the result of a full forward pass.

Theory makes the difference precise. Li et al. (2024) show that transformers of constant depth with constant-bit precision, answering directly, can only solve problems in the circuit class AC0\mathrm{AC}^0, which excludes even computing the parity of a bit string; with TT steps of chain of thought, the same kind of transformer, with embeddings of size O(log⁡n)O(\log n), can solve any problem that boolean circuits of size TT solve. Problems in which each step needs the result of the previous one, such as following a value through a long sequence of operations, are exactly the ones that need the extra steps.

Extra tokens are necessary, not sufficient. In the ablation above, dots of the same length did not help a prompted model. Pfau, Merrill and Bowman (2024) found that transformers can learn to use meaningless filler tokens for extra computation on two algorithmic tasks, but only with specific, dense supervision; prompted models do not do it on their own. The content of the steps matters too: written-out results are what later tokens can read.

Self-consistency: vote over reasoning paths#

A reasoning path is not part of the answer; it is a means to it. The probability of an answer is a sum over all paths that reach it,

P(y∣x)=∑rpθ(r,y∣x),P(y \mid x) = \sum_{r} p_\theta(r, y \mid x),

and the answer we want is the most probable one, arg⁡max⁡yP(y∣x)\arg\max_y P(y \mid x). Greedy decoding does something else: it follows, token by token, the most likely continuation, which approximates the single most probable path. When the correct answer can be reached by many different paths and a wrong one by a single popular path, the two disagree.

Self-consistency (Wang et al., 2023) estimates the marginal by sampling. Draw nn paths at a temperature above zero, (ri,yi)∼pθ(⋅∣x)(r_i, y_i) \sim p_\theta(\cdot \mid x), parse each answer, and return the most frequent:

  y^n=arg⁡max⁡y∑i=1n1[yi=y].  \boxed{\;\hat y_n = \arg\max_{y} \sum_{i=1}^{n} \mathbb 1[y_i = y].\;}

The relative frequency of each answer is an average of independent indicators, so by the law of large numbers it converges to P(y∣x)P(y \mid x), and y^n\hat y_n converges to the mode of the answer distribution.

Worked example. Take the question 17 + 6 × 4 − 9 in a stand-in model, the one of the Code section. It solves the problem by one of three correct plans that begin differently (6 * 4 = 24, 17 - 9 = 8, 4 * 6 = 24) or, with probability qq, by a misconception that computes from left to right, 17 + 6 = 23, and ends at 83. With q=0.35q = 0.35, each correct plan has probability 0.65/3=0.2170.65 / 3 = 0.217 and the misconception 0.350.35. Greedy decoding takes the most likely first step, the misconception, and answers 83. Yet P(32∣x)=0.65P(32 \mid x) = 0.65 and P(83∣x)=0.35P(83 \mid x) = 0.35: the vote of many samples answers 32.

Figure

Self-consistency: five reasoning paths and a vote

Self-consistency: five reasoning paths and a voteOn the left the question 17 + 6 × 4 − 9. Five arrows fan out from it to five reasoning paths: 6 × 4 = 24, 17 + 24 = 41, 41 − 9 = 32; 17 + 6 = 23, 23 × 4 = 92, 92 − 9 = 83; 17 − 9 = 8, 6 × 4 = 24, 8 + 24 = 32; 6 × 4 = 24, 17 + 24 = 43, 43 − 9 = 34; 4 × 6 = 24, 24 − 9 = 15, 17 + 15 = 32. Each path has its answer on the right: 32, 83, 32, 34, 32. The answers converge on a vote box: 32 × 3, 83 × 1, 34 × 1; the result is 32.question x17 + 6 × 4 − 91n = 5, τ = 0.7sampled reasoning paths6 × 4 = 24, 17 + 24 = 41, 41 − 9 = 3217 + 6 = 23, 23 × 4 = 92, 92 − 9 = 8317 − 9 = 8, 6 × 4 = 24, 8 + 24 = 326 × 4 = 24, 17 + 24 = 43, 43 − 9 = 344 × 6 = 24, 24 − 9 = 15, 17 + 15 = 322answer32833234323vote32 × 383 × 134 × 1324Self-consistency: five reasoning paths and a voteOn the left the question 17 + 6 × 4 − 9. Five arrows fan out from it to five reasoning paths: 6 × 4 = 24, 17 + 24 = 41, 41 − 9 = 32; 17 + 6 = 23, 23 × 4 = 92, 92 − 9 = 83; 17 − 9 = 8, 6 × 4 = 24, 8 + 24 = 32; 6 × 4 = 24, 17 + 24 = 43, 43 − 9 = 34; 4 × 6 = 24, 24 − 9 = 15, 17 + 15 = 32. Each path has its answer on the right: 32, 83, 32, 34, 32. The answers converge on a vote box: 32 × 3, 83 × 1, 34 × 1; the result is 32.question x17 + 6 × 4 − 915 paths, τ = 0.76×4=24, 17+24=41, 41−9=3217+6=23, 23×4=92, 92−9=8317−9=8, 6×4=24, 8+24=326×4=24, 17+24=43, 43−9=344×6=24, 24−9=15, 17+15=3223283323432332 × 3 83 × 1 34 × 1answer: 324
The paths come from the stand-in model of the Code section. The second path is the misconception that computes from left to right; the fourth slips in an addition (17 + 24 = 43). The correct paths begin differently, so greedy decoding, which follows the most likely first step, picks the misconception when q = 0.35 and answers 83. The vote adds up the probability of all paths that reach the same answer and returns 32; the paths themselves are discarded.
  1. Prompt. The question goes into the context, with chain-of-thought examples or an instruction to reason step by step.
  2. Sample. The model writes nn reasoning paths independently, at a temperature such as 0.70.7; here n=5n = 5.
  3. Parse. A regular expression reads the final answer of each path: 32, 83, 32, 34, 32. The fourth path slipped in one addition.
  4. Vote. The most frequent answer, 32 with three votes, is returned. The paths themselves are discarded.

On GSM8K with PaLM 540B, sampling 40 paths at temperature 0.7 with top-kk = 40 and voting raised accuracy from 56.5 % for greedy chain of thought to 74.4 %; with code-davinci-002, from 60.1 % to 78.0 % (Wang et al., 2023, Table 2). Weighting each vote by the normalized probability of its path gave 74.1 %, no better than the plain count (Table 1). The cost is nn times the tokens of one chain.

How much the vote helps#

When every wrong answer is the same, or when only “correct” and “wrong” matter, the vote is a majority vote between two outcomes. If, given the question, the nn samples are independent and each is correct with probability pp, the number of correct samples is binomial (Discrete distributions). The majority is correct when more than half the samples are, and a tie, possible when nn is even, is broken by a fair coin:

K∼Bin(n,p),P(K=k)=(nk)pk(1−p)n−k(independent samples)An(p)=P(K>n2)+12 P(K=n2)(majority wins, ties by a coin)=  ∑k>n/2(nk)pk(1−p)n−k  +  12(nn/2)(p(1−p))n/2 1[n even].  \begin{aligned} K &\sim \mathrm{Bin}(n, p), \qquad P(K = k) = \binom{n}{k} p^{k} (1 - p)^{n - k} && \text{(independent samples)} \\ A_n(p) &= P\big(K > \tfrac n2\big) + \tfrac12\, P\big(K = \tfrac n2\big) && \text{(majority wins, ties by a coin)} \\ &= \boxed{\;\sum_{k > n/2} \binom{n}{k} p^{k}(1-p)^{n-k} \;+\; \tfrac12 \binom{n}{n/2} \big(p(1-p)\big)^{n/2} \,\mathbb 1[n \text{ even}].\;} \end{aligned}

Worked example. With p=0.6p = 0.6 and n=5n = 5:

A5(0.6)=10⋅0.63 0.42⏟k=3:  0.3456+5⋅0.64 0.4⏟k=4:  0.2592+0.65⏟k=5:  0.0778=0.683.A_5(0.6) = \underbrace{10 \cdot 0.6^{3}\, 0.4^{2}}_{k = 3:\; 0.3456} + \underbrace{5 \cdot 0.6^{4}\, 0.4}_{k = 4:\; 0.2592} + \underbrace{0.6^{5}}_{k = 5:\; 0.0778} = 0.683 .

Three properties follow from the formula.

  • The vote amplifies whichever side is ahead. For p=0.6p = 0.6, AnA_n rises from 0.60.6 to 0.6480.648, 0.6830.683, 0.7530.753 and 0.9030.903 at n=1,3,5,11,41n = 1, 3, 5, 11, 41. For p=0.4p = 0.4 it falls symmetrically: 0.40.4, 0.3520.352, 0.3170.317, 0.2470.247, 0.0970.097. Voting does not create accuracy; it sharpens the model’s own tendency.
  • The error falls exponentially. For p>1/2p > 1/2, Hoeffding’s inequality bounds the error by 1−An(p)≤exp⁡(−2n(p−12)2)1 - A_n(p) \le \exp\big(-2n(p - \tfrac12)^2\big). At n=41n = 41 and p=0.6p = 0.6 the bound is 0.4400.440 against the exact 0.0970.097: loose, but it shows the rate.
  • An even number of samples adds nothing. Going from 2m−12m - 1 samples to 2m2m, a correct majority of exactly mm becomes a tie when the new sample is wrong, and a wrong majority with m−1m - 1 correct becomes a tie when the new sample is right. The two events have probabilities (2m−1m)pm(1−p)m\binom{2m-1}{m} p^m (1-p)^m and (2m−1m−1)pm(1−p)m\binom{2m-1}{m-1} p^m (1-p)^m, which are equal, and each tie is won half the time, so A2m=A2m−1A_{2m} = A_{2m - 1}.

Real wrong answers are not all the same. A slip in one step produces a different wrong number on each path, while a shared misconception produces the same wrong number every time. With several answers, the vote is a plurality, and the correct answer wins in the limit exactly when it is the most frequent one, even if p<1/2p < 1/2. With the correct answer at p=0.4p = 0.4 and three wrong answers at 0.30.3, 0.20.2 and 0.10.1, the exact plurality accuracy, computed by summing the multinomial probabilities of all vote counts, is 0.40.4, 0.4400.440, 0.4900.490, 0.5810.581 and 0.7630.763 at n=1,3,5,11,41n = 1, 3, 5, 11, 41, and it tends to 1. With the same p=0.4p = 0.4 and a single wrong answer at 0.60.6, it tends to 0.

Figure

Accuracy of the vote against the number of samples

Accuracy of the vote against the number of samplesThree curves of vote accuracy for n from 1 to 40. Blue: the correct answer with probability 0.6 against one wrong answer; it rises from 0.6 to 0.898 at n = 40, in steps, because an even n is no better than n − 1. Green: the correct answer with probability 0.4 against three wrong answers with 0.3, 0.2 and 0.1; it rises from 0.4 to 0.760. Red: 0.4 against one wrong answer with 0.6; it falls from 0.4 to 0.102.0.00.20.40.60.81.0110203040number of paths naccuracy of the vote0.6 vs one wrong answer0.4 vs 0.3, 0.2, 0.10.4 vs one wrong answerAccuracy of the vote against the number of samplesThree curves of vote accuracy for n from 1 to 40. Blue: the correct answer with probability 0.6 against one wrong answer; it rises from 0.6 to 0.898 at n = 40, in steps, because an even n is no better than n − 1. Green: the correct answer with probability 0.4 against three wrong answers with 0.3, 0.2 and 0.1; it rises from 0.4 to 0.760. Red: 0.4 against one wrong answer with 0.6; it falls from 0.4 to 0.102.0.00.20.40.60.81.0110203040number of paths naccuracy of the vote0.6 vs one wrong answer0.4 vs 0.3, 0.2, 0.10.4 vs one wrong answer
Exact values: the binomial tail for two outcomes, and the sum of multinomial probabilities for several wrong answers. The vote amplifies whichever side is ahead: at 0.6 the accuracy rises towards 1, and at 0.4 against a single wrong answer it falls towards 0. When the wrong answers are scattered, a correct answer with probability 0.4 is still the most frequent one, and the vote converges to it anyway: 0.490 at n = 5, 0.760 at n = 40.

Over a dataset, the questions differ. Accuracy at nn samples is the average of the per-question curves, and as nn grows it approaches the fraction of questions whose correct answer is the mode of the model’s answer distribution. Questions where the model is confidently wrong stay wrong however many paths are sampled, so the curve rises and then flattens. In the stand-in model of the Code section, with 200 questions whose misconception and slip rates vary, one sampled path is correct 53.6 % of the time and greedy decoding 36 %; voting over 5, 10, 20 and 40 paths gives 69.3 %, 73.9 %, 76.4 % and 77.7 %, approaching the 78 % of questions whose correct answer is the mode.

Decomposition and search over thoughts#

Chain of thought and self-consistency produce paths independently and from left to right. Two refinements change the shape of the computation.

Least-to-most prompting (Zhou et al., 2023) splits the work into two stages. A first prompt, with examples of decompositions, asks the model to break the problem into simpler subquestions. Then the model answers the subquestions in order, each prompt containing the answers found so far, and the original question last. The order matters when a problem is harder than any example in the prompt. On the length split of SCAN, where the test commands translate into longer action sequences than any training command, code-davinci-002 reached 99.7 % with least-to-most prompting, against 16.2 % with chain of thought and 16.7 % with standard prompting. On last-letter concatenation of 12-word lists it reached 74.0 % against 31.8 %. On GSM8K the two were close, 62.4 % and 60.9 %.

Tree of Thoughts (Yao et al., 2023b) turns reasoning into the search of Search and planning. A node is a partial solution, a sequence of thoughts. The model proposes several next thoughts, which are the successors of the node, and also rates how promising each partial solution is, which plays the part of the heuristic. Breadth-first or depth-first search keeps the best nodes and backtracks from dead ends, which a single left-to-right chain cannot do. The search note gives its result on the Game of 24; Planning with language models develops search with a model as successor function and heuristic.

methodshape of the computationwhat is chosenmodel calls
chain of thoughtone path, left to rightthe path’s answer1
self-consistencynn independent pathsthe most frequent answernn
least-to-mosta list of subquestions, answered in orderthe last answer, built on the earlier ones1 + number of subquestions
Tree of Thoughtsa tree of partial solutions, searched with backtrackingthe best leaf by the model’s own ratingproposals plus evaluations per node

Is the chain of thought faithful?#

A written chain is easy to read, and it is tempting to treat it as an explanation of how the model reached its answer. It is a generated text like any other, and several lines of evidence show that it can differ from the computation that produced the answer.

  • Biased contexts. Turpin et al. (2023) reordered the options of few-shot examples so that the correct answer was always (A). GPT-3.5 and Claude 1.0 then chose (A) more often for new questions, with accuracy falling by up to 36 % on 13 BIG-Bench Hard tasks, and their chains of thought justified the choice without mentioning the bias. In a test of social bias, the explanations rationalized stereotyped answers in the same way.
  • Interventions on the chain. Lanham et al. (2023) truncated chains, inserted mistakes and paraphrased them, and measured how often the answer changed. The dependence on the chain varied widely between tasks: on some the answer followed the chain, on others the model largely ignored it. On most tasks they studied, larger and more capable models produced less faithful reasoning.
  • Hints in reasoning models. Chen et al. (2025) placed hints to the answer in prompts and checked whether models that used a hint said so. Averaged over their hint types, Claude 3.7 Sonnet mentioned the hint 25 % of the time and DeepSeek-R1 39 %. Outcome-based reinforcement learning first made the chains more faithful, then stopped improving them.
  • Hidden computation. The filler-token result above shows that a transformer can, in principle, compute with tokens whose text says nothing about what is computed.

For agents the consequence is practical. A trace of thoughts is evidence about what the agent is doing, often good evidence, and the main tool people have for debugging agents and monitoring them. It is not a proof. A safety argument that relies on reading the chain needs the chain to be necessary for the task, so that the model cannot reach the answer without writing its real reasoning down; Alignment and oversight of agents returns to monitoring.

From prompted reasoning to reasoning models#

Everything in this note is done by prompting a fixed model. From 2024, models have been trained with reinforcement learning to write long chains before they answer: OpenAI’s o1 (September 2024) and DeepSeek-R1 (January 2025) are the first widely known examples. Accuracy then grows with the length of the reasoning and the number of samples spent at inference, which turns the serial-depth argument and the voting arithmetic of this note into a budget to be allocated. Reasoning models and test-time compute covers how such models are trained and how to spend computation at inference time.

What changed#

answer directlychain of thoughtself-consistency
tokens before the answernoneone written chainnn chains
serial computationLL layersabout L(T+1)L(T + 1)the same per chain
what is returnedthe first answerthe chain’s answerthe most frequent answer
decodinggreedy or sampledusually greedysampled, temperature above zero
cost1the length of the chainnn times that
what fixes errorsnothingnothingthe vote, if the correct answer is the mode

Limitations#

  • Cost. A chain of hundreds of tokens per answer, and nn chains for self-consistency, multiply the latency and the price of every step of an agent.
  • Errors propagate along the chain. A slip in step two is copied into everything after it, and the model rarely notices; Reflection and self-correction is about checking.
  • Not always helpful. Liu et al. (2024) found tasks, taken from studies where deliberating makes people worse, on which chain of thought lowered accuracy: on three of six such tasks, by up to 36.3 points of absolute accuracy (OpenAI o1-preview compared with GPT-4o).
  • Voting needs a canonical answer. Numbers and multiple-choice letters can be counted; free text, code and plans need a comparison or a checker instead.
  • Samples are not independent across questions or prompts. The binomial formula holds for one question given the prompt. Errors shared by every sample, such as a misconception, are untouched by the vote.
  • Faithfulness is not guaranteed. The chain can omit what drove the answer.

What you should remember#

  • Chain of thought: show or ask for intermediate steps before the answer. Few-shot (examples with steps) or zero-shot (Let’s think step by step). On GSM8K with PaLM 540B and eight examples: 17.9 % to 56.9 %.
  • Generated tokens are fed back as inputs, so the serial depth before the answer grows from about LL to about L(T+1)L(T + 1); dots of the same length do not help a prompted model, so the written content matters too.
  • Self-consistency samples nn paths and returns the most frequent answer: a Monte Carlo estimate of arg⁡max⁡y∑rp(r,y∣x)\arg\max_y \sum_r p(r, y \mid x), which greedy decoding does not compute.
  • Majority accuracy with two outcomes is a binomial tail, An(p)=P(K>n/2)+12P(K=n/2)A_n(p) = P(K > n/2) + \frac12 P(K = n/2). It tends to 1 if p>1/2p > 1/2 and to 0 if p<1/2p < 1/2; even nn adds nothing over n−1n - 1. With scattered wrong answers, the correct answer wins whenever it is the mode. Over a dataset the curve flattens at the share of questions whose mode is correct.
  • Least-to-most prompting decomposes the problem and answers subquestions in order; Tree of Thoughts searches over partial solutions with the model as successor function and heuristic.
  • The written chain is evidence, not proof: models can be steered by things their chains do not mention.

Code#

A scripted stand-in for a model that reasons in text about a + b × c − d: three correct plans, one misconception and random slips, each path written as text and its answer read by a regular expression. The script runs self-consistency on 200 questions, computes the exact answer distribution of each question by enumeration to find where the vote converges, and checks the exact binomial and plurality formulas. With a real model, sample_path becomes a call to the model at a temperature above zero, and answer_distribution is unknown: only the samples are available. Seeds are fixed; exact numbers can differ slightly across platforms and library versions. The script runs in about five seconds.

import re
from collections import Counter
from itertools import product
from math import comb, exp, factorial
import numpy as np

# 1. a scripted stand-in for a model that reasons in text about  a + b * c - d
#    three correct plans that start differently, one misconception (left to right); any step can slip
SLIPS = (-10, -2, -1, 1, 2, 10)
def plans(a, b, c, d):        # each step: (left operand, operator, right operand); 'r0', 'r1' are earlier results
    return [[(a, '+', b), ('r0', '*', c), ('r1', '-', d)],      # the misconception: (a + b) * c - d
            [(b, '*', c), (a, '+', 'r0'), ('r1', '-', d)],      # three correct orders
            [(a, '-', d), (b, '*', c), ('r0', '+', 'r1')],
            [(c, '*', b), ('r0', '-', d), (a, '+', 'r1')]]

def run_plan(plan, slips):
    res, text = [], []
    for (x, sym, y), s in zip(plan, slips):
        x, y = [res[int(v[1])] if isinstance(v, str) else v for v in (x, y)]
        r = {'+': x + y, '-': x - y, '*': x * y}[sym] + s
        res.append(r); text.append(f'{x} {sym} {y} = {r}.')
    return ' '.join(text) + f' The answer is {res[-1]}.'

def sample_path(a, b, c, d, q, eps, rng):
    k = 0 if rng.random() < q else 1 + rng.integers(3)
    slips = [int(rng.choice(SLIPS)) if rng.random() < eps else 0 for _ in range(3)]
    return run_plan(plans(a, b, c, d)[k], slips)

def answer_distribution(a, b, c, d, q, eps):      # exact, by enumerating every plan and every slip
    dist = Counter()
    outcomes = [(0, 1 - eps)] + [(s, eps / len(SLIPS)) for s in SLIPS]
    for k, plan in enumerate(plans(a, b, c, d)):
        for steps in product(outcomes, repeat=3):
            pr = (q if k == 0 else (1 - q) / 3) * np.prod([w for _, w in steps])
            dist[extract(run_plan(plan, [s for s, _ in steps]))] += pr
    return dist

def extract(path):                                                # the answer parser
    m = re.search(r'The answer is (-?\d+)\.', path)
    return int(m.group(1)) if m else None

def vote(answers, rng):                                           # plurality vote, ties broken at random
    counts = Counter(answers)
    top = max(counts.values())
    return rng.choice(sorted(a for a, k in counts.items() if k == top))

# 2. a dataset of 200 questions; each has its own misconception rate q and slip rate eps
rng = np.random.default_rng(0)
qs = [(*rng.integers(2, 20, size=4), rng.uniform(0, 0.6), rng.uniform(0, 0.15)) for _ in range(200)]
for k in range(4): print(run_plan(plans(17, 6, 4, 9)[k], [0, 0, 0]))
# 17 + 6 = 23. 23 * 4 = 92. 92 - 9 = 83. The answer is 83.
# 6 * 4 = 24. 17 + 24 = 41. 41 - 9 = 32. The answer is 32.
# 17 - 9 = 8. 6 * 4 = 24. 8 + 24 = 32. The answer is 32.
# 4 * 6 = 24. 24 - 9 = 15. 17 + 15 = 32. The answer is 32.

ns, trials = (1, 5, 10, 20, 40), 50
acc = {n: 0.0 for n in ns}
greedy = mode_ok = p_single = 0
for a, b, c, d, q, eps in qs:
    truth = a + b * c - d
    greedy += (1 - q) / 3 > q                    # greedy follows the likeliest first step: one correct plan, or the misconception
    dist = answer_distribution(a, b, c, d, q, eps)
    mode_ok += dist[truth] > max(v for k, v in dist.items() if k != truth)   # is the correct answer the mode?
    p_single += dist[truth]
    for _ in range(trials):
        answers = [extract(sample_path(a, b, c, d, q, eps, rng)) for _ in range(max(ns))]
        for n in ns:
            acc[n] += vote(answers[:n], rng) == truth
print('one sample', round(p_single / len(qs), 3), 'greedy', greedy / len(qs), 'mode correct', mode_ok / len(qs))
print({n: round(float(acc[n]) / (len(qs) * trials), 3) for n in ns})
# one sample 0.536 greedy 0.36 mode correct 0.78
# {1: 0.526, 5: 0.693, 10: 0.739, 20: 0.764, 40: 0.777}

# 3. the exact majority vote: n independent samples, each correct with probability p, two possible answers
def majority(n, p):
    win = sum(comb(n, k) * p**k * (1 - p)**(n - k) for k in range(n // 2 + 1, n + 1))
    tie = comb(n, n // 2) * (p * (1 - p))**(n // 2) if n % 2 == 0 else 0.0
    return win + tie / 2                                          # a tie is broken by a fair coin

for p in (0.6, 0.4):
    print(p, [round(majority(n, p), 4) for n in (1, 3, 5, 11, 41)])
print(all(abs(majority(2 * m, 0.6) - majority(2 * m - 1, 0.6)) < 1e-12 for m in range(1, 30)))  # even n adds nothing
print(round(1 - majority(41, 0.6), 4), round(exp(-2 * 41 * 0.1**2), 4))                       # error and Hoeffding bound
# 0.6 [0.6, 0.648, 0.6826, 0.7535, 0.9035]
# 0.4 [0.4, 0.352, 0.3174, 0.2465, 0.0965]
# True
# 0.0965 0.4404

# 4. the exact plurality vote with several wrong answers: the correct one wins if it is the mode
def plurality(n, probs):
    total = 0.0
    for ks in product(range(n + 1), repeat=len(probs) - 1):
        k0 = n - sum(ks)
        if k0 < 0: continue
        counts = (k0, *ks)
        pr = factorial(n) * np.prod([pi**k / factorial(k) for pi, k in zip(probs, counts)])
        top = max(counts)
        if k0 == top: total += pr / counts.count(top)
    return total

print([round(float(plurality(n, (0.4, 0.3, 0.2, 0.1))), 4) for n in (1, 3, 5, 11, 41)])
# [0.4, 0.44, 0.4902, 0.5815, 0.7631]

# 5. a simulation of the binary vote agrees with the formula
sim = np.mean([(rng.random(5) < 0.6).sum() >= 3 for _ in range(100_000)])
print(round(float(sim), 4), round(majority(5, 0.6), 4))
# 0.6836 0.6826

The run reports 0.526 for one sampled path, a Monte Carlo estimate of the exact 0.536. Greedy decoding is worse than a single sample here, as in the worked example: on every question with q>0.25q > 0.25 it follows the misconception.

Next#

The model can now think before it answers, but everything it thinks with is in its weights and its context. It cannot look up a fact it does not know, compute reliably beyond what its chain gets right, or change anything in the world. The next note gives it actuators: functions described by JSON schemas, the round trip through which the runtime executes a call and returns the result, constrained decoding that makes every call valid by construction, and what happens when a call fails.

References#