Module contents
Lesson 2 of 31Core 90 min

Chain of thought: reasoning by generating intermediate steps

Formalize chain of thought as a latent variable to marginalize, study when intermediate reasoning helps, build an audited answer extractor, and use interventions to measure whether written steps faithfully reflect model computation.

After this lesson you can

  • Formulate answers as the marginal p(a | x) = Σ_z p(z | x) p(a | x, z) over reasoning chains z.
  • Compare direct answers with few-shot and zero-shot chain of thought under controlled token budgets.
  • Implement a format-robust answer extractor and measure its error on a manually labeled sample.
  • Design truncation and error-insertion experiments to measure chain-of-thought faithfulness.
  • Identify the task types that empirically benefit from chain of thought.

Before you start

An answer can have many paths

A direct answer compresses computation into a single continuation. Asking for intermediate steps gives the model more generation positions where it can maintain a partial state and continue from it. That does not guarantee each step is correct or that the written explanation reveals everything influencing the answer. Chain of thought (CoT) is a sequence of steps expressed before the answer, not automatic proof that the model reasoned faithfully.

Wei and colleagues studied examples showing both steps and answers; with 540-billion-parameter PaLM and eight examples they reported a notable GSM8K improvement. Kojima and colleagues studied asking for steps without demonstrations. A third idea, the Nye and colleagues scratchpad, makes intermediate computation states explicit. These are different experimental designs: do not extrapolate results from one model or task to every other.

In Table 6 of Wei’s paper, for LaMDA 137B and GSM8K, standard prompting achieves 6.5 ± 0.4% and CoT 14.3 ± 0.4%; reported variation corresponds to example orderings across five seeds. An ablation adding dots without informative steps reaches 6.4 ± 0.3%. This comparison limits the hypothesis that merely generating more text suffices in that experiment, but alone identifies no universal mechanism. These are published results, not measurements of this lab’s small model.

A latent variable, not a single path

For the autoregressive policy, let xx be the problem, zz a complete chain of steps, and aa an answer extracted by a fixed rule. The interpretation of steps as a latent variable applies the law of total probability:

p(a∣x)=∑zp(z∣x)p(a∣x,z).p(a\mid x)=\sum_z p(z\mid x)p(a\mid x,z).

The sum requires possible values of zz to form a well-defined partition and probabilities to belong to the same policy, including its stopping rule. If aa is a deterministic function of the complete sequence, p(a∣x,z)p(a\mid x,z) is an indicator. If zz ends before generating aa, that distribution is the continuation distribution under the specified policy.

Consider three exhaustive paths with masses 0.40.4, 0.30.3, and 0.30.3. The first leads to AA and the other two to BB. The most probable path produces AA, but p(A∣x)=0.4p(A\mid x)=0.4 and p(B∣x)=0.6p(B\mid x)=0.6. Maximizing a trajectory and summing trajectory masses by answer are different operations. Greedy decoding also selects the most probable token at each step: it need not find the most probable complete path.

InteractiveMaximum path and marginal

Three exhaustive paths: A, B₁ and B₂

00.20.40.60.81A0.4B₁0.3B₂0.3

Two answers: paths with the same answer are summed

00.20.40.60.81A0.4B0.6
0.40
Most probable pathA
Marginal answerB
Mass of B0.60
Move the mass of path A. The other two masses are equal and sum to the remainder. This is an exact mathematical three-path model, not a language-model measurement.

If qq denotes A’s mass, each B path has (1−q)/2(1-q)/2. Individual path A wins if q>1/3q > 1/3; marginal answer B wins if q<1/2q < 1/2. For 1/3<q<1/21/3 < q < 1/2 the two rules disagree. At endpoints q=1/3q=1/3 and q=1/2q=1/2 the respective rule ties, requiring explicit resolution.

If you obtain NN independent samples from the policy, each answer’s frequency estimates its marginal mass. Do not sum sampled sequence probabilities as if they were an exhaustive list: a frequent sequence may appear multiple times, and weighting each occurrence again by its probability changes the estimator. Failed extraction should be counted and audited, not silently discarded.

InteractiveForty real trajectories
Janet’s ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her friends every day with four. She sells the remainder at the farmers' market daily for $2 per fresh duck egg. How much in dollars does she make every day at the farmers' market?
0.000.200.400.600.801.00Not extracted0.70180.28−180.03

Path text: scroll to read it in full.

To determine how much Janet makes from selling the eggs at the farmers' market each day, we need to follow these steps: 1. Calculate the total number of eggs laid per day. 2. Determine how many eggs are eaten for breakfast. 3. Subtract the number of eggs eaten for breakfast from the total number of eggs laid to find out how many eggs are left for baking muffins. 4. Subtract the number of eggs used for baking muffins from the remaining eggs to find out how many eggs are sold at the farmers' market. 5. Calculate the revenue from selling the eggs at the farmers' market. Let's go through these steps one by one: 1. **Total number of eggs laid per day**: \[ 16 \text{ eggs/day} \] 2. **Number of eggs eaten for breakfast**: \[ 3 \text{ eggs/day} \] 3. **Remaining eggs after breakfast**: \[ 16 - 3 = 13 \text{ eggs/day} \] 4. **Number of eggs used for baking muffins**: \[ 4 \text{ eggs/day} \] 5. **Remaining eggs available for sale at
Extracted answerNot extracted
Base model log probability−46.48
Reference18
Choose a seed and read its continuation. Bars count frequencies of 40 Qwen2.5-1.5B-Instruct samples on the first GSM8K test problem; the greedy trajectory is another run. “No extraction” includes truncated text or formats the extractor did not recognize. Scores are base-model log probabilities, not sampling-policy probabilities.

In this run, 11 of 40 samples yielded 18 to the extractor, one yielded -18, and 28 produced no answer recognized by its rules. The comparison greedy answer was truncated without an extractable number. You cannot conclude that 28 samples were mathematically incorrect: some express an answer in prose that the conservative extractor does not recognize. Bar calculation retains that category and uses all 40 samples as denominator. Dashes are normalized in visible transcripts; the lab saves original text. The question and reference come from GSM8K, and samples can be reproduced in this lesson’s cell.

[ ]Marginalize exhaustive pathsBrowser
caminos = [(0.4, "A"), (0.3, "B"), (0.3, "B")]
masa = {}
for probabilidad, respuesta in caminos:
    masa[respuesta] = masa.get(respuesta, 0.0) + probabilidad
print("Masa por respuesta:", masa)
print("Camino más probable:", max(caminos)[1])
print("Respuesta marginal:", max(masa, key=masa.get))

Extraction is part of the experiment

Text may contain intermediate operations, units, thousands separators, or an answer inside a box. The answer extractor converts output into an answer comparable with the reference. Define accepted formats in advance and what happens with multiple incompatible answers or none. An extractor taking the first number will incorrectly evaluate “2 + 2 = 4” as 2. One taking the last number may be confused by a unit or later date.

Audit a sample of real outputs with human labels independent of the extractor: save original text, label, extracted result, and disagreement cause. Extractor error rate is disagreements divided by audited count, with uncertainty if the sample is small. If the extractor fails differently between conditions, it can create or hide an accuracy difference between direct answer and CoT.

An interpretable comparison

Use the same problems, model, version, evaluation set, and extraction rule for direct answers, zero-shot, and examples with chains. Context examples must come from training, not evaluation. Fix generation limits and record input and output tokens: equal limits do not imply equal consumed cost, and demonstrations also spend context.

Compare answers per problem, not just two aggregate percentages. Count how often only direct mode succeeds and how often only CoT succeeds; their difference divided by the problem count is the paired accuracy difference. A Wilson interval describes uncertainty in a binomial proportion under its assumptions; it is not by itself an interval for the paired difference. Also retain outputs and extraction failures.

Lab: three conditions on GSM8K

Run the following experiment locally with PyTorch, Transformers, and datasets. Use the same checkpoint and first 300 test problems in each condition; all eight context examples come exclusively from the training set. The code is a batched extension of the previous harness: it retains prompt, answer, tokens, configuration, and results in its own JSON. Its 256-token limit applies to all three modes; output without an extractable answer counts as incorrect in the automatic metric and is logged separately for audit. The cell does not run automatically because it performs 900 generations and can take considerable time.

With left padding and repetition penalty, the padding token is not neutral: the logits processor can count it in history even when attention masks it. Here <|im_start|>, already present in every Qwen prompt, avoids artificially introducing EOS into that history. In the initial test, even with this adjustment, two of three batched direct outputs differed from single-item output and one changed extracted answer. Do not attribute the difference to one cause: retain batch size and composition as part of the design and compare all three conditions using the same strategy.

[ ]Paired evaluation with batchesLocal GPU
import json, re, time
from decimal import Decimal, InvalidOperation
from pathlib import Path
import torch
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer

model_id = "Qwen/Qwen2.5-1.5B-Instruct"
revision = "989aa7980e4cf806f80c7fef2b1adb7bc71aa306"
data = load_dataset("openai/gsm8k", "main", revision="740312add88f781978c0658806c59bc2815b9866")
tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision, padding_side="left")
tokenizer.pad_token = "<|im_start|>"
model = AutoModelForCausalLM.from_pretrained(model_id, revision=revision, dtype=torch.bfloat16).to("cuda").eval()
instruccion = "Give the final numerical answer on its own line as #### followed by the number."
ejemplos = []
for row in data["train"].select(range(8)):
    razonamiento = re.sub(r"<<[^>]*>>", "", row["answer"])
    ejemplos += [{"role": "user", "content": row["question"] + chr(10) + instruccion},
                 {"role": "assistant", "content": razonamiento}]

def extraer(texto):
    numero = r"[+-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?![\d,]|\.\d)"
    hallados = re.findall(r"####\s*\$?\s*(" + numero + r")", texto)
    if not hallados:
        hallados = re.findall(r"\\boxed\{\s*(" + numero + r")\s*\}", texto)
    if not hallados:
        hallados = re.findall(r"(?i)\b(?:the\s+)?answer\s+is\s*[:$]?\s*(" + numero + r")", texto)
    if not hallados:
        hallados = re.findall(r"(?i)\b(?:the\s+)?final\s+(?:number|answer)\s+(?:is\s*)?[:]?\s*\*{0,2}\$?\s*(" + numero + r")", texto)
    if not hallados:
        m = re.fullmatch(r"\s*\$?\s*(" + numero + r")\s*(?:[A-Za-z%]+)?[.\s]*", texto)
        hallados = [m.group(1)] if m else []
    if not hallados:
        return None
    try:
        return str(Decimal(hallados[-1].replace(",", "")).normalize())
    except InvalidOperation:
        return None

eos = model.generation_config.eos_token_id
eos = set(eos if isinstance(eos, list) else [eos])
filas = []
for modo in ("directo", "cero", "ocho"):
    for inicio in range(0, 300, 8):
        lote = data["test"].select(range(inicio, min(inicio + 8, 300)))
        chats = []
        for row in lote:
            prefijo = "Answer directly. " if modo == "directo" else "Solve step by step. "
            mensajes = (ejemplos.copy() if modo == "ocho" else []) + [
                {"role": "user", "content": prefijo + row["question"] + chr(10) + instruccion}]
            chats.append(tokenizer.apply_chat_template(mensajes, tokenize=False, add_generation_prompt=True))
        inputs = tokenizer(chats, return_tensors="pt", padding=True, add_special_tokens=False).to("cuda")
        torch.cuda.synchronize()
        tic = time.perf_counter()
        with torch.inference_mode():
            salidas = model.generate(**inputs, max_new_tokens=256, do_sample=False,
                                     repetition_penalty=1.1, pad_token_id=tokenizer.pad_token_id)
        torch.cuda.synchronize()
        segundos_lote = time.perf_counter() - tic
        ancho = inputs["input_ids"].shape[1]
        for j, (row, secuencia) in enumerate(zip(lote, salidas)):
            ids = secuencia[ancho:].tolist()
            parada = next((k for k, token in enumerate(ids) if token in eos), None)
            if parada is not None:
                ids = ids[:parada + 1]
            texto = tokenizer.decode(ids, skip_special_tokens=True)
            filas.append({"indice": inicio + j, "modo": modo, "pregunta": row["question"],
                          "referencia": extraer(row["answer"]), "extraida": extraer(texto),
                          "texto": texto, "tokens_entrada": int(inputs["attention_mask"][j].sum()),
                          "tokens_salida": len(ids), "truncada": parada is None,
                          "segundos_lote": segundos_lote, "tamano_lote": len(lote)})
        Path("gsm8k_results.json").write_text(json.dumps(filas, ensure_ascii=False, indent=2), encoding="utf-8")
        print(modo, min(inicio + 8, 300), "de 300")

def wilson(k, n, z=1.96):
    p = k / n
    den = 1 + z*z/n
    centro = (p + z*z/(2*n))/den
    radio = z * (p*(1-p)/n + z*z/(4*n*n))**0.5 / den
    return centro-radio, centro+radio

for modo in ("directo", "cero", "ocho"):
    grupo = [r for r in filas if r["modo"] == modo]
    aciertos = sum(r["extraida"] is not None and r["extraida"] == r["referencia"] for r in grupo)
    print(modo, "aciertos:", aciertos, "/", len(grupo), "Wilson:", wilson(aciertos, len(grupo)),
          "sin extracción:", sum(r["extraida"] is None for r in grupo),
          "truncadas:", sum(r["truncada"] for r in grupo),
          "tokens de entrada medios:", sum(r["tokens_entrada"] for r in grupo)/len(grupo),
          "tokens de salida medios:", sum(r["tokens_salida"] for r in grupo)/len(grupo))

directo = {r["indice"]: r for r in filas if r["modo"] == "directo"}
for modo in ("cero", "ocho"):
    otro = {r["indice"]: r for r in filas if r["modo"] == modo}
    pares = [(directo[i], otro[i]) for i in sorted(directo)]
    solo_directo = sum(a["extraida"] is not None and a["extraida"] == a["referencia"] and b["extraida"] != b["referencia"] for a, b in pares)
    solo_otro = sum(b["extraida"] is not None and b["extraida"] == b["referencia"] and a["extraida"] != a["referencia"] for a, b in pares)
    print(modo, "solo directo:", solo_directo, "solo otro:", solo_otro,
          "diferencia pareada:", (solo_otro-solo_directo)/len(pares))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The Wilson interval in that output is for each proportion under the binomial model; the fixed sample of first problems is not automatically a random sample representative of all tasks. A paired comparison reveals disagreements, but conditions also change prompt length and context examples. To compare cost, sum input and output tokens separately; do not distribute batch time among calls as if they were independent executions.

A local run on a 12 GiB RTX 3060, with the indicated checkpoint and parameters, produced these automatic results on the first 300 problems. Wilson intervals are 95%, and outputs without extraction count as incorrect:

  • Direct: 66/300 correct; Wilson 17.7 to 27.0%. There were 124 outputs without extraction and 86 truncated. Mean: 108.4 input and 131.9 output tokens.
  • Zero-shot: 64/300 correct; Wilson 17.1 to 26.3%. There were 218 outputs without extraction and 144 truncated. Mean: 111.4 input and 222.3 output tokens.
  • Eight examples: 168/300 correct; Wilson 50.3 to 61.5%. There were 35 outputs without extraction and 8 truncated. Mean: 1318.4 input and 98.8 output tokens.

Against direct mode, zero-shot alone solved 43 problems and direct alone 45, a paired difference of −2/300. With eight examples the counts were 112 and 10, difference +102/300. These metrics depend on this extraction and budget; extraction failures differ substantially across conditions and examples greatly increase input tokens. Do not attribute the entire difference to reasoning quality or compare only marginal intervals as though they were an interval for the paired difference.

To audit 50 outputs, select indices reproducibly, save original text, and label first without looking at extraida. Record a normalized number or NO_EXTRAIBLE if no final answer can be identified; then compare with the extractor. Retain criteria and disagreements, including the distinction between “extractor failed” and “model answered incorrectly.” Extractor error rate has denominator 50 only when all 50 labels are complete. Sampling stratified by mode and unextracted answers may be more informative, but weight correctly if estimating a rate for the whole set.

[ ]Prepare the manual auditLocal GPU
import csv
seleccion = []
for modo, cantidad in [("directo", 17), ("cero", 17), ("ocho", 16)]:
    grupo = [r for r in filas if r["modo"] == modo]
    seleccion.extend(grupo[:cantidad])
with open("auditoria.csv", "w", newline="", encoding="utf-8") as f:
    escritor = csv.DictWriter(f, fieldnames=["indice", "modo", "texto", "etiqueta_humana"])
    escritor.writeheader()
    for r in seleccion:
        escritor.writerow({"indice": r["indice"], "modo": r["modo"], "texto": r["texto"], "etiqueta_humana": ""})
print("Etiqueta las 50 filas en auditoria.csv sin consultar el extractor.")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With the labeled file, read it again and compare each label with extraer(texto). Keep discrepancies to understand them before correcting rules. The first examples of each mode are a convenience sample, not a random selection; that audit does not automatically estimate overall error. Do not reuse those same 50 outputs as an unbiased test of an extractor modified using them: reserve another sample to validate the correction.

In a manual audit of the first 17 direct, 17 zero-shot, and 16 eight-example cases, there were six disagreements among 50 outputs. Five were explicit prose answers the extractor did not recognize; in another case it accepted a number from an ambiguous conclusion. Some rules were adjusted after observing outputs from this same exercise, so this figure is diagnostic, not an independent error estimate. An extracted answer may also be mathematically incorrect: extraction and evaluation are different jobs.

[ ]Quantify extraction disagreementsLocal GPU
with open("auditoria.csv", newline="", encoding="utf-8") as f:
    auditadas = list(csv.DictReader(f))
if len(auditadas) != 50 or any(not r["etiqueta_humana"].strip() for r in auditadas):
    raise ValueError("Completa las 50 etiquetas antes de calcular la tasa")
desacuerdos = []
for r in auditadas:
    etiqueta = r["etiqueta_humana"].strip()
    humana = None if etiqueta == "NO_EXTRAIBLE" else str(Decimal(etiqueta.replace(",", "")).normalize())
    automatica = extraer(r["texto"])
    if humana != automatica:
        desacuerdos.append((r["modo"], r["indice"], humana, automatica))
print("Desacuerdos:", len(desacuerdos), "/", len(auditadas))
print(desacuerdos)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

To explore one question with 40 trajectories, run this cell after the preceding preparation. Each seed produces a sample with temperature 0.8 and top-p 0.9. The saved sum of log probabilities belongs to the unprocessed base model, whereas samples come from the policy modified by penalty, temperature, and truncation. Do not treat those scores as already corrected importance weights. Trajectories ending at the length limit may lack an answer and must be retained as such.

[ ]Forty trajectories for one problemLocal GPU
row = data["test"][0]
mensajes = [{"role": "user", "content": "Solve step by step. " + row["question"] + chr(10) + instruccion}]
entrada = tokenizer.apply_chat_template(mensajes, add_generation_prompt=True, return_tensors="pt").to("cuda")
caminos = []
for semilla in range(40):
    torch.manual_seed(semilla)
    with torch.inference_mode():
        salida = model.generate(**entrada, do_sample=True, temperature=0.8, top_p=0.9, top_k=0,
                                repetition_penalty=1.1, max_new_tokens=256, output_logits=True,
                                return_dict_in_generate=True, pad_token_id=tokenizer.eos_token_id)
    ids = salida.sequences[0, entrada["input_ids"].shape[1]:]
    logits = torch.stack([paso[0].float() for paso in salida.logits])
    logp = torch.log_softmax(logits, dim=-1).gather(1, ids[:, None]).squeeze(1)
    texto = tokenizer.decode(ids, skip_special_tokens=True)
    caminos.append({"semilla": semilla, "texto": texto, "respuesta": extraer(texto),
                    "logp_modelo_base": float(logp.sum()), "tokens": len(ids)})
    Path("gsm8k_paths.json").write_text(json.dumps({"pregunta": row["question"], "caminos": caminos}, ensure_ascii=False, indent=2), encoding="utf-8")
print("Respuestas extraídas:", {a: sum(c["respuesta"] == a for c in caminos) for a in set(c["respuesta"] for c in caminos)})
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

To separate problem depth from text length, also construct a synthetic task with an integer state and chained operations. The generator fixes a seed and computes the exact answer in Python. Compare “direct answer” with “write each intermediate result” for depths one through six, using the same model and operations in both modes. Five problems per depth are a small exploration, not a general performance curve; record cases without answers and repeat with more seeds before concluding.

InteractiveDepth and written steps
  • Direct
  • Steps
3
Direct correct0/5
Correct with steps5/5
Not extracted, direct / steps0 / 0
Change depth and compare correct answers and unextracted responses. These are 30 tasks generated with seed 42, five per depth and two prompts, run locally with Qwen2.5-1.5B-Instruct; extraction failures count as incorrect.

This run does not produce a monotonic curve: at one step direct mode gets 4 of 5 correct and step mode 0 of 5; at two, three, and four steps, step mode gets 5 of 5 in each group. At depths five and six, respectively 4 and 3 of the 5 step answers remain unextracted. The extractor was extended after observing output formats, and the concise prompt replaced an initial attempt in which the original extractor left 29 of 30 step answers unextracted. These exploratory choices and sample size prevent interpreting the figure as an unbiased comparison or scaling law; they help identify controls for a larger experiment.

[ ]Depth in a composition taskLocal GPU
import numpy as np
rng = np.random.default_rng(42)
tareas = []
for profundidad in range(1, 7):
    for _ in range(5):
        inicial = int(rng.integers(1, 10))
        valor, pasos = inicial, []
        for _ in range(profundidad):
            delta = int(rng.choice([-3, -2, -1, 1, 2, 3]))
            valor += delta
            pasos.append(("add " if delta > 0 else "subtract ") + str(abs(delta)))
        tareas.append({"profundidad": profundidad, "inicial": inicial, "pasos": pasos,
                       "referencia": str(Decimal(valor).normalize())})

resultados_profundidad = []
for modo in ("directo", "pasos"):
    for inicio in range(0, len(tareas), 8):
        lote = tareas[inicio:inicio+8]
        chats = []
        for tarea in lote:
            prompt = "Start at " + str(tarea["inicial"]) + ". In order, " + ", then ".join(tarea["pasos"]) + ". "
            prompt += "Give only the final number, no explanation. " if modo == "directo" else "Use one short equation for each intermediate result. "
            prompt += "Give the final number on its own line as #### followed by the number."
            chats.append(tokenizer.apply_chat_template([{"role": "user", "content": prompt}], tokenize=False, add_generation_prompt=True))
        inputs = tokenizer(chats, return_tensors="pt", padding=True, add_special_tokens=False).to("cuda")
        with torch.inference_mode():
            salidas = model.generate(**inputs, max_new_tokens=192, do_sample=False,
                                     repetition_penalty=1.1, pad_token_id=tokenizer.pad_token_id)
        for tarea, secuencia in zip(lote, salidas):
            texto = tokenizer.decode(secuencia[inputs["input_ids"].shape[1]:], skip_special_tokens=True)
            resultados_profundidad.append({**tarea, "modo": modo, "texto": texto, "extraida": extraer(texto)})
Path("profundidad.json").write_text(json.dumps(resultados_profundidad, ensure_ascii=False, indent=2), encoding="utf-8")
for profundidad in range(1, 7):
    for modo in ("directo", "pasos"):
        grupo = [r for r in resultados_profundidad if r["profundidad"] == profundidad and r["modo"] == modo]
        print(profundidad, modo, "aciertos", sum(r["extraida"] == r["referencia"] for r in grupo), "/", len(grupo),
              "sin extracción", sum(r["extraida"] is None for r in grupo))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Are the steps faithful?

Chain faithfulness asks how much written text reveals about the process determining the answer. Lanham and colleagues intervened in chains using truncation, errors, and paraphrases, finding task-dependent variation. For truncation, request an answer after different prefixes of the same chain and compare with the full-chain answer. If removing the end does not change the answer, the result shows stability under that intervention; it does not alone prove the entire chain irrelevant or reveal internal computation.

Inserting an error into a step and measuring its propagation is another intervention. Check that the edit retains interpretable context, the error is actually incorrect, and the answer is extracted the same way. Paraphrase changes form while ideally preserving content. Each intervention answers a different question and can produce input outside the usual distribution.

The next lab uses real zero-shot chains ending with ####. It removes that marker and retokenizes visible text; for each prefix fraction it forces a numeric answer and compares it with the answer after the full prefix. It then identifies a correct integer addition, subtraction, or multiplication, changes the result by one, and compares continuations from correct and altered steps. Cases without a recognizable operation are excluded from that intervention, and extraction failures are counted separately. This does not reproduce the original paper’s numbers: it is a small test with this model and editing rules.

[ ]Truncation and errors in real stepsLocal GPU
import math, re
elegibles = [r for r in filas if r["modo"] == "cero" and "####" in r["texto"] and r["extraida"] is not None][:20]
fracciones = [0, 0.25, 0.5, 0.75, 1]
truncados, errores = [], []

def completar(pregunta, prefijo):
    mensajes = [{"role": "user", "content": "Solve step by step. " + pregunta + chr(10) + instruccion}]
    base = tokenizer.apply_chat_template(mensajes, add_generation_prompt=True, return_tensors="pt").to("cuda")
    cola = tokenizer(prefijo + chr(10) + "Final answer: #### ", add_special_tokens=False, return_tensors="pt").to("cuda")
    ids = torch.cat([base["input_ids"], cola["input_ids"]], dim=1)
    with torch.inference_mode():
        salida = model.generate(input_ids=ids, attention_mask=torch.ones_like(ids), do_sample=False,
                                repetition_penalty=1.1, max_new_tokens=32, pad_token_id=tokenizer.eos_token_id)
    texto = tokenizer.decode(salida[0, ids.shape[1]:], skip_special_tokens=True)
    return extraer("#### " + texto), texto

operacion = re.compile(r"(?<!\d)(\d{1,4})\s*([+*\-])\s*(\d{1,4})\s*=\s*(\d{1,7})(?!\d)")
for r in elegibles:
    cadena = r["texto"].rsplit("####", 1)[0]
    ids = tokenizer.encode(cadena, add_special_tokens=False)
    respuestas = []
    for f in fracciones:
        prefijo = tokenizer.decode(ids[:math.floor(len(ids)*f)], skip_special_tokens=True)
        respuesta, texto = completar(r["pregunta"], prefijo)
        respuestas.append({"fraccion": f, "respuesta": respuesta, "continuacion": texto})
    truncados.append({"indice": r["indice"], "respuestas": respuestas})
    for m in operacion.finditer(cadena):
        x, operador, y, resultado = int(m[1]), m[2], int(m[3]), int(m[4])
        verdadero = x+y if operador == "+" else x-y if operador == "-" else x*y
        if verdadero != resultado:
            continue
        correcto = cadena[:m.end()]
        alterado = cadena[:m.start(4)] + str(resultado + 1)
        respuesta_ok, texto_ok = completar(r["pregunta"], correcto)
        respuesta_error, texto_error = completar(r["pregunta"], alterado)
        errores.append({"indice": r["indice"], "paso": m.group(), "paso_alterado": m.group()[:m.start(4)-m.start()] + str(resultado+1),
                        "correcto": respuesta_ok, "alterado": respuesta_error,
                        "continuacion_correcta": texto_ok, "continuacion_alterada": texto_error})
        break

Path("fidelidad.json").write_text(json.dumps({"truncados": truncados, "errores": errores}, ensure_ascii=False, indent=2), encoding="utf-8")
for j, f in enumerate(fracciones):
    comparables = [(r["respuestas"][j]["respuesta"], r["respuestas"][-1]["respuesta"]) for r in truncados]
    validas = [(a, b) for a, b in comparables if a is not None and b is not None]
    print("Fracción", f, "cambios", sum(a != b for a, b in validas), "/", len(validas),
          "no comparables", len(comparables)-len(validas))
validos = [r for r in errores if r["correcto"] is not None and r["alterado"] is not None]
print("Errores editados:", len(errores), "cambios de respuesta:", sum(r["correcto"] != r["alterado"] for r in validos), "/", len(validos))
# Coincidir con el valor editado es una señal limitada, no una prueba causal.
igual_al_error = 0
for r in validos:
    m = operacion.fullmatch(r["paso_alterado"])
    igual_al_error += Decimal(r["alterado"]) == Decimal(m[4])
print("Respuesta igual al valor erróneo del paso:", igual_al_error, "/", len(validos))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The preceding rate measures answer change, not whether the edited error value propagated or whether the answer is correct. Examine fidelidad.json and separately label propagation, correctness, and ambiguous cases. Since the intervention forces an answer with a particular template, a change may also result from that template or edited context.

The following paraphrase uses the first eligible correct step and retains operands and result, but expresses the operation in words. Semantic equality concerns only that arithmetic step; changing its wording also changes the model’s context. One pair is an inspection, not a rate estimate.

[ ]Paraphrase an arithmetic stepLocal GPU
if errores:
    caso = errores[0]
    fila = next(r for r in elegibles if r["indice"] == caso["indice"])
    cadena = fila["texto"].rsplit("####", 1)[0]
    m = next(m for m in operacion.finditer(cadena) if m.group() == caso["paso"])
    palabras = {"+": "plus", "-": "minus", "*": "times"}
    frase = m[1] + " " + palabras[m[2]] + " " + m[3] + " equals " + m[4] + "."
    respuesta, continuacion = completar(fila["pregunta"], cadena[:m.start()] + frase)
    comparacion = {"indice": caso["indice"], "paso_original": caso["paso"], "parafrasis": frase,
                   "respuesta_original": caso["correcto"], "respuesta_parafrasis": respuesta,
                   "continuacion": continuacion}
    Path("parafraseo.json").write_text(json.dumps(comparacion, ensure_ascii=False, indent=2), encoding="utf-8")
    print(comparacion)
else:
    print("No hubo un paso aritmético elegible para parafrasear.")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The full prefix may include the answer in prose before ####, so comparison with fraction 1 may leak the answer. A stable result also does not imply steps were causally used: the original prompt may contain enough information to solve again. Inspect prefixes and repeat with chains whose answer has not been revealed before the cut if interpreting the curve as dependence on written reasoning.

In a local run of this procedure, all 20 selected chains were comparable at every fraction. Against the full prefix, the answer changed in 15, 17, 19, and 10 cases for fractions 0, 0.25, 0.5, and 0.75 respectively. Eight chains contained an eligible operation; the answer changed after editing in all eight. In seven of eight the altered answer exactly matched the inserted wrong value; in the other it changed from 9 to 10 without matching the inserted 6. That match is a limited propagation signal and does not prove its causal mechanism. These are results for this template and a sample selected for containing a marked answer, with the possible full-prefix leakage described above.

InteractiveIntervene in a real chain

Problem: Toula went to the bakery and bought various types of pastries. She bought 3 dozen donuts which cost $68 per dozen, 2 dozen mini cupcakes which cost $80 per dozen, and 6 dozen mini cheesecakes for $55 per dozen. How much was the total cost?

Displayed prefix:

To calculate the total cost, we need to multiply the quantity of each item by its respective price and then sum up all these amounts. 1. **Donuts:** - Quantity: 3 dozen - Price per dozen: $68 - Total cost for donuts = \( 3 \times 68 = \$204 \) 2. **Mini Cupcakes:** - Quantity: 2 dozen - Price per dozen: $80 - Total cost for mini cupcakes = \( 2 \times 80 = \$160 \) 3

Forced continuation:

464
Intervention
0.50
Answer with prefix464
With full prefix794
Comparable changes19/20
Choose a case and truncate its prefix, alter a step, or show the paraphrase. The curve uses 20 chains and the eight edited steps were eligible under the lab’s arithmetic rule. Value 1 is the comparison’s own reference, not proof of faithfulness.

In the only paraphrase run, 4 + 1 = 5 became 4 plus 1 equals 5. and the forced answer was 9 in both cases. One pair does not establish a robustness rate. Figure texts come from those runs; dashes are normalized for display and lab-generated files retain original text.

Turpin and colleagues showed that certain biased cues can influence answers without appearing in the explanation. A fluent explanation can rationalize an answer; do not treat it as proof that a cue had no influence.

When it helps

Task dependence is empirical. The meta-analysis by Sprague and colleagues assembled over 100 publications and also evaluated 20 datasets with 14 models; strong benefits in their results concentrated mainly in mathematical or logical tasks. That conclusion concerns their task and model sample, not a guarantee for a new prompt or model. A negative result requires examining statistical power, format, length, extraction, and budget before concluding that steps add nothing.

Exercises

ProofMaximum versus sum
Prove: Give a distribution where the answer of the most probable joint path differs from the most probable marginal answer.
0
There are three mutually exclusive paths with probabilities 0.46, 0.27, and 0.27; each determines an answer.

Step 1 of 2. Which assignment works?

Numeric
Five exhaustive paths have masses 0.25, 0.20, 0.15, 0.25, and 0.15. The first three answer A and the last two B. What is A’s marginal mass?
Quiz
The final 75% of a chain is removed and the answer stays the same. What follows?
Quiz
Within the scope of Sprague and colleagues’ study, where were the strongest consistent gains observed?
Code
Implement extract_answer(text), looking for the last number marked by ####; if absent, find the last inside a boxed expression; then the last after 'The answer is' or 'The final number is'; finally accept text consisting only of a number and optional unit. Support sign, thousands separators, and decimals. Return a Decimal or None when no format is recognized; do not choose arbitrary intermediate-step numbers.
def extract_answer(text):
  pass
Shift+Enter to run
Key idea
An answer groups many possible paths; a generated chain is one sample and readability does not guarantee faithfulness.