Dev.to AI 🤖 Ai 👁 0 📖 14 min read

Rewarding the Computation, Not the Transcript: A Practical Look at Attention Process Reward Models

If your reward model only reads the text, two trajectories that think differently but write the same thing are indistinguishable to it and RL will happily optimize toward whichever one is cheaper. The Real Prob

If your reward model only reads the text, two trajectories that think differently but write the same thing are indistinguishable to it and RL will happily optimize toward whichever one is cheaper.

The Real Problem / Why Naive Approaches Fail

Most RL pipelines for LLM reasoning reward one of two things. Outcome reward models score the final answer. Process reward models (PRMs) score each textual step of the chain of thought. Both score what the model says.

The paper behind this article asks a sharper question. Can we reward how a model thinks internally, rather than merely what it writes down? Its starting point is a failure mode it calls textual reward aliasing and once you see it you cannot unsee it.

A reward model is a function from text to a scalar. Many different internal computations can produce the same text. Consider a model solving a multi-step arithmetic word problem. In trajectory A, the tokens of step 3 are produced while the model actually attends to the quantities in the problem statement and the intermediate result from step 2. In trajectory B, the same tokens appear because the model pattern-matched a familiar template and the numbers happen to come out right. A text-only PRM sees identical strings. It assigns identical rewards. The mapping from internal process to reward is many-to-one and the information that distinguishes sound reasoning from lucky reasoning has been aliased away before the reward is even computed.

This matters more in RL than in evaluation. Policy gradient methods push probability mass toward whatever earns reward. If the shortcut and the real computation earn the same reward, the optimizer has no reason to prefer the real one and shortcuts are usually cheaper to learn. Teams often notice this as reward climbing on the training distribution while out-of-distribution accuracy stalls or as chains of thought that read well but do not actually drive the answer. The literature on unfaithful chain of thought (Turpin et al.) documents that stated reasoning and actual decision process can diverge. A text-only reward cannot detect that divergence by construction.

The Attention Process Reward Model (APRM) proposal is to move the reward signal one level down: score reasoning steps using the model's attention patterns, which are a (partial, noisy) trace of what information each step actually consumed.

A note on scope. The abstract I am working from is truncated, so I am not going to claim specific numbers or architectural details from the paper. What follows is my engineering reading of how you would build and operate an attention-based process reward in a real RL loop, with the design choices called out as mine.

Architecture & Inner Mechanics

The core idea decomposes into three pieces.

1. Segment the trajectory into steps. Same as any PRM. Newline-delimited steps, explicit Step k: markers or a delimiter token. Each step becomes a token span [s_k, e_k).

2. Extract attention features per step. For each step, look at the attention from the step's tokens back to the context. The useful question is where the attention mass lands: on the problem statement, on previous steps, on the step's own tokens or on attention sinks like the BOS token. You also want shape statistics such as entropy (diffuse vs focused) and peak concentration. These get computed per selected layer and averaged over heads, giving a compact feature vector per step.

3. Score each step with a small learned head. A lightweight model maps attention features (optionally concatenated with a hidden-state summary of the step) to a step-quality score. That head is trained on step-level labels, which you can get from human annotation (the PRM800K approach) or from Monte Carlo rollouts that estimate whether a step still leads to a correct answer (the Math-Shepherd approach).

Then the RL loop combines step scores with the outcome reward to produce advantages.

sequenceDiagram
    participant P as Policy LLM
    participant S as Step Segmenter
    participant F as Attention Feature Extractor
    participant H as APRM Head (small MLP)
    participant O as Outcome Verifier
    participant R as GRPO Advantage Calc

    P->>P: Sample G trajectories per prompt
    P->>S: Token ids + text
    S->>F: Step spans [s_k, e_k)
    F->>P: Re-forward pass (eager attn, hooks on selected layers)
    P-->>F: Per-layer attention, reduced in-hook to step x region mass
    F->>H: Feature vector per step (mass, entropy, peak)
    H-->>R: Step scores q_1..q_K in [0,1]
    O-->>R: Final answer correct? (0/1)
    R->>R: r = r_outcome + lambda * agg(q), group-normalize
    R->>P: Advantages for policy update

One architectural decision deserves attention before you write any code: whose attention do you read?

Option one is the policy itself. This gives the most faithful view of how the policy produced its tokens, which is the entire point. The risk is Goodhart. The policy's attention patterns are now directly optimized and a sufficiently capable optimizer can learn to produce attention patterns that look like "reasoning" to the head without the underlying computation improving.

Option two is a frozen reference model reading the policy's tokens. This is harder to game, but now you are measuring how a different model processes the text, which reintroduces a form of the aliasing you were trying to escape.

I lean toward reading the policy's attention, keeping the head small and periodically retraining it on fresh rollouts, plus always anchoring to a verifiable outcome reward. I do not know which variant the paper uses, so treat this as my design preference.

Production Implementation

Below is a working feature extractor and reward head against Hugging Face transformers. Two things make this harder than it sounds.

First, FlashAttention and SDPA kernels never materialize the full attention matrix, which is precisely why they are fast. You need attn_implementation="eager" for the scoring pass. Second, output_attentions=True on a full model will try to keep every layer's [heads, seq, seq] tensor alive. For a 28-layer, 28-head model at 4,096 tokens in bf16, that is 28 * 28 * 4096^2 * 2 bytes ≈ 26.3 GB per sequence. That is arithmetic, not a benchmark and it rules out the naive approach on anything short of a large accelerator.

The fix is to reduce attention inside a forward hook, on selected layers only and drop the full tensor before the next layer runs.

# aprm_features.py
import math
from dataclasses import dataclass, field

import torch
import torch.nn as nn
from transformers import AutoModelForCausalLM, AutoTokenizer


@dataclass
class StepSpan:
    start: int  # inclusive token index
    end: int    # exclusive token index


@dataclass
class ExtractorConfig:
    layers: list[int] = field(default_factory=lambda: [-8, -6, -4, -2])
    sink_tokens: int = 1          # exclude BOS-style attention sinks
    eps: float = 1e-9


def segment_steps(tokenizer, prompt: str, response: str, delimiter: str = "\n"):
    """Return token ids and step spans over the response region."""
    prompt_ids = tokenizer(prompt, add_special_tokens=True)["input_ids"]
    spans, ids = [], list(prompt_ids)
    for chunk in response.split(delimiter):
        if not chunk.strip():
            continue
        chunk_ids = tokenizer(chunk + delimiter, add_special_tokens=False)["input_ids"]
        start = len(ids)
        ids.extend(chunk_ids)
        spans.append(StepSpan(start, len(ids)))
    return torch.tensor([ids]), len(prompt_ids), spans


class AttentionFeatureExtractor:
    """Hooks selected attention modules and reduces weights in-place to per-step features."""

    def __init__(self, model, cfg: ExtractorConfig):
        self.model = model
        self.cfg = cfg
        n_layers = model.config.num_hidden_layers
        self.layer_ids = [l % n_layers for l in cfg.layers]
        self._handles = []
        self._ctx = None
        self.features: dict[int, torch.Tensor] = {}

    def _make_hook(self, layer_idx: int):
        def hook(module, args, output):
            # Recent HF attention modules return (attn_output, attn_weights).
            # This tuple layout varies across transformers versions; pin your version.
            if not isinstance(output, tuple) or len(output) < 2 or output[1] is None:
                raise RuntimeError(
                    f"Layer {layer_idx}: no attention weights. Use attn_implementation='eager'."
                )
            attn = output[1]  # [batch, heads, q, k]
            with torch.no_grad():
                self.features[layer_idx] = self._reduce(attn[0].float().mean(0))
            # Drop the full tensor so it is not accumulated in model outputs.
            return (output[0], None) + tuple(output[2:])
        return hook

    def _reduce(self, a: torch.Tensor) -> torch.Tensor:
        """a: [q, k] head-averaged attention. Returns [num_steps, 6]."""
        prompt_len, spans = self._ctx
        sink, eps = self.cfg.sink_tokens, self.cfg.eps
        rows = []
        for i, sp in enumerate(spans):
            block = a[sp.start:sp.end]                       # [step_len, k]
            sink_mass = block[:, :sink].sum(-1).mean()
            prompt_mass = block[:, sink:prompt_len].sum(-1).mean()
            prev_end = spans[i - 1].end if i > 0 else prompt_len
            prev_mass = block[:, prompt_len:prev_end].sum(-1).mean()
            self_mass = block[:, sp.start:sp.end].sum(-1).mean()
            # Entropy over non-sink keys, renormalized.
            body = block[:, sink:sp.end]
            body = body / (body.sum(-1, keepdim=True) + eps)
            ent = -(body * (body + eps).log()).sum(-1).mean()
            ent_norm = ent / math.log(max(sp.end - sink, 2))
            peak = body.max(-1).values.mean()
            rows.append(torch.stack([sink_mass, prompt_mass, prev_mass,
                                     self_mass, ent_norm, peak]))
        return torch.stack(rows)

    def __enter__(self):
        blocks = self.model.model.layers  # Llama/Qwen/Mistral layout
        for idx in self.layer_ids:
            h = blocks[idx].self_attn.register_forward_hook(self._make_hook(idx))
            self._handles.append(h)
        return self

    def __exit__(self, *exc):
        for h in self._handles:
            h.remove()
        self._handles.clear()

    @torch.no_grad()
    def extract(self, input_ids, prompt_len, spans) -> torch.Tensor:
        if not spans:
            raise ValueError("Response produced zero steps; cannot score.")
        self._ctx = (prompt_len, spans)
        self.features.clear()
        self.model(input_ids.to(self.model.device), output_attentions=True, use_cache=False)
        missing = set(self.layer_ids) - set(self.features)
        if missing:
            raise RuntimeError(f"Hooks did not fire for layers {missing}")
        # [num_steps, num_layers * 6]
        return torch.cat([self.features[l] for l in self.layer_ids], dim=-1)


class APRMHead(nn.Module):
    """Small scorer: attention features -> step quality in [0, 1]."""

    def __init__(self, in_dim: int, hidden: int = 64):
        super().__init__()
        self.net = nn.Sequential(
            nn.LayerNorm(in_dim),
            nn.Linear(in_dim, hidden), nn.GELU(),
            nn.Dropout(0.1),
            nn.Linear(hidden, 1),
        )

    def forward(self, x):
        return torch.sigmoid(self.net(x)).squeeze(-1)


def load_policy(name: str):
    tok = AutoTokenizer.from_pretrained(name)
    model = AutoModelForCausalLM.from_pretrained(
        name, torch_dtype=torch.bfloat16, device_map="auto",
        attn_implementation="eager",  # required: fused kernels hide weights
    )
    model.eval()
    return tok, model

A few choices worth defending. I average over heads because per-head features multiply the feature dimension by 28 or more and the head becomes easy to overfit with the few thousand labeled steps most teams can afford. I pick late-middle layers because early layers mostly do local token mixing. And I separate the sink mass explicitly. StreamingLLM (Xiao et al.) showed that a large share of attention lands on the first token regardless of content. If you do not strip it out, your "prompt mass" feature is mostly measuring the sink.

The reward combination for a GRPO-style update:

# aprm_reward.py
import torch


def combine_rewards(outcome: torch.Tensor, step_scores: list[torch.Tensor],
                    lam: float = 0.3, agg: str = "min") -> torch.Tensor:
    """outcome: [G] in {0,1}. step_scores: list of G tensors, each [K_i]."""
    if agg == "min":
        process = torch.stack([s.min() for s in step_scores])
    elif agg == "mean":
        process = torch.stack([s.mean() for s in step_scores])
    else:
        raise ValueError(agg)
    return outcome.float() + lam * process


def group_advantages(rewards: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
    """GRPO normalization within a group of G samples for one prompt."""
    std = rewards.std(unbiased=False)
    if std < eps:
        # All samples tied: no learning signal. Return zeros, do not divide by ~0.
        return torch.zeros_like(rewards)
    return (rewards - rewards.mean()) / (std + eps)

I default to min aggregation. A chain is only as sound as its weakest step and mean lets one good-looking step mask a broken one. Lightman et al. used a product of step correctness probabilities, which behaves similarly.

Production Gotchas, Edge Cases & Failure Modes

The eager attention tax. Your rollout generation can still use vLLM or FlashAttention. The scoring pass cannot. That means a second, slower forward pass per trajectory with quadratic memory per layer. At 4,096 tokens, a single layer's head-stacked attention in bf16 is roughly 940 MB transiently (28 * 4096^2 * 2). Fine on a 24 GB card. At 16K tokens it is about 15 GB per layer and long reasoning traces will hit that.

Hook fragility. The (attn_output, attn_weights) tuple layout has changed between transformers releases. Pin the version and keep the RuntimeError checks. A silent None produces a zero feature vector and a meaningless reward that the optimizer will still chase.

Tokenizer boundary drift. Tokenizing steps separately and concatenating can produce different ids than tokenizing the full string, because BPE merges across boundaries. The scoring pass must use the exact ids the policy generated. In production, segment on the generated id sequence directly rather than re-tokenizing text.

Attention is not explanation. Jain and Wallace showed attention weights can be permuted without changing predictions in some settings and Wiegreffe and Pinter pushed back with a more careful framing. The honest position: attention is a partial signal about information flow, not a ground-truth readout of reasoning. Abnar and Zuidema's attention rollout and flow methods account for residual mixing across layers and may give cleaner features than raw per-layer weights.

Goodhart on internals. This is the failure mode I would watch most closely. If the policy's own attention is scored, gradient pressure flows toward attention patterns the head likes. Teams often see a reward model drift when the policy finds its blind spots and an internal reward is no exception. Signals to monitor: APRM score rising while held-out accuracy stays flat and feature distributions (prompt mass, entropy) drifting sharply away from where the head was trained.

When I would not use this.

  • API-only models. No attention weights, no APRM. Full stop.
  • Tasks without verifiable outcomes. Without an outcome anchor, an internal-signal reward is too easy to exploit.
  • Very long contexts. The quadratic scoring pass becomes the dominant cost.
  • Tiny label budgets. If you cannot produce a few thousand step labels, a text PRM or plain outcome reward with GRPO is a better use of time.
  • Architectures without standard attention. State space models and hybrid linear-attention models do not expose comparable weights.

Benchmark Comparison & Cost Tradeoffs

I have not run the paper's experiments and the abstract does not give me its numbers, so I will not invent accuracy deltas. What I can give you is arithmetic on the system costs, which is what decides whether this fits your budget.

Attention memory per sequence (bf16, 28 layers, 28 heads, computed as layers * heads * seq^2 * 2 bytes):

| Sequence length | All layers retained | One layer transient | Reduced features (4 layers, 30 steps) |
|, -|, -|, -|, -|
| 1,024 | 1.6 GB | 59 MB | < 4 KB |
| 4,096 | 26.3 GB | 940 MB | < 4 KB |
| 8,192 | 105 GB | 3.8 GB | < 4 KB |
| 16,384 | 421 GB | 15 GB | < 4 KB |

The right column is the whole argument for in-hook reduction. You discard many gigabytes of attention per sequence and keep a few hundred floats.

Relative cost per training step, assuming G samples per prompt:

| Reward type | Extra forward passes | Kernel | Label cost | Gaming risk |
|, -|, -|, -|, -|, -|
| Outcome only (verifier) | 0 | n/a | None | Low, if verifier is sound |
| Text PRM (separate model) | G passes of PRM | Fused OK | High (step labels) | Medium |
| APRM on policy attention | G passes of policy | Eager only | High (step labels) | Medium to high, internal |
| APRM on frozen reference | G passes of reference | Eager only | High (step labels) | Lower, but reintroduces aliasing |

The APRM head itself is negligible. A 64-unit MLP over 24 features costs nothing next to the forward pass. The real bill is the extra eager pass. On a rented single A100 at typical on-demand cloud rates (a few dollars per hour, check your provider), the scoring pass is the line item to measure before you commit. Profile it on 50 trajectories at your real sequence length before scaling up.

Pragmatic Checklist for Monday Morning

  1. Confirm you can read attention. Load your policy with attn_implementation="eager", attach one hook, verify output[1] is not None. Pin transformers.
  2. Measure the aliasing first. Take pairs of correct-answer trajectories with near-identical text from your existing pipeline and compare their attention features. If they barely differ, APRM has little to work with on your task.
  3. Fix your step segmentation on token ids, not re-tokenized text.
  4. Strip attention sinks before computing any mass feature.
  5. Generate step labels via Monte Carlo rollouts (Math-Shepherd style) on a few thousand steps. Hold out 20 percent.
  6. Train the head and check it beats a text-only PRM baseline on held-out step labels before putting it in the RL loop. If it does not, stop here.
  7. Keep outcome reward dominant. Start with lam around 0.1 to 0.3 and use min aggregation.
  8. Log feature drift every N updates. Alert when mean prompt mass or entropy leaves the training distribution.
  9. Retrain the head on fresh rollouts on a fixed schedule to stay ahead of policy drift.
  10. Evaluate out of distribution. In-distribution reward going up proves nothing on its own.

References & Further Reading

  • Lightman et al., Let's Verify Step by Step (PRM800K, process supervision). arXiv:2305.20050
  • Uesato et al., Solving Math Word Problems with Process- and Outcome-Based Feedback. arXiv:2211.14275
  • Wang et al., Math-Shepherd: Verify and Reinforce LLMs Step-by-step without Human Annotations. arXiv:2312.08935
  • Shao et al., DeepSeekMath (introduces GRPO). arXiv:2402.03300
  • DeepSeek-AI, DeepSeek-R1. arXiv:2501.12948
  • Schulman et al., Proximal Policy Optimization Algorithms. arXiv:1707.06347
  • Turpin et al., Language Models Don't Always Say What They Think. arXiv:2305.04388
  • Jain and Wallace, Attention is not Explanation. arXiv:1902.10186
  • Wiegreffe and Pinter, Attention is not not Explanation. arXiv:1908.04626
  • Abnar and Zuidema, Quantifying Attention Flow in Transformers. arXiv:2005.00928
  • Xiao et al., Efficient Streaming Language Models with Attention Sinks. arXiv:2309.17453
  • Dao et al., FlashAttention. arXiv:2205.14135
  • Skalse et al., Defining and Characterizing Reward Hacking. arXiv:2209.13460
  • Hugging Face TRL (GRPO trainer and reward modeling): https://github.com/huggingface/trl
  • The source paper: From Rewarding What Models Say to How They Think: Attention Process Reward Model for LLM Reinforcement Learning. Read the full text for its exact architecture and results. This article interprets the abstract only.
📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.