Skip to content
Skip to lesson
Back to Topics
LearnTraining, Fine-Tuning & AlignmentReasoning & Test-Time Compute
HardReasoning & Scaling12 min read

Reasoning & Test-Time Compute

How reasoning models trade inference tokens for accuracy via chain-of-thought, Best-of-N, sequential revision, and PRM tree search alongside KV cache and latency limits.

On this page

Ask a language model for all integer solutions to (x2−7x+11)x2−13x+42=1(x^2 - 7x + 11)^{x^2 - 13x + 42} = 1. Under single-pass greedy decoding, the model gets one forward pass per to jump straight to the answer. Because ab=1a^b = 1 splits into three regimes (a=1a = 1, a=−1a = -1 with even bb, and b=0b = 0 with a≠0a \ne 0), a single pass often returns {2,5,6,7}\{2, 5, 6, 7\} and misses the negative-base roots {3,4}\{3, 4\}. Allowing intermediate derivations, parallel rollouts, verification, or tree search turns fixed-depth recall into an explicit search computation.

This is scaling: trading inference tokens and verifier calls under frozen weights for higher accuracy. Strategies span single-pass decoding to flat Best-of-NN (scoring NN full candidates over a shared prompt prefix) to step-level guided by a , while expanding KV caches, delaying visible text behind hidden thought, and multiplying output bills.

Two axes of compute scaling

Pretraining scaling laws [1] tie loss to parameters NN, tokens DD, and train compute Ctrain≈6NDC_{\text{train}} \approx 6ND, yet standard decoding spends constant FLOPs per token regardless of task hardness. Test-time compute adds an orthogonal axis that adapts search effort per prompt:

Accuracy(x)=f ⁣(Ctrain,  Cinference(x),  difficulty(x))\text{Accuracy}(x) = f\!\left(C_{\text{train}},\; C_{\text{inference}}(x),\; \text{difficulty}(x)\right)

Snell et al. [2] showed on MATH [3] that a 14x smaller model with adaptive test-time search matches or beats a much larger single-pass model at equal FLOPs. OpenAI o1 [4] confirmed smooth AIME gains from both RL training compute and inference search compute.

Line chart comparing test-time compute scaling across inference multipliers (1x to 64x FLOPs). PRM-guided tree search on a 14x smaller base model overtakes a large single-pass model baseline as search compute increases.
Small models with test-time search overtake larger single-pass baselines as search compute grows, with PRM search beating flat Best-of-N on hard problems.

Chain-of-thought scaling and hidden reasoning budgets

[5] converts extra token positions into working memory. RL-trained reasoning models such as o1 [4] and DeepSeek-R1 [6] self-check and backtrack, yet longer traces are not universally better: overthinking [7] [8] and inverse-scaling studies [9] show excess thinking on easy prompts can overturn correct initial answers.

TechniqueCore MechanismBest FitPrincipal Failure Mode
Extended CoTOne self-correcting traceMulti-step synthesis and logicOverthinking easy tasks; output cutoff
Best-of-NSample NN full paths, vote/rerankVerifiable code and mathProxy reward hacking; wasted easy-prompt work
Sequential RevisionCritique and edit drafts in roundsTest-guided code repairUnverified self-edits drifting off truth
PRM Tree SearchScore partial prefixes and pruneDeep symbolic proofsFalse pruning from noisy step scorers

Across OpenAI (reasoning.effort + max_output_tokens) [10], Gemini (thinking_budget) [11], and Claude extended thinking (budget_tokens) [12], hidden reasoning tokens bill as output and share max_output_tokens (so a tight 2,000-token cap can finish inside hidden reasoning with zero visible text), yet are dropped from Turn 2 prompt history so multi-turn context grows only with prompts and visible replies.

Best-of-N sampling: coverage vs. selection

Best-of-NN draws NN independent trajectories at nonzero temperature and selects one winner. Having a right answer in the pool (coverage) and picking it (selection) are distinct problems. At single-sample success rate pp, coverage is 1−(1−p)N1 - (1 - p)^N. From M≥kM \ge k samples with cc correct solutions, the unbiased pass@k estimator is:

pass@k=1−(M−ck)(Mk)\text{pass@}k = 1 - \frac{\binom{M - c}{k}}{\binom{M}{k}}

Easy prompts saturate fast (p=0.60p = 0.60 hits 97.4%97.4\% at N=4N = 4), whereas hard prompts (p=0.05p = 0.05) need N=64N = 64 to reach 96.2%96.2\%, showing why uniform NN wastes compute.

Line chart of pass@N coverage from N=1 to N=64 for single-sample success rates p=0.60, p=0.25, and p=0.05. Easy prompts saturate above 97% by N=4, medium prompts exceed 99% by N=16, and hard prompts climb steadily from 5% to 96.3%.
Marginal coverage gains shrink near saturation, shifting optimal N sharply with prompt difficulty.
pass-at-k-numpy.py
import numpy as np
from scipy.special import comb

n_values = np.array([1, 2, 4, 8, 16, 32, 64])
for p in [0.60, 0.25, 0.05]:
    print(f"p={p:.2f} -> coverage@N:", np.round(1.0 - (1.0 - p) ** n_values, 3).tolist())

M, c_counts = 32, np.array([28, 14, 5, 2, 0])
for k in [1, 4, 8]:
    print(f"Batch mean unbiased pass@{k}: {(1.0 - comb(M - c_counts, k) / comb(M, k)).mean():.4f}")
Output
p=0.60 -> coverage@N: [0.6, 0.84, 0.974, 0.999, 1.0, 1.0, 1.0]
p=0.25 -> coverage@N: [0.25, 0.438, 0.684, 0.9, 0.99, 1.0, 1.0]
p=0.05 -> coverage@N: [0.05, 0.098, 0.185, 0.337, 0.56, 0.806, 0.962]
Batch mean unbiased pass@1: 0.3063
Batch mean unbiased pass@4: 0.5329
Batch mean unbiased pass@8: 0.6457

Maj@k, weighted voting, and Goodhart over-optimization

Without an exact unit test or symbolic checker, pipelines pick winners via majority voting (Maj@k), verifier-weighted voting (summing verifier scores per equivalent final answer), or argmax over a reward model:

  • Maj@k (self-consistency) works only when the right answer is the plurality mode; a systematic misconception occurring >50% of the time drives Maj@k to 0% as NN grows.
  • Weighted voting dampens outlier hallucinations by combining verifier confidence with answer consensus.
  • Noisy proxy argmax (Goodhart decay): under R^(x,y)=Rtrue(x,y)+ϵ\hat{R}(x, y) = R_{\text{true}}(x, y) + \epsilon, extreme noise max⁡iϵi∝log⁡N\max_i \epsilon_i \propto \sqrt{\log N} eventually lets confident wrong traces win. Below, oracle coverage reaches 1.000 and max proxy score climbs to 1.090, yet true accuracy peaks at N = 8 (0.570) before collapsing to 0.335 at N = 64.
Line chart of Goodhart over-optimization in Best-of-N selection from N=1 to N=64. The noisy proxy verifier score rises monotonically from 61% to 95%, while true problem solve rate peaks at 76% around N=8 and drops to 60% by N=64.
Under a noisy proxy verifier, selected score climbs with N while true accuracy peaks and turns downward once outlier errors win.
goodhart-best-of-n.py
rng = np.random.default_rng(7)
n_prompts, max_n = 2000, 64
is_correct = rng.random((n_prompts, max_n)) < 0.35
proxy = np.where(is_correct, rng.normal(0.72, 0.14, (n_prompts, max_n)), rng.normal(0.45, 0.28, (n_prompts, max_n)))

for N in [1, 2, 4, 8, 16, 32, 64]:
    sub_corr, sub_score = is_correct[:, :N], proxy[:, :N]
    picked = sub_corr[np.arange(n_prompts), np.argmax(sub_score, axis=1)]
    print(f"N={N:2d} | oracle_cov={sub_corr.any(axis=1).mean():.3f} | max_proxy={sub_score.max(axis=1).mean():.3f} | true_acc={picked.mean():.3f}")
Output
N= 1 | oracle_cov=0.364 | max_proxy=0.556 | true_acc=0.364
N= 2 | oracle_cov=0.591 | max_proxy=0.700 | true_acc=0.495
N= 4 | oracle_cov=0.810 | max_proxy=0.805 | true_acc=0.569
N= 8 | oracle_cov=0.965 | max_proxy=0.892 | true_acc=0.570
N=16 | oracle_cov=0.999 | max_proxy=0.963 | true_acc=0.521
N=32 | oracle_cov=1.000 | max_proxy=1.027 | true_acc=0.429
N=64 | oracle_cov=1.000 | max_proxy=1.090 | true_acc=0.335

Do not equate pass@1 gains with pass@k exploration [13]. Because 1−(1−pi)k1 - (1 - p_i)^k is concave in pip_i, sharpening easy prompts (0.70→0.900.70 \to 0.90) while collapsing hard tails (0.20→0.050.20 \to 0.05) lifts mean pass@1 (0.450 -> 0.475) while slashing true pass@4 (0.791 -> 0.593). Always compute 1 - (1 - p_i)^k per prompt before averaging.

Sequential revision

Sequential revision conditions round tt on draft t−1t - 1 plus verifier feedback or compiler tracebacks. With external tests, accuracy jumps across rounds t1 to t3 before plateauing; unverified self-edits drift downward past t2. Stop once marginal gain drops below τ\tau and retain the highest-verified draft.

Tree search: beam search, MCTS, and lookahead

Step-level tree search branches after intermediate steps (s1,…,sts_1, \dots, s_t) instead of waiting until completion to discard broken traces:

  • PRM beam search expands each active prefix into MM next steps, scores them with a PRM, and retains the top-BB beams. Solving (x2−7x+11)x2−13x+42=1(x^2 - 7x + 11)^{x^2 - 13x + 42} = 1 at B=2B = 2 keeps both a=1a = 1 (0.91) and a=−1a = -1 (0.89) alive to recover all six roots {2,3,4,5,6,7}\{2, 3, 4, 5, 6, 7\}, pruning incomplete paths (0.24) at step 2.
  • Lookahead search rolls candidate steps kk steps forward before scoring, reducing greedy myopia at higher compute cost.
  • balances exploration and exploitation via UCB/PUCT selection and value backpropagation, thriving on deep trees with exact terminal checks at the cost of sequential latency.
Beam search tree (width B=2) solving (x^2 - 7x + 11)^(x^2 - 13x + 42) = 1. Branches for a=1 and a=-1 with even exponent receive high PRM scores (0.91 and 0.89) and verify all six integer roots {2, 3, 4, 5, 6, 7}, while omitting a=-1 scores 0.24 and is pruned at step 2.
Step-level beam search prunes the omitted-branch trace at step 2 before wasting decode compute on an incomplete root set.

Aggregating step scores via min⁡i≤tri\min_{i \le t} r_i or ∏i=1tri\prod_{i=1}^t r_i creates a monotone upper bound for exact branch-and-bound pruning, but permanently penalizes temporary early uncertainty. Snell et al. [2] showed that last-step PRM scoring (rtr_t alone) beats min and prod because rtr_t summarizes completion probability from the whole prefix s1:ts_{1:t}. Below, a compact PyTorch PRM preserves a recovered trajectory (last=0.999) that min caps at 0.321:

torch-prm-beam-search.py
class StepPRM(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.net = nn.Sequential(nn.Linear(4, 8), nn.Tanh(), nn.Linear(8, 1), nn.Sigmoid())
        with torch.no_grad():
            self.net[0].weight.copy_(torch.tensor([
                [1.4, 1.2, -1.6, -1.8], [0.9, 1.1, -1.2, -1.4],
                [-1.1, -0.9, 1.5, 1.6], [0.8, 0.7, -0.8, -1.0],
                [1.0, 0.5, -1.1, -1.2], [0.4, 1.3, -0.9, -1.5],
                [-0.6, -0.8, 1.2, 1.1], [0.7, 0.9, -0.7, -0.9],
            ]))
            self.net[0].bias.zero_()
            self.net[2].weight.copy_(torch.tensor([[1.1, 0.9, -1.2, 0.7, 0.8, 1.0, -0.9, 0.7]]))
            self.net[2].bias.fill_(-0.2)

    def forward(self, features: torch.Tensor) -> torch.Tensor:
        return self.net(features).squeeze(-1)

prm = StepPRM().eval()
paths = {
    "a=1 & a=-1 (even b)": torch.tensor([[0.8, 0.9, 0.1, 0.0], [1.0, 1.0, 0.0, 0.0]]),
    "a=1 & b=0 (skip a=-1)": torch.tensor([[0.8, 0.2, 0.1, 0.8], [0.7, 0.1, 0.0, 0.9]]),
    "uncertain split -> recovered": torch.tensor([[0.3, 0.4, 0.5, 0.1], [1.0, 1.0, 0.0, 0.0]]),
}

with torch.no_grad():
    for label, feats in paths.items():
        scores = prm(feats)
        print(f"{label:28s} | last={scores[-1]:.3f} | min={scores.min():.3f}")
Output
a=1 & a=-1 (even b)          | last=0.999 | min=0.998
a=1 & b=0 (skip a=-1)        | last=0.029 | min=0.029
uncertain split -> recovered | last=0.999 | min=0.321

PRM vs. ORM verification tradeoffs

An Outcome Reward Model (ORM) scores only the finished answer RORM(x,y)∈[0,1]R_{\text{ORM}}(x, y) \in [0, 1]. ORMs are cheap to supervise from final answers or tests, but give sparse terminal credit: a sign error at step 4 of an 8-step proof triggers one low score at step 8 with zero localization.

A Process Reward Model (PRM) scores every prefix RPRM(x,s1:t)∈[0,1]R_{\text{PRM}}(x, s_{1:t}) \in [0, 1]. Instead of costly human step annotations like PRM800K [14], automated systems like Math-Shepherd [15] define PRM targets via Monte Carlo rollout recoverability, estimating the fraction of KK completions from (x,s1:t)(x, s_{1:t}) that reach a verified final answer:

V(s1:t)=P(final answer correct∣x,s1:t)≈1K∑j=1KI ⁣[verify ⁣(x,s1:t,y>t(j))]V(s_{1:t}) = P(\text{final answer correct} \mid x, s_{1:t}) \approx \frac{1}{K} \sum_{j=1}^{K} \mathbb{I}\!\left[\text{verify}\!\left(x, s_{1:t}, y^{(j)}_{>t}\right)\right]

Notice that a Monte Carlo PRM measures completion recoverability rather than strictly local step truth: if a generator self-corrects an earlier slip on 2 of 5 continuations, V=0.40V = 0.40, whereas an unrecoverable error yields V=0.00V = 0.00.

Heatmap comparing Outcome Reward Model (ORM) and Process Reward Model (PRM) scores across steps S1 through S8. The ORM gives no intermediate signal and scores 0.12 at S8, whereas the PRM scores S1 to S3 near 0.90 and drops immediately to 0.15 at error step S4.
Sparse terminal ORM scoring assigns credit only at step S8, whereas a PRM flags the exact step S4 where recoverability collapses.

Early PRM pruning cuts wasted decode work (~30% or more on failed branches), at two costs: generating KK rollouts per prefix makes training data expensive, and noisy small-KK labels can falsely prune valid unconventional derivations.

Training models to reason with RLVR

Rather than relying purely on external search, models can internalize reflection, checking, and backtracking directly via Reinforcement Learning with Verifiable Rewards (RLVR), as in DeepSeek-R1-Zero and the four-stage DeepSeek-R1 pipeline (cold-start SFT, verifiable GRPO, rejection-sampled SFT on fresh V3-Base weights, and broad RL).[6] As developed in RLVR & Verifiable Rewards Training, GRPO computes group-relative advantages directly from verifiable outcomes without a separate critic network.

Compute-optimal test-time scaling and routing

Snell et al. [2] frame compute-optimal scaling as allocating both strategy and FLOPs by estimated prompt difficulty d^(x)\hat{d}(x), balancing pretraining parameters against inference search:

  • Easy prompts: single-pass decoding or light revision; extra search wastes latency and invites overthinking.
  • Medium prompts: sequential revision or moderate Best-of-NN (N=4N = 4 to 88) yields steep accuracy gains per FLOP.
  • Hard prompts (p≪0.1p \ll 0.1): PRM beam search or deep CoT outperforms flat Best-of-NN and lets smaller models overtake larger single-pass models; on the hardest prompts where base coverage nears zero, pretraining a stronger base model still wins.

In serving, a difficulty router applies accuracy and p95 latency cutoffs first, then picks the lowest-cost feasible tier on the Pareto frontier (for example, routing easy prompts to single-pass at 0.2 s, medium to revision at 3.8 s, and only hard prompts to deep PRM search at 11.5 s):

Quadrant chart plotting four inference tiers by p95 latency (seconds) versus solve accuracy, with a 4.5s latency SLO and 80% accuracy floor. Single-pass (0.2s, 56%) and Low Bo4 (1.4s, 74%) fall below quality; Deep PRM (11.5s, 93%) exceeds latency; Med Rev (3.8s, 87%) sits in the feasible Pareto region.
A difficulty router applies latency and accuracy cutoffs first, isolating the Pareto-optimal tier inside the feasible upper-left region.

Serving geometry: KV sharing, visible TTFT, and distillation

Prefix-shared KV caching and visible TTFT

Each cached token position in a transformer with LL layers, HkvH_{\text{kv}} KV heads, head dimension dheadd_{\text{head}}, and bb bytes per scalar occupies 2LHkvdheadb2 L H_{\text{kv}} d_{\text{head}} b bytes (128 KiB/token for 32 layers, 8 KV heads, dhead=128d_{\text{head}} = 128, FP16). Across N=8N = 8 parallel branches on a 4,0964,096-token prompt with 1,0241,024-token tails, unshared caches use 5.00 GiB, whereas copy-on-write prefix sharing via [16] or RadixAttention [17] keeps one prompt block plus eight tails (1.50 GiB, saving 70%).

Baseline-aligned 8x5 KV cache page grids comparing unshared parallel sampling (N=8) with prefix sharing. Left: Unshared stores 8 duplicate 4,096-token prompt blocks (32 pages) plus 8 private 1,024-token tails (8 pages), totaling 40,960 KV slots (5.0 GiB). Right: Prefix-shared stores 1 read-only prompt block (4 pages) referenced by all 8 branches plus 8 isolated private tails (8 pages), cutting cache footprint by 70% to 12,288 KV slots (1.5 GiB).
Sharing read-only prompt KV pages across parallel branches cuts cache footprint by 70% while isolating private tails.

Hidden thinking tokens decode autoregressively before the first visible token arrives:

TTFTvisible≈tprefill(P)+H⋅tdecode\text{TTFT}_{\text{visible}} \approx t_{\text{prefill}}(P) + H \cdot t_{\text{decode}}

At 80 tokens/s, H=1,024H = 1,024 hidden tokens delay visible output to 13.0 s (200 ms prefill plus 12.8 s hidden decode), capping hidden thought at 224 tokens under a 3,000 ms TTFT budget. Because hidden tokens bill at output rates, 2,700 hidden plus 300 visible tokens cost 10x a direct answer.

kv-prefix-and-ttft.py
bytes_per_tok = 2 * 32 * 8 * 128 * 2
prompt_tok, branch_tok, n_branches = 4096, 1024, 8

unshared_gib = n_branches * (prompt_tok + branch_tok) * bytes_per_tok / (1024 ** 3)
shared_gib = (prompt_tok + n_branches * branch_tok) * bytes_per_tok / (1024 ** 3)
max_hidden_tok = int((3000.0 - 200.0) * 80.0 / 1000.0)

print(f"KV footprint: unshared={unshared_gib:.2f} GiB vs shared={shared_gib:.2f} GiB (concurrency={int(24.0 // shared_gib)} in 24 GiB)")
print(f"Max hidden CoT under 3000 ms visible TTFT at 80 tok/s: {max_hidden_tok} tokens")
Output
KV footprint: unshared=5.00 GiB vs shared=1.50 GiB (concurrency=16 in 24 GiB)
Max hidden CoT under 3000 ms visible TTFT at 80 tok/s: 224 tokens

Distillation into compact models

Supervised on verified traces from a large reasoning teacher transfers structured backtracking into compact dense students without online RL.[6] On AIME 2024, distilled Qwen models reach 28.9% (1.5B), 55.5% (7B), and 72.6% (32B) versus 79.8% for 671B DeepSeek-R1. Because trace-only distillation imitates accepted paths without conferring an external verifier, distilled students still benefit from domain verifiers at runtime.

Mastery Quiz

Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 5 answered
1.Two equally weighted prompts have single-sample solve rates [0.98, 0.08] before post-training and [0.95, 0.10] afterward. Across 3 independent attempts, how do mean pass@1 and mean pass@3 change?
2.An intermediate step writes 8 * 9 = 70. Five rollouts from Policy A finish at [70, 71, 70, 71, 71], while five from Policy B self-correct to [72, 71, 72, 71, 71]. Against exact answer 72, what are local validity and each policy's rollout PRM score?
3.A beam frontier holds a finished answer scoring 0.81 and an active prefix at 0.79 (later steps can score up to 1.00). Compare prefix minimum P against last-step scoring L: which guarantees the active prefix cannot beat 0.81?
4.With 150 ms prefill, 100 tokens/s decode speed, and a 2,000 ms visible TTFT budget, how do 200 vs. 180 hidden reasoning tokens behave?
5.Why does Best-of-N with a learned reward model eventually degrade true accuracy as N grows large?

5 questions remaining.

References

Scaling Laws for Neural Language Models

Kaplan et al. · 2020

https://arxiv.org/abs/2001.08361

Scaling LLM Test-Time Compute Optimally Can Be More Effective Than Scaling Model Parameters.

Charlie Snell, Jaehoon Lee, Kelvin Xu, and Aviral Kumar · 2024 · ICLR 2025

https://arxiv.org/abs/2408.03314

Measuring Massive Multitask Language Understanding (MMLU).

Hendrycks, D., et al. · 2021 · ICLR 2021

https://arxiv.org/abs/2009.03300

Learning to reason with LLMs

OpenAI · 2024

https://openai.com/index/learning-to-reason-with-llms/

Chain-of-Thought Prompting Elicits Reasoning in Large Language Models.

Wei, J., et al. · 2022 · NeurIPS

https://arxiv.org/abs/2201.11903

DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning

DeepSeek-AI · 2025

https://arxiv.org/abs/2501.12948

Rethinking Fine-Tuning when Scaling Test-Time Compute: Limiting Confidence Improves Mathematical Reasoning

Chen, F., Raventos, A., Cheng, N., Ganguli, S., & Druckmann, S. · 2025 · NeurIPS 2025

https://proceedings.neurips.cc/paper_files/paper/2025/hash/e8f4eae0a41cab67fdead3aa6b77f083-Abstract-Conference.html

Does Thinking More Always Help? Mirage of Test-Time Scaling in Reasoning Models

Ghosal, S. S., Chakraborty, S., Reddy, A., et al. · 2025

https://arxiv.org/abs/2506.04210

Inverse Scaling in Test-Time Compute

Anthropic · 2025

https://alignment.anthropic.com/2025/inverse-scaling/

Reasoning models

OpenAI · 2026

https://developers.openai.com/api/docs/guides/reasoning

Gemini thinking

Google · 2025

https://ai.google.dev/gemini-api/docs/thinking

Building with extended thinking

Anthropic · 2025

https://platform.claude.com/docs/en/build-with-claude/extended-thinking

Scaling Test-Time Compute Without Verification or RL is Suboptimal

Setlur, A., Rajaraman, N., Levine, S., & Kumar, A. · 2025

https://arxiv.org/abs/2502.12118

Let's Verify Step by Step.

Lightman, H., et al. · 2024 · ICLR 2024

https://arxiv.org/abs/2305.20050

Math-Shepherd: Verify and Reinforce LLMs Step-by-step without Human Annotations

Wang, P., et al. · 2023

https://arxiv.org/abs/2312.08935

Efficient Memory Management for Large Language Model Serving with PagedAttention

Kwon, W., et al. · 2023 · SOSP 2023

https://arxiv.org/abs/2309.06180

SGLang v0.4: Zero-Overhead Batch Scheduler, Cache-Aware Load Balancer, Faster Structured Outputs

SGLang Team · 2024

https://www.lmsys.org/blog/2024-12-04-sglang-v0-4/

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.