Engineering Reasoning Models from Scratch: Deconstructing Test-Time Compute, Process Reward Verifiers, and Guided Search
Discover how modern AI reasoning architectures move beyond standard autoregressive sampling through test-time compute, Process Reward Models, and search-guided decoding. Learn how to implement step-level verification and tree search to elevate raw LLMs into deterministic problem solvers.
The Shift from Pure Autoregression to Deliberative Reasoning
Traditional autoregressive Large Language Models (LLMs) operate under a straightforward objective: predicting the next token conditioned on preceding tokens. While scaling parameters and pre-training corpora yields emergent zero-shot capabilities, standard sampling frequently fails on tasks requiring multi-step deductive logic, formal verification, or algorithmic problem-solving. When an autoregressive model commits to an erroneous deduction early in its token stream, causal self-attention forces it to rationalize that failure mode downstream, culminating in hallucinations.
Recent breakthroughs in reasoning models demonstrate that true system-level deduction requires decoupling computation time from generation length. Instead of allocating fixed compute per token, reasoning architectures scale test-time compute—giving models the budget to explore multiple execution branches, backtrack upon reaching logical contradictions, and verify intermediate states.
Building these capabilities from scratch requires understanding three primary pillars: Process Reward Models (PRMs), search-guided decoding algorithms (such as Monte Carlo Tree Search and Best-First Search), and Reinforcement Learning with Verifiable Rewards (RLVR). This guide breaks down the underlying engineering mechanisms and provides an architectural blueprint for assembling reasoning pipelines from first principles.
Test-Time Compute vs. Train-Time Compute: Shifting the Frontier
For years, scaling laws focused predominantly on train-time FLOPs: bigger models, larger context windows, and trillions of tokens. However, the marginal utility of pre-training scale is encountering data exhaustion and diminishing returns on reasoning benchmarks. Test-time compute fundamentally reallocates compute resources by shifting work to the inference phase.
Formally, let the probability of reaching a correct final answer $y^$ given input prompt $x$ be denoted as $P(y^ \mid x)$. In standard autoregressive decoding with temperature $T$, $P(y^* \mid x)$ is bounded by the static weights $\theta$. In a test-time search framework, the probability is transformed into:
$$P(y^* \mid x) = \sum_{z \in \mathcal{Z}} P(y^* \mid z, x) P(z \mid x)$$
Where $z = (s_1, s_2, \dots, s_k)$ represents an explicit sequence of intermediate reasoning steps. By allocating compute to generate, score, and filter intermediate reasoning paths $\mathcal{Z}$, we systematically maximize the expectation of reaching a verifiable terminal state.
Two primary operational modes define test-time compute scaling:
- Parallel Sampling (Best-of-$N$ / Rejection Sampling): Sampling $N$ independent candidate chains from the base policy and picking the highest-scoring candidate via an external reward verifier.
- Sequential Search (Lookahead & Backtracking): Constructing a decision tree of intermediate steps where low-confidence reasoning branches are pruned before complete generation, mimicking System 2 cognitive processing.
Verifier Architecture: Outcome Reward Models vs. Process Reward Models
To guide search, an LLM requires an objective feedback signal. Traditional Reinforcement Learning from Human Feedback (RLHF) utilizes an Outcome Reward Model (ORM). An ORM accepts the prompt $x$ and the complete generation $y$, returning a scalar reward $r(x, y) \in [0, 1]$.
While ORMs work well for stylistic alignment or simple extractive tasks, they fail catastrophically in multi-step mathematical and logic reasoning due to credit assignment ambiguity. If a 15-step proof has a fatal flaw at Step 3 but accidentally arrives at the right number through compensating errors, an ORM rewards the entire chain. Conversely, a flawed calculation at Step 15 penalizes 14 steps of brilliant deduction.
A Process Reward Model (PRM) resolves credit assignment by providing step-level feedback. The reasoning trace is delimited by explicit step tokens (e.g., \n\n or specialized <step> tags). The PRM scores each discrete transition $s_i$ conditioned on previous steps:
$$r_t = f_\phi(x, s_1, s_2, \dots, s_t)$$
from dataclasses import dataclass
from typing import List, Optional
import torch
import torch.nn as nn
@dataclass
class ReasoningStep:
step_index: int
text: str
score: Optional[float] = None
class ProcessRewardModel(nn.Module):
"""
Evaluates reasoning chains step-by-step.
Extracts hidden states corresponding to step delimiter tokens
and projects them to a scalar probability of correctness.
"""
def __init__(self, base_transformer: nn.Module, hidden_dim: int):
super().__init__()
self.backbone = base_transformer
self.reward_head = nn.Linear(hidden_dim, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, input_ids: torch.Tensor, step_token_indices: List[int]) -> torch.Tensor:
outputs = self.backbone(input_ids=input_ids, output_hidden_states=True)
last_hidden_state = outputs.hidden_states[-1] # [Batch, Seq_Len, Hidden_Dim]
# Gather states at the exact delimiter locations
step_embeddings = last_hidden_state[:, step_token_indices, :]
logits = self.reward_head(step_embeddings)
step_probabilities = self.sigmoid(logits)
return step_probabilities.squeeze(-1)
Training a PRM typically requires either extensive synthetic tree generation with Monte Carlo rollouts to label step correctness, or automated consensus verification across thousands of branching paths.
Implementing Search-Guided Decoding: Step-Wise Best-First Search
With a frozen base policy model $\pi_\theta$ acting as a generator and a trained PRM $f_\phi$ acting as an evaluator, we can construct an inference engine that moves beyond beam search. Standard beam search operates at the token level, which introduces high variance and fails to capture semantic coherence.
Instead, we implement Step-Wise Best-First Search, where candidate expansions happen at the boundary of discrete thoughts.
import heapq
class SearchNode:
def __init__(self, state_text: str, cumulative_score: float, step_depth: int):
self.state_text = state_text
self.cumulative_score = cumulative_score
self.step_depth = step_depth
def __lt__(self, other):
# Max-heap based on cumulative score normalized by depth
return (self.cumulative_score / (self.step_depth + 1e-6)) > \
(other.cumulative_score / (other.step_depth + 1e-6))
def step_wise_search(
prompt: str,
generator_model,
prm_model,
tokenizer,
max_steps: int = 8,
branching_factor: int = 3,
beam_width: int = 4
) -> str:
frontier = [SearchNode(state_text=prompt, cumulative_score=0.0, step_depth=0)]
completed_solutions = []
while frontier and len(completed_solutions) < beam_width:
current_node = heapq.heappop(frontier)
if current_node.step_depth >= max_steps or "Final Answer:" in current_node.state_text:
completed_solutions.append(current_node)
continue
# Generate k alternative candidates for the next step
step_candidates = generator_model.generate_next_steps(
current_node.state_text,
k=branching_factor,
stop_sequence="\n\n"
)
for candidate in step_candidates:
extended_trace = current_node.state_text + candidate + "\n\n"
step_score = prm_model.evaluate_step(extended_trace)
# Threshold pruning: Ignore low-confidence hallucinations immediately
if step_score > 0.40:
child_node = SearchNode(
state_text=extended_trace,
cumulative_score=current_node.cumulative_score + step_score,
step_depth=current_node.step_depth + 1
)
heapq.heappush(frontier, child_node)
# Select the completed path with highest average reward
best_node = max(completed_solutions, key=lambda node: node.cumulative_score / node.step_depth)
return best_node.state_text
This architecture guarantees that the generator does not waste compute exploring the consequences of an invalid deduction. If step $s_2$ receives a confidence score of $0.12$, the search frontier drops it from the priority queue, backtracking to explore step $s_2'$ from ancestor state $s_1$.
Reinforcement Learning with Verifiable Rewards (RLVR)
While external search algorithms demonstrate the power of test-time compute, running external tree search for every user query introduces unacceptable latency for many real-time applications. The next engineering phase is internalizing search traces into model weights via RLVR.
RLVR relies on problems where the final outcome can be verified deterministically via symbolic compilers, formal theorem provers, or execution sandboxes:
- Competitive Programming: Does the generated code pass unit test suites within memory and time constraints?
- Formal Mathematics: Does the proof compile under Lean 4 or Isabelle?
- Symbolic Algebra: Does the final expression simplify into equivalence via SymPy?
The Optimization Objective: PPO vs. GRPO
Standard Proximal Policy Optimization (PPO) requires maintaining four massive models in VRAM: the Actor (policy $\pi_\theta$), the Critic (value model $V_\psi$), the Reference Policy $\pi_{\text{ref}}$, and the Reward Model.
Modern reasoning pipelines frequently replace PPO with Group Relative Policy Optimization (GRPO). GRPO eliminates the critic network entirely, reducing VRAM overhead by approximately 40%. Instead of estimating absolute baselines, GRPO samples a group of $G$ outputs ${o_1, o_2, \dots, o_G}$ for a prompt $q$ from the existing policy, verifies each output deterministically, and normalizes the rewards within that group:
$$\hat{A}_i = \frac{r_i - \text{mean}({r_1, \dots, r_G})}{\text{std}({r_1, \dots, r_G}) + \epsilon}$$
The policy is updated by maximizing:
$$\mathcal{L}{\text{GRPO}}(\theta) = \mathbb{E}{q \sim P(Q), {o_i}{i=1}^G \sim \pi{\theta_{\text{old}}}(O|q)} \left[ \frac{1}{G} \sum_{i=1}^G \min \left( \frac{\pi_\theta(o_i|q)}{\pi_{\theta_{\text{old}}}(o_i|q)} \hat{A}i, \text{clip}\left(\frac{\pi\theta(o_i|q)}{\pi_{\theta_{\text{old}}}(o_i|q)}, 1-\epsilon, 1+\epsilon\right) \hat{A}i \right) - \beta D{\text{KL}}(\pi_\theta \parallel \pi_{\text{ref}}) \right]$$
Through GRPO, the model learns exploratory behaviors naturally. It encounters self-correction patterns during long chains of thought: when paths hit dead ends, the internal attention weights learn to emit tokens such as "Wait, this contradicts our initial assumption. Let us re-evaluate." Because only traces that converge to verified solutions receive positive relative advantages, the internal chain of thought naturally self-regulates.
Production Bottlenecks: Memory, Latency, and KV-Cache Scaling
Deploying reasoning systems at scale introduces unique hardware and systems-level bottlenecks:
| Bottleneck | Cause | Mitigation Strategy | | :--- | :--- | :--- | | KV-Cache Fragmentation | Branching tree searches instantiate diverging key-value matrices across identical prompt prefixes. | Implement Radix Trees / Prefix Caching (e.g., vLLM, SGLang) to share KV-cache pages across search branches. | | Generation Length Inflation | Models trained on RLVR expand prompt-to-token ratios from $1:2$ to $1:30$, spiking end-to-end latency. | Dynamic compute throttling; set max depth based on initial PRM confidence on step zero. | | Verifier Overhead | Invoking a PRM transformer after every generated step stalls tensor parallelism pipelines. | Speculative Verification: Run PRM inference asynchronously on a smaller distilled model while the actor continues expanding steps. |
Prefix Cache (Shared Prompt Tokens)
│
├── Step 1 [Shared Cache]
│ ├── Step 2a [PRM: 0.92] -> Continues to Step 3a
│ └── Step 2b [PRM: 0.18] -> PRUNED (Cache Evicted)
By leveraging Radix-based page sharing, tree-based search architectures avoid redundant self-attention computation over shared prefixes, preserving memory bandwidth on modern accelerator clusters.
The Path Forward
Building modern reasoning models shifts AI engineering from mere data curation to architectural search and reward system design. By pairing autoregressive generation with Process Reward Models, leveraging test-time compute through tree search, and fine-tuning via verification-driven RL, engineering teams can build models that don't just mimic syntax, but execute verifiable, self-correcting logic. The future of computational intelligence belongs to systems that think before they speak.