Chain-of-Thought Reasoning
Ask a large language model "what is 47 times 38, plus 12?" Demand only the final number, and it will often guess wrong. Ask it to "think step by step" and show its work. Accuracy on the same question jumps dramatically. This gap is not a curiosity. It is one of the most consequential discoveries in the practical use of large language models. It also reveals something deep about how these systems compute. A transformer language model generates one token at a time. Every generated token becomes part of the input for generating the next one. This means the model's output is not just an answer. It can also be a scratchpad. Chain-of-thought (CoT) reasoning is the technique of prompting or training a model to externalize its intermediate reasoning steps as text before committing to a final answer. This turns the autoregressive generation process itself into a sequential computation device. Why does this matter for real systems? Multi-step arithmetic, symbolic manipulation, multi-hop question answering, code synthesis with intermediate design decisions, and commonsense reasoning chains all benefit substantially. Production systems — coding assistants, math tutors, agentic pipelines that plan and act — routinely elicit or fine-tune for chain-of-thought behavior. Later reasoning-specialized models bake extended chains of thought into training itself, rather than relying purely on prompting. This article builds the idea from first principles: what chain-of-thought is, how to elicit it via prompting (few-shot and zero-shot), the computational-complexity argument for why it helps. It also covers the self-consistency decoding strategy that squeezes more reliability out of it. Finally, it covers the failure modes practitioners must guard against, such as plausible-sounding but unfaithful rationales.
- Chain-of-thought (CoT) prompts a model to emit intermediate reasoning steps as text before the final answer.
- It works because autoregressive generation is a sequential computation: each emitted token adds usable "scratch space" to the context the model conditions on next.
- Few-shot CoT provides worked examples with reasoning; zero-shot CoT simply appends a trigger phrase like "Let's think step by step."
- Self-consistency samples multiple reasoning paths and takes a majority vote over final answers, substantially boosting accuracy over greedy decoding.
- CoT gains scale with model size: they are large in sufficiently large models and can be negligible or even harmful in small models.
- The written reasoning is not guaranteed to reflect the model's true internal computation — it can be a fluent post-hoc rationalization, a key alignment concern.
Letting a language model spend extra generated tokens as intermediate "thinking" steps effectively grants it more sequential computation before it must commit to an answer, which is why chain-of-thought prompting improves performance on multi-step reasoning tasks.
The idea
A standard prompt-and-answer interaction asks a model to map an input x directly to an output y. For multi-step problems — arithmetic word problems, multi-hop factual questions, logical deduction — this direct mapping forces the model to perform an entire chain of latent computation within a single forward pass, compressed into whatever internal representation the final answer token can carry. Chain-of-thought reasoning instead asks the model to generate an intermediate sequence of natural-language reasoning steps z₁, z₂, …, zₖ between x and y, so the joint generation is x → z₁ → z₂ → … → zₖ → y. Each intermediate step is conditioned on all the previous ones, because generation is autoregressive: the model's own prior output becomes part of its input. The technique was popularized as a prompting strategy exploiting in-context learning: instead of fine-tuning the model, one includes a handful of demonstrations in the prompt showing a question, a worked chain of reasoning, and an answer. The model, conditioned on these demonstrations, imitates the pattern — question, reasoning, answer — on a new question. This is called few-shot CoT. A simpler variant, zero-shot CoT, needs no worked examples at all: appending a fixed trigger phrase such as "Let's think step by step" after the question is often enough to induce a reasoning trace, because the model has seen enormous amounts of step-by-step explanatory text during pretraining and the phrase cues that distributional mode. A third regime, increasingly dominant in modern systems, is trained-in chain-of-thought: models are fine-tuned or reinforcement-learned specifically to produce long, high-quality reasoning traces before answering, sometimes with the trace itself optimized against a verifier or reward signal rather than merely imitated from prompt demonstrations. In all three regimes the underlying mechanism is identical — the reasoning tokens are genuinely part of the sequence the model conditions on, so they change what the final answer token can "see."
How it works
The mechanics of eliciting chain-of-thought are simple to describe, but the effect they have on the model's underlying computation is the important part to internalize.
Step 1 — Prompt construction. For few-shot CoT, build a prompt containing several `(question, reasoning, answer)` triples, followed by the target question alone. For zero-shot CoT, take the target question and append a reasoning trigger.
Step 2 — Autoregressive decoding. The model generates tokens left to right. Because the reasoning steps are generated before the final answer, each subsequent token — including the answer — is conditioned on the entire reasoning trace, not just the original question.
Step 3 — Answer extraction. Once generation stops (at an end token or a fixed pattern like "The answer is"), a simple parser extracts the final answer from the generated text, discarding the reasoning trace for downstream use (though the trace is often kept for interpretability or debugging).
Step 4 (optional) — Self-consistency. Rather than decoding once greedily, sample the reasoning-and-answer generation multiple times with temperature or nucleus sampling, extract the final answer from each sample, and return the majority answer across samples. This trades extra inference compute for higher reliability, because different sampled reasoning paths that agree on an answer are strong evidence that answer is correct, while greedy decoding commits irrevocably to one path even if it goes astray early. ``` function CHAIN_OF_THOUGHT_PROMPT(question, exemplars, mode): if mode == "few-shot": prompt = "" for (q_i, reasoning_i, answer_i) in exemplars: prompt += "Q: " + q_i + "\n" prompt += "A: " + reasoning_i + " So the answer is " + answer_i + "\n\n" prompt += "Q: " + question + "\nA:" else if mode == "zero-shot": prompt = "Q: " + question + "\nA: Let's think step by step.\n" return prompt
function GENERATE(model, prompt, temperature): tokens = tokenize(prompt) generated = [] loop: logits = model.forward(tokens + generated) next_token = sample(logits[-1], temperature) # temperature = 0 -> greedy/argmax if next_token == END_OF_SEQUENCE: break generated.append(next_token) if length(generated) > MAX_LEN: break return detokenize(generated)
function EXTRACT_ANSWER(text):
# crude but typical: take content after last occurrence of an answer marker if "the answer is" in text.lower(): return text.lower().split("the answer is")[-1].strip(" .\n") return last_number_or_token(text)
function SELF_CONSISTENCY(model, question, exemplars, mode, num_samples, temperature): prompt = CHAIN_OF_THOUGHT_PROMPT(question, exemplars, mode) answer_counts = empty map from answer -> count for i in 1..num_samples: completion = GENERATE(model, prompt, temperature) a = EXTRACT_ANSWER(completion) answer_counts[a] += 1 return argmax over answer_counts # majority vote ``` The pseudocode has two edge cases worth noting explicitly. First, `MAX_LEN` guards against unbounded generation if the model never emits an end token — a real failure mode in practice for degenerate reasoning loops. Second, `EXTRACT_ANSWER` must handle the case where no explicit marker phrase appears; a production system falls back to heuristics (last number in the text, last quoted token) or simply re-prompts the model to restate its answer in a fixed format.
Complexity & correctness
Inference cost. Let a direct-answer generation cost O(1) decoding steps beyond the prompt (a short answer) with a single forward pass of cost O(n·d² + n²·d) for sequence length n and hidden size d (the standard transformer self-attention plus feed-forward cost per layer, summed over layers). Chain-of-thought generation instead produces k additional reasoning tokens, so total decode cost grows to roughly O((n+k)·d² + (n+k)²·d), i.e. linear-to-quadratic in the extra reasoning length k. Self-consistency multiplies this by the number of sampled paths m, giving O(m·(n+k)·(d² + (n+k)·d)). This is the fundamental tradeoff: CoT and self-consistency buy accuracy with extra compute and extra latency, paid at inference time rather than training time.
Why extra generated tokens help — the expressivity argument. A transformer with a fixed number of layers L computes, in one forward pass, a function whose "circuit depth" is bounded by L regardless of input length. Problems that require more than L sequential composition steps — such as multi-digit multiplication, which needs a number of dependent carry-propagation steps growing with the number of digits — cannot in general be computed by such a bounded-depth circuit in a single pass, no matter how wide the layers are, unless the model has memorized shortcuts specific to the training distribution. This is analogous to the classical circuit-complexity fact that bounded-depth circuits (e.g., AC⁰) cannot compute certain functions (like parity) that unbounded-depth circuits can compute trivially. Chain-of-thought sidesteps the fixed-depth ceiling: each new generated token is produced by a fresh forward pass that can attend to all previously generated tokens, so a reasoning trace of length k effectively simulates a computation of depth proportional to k layers, chained together through the autoregressive loop. This is why CoT specifically helps on tasks whose intrinsic sequential-computation requirement exceeds the model's depth, and why it gives little benefit on tasks a single pass can already solve (simple lookups, short common-sense facts).
Correctness is not guaranteed — an important caveat. Chain-of-thought is a mechanism that increases the ceiling on achievable accuracy, not a proof procedure. Three distinct failure modes must be kept separate: 1. Reasoning error: the trace itself contains a wrong step (e.g., a mis-multiplication), propagating to a wrong final answer. More reasoning tokens create more surface area for such errors, which is why self-consistency (voting across independent samples) helps — errors in different sampled paths are less correlated than the signal toward the correct answer, so majority vote suppresses idiosyncratic mistakes if correct reasoning paths are more probable than any single wrong one under the model's distribution. Formally, if the model assigns probability p > 1/2 to reaching the correct final answer along some self-consistent majority of sampled reasoning paths (not literally that each path is correct with probability > 1/2, but that correct-answer paths outnumber any single incorrect-answer variant), then majority voting over m i.i.d. samples converges to the correct answer with probability approaching 1 as m grows, by a Chernoff-bound argument identical to that used for ensemble/bagging methods. 2. Unfaithful rationalization: the model produces a fluent, plausible-looking chain of reasoning that does not correspond to the actual computation that produced the answer — the trace is generated to look like good reasoning given the question and the answer distribution the model tends toward, not necessarily reflecting genuine intermediate belief states. This is a known and actively studied gap between CoT interpretability appeal and CoT faithfulness. 3. Prompt-format sensitivity: small changes in exemplar wording, ordering, or the trigger phrase can shift performance non-trivially, because the model is pattern-matching to the style of reasoning in-context, not executing a verified algorithm. None of this contradicts the core claim — CoT reliably raises accuracy on multi-step benchmarks in sufficiently capable models — but "reliably raises accuracy" is an empirical, statistical statement about aggregate performance, not a per-instance correctness guarantee.
Worked example
Consider the arithmetic word problem: "A juggler has 16 balls. Half are golf balls, and half of the golf balls are blue. How many blue golf balls are there?" The correct answer is 4.
| Stage | Direct prompting | Few-shot chain-of-thought |
|---|---|---|
| Prompt tail | `Q: ... How many blue golf balls?\nA:` | `Q: ... How many blue golf balls?\nA: Let's think step by step.` (plus few-shot exemplars) |
| Generated text | `8` | `Half of 16 balls are golf balls: 16 / 2 = 8 golf balls. Half of the golf balls are blue: 8 / 2 = 4. So the answer is 4.` |
| Extracted answer | 8 (wrong — model conflated "half of 16" with the final quantity) | 4 (correct) |
| Why it differs | Single pass must implicitly track two nested divisions and select the right one to output, with no external scratch space | Each division is written out explicitly and becomes input to the next step, so the second division operates on "8," a value already committed to text, not a value that must be held only in hidden activations |
Now trace self-consistency on a harder variant with m = 5 samples at nonzero temperature:
| Sample | Reasoning path (abbreviated) | Extracted answer |
|---|---|---|
| 1 | 16/2=8 golf; 8/2=4 blue | 4 |
| 2 | 16/2=8 golf; 8/2=4 blue | 4 |
| 3 | mis-reads "half" as "a third"; 16/3≈5; 5/2≈2 | 2 |
| 4 | 16/2=8 golf; 8/2=4 blue | 4 |
| 5 | 16/2=8 golf; forgets second half-step, answers 8 | 8 |
Majority vote across the five samples: 4 appears 3 times, 2 once, 8 once → the self-consistency answer is 4, the correct one, even though 2 of 5 individual samples were wrong. This concretely illustrates the Chernoff-bound intuition above: as long as correct reasoning is the model's dominant mode rather than merely a possible mode, sampling and voting suppresses the minority error modes.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| CoT hurts small models | Models below a certain scale generate fluent-looking but logically inconsistent chains, adding noise rather than signal | Prefer direct prompting or fine-tuned small task-specific models for very small LLMs; benchmark before deploying CoT |
| Answer extraction bugs | Regex/parsing assumes a fixed phrase like "the answer is" that the model doesn't always produce | Constrain output format explicitly (e.g., require a final line `Answer: X`) or use a structured output schema |
| Treating rationale as ground truth explanation | The written reasoning can be an unfaithful post-hoc rationalization rather than the true causal process | Use faithfulness-testing methods (e.g., perturbing intermediate steps and checking if the answer changes accordingly) before trusting CoT traces for auditing |
| Ignoring latency/cost budget | Longer generations and self-consistency sampling multiply inference cost by the trace length and sample count | Cap reasoning length, use fewer samples with early-stopping on vote consensus, or reserve CoT for genuinely hard queries |
| Exemplar leakage / overfitting to prompt style | Few-shot exemplars with a rigid template can make the model copy surface patterns instead of solving the actual problem | Vary exemplar phrasing and difficulty; test on out-of-distribution problem structures, not just harder numbers |
| Compounding errors in very long chains | Each additional reasoning step is another opportunity for a mistake, and errors early in the chain propagate forward | Insert verification steps, use self-consistency, or decompose into smaller verified sub-chains |
Pioneers & history
Chain-of-thought prompting emerged from empirical observations that large language models' latent capabilities could be unlocked purely through how a prompt is phrased, without any change to model weights — a discovery closely tied to the broader study of In-Context Learning and emergent abilities in scaled models. The technique's clean articulation — that inserting worked reasoning examples into a few-shot prompt substantially improves multi-step arithmetic, commonsense, and symbolic reasoning benchmarks in sufficiently large models — reframed prompting from a surface-level trick into a window onto how autoregressive computation can simulate multi-step algorithms.
Origins · 1 minJason Wei and how this was discovered
Wei and collaborators demonstrated that a simple change — including reasoning steps in few-shot exemplars — produced large accuracy gains on math word-problem and multi-step reasoning benchmarks, and crucially showed this benefit emerges reliably only past a certain model scale, tying chain-of-thought directly to the broader study of emergent capabilities in large language models.
Where this matters
Chain-of-thought is now a default ingredient in production LLM deployments wherever multi-step correctness matters more than latency. Coding assistants use it to plan an implementation before writing code, reducing logically inconsistent output. Math and STEM tutoring systems rely on step-by-step traces both for correctness and for pedagogical value — showing the student the reasoning, not just the answer. Retrieval-augmented question-answering pipelines use intermediate reasoning to decide what to search for next, chaining retrieval and reasoning steps together. This naturally extends toward LLM Agents, where a model does not just reason in text but interleaves reasoning steps with tool calls, API invocations, and environment observations — chain-of-thought is the connective tissue that lets an agent plan, act, observe a result, and re-plan, all within the same autoregressive stream. Reasoning-specialized models increasingly generate very long internal chains of thought before producing a final answer, treating extended sequential computation as a first-class capability rather than a prompting trick, which is the direct technological descendant of the ideas covered here.
Ask the tutor: How would you design an experiment to test whether a model's chain-of-thought trace is faithful to its actual computation, rather than a post-hoc rationalization?
Does chain-of-thought prompting require retraining or fine-tuning the model?
No — the original and most common form of chain-of-thought is purely a prompting technique, relying on In-Context Learning and requiring no gradient updates at all. You simply change the text given to the model, either by including worked reasoning exemplars (few-shot CoT) or by appending a trigger phrase like "Let's think step by step" (zero-shot CoT). That said, modern systems increasingly also train models explicitly to produce long, high-quality reasoning traces via supervised fine-tuning or reinforcement learning, which is a separate, complementary technique that bakes the behavior into the weights rather than relying on prompt-time elicitation.
Why does chain-of-thought help more with larger models and sometimes not at all with smaller ones?
Empirically, the accuracy improvement from chain-of-thought prompting tends to appear only past a certain model scale, and can even hurt performance in small models. The leading explanation is that generating a coherent, logically consistent multi-step reasoning trace is itself a nontrivial capability requiring sufficient model capacity; small models may generate reasoning-shaped text that is fluent but logically incoherent, adding noise to the final answer rather than useful intermediate computation. This scale-dependence is one of the pieces of evidence cited in discussions of emergent capabilities in large language models.
What is self-consistency and why is it better than just picking the most likely single reasoning path?
Self-consistency samples several independent reasoning paths at nonzero temperature, extracts the final answer from each, and returns the majority answer rather than trusting a single greedy decode. Greedy decoding commits irreversibly to the single highest-probability token at each step, so one early mistake can derail the entire chain with no chance of recovery. Sampling multiple paths and voting exploits the fact that different sampled chains tend to make different, largely uncorrelated errors, while genuinely correct reasoning is typically the dominant mode across samples — so aggregating suppresses idiosyncratic mistakes, at the cost of extra inference compute proportional to the number of samples.
Is a chain-of-thought trace a faithful explanation of what the model actually computed?
Not necessarily, and this is one of the most important caveats in the whole topic. The trace is generated by the same next-token prediction process as any other text, optimized to look like plausible reasoning given the context, not to transparently report the model's internal computation. Research on faithfulness has shown that perturbing or altering steps in a chain of thought does not always change the final answer in the way it should if the trace were causally driving the answer, indicating the model can sometimes produce fluent rationalizations rather than genuine derivations. This matters heavily for using CoT traces in safety-critical auditing.
How does chain-of-thought relate to LLM agents and tool use?
Chain-of-thought provides the reasoning substrate that agentic systems build on: an agent typically needs to reason about what to do next, decide on an action (such as a tool call or API request), observe the result, and reason again. This interleaved reasoning-action-observation loop is a direct extension of chain-of-thought's core mechanism — using generated text as working memory that conditions future generation — extended to include external actions and their results as additional context. This connective role is why chain-of-thought is considered a foundational building block leading toward LLM Agents.
What is the computational-complexity intuition for why more generated tokens can solve harder problems?
A transformer with a fixed number of layers computes, in a single forward pass, a function of bounded "circuit depth" regardless of input length — it cannot perform an unbounded number of dependent sequential steps in one pass. Certain problems, like multi-digit multiplication with carrying, intrinsically require a number of dependent steps that grows with problem size. By generating reasoning tokens one at a time, with each new token's forward pass able to attend to all previously generated ones, the model chains many bounded-depth computations together, effectively simulating a deeper, more sequential computation than any single pass allows.
Does chain-of-thought always improve accuracy, and are there cases where it should be avoided?
No — it is a statistical, aggregate improvement on tasks whose difficulty stems from needing multiple sequential computation steps, not a universal guarantee. On tasks a single forward pass already solves well (simple factual lookup, short classification), CoT adds latency and cost with little or no accuracy benefit, and in small or undertrained models it can actively hurt performance by introducing incoherent reasoning noise. Latency-sensitive or cost-sensitive applications should benchmark whether CoT's accuracy gain justifies its computational overhead before deploying it by default.