In large-scale LLM reinforcement learning, the model that generates rollouts (the sampler $\mu_\theta$) and the model that computes gradients (the trainer $\pi_\theta$) run on separate software stacks. Even at identical weights $\theta$, practical inference optimizations such as low-precision quantization, cause the two models to assign different probabilities to the exact same tokens. Most existing recipes handle this training–inference mismatch (TIM) in one of two ways: either constrain the inference engine to match the bf16 trainer (for instance via batch-invariant kernelsHorace He and Thinking Machines Lab, Defeating Nondeterminism in LLM Inference (2025).), sacrificing training efficiency, or patch the probability gap in the loss via truncated importance sampling or Score Centering.Martin Marek and Max Ryabinin, Score Centering Stabilizes Off-policy Reinforcement Learning, arXiv:2609.20807 (2026).
In this post, we first diagnose what output-level fixes miss, and then show how to address the underlying problem directly.
TL;DR
The mismatch isn’t only in the loss; it’s in the gradient.
Reweighting or centering probabilities patches the loss at the final layer, while backpropagation still relies on the trainer’s mismatched activations. The gradient update may push the sampler in the wrong direction. Aligning internal computations recovers on-policy learning.
The closer the trainer’s activations are to the sampler’s, the more faithful a differentiable surrogate it becomes. We close the gap in two complementary ways: matching the sampler’s numerics withquantization-aware training (QAT), and replaying the sampler’s hidden activations straight-through into the trainer with Residual Resets Concurrent independent work by Aghajohari et al., Sampler Replay: Train The Sampler Not The Trainer in Reinforcement Learning with Verifiable Rewards (arXiv:2611.41862, Nov 2026), arrives at the same sampler-centric framing, derives the logit-replay equivalence of Score Centering, and proposes replaying activations. Below, we examine how matching layer numerics (QAT) and Residual Resets differ and contribute to aligning gradients.. Matching precision means one reset is enough.
On Qwen3-8B-Base with an INT4 KV-cache SGLang sampler, a bf16 KV trainer needs ~12 residual resets (48 GiB/step) to close the trainer-inference mismatch. Emulating the INT4 KV cache in the trainer cuts this to a single reset (4 GiB/step), achieving comparable gradient cosine similarity, training reward, and eval performance.
1. TIM Is a Surrogate-Gradient Problem #
In standard RL pipelines for LLMs, training-inference mismatch is treated as an “off-policy” problem, because any discrepancy between the sampler’s rollout probabilities $\mu_\theta$ and the trainer’s $\pi_\theta$ looks the same at the loss level. In practice, though, $\pi_\theta$ and $\mu_\theta$ can disagree for two fundamentally different reasons:
- Weight staleness ($\theta_{\text{old}} \neq \theta$): in asynchronous RL, rollouts can be generated by an older checkpoint $\theta_{\text{old}}$ while gradients are computed at updated weights $\theta$. This is genuine off-policyness: the data came from a past distribution we have already moved away from.
- Execution mismatch ($\pi_\theta \neq \mu_\theta$ at identical $\theta$): even in synchronous RL where sampler and trainer share the exact same weights $\theta$, system level optimizations such as quantization, cause TIM, making $\mu_\theta$ and $\pi_\theta$ compute different forward passes. Crucially, rollouts $y \sim \mu_\theta$ here arealready on-policy for $\mu_\theta$, which is the exact model we evaluate, deploy, and use to sample the next batch of rollouts.
Execution mismatch looks “off-policy” only if we treat the bf16 trainer $\pi_\theta$ as the target policy and view the quantized sampler $\mu_\theta$ as a noisy approximation to it. Flipping that relationship clarifies what RL actually optimizes: the sampler $\mu_\theta$ is the true policy of interest, and the trainer $\pi_\theta$ is simply a differentiable surrogate used to estimate $\mu_\theta$’s gradient.
Viewed through this lens, adapting the inference engine so its numerics match a higher precision trainer works backwards. Although, because we cannot differentiate through a quantized inference engine directly, we still need the trainer to compute gradients on the sampler’s behalf; rather than forcing the sampler to match the trainer, we should keep the sampler fast and adapt the trainer so its gradients faithfully track $\mu_\theta$’s. To see what that requires, we first examine why existing loss-level corrections fall short, and how generalizing such approach and matching numerics can help.
2. Score Centering Swaps Only the Last Activations #
Following the Score Centering2 paper, at decoding step $t$ the sampler draws $y_t \sim \mu_\theta$ and receives a scalar advantage $A$. The trainer’s score for token $v \in V$ is $s_v = \nabla_\theta \log \pi_\theta(v)$, and its average under the sampler is $\bar{s} = \sum_{v} \mu_\theta(v), s_v$.
Under training–inference mismatch, $\bar{s} \neq 0$, so the standard policy gradient loss includes a reward-independent drift $\mathbb{E}{\mu\theta}[A],\bar{s}$ term. Score Centering (SC) uses the centered score $s_{y_t} - \bar{s}$ instead, which cancels the drift and keeps only the signal:
SC only changes the gradient at the logits. Writing $\log \pi_\theta(v) = z^\pi_{t,v} - \log \sum_w e^{z^\pi_{t,w}}$, the log-normalizer’s gradient cancels in $s_{y_t} - \bar{s}$, because it is the same for every $v$ and $\sum_v \mu_\theta(v) = 1$:
This is the exact logit gradient an ordinary policy gradient on $\mu_\theta$ would produce. The only difference is that this gradient still backpropagates through the trainer.
Equivalently, SC is a straight-through swap to the sampler’s logits. Let $z^\mu_{t,v}$ be the sampler’s logit and replace the trainer’s with
where the stop-gradient $\mathrm{sg}(\cdot)$ is the identity in the forward pass and has zero gradient in the backward pass. The forward pass then outputs the sampler’s distribution ($\tilde{z}{t,v} = z^\mu{t,v}$), while the backward pass is unchanged ($\nabla_\theta \tilde{z}{t,v} = \nabla\theta z^\pi_{t,v}$).
SC fixes the output distribution, but the trainer’s logit Jacobian $J^\pi_t = \partial z^\pi_t / \partial \theta$ (each layer’s derivative $\nabla_\theta z^\pi_{t,v}$ across all tokens $v$) is still evaluated on the trainer’s drifted activations. Compared to an ideal differentiable sampler with Jacobian $J^\mu_t = \partial z^\mu_t / \partial \theta$, the only error left is the Jacobian mismatch $J^\pi_t - J^\mu_t$ between their backward passes.
Takeaway Score Centering swaps only the final logits
Subtracting the expected trainer score is mathematically identical to a straight-through replacement of the output logits. It eliminates distribution drift at the head, but still evaluates every upstream layer’s Jacobian on the trainer’s drifted hidden states.
3. Optimizing the Sampler #
Why does the trainer’s Jacobian $J_t^\pi$ diverge from the sampler’s $J_t^\mu$? By the chain rule across an $L$-layer network, the logit Jacobian is a product of block-wise derivatives, each depending both on the numerical operations executed inside block $\ell$ and on the input hidden state $h_{\ell-1}$ at which that block is linearized.
Our real objective is to optimize the sampler: it is both the model we serve and the one generating the next batch of rollouts during RL. Because gradients are computed on the trainer, this must act as a faithful differentiable surrogate with matching Jacobians, $J_t^\pi \approx J_t^\mu$. In the strictly on-policy regime, both models perform the exact same computations rather than merely sharing weights, so any gain on the trainer translates directly to the sampler. Once they diverge, that guarantee weakens, and the trainer’s gradient becomes a biased estimate of the true improvement direction for the sampler.
Achieving this requires two forms of alignment:
- Numerical alignment. The trainer must run under the same numerical constraints as the sampler (e.g., matching KV-cache quantization) so both execute the same operations at the same precision.
- Hidden activation alignment. The trainer’s forward activations must match the sampler’s so backpropagation evaluates the Jacobian at the exact states the sampler visited.
We can either (1) align the trainer to the sampler’s numerical precision and run identical kernels, or (2) rely on residual resets to inject the sampler’s hidden activations directly into the trainer.
3.1 Numerical Alignment
Running identical kernels on the trainer and the sampler sounds straightforward on paper, but the two workloads sit in opposite hardware regimes:
- Training is compute-bound; decoding is memory-bandwidth-bound. A trainer processes complete rollout sequences in parallel, packing large dense matrix multiplications to saturate GPU Tensor Core FLOP/s. Autoregressive rollout generation produces one token per sequence at a time, repeatedly streaming model weights and KV-cache pages from HBM; its throughput is governed almost entirely by memory bandwidth and footprint.
- Dynamic batching breaks batch invariance. High-throughput inference engines such as vLLMWoosuk Kwon et al.,Efficient Memory Management for Large Language Model Serving with PagedAttention , SOSP 2023. and SGLangLianmin Zheng et al.,SGLang: Efficient Execution of Structured Language Model Programs , arXiv:2312.07104 (2023);github.com/sgl-project/sglang . rely on continuous batching, paged KV caches, and Split-KV attention kernels whose reduction order changes dynamically with batch composition and sequence length.1 Enforcing batch-invariant reductions to match a dense training pass disables optimizations like Split-KV right at the rollout stage, the primary wall-clock bottleneck of an RL update.
Because training and decoding sit in opposite hardware regimes, forcing bitwise kernel parity across both enginesMicrosoft AI, RL Infrastructure at Microsoft AI (Rocket) (2026). carries a steep throughput penalty—whereas emulating the sampler’s intentional quantization format (such as 4-bit weights or KV caches) on the trainer via Quantization-Aware Training (QAT) aligns the largest source of per-layer error without touching fast inference kernels.
3.2 Residual Resets: Replaying Hidden Activations
To stop hidden-state drift from compounding across depth, we can push Score Centering’s straight-through swap into the internals of the network—an activation-replay mechanism we refer to as Residual Resets (explored concurrently as Sampler Replay by Aghajohari et al.3). During rollout generation, the sampler records its residual stream $h_\ell^\mu$ after selected transformer blocks $\ell$. During the training forward pass, the trainer overwrites its own residual state $h_\ell^\pi$ with $h_\ell^\mu$ while passing gradients straight through unchanged:
Mechanically, block $\ell + 1$ now executes its forward pass and evaluates its backward Jacobian at the exact residual state $h_\ell^\mu$ visited by the sampler. At the same time, gradients still flow end-to-end through all upstream blocks via the identity path of $\operatorname{sg}(\cdot)$. Residual Resets broaden Score Centering, which appears as a special case of resetting only the final logits, and generalize discrete MoE Rollout Routing Replay (R3)Wenhan Ma et al., Stabilizing MoE Reinforcement Learning by Aligning Training and Inference Routers, arXiv:2510.11370 (2025). to continuous hidden states at arbitrary depths.
4. Controlled Setup #
On a production quantized inference engine, the sampler $\mu_\theta$ is non-differentiable: we can neither measure $\nabla_\theta \mathcal{L}_\mu$ directly to check how misaligned a trainer update is, nor run an exact on-policy baseline for comparison.
To make the true sampler gradient observable, we begin with a controlled toy setting: a 4-layer Transformer (width 32) trained with GRPO on 5-digit addition, where the sampler injects fixed multiplicative noise into its activations as $\tilde{x} = x + s,U\cdot\operatorname{sg}(x)$.
Crucially, the sampler and trainer here execute identical linear and attention operators with identical weights; they differ only in the activation points at which those operators are evaluated. That symmetry enables the two ways to recover the exact sampler gradient: run the trainer with the same activation noise (matched computation, $\hat{\mu} = \hat{\pi}$), or replay the sampler’s residual stream into the clean trainer (Residual Resets). Both evaluate identical block Jacobians at identical states—so in this setting, numerical alignment and activation alignment are an exact “either/or.”
- True on-policy updates follow the same weight-space trajectory even under noise. In the 3D plot, noiseless on-policy training ($\mu = \pi$) and matched-noise on-policy training ($\hat{\mu} = \hat{\pi}$) travel along similar path in the weight space (measured along the principal directions $(\theta_1, \theta_2)$) and reach the same ceiling sampler reward (~0.99). At a finer grain, matched-noise updates still adapt to the sampler’s noisy execution: evaluating those learned weightswithout noise on the clean trainer yields only 0.58 reward (first figure, top right), yet, their optimization path stays tightly aligned with the ideal baseline.
- Plain PG and Score Centering stall as gradients decouple. Without $\hat{\mu}$-$\pi$ internal alignment, both plain policy gradient and Score Centering drive away from the on-policy path, as their gradient cosine decays over training. Even though Score Centering removes output drift at step 0 (lifting initial cosine from 0.70 to 0.88), the upstream Jacobian mismatch still steers parameters into a suboptimal basin which doesn’t point to the direction where $\hat{\mu}$ attains higher reward.
- Residual Resets match the on-policy path without noisy training. Adding Residual Resets (SC + reset) keeps gradient cosine locked close to 1 throughout all 4,000 steps. In the 3D plot, instead of drifting onto the $\theta_2 > 0$ branch like the other mismatched runs, SC + reset tracks the two on-policy baselines in weight space and reaches the same ceiling reward (0.99).
- Auxiliary KL or MSE penalties fail to align the Jacobian. Pulling the trainer toward the sampler via a logit KL penalty or a residual-stream MSE penalty (Appendix A1) leaves upstream layers differentiated at mismatched states: moderate penalties close roughly half the reward gap, and strong penalties shrink KL only by collapsing the policy.
Takeaway Gradient alignment governs on-policy recovery, not low output KL.
Even after Score Centering or KL regularization shrinks output divergence, Jacobian mismatch steers updates away from the sampler’s optimum. Aligning internal states, either by matching the forward perturbation or by applying Residual Resets, restores near-unit gradient cosine and full on-policy reward.
5. Does it hold on an LLM? #
The toy experiment modeled numerical mismatch as additive activation perturbations while keeping layer weights identical. Next, we test real low-precision quantization on a pretrained language model, training Qwen2.5-0.5B-Instruct on GSM8KKarl Cobbe et al., Training Verifiers to Solve Math Word Problems, arXiv:2110.14168 (2021). with GRPO while quantizing the sampler’s linear weights to NVFP4.
To isolate quantization mismatch from cross-engine kernel noise or weight staleness, both sampler and trainer share weights $\theta$ inside a single PyTorch process. Weight precision (NVFP4 vs. bf16) is therefore the only discrepancy between the two passes: running NVFP4 with straight-through rounding on the trainer is genuinely on-policy and gives us the exact reference gradient of the quantized model.
We compare:
- bf16 / bf16 ($\mu = \pi$): Unquantized on-policy reference.
- NVFP4 / NVFP4 ($\hat{\mu} = \hat{\pi}$): Quantized on-policy reference (QAT with straight-through rounding on the trainer).
- NVFP4 / bf16 ($\hat{\mu} \neq \pi$): Mismatched baseline trained with plain policy gradient (PG), Score Centering (SC), Residual Resets (at all layers), and SC + Residual Resets.
Experimental details #
700 steps of synchronous GRPO without advantage standard-deviation normalization or KL regularization; batch size 64 prompts $\times$ group size 8 rollouts (up to 512 tokens at temperature 1.0); AdamW with learning rate $10^{-6}$ and gradient clipping at 1.0; 4 seeds per configuration. Residual Resets are applied after all 24 transformer blocks. Full details in Appendix A2.
The GSM8K runs confirm the toy findings while exposing where operator mismatch separates QAT from Residual Resets:
- Plain policy gradient collapses across every seed. Updating a bf16 trainer on NVFP4 rollouts collapses gradient cosine as uncorrected hidden-state drift nearly doubles, crashing test accuracy from 29.4% to 4.3%.
- Score Centering prevents collapse, but bias accumulates. Swapping the final logits lifts initial gradient cosine to 0.81 and stabilizes training, yet as upstream activation mismatch grows (18% → 22%), gradient cosine erodes to 0.49, making this bias cap final test accuracy at 10% below the other unbiased methods.
- Matched computation (NVFP4 / NVFP4) defines the quantized on-policy ceiling. Quantizing the trainer’s forward pass matches the sampler’s gradient identically (cosine = 1.00) and reaches 54.9% test accuracy. In a multi-engine production stack, however, matching weight formats alone is a best case rather than a guarantee, since kernel and batching differences remain.
- Residual Resets match QAT without quantizing the trainer. Unlike in the toy setup, Residual Resets donot reach a cosine of 1.00 here: even though every block starts from the sampler’s exact hidden state $h_\ell^\mu$, each block still differentiates through bf16 rather than NVFP4 weights. Empirically, holding gradient cosine steady at 0.90–0.94 is enough, reaching 56.2% with resets alone and 55.3% with SC + reset, matching the exact on-policy NVFP4 / NVFP4 run within seed variance.
Takeaway Emulate quantization on the trainer when feasible, reset residuals when not.
QAT is the simplest exact fix. When it is not feasible, Residual Resets keep gradient cosine high on a bf16 trainer and recover the exact same GSM8K accuracy.
6. Can we scale up? #
In Sections 4 and 5, sampler and trainer shared a single PyTorch process so we could isolate precision mismatch cleanly. Production RL pipelines instead split rollout generation and gradient computation across separate engines—in our setup, SGLang5 for inference and MegatronMohammad Shoeybi et al., Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism, arXiv:1909.08053 (2019); github.com/NVIDIA/Megatron-LM. for training—whose kernels cannot be matched bit-for-bit without sacrificing throughput. We test whether our findings hold in a more realistic regime: we train Qwen3-8B-BaseAn Yang et al., Qwen3 Technical Report, arXiv:2505.09388 (2025). on Big-Math,Alon Albalak et al., Big-Math: A Large-Scale, High-Quality Math Dataset for Reinforcement Learning in Language Models, arXiv:2502.17387 (2025). quantizing the sampler’s KV cache to INT4 while keeping weights and activations in bf16. All runs use Score Centering, isolating upstream Jacobian mismatch from output-level drift. Across five configurations, we compare matching the trainer’s KV precision to the sampler’s (QAT), replaying activations via Residual Resets, and combining both.
Configurations and experimental details #
With Score Centering enabled in every run, we compare five sampler / trainer configurations:
- bf16 KV / bf16 KV: High-precision reference without KV-cache quantization (differing only in SGLang vs. Megatron kernels).
- INT4 KV / bf16 KV: Standard Score Centering under KV-cache quantization mismatch.
- INT4 KV / INT4 KV: Trainer-side emulated INT4 KV quantization (group size 64, straight-through rounding) to align per-layer numerics.
- INT4 KV / bf16 KV + residual resets: All-layer Residual Resets (layers 0–34) on an unquantized bf16 trainer.
- INT4 KV / INT4 KV + residual resets: Combined trainer-side INT4 KV quantization and all-layer Residual Resets.
All runs train for 400 steps of synchronous GRPO without std normalization or KL regularization, using batch size 64 $\times$ group size 8, max sequence length 2048 tokens, and AdamW with learning rate $3 \times 10^{-6}$ across 5 seeds per configuration. Full details in Appendix A3.
Do Residual Resets Help at Scale? Does QAT improve on that?
| Sampler / Trainer | Step-0 Grad. Cosine | Train Reward | MATH-500 |
|---|---|---|---|
| bf16 KV / bf16 KV (high precision reference) | 0.997 ± 0.002 | 0.785 ± 0.015 | 0.816 ± 0.019 |
| INT4 KV / bf16 KV | 0.664 ± 0.248 | 0.653 ± 0.019 | 0.668 ± 0.008 |
| INT4 KV / INT4 KV | 0.783 ± 0.189 | 0.720 ± 0.011 | 0.731 ± 0.005 |
| INT4 KV / bf16 KV + residual reset | 0.912 ± 0.064 | 0.740 ± 0.007 | 0.750 ± 0.019 |
| INT4 KV / INT4 KV + residual reset | 1.000 ± 0.000 | 0.741 ± 0.007 | 0.745 ± 0.012 |
Effect of KV-cache quantization and Residual Resets on Qwen3-8B-Base (train reward and MATH-500 at temperature 1.0; mean over 5 seeds, 95% interval). Step-0 gradient cosine is measured against a reference pass with all-layer resets and straight-through INT4 KV rounding (Appendix A3).
- Quantization-aware training recovers most of the gap (but not all of it). Emulating INT4 KV rounding in the trainer raises the step-0 gradient cosine from 0.664 to 0.783, and adds +6.7 points of train reward and +6.3 points of MATH-500The 500-problem test subset introduced by Hunter Lightman et al.,Let’s Verify Step by Step , arXiv:2305.20050 (2023), of the MATH dataset: Dan Hendrycks et al.,Measuring Mathematical Problem Solving With the MATH Dataset , arXiv:2103.03874 (2021). over plain Score Centering (bf16 KV trainer). Making the trainer’s computations resemble the sampler’s is clearly beneficial on its own.
- Residual Resets close the remaining gap. Replaying the sampler’s residual stream is the strongest driver of improvement, raising gradient cosine to 0.912 (bf16 KV trainer) and 1.000 (INT4 KV trainer) when applied after every layer. Resetting prevents small numerical differences from propagating between layers, regardless of layer precision.
- High alignment is enough. As on GSM8K, a cosine of 0.912 is enough to reach the quantized on-policy ceiling: with all-layer residual resets, the bf16 KV and INT4 KV trainers achieve identical train and eval rewards. The remaining gap to the bf16 KV / bf16 KV reference reflects the information loss of lower precision, not trainer misalignment (Appendix A3).
Since our results highlight that we don’t need perfect gradient alignment, can we reset fewer layers and avoid the 140 GiB per step that residual resets add?
Trading Numerical Alignment for Lower Data Overhead
Replay data grows with hidden dim × reset layers × tokens. For Qwen3-8B-Base each reset layer adds 8 KiB per token, so resetting all 35 layers moves 280 KiB per token (about 140 GiB per step) and leaves only 34% of SGLang’s KV pool in a naive implementation (Appendix A3).
If trainer-side INT4 KV emulation already keeps per-layer numerics close to the sampler, resetting every layer could be unnecessary. To test how far we can trade cheap numerical alignment for lower communication overhead, we experiment with a growing number of resets, starting from resetting only one layer, up to all layers.
Selected reset layers #
- 1 layer (8 KiB/tok, ~4 GiB/step): 15 (see Appendix A3 for why L15 is chosen)
- 4 layers (32 KiB/tok, ~16 GiB/step): 9, 15, 27, 34
- 12 layers (96 KiB/tok, ~48 GiB/step): 2, 5, 9, 12, 15, 18, 21, 24, 27, 30, 32, 34
- 35 layers (280 KiB/tok, ~140 GiB/step): 0–34
Note: Qwen3-8B-Base has 36 layers, but residual reset moves at most 35. Score Centering already corrects for the last layer in the loss, so it needs no replay in the forward pass.
- A bf16 KV trainer needs multiple resets, which doesn’t scale. Without INT4 KV emulation, the trainer’s error builds up layer by layer, so every extra reset helps. Step-0 gradient cosine, train reward and MATH-500 keep improving up to about 12 resets, which add +0.225 to the cosine and +0.083 to MATH-500. In contrast, a single reset recovers roughly half the gap: +0.081 cosine and +0.034 MATH-500. With 12 resets, the transfer is already 48 GiB per step in our setup, and it grows with model size and sequence length.
- Trainer-side quantization makes one reset almost enough. Once the trainer emulates INT4 KV rounding, the mismatch between trainer and sampler shrinks, and far fewer resets are needed. A single reset increases the step-0 gradient cosine from 0.783 to 0.887, the train reward from 0.720 to 0.734, and MATH-500 from 0.731 to 0.742. More resets keep raising the cosine but barely move the reward or MATH-500. With trainer-side quantization, one reset is enough: 4 GiB per step, 12× less than the optimal for bf16 KV trainer.
Takeaways Matching the sampler’s precision reduces how many resets you need.
Trainer-side quantization turns 12 resets into 1. Aligning the trainer to the sampler’s numerical precision significantly improves gradient alignment on its own, leaving much less drift for Residual Resets to correct.
7. Closing Thoughts #
This post explores a different way of thinking about reinforcement learning post-training: instead of forcing a fast sampler to mimic the trainer, we should adapt the trainer to faithfully approximate the sampler. Our broader goal is to highlight the core mechanism behind training–inference mismatch: computational differences between the two stacks introduce a systematic bias in the trainer’s gradient that compounds over training, leading to suboptimal convergence or collapse. Because final-layer metrics like loss and output KL can hide this bias, tracking internal signals—activation drift and gradient alignment—is essential for seeing where the two models actually decouple.
Quantization-aware training and Residual Resets offer practical first steps in this direction, showing that cheap trainer-side quantization paired with even a single targeted reset recovers nearly the full on-policy gain at minimal transfer cost. Still, both warrant deeper study, alongside automating layer selection, reducing transfer overhead, and designing alternative ways to estimate faithful gradients for fast samplers. Moreover, our experiments focused strictly on execution mismatch at identical weights ($\theta_{\text{old}} = \theta$); extending internal alignment to asynchronous RL pipelines with weight staleness ($\theta_{\text{old}} \neq \theta$) remains open for future work.
Concurrent work by Aghajohari et al.,3 independently arrives at a similar sampler-centric framing of TIM, derives the logit-replay view of Score Centering, and studies full activation and router replay. Our work complements theirs by examining how trainer-side quantization interacts with resets and how these are not necessary across the whole network.
Citation
Please cite this work as:
Garcia Giraldo, J., Santelmo, M., Leleytner, G., & Tazza, O. A. “Optimizing the Sampler, Not the Trainer.” Tufa Labs Research, December 4, 2026. https://tufalabs.ai/research/optimizing-the-sampler/
@article{garciagiraldo2026optimizing,
title = {Optimizing the Sampler, Not the Trainer},
author = {Garcia Giraldo, Juan and Santelmo, Matteo and Leleytner, Gregory and Tazza, Oscar Alessandro},
journal = {Tufa Labs Research},
year = {2026},
month = {dec},
day = {4},
url = {https://tufalabs.ai/research/optimizing-the-sampler/}
}
Appendix #
A1. Matching Computation: additional toy experiments
How much noise before the gradient breaks
Section 4 uses noise $s = 0.1$. Here we sweep it, 10 seeds per value.
- Up to $s = 0.05$ the mismatch is self-correcting: the cosine recovers during training and every method reaches the no-noise reward.
- From $s = 0.1$ the cosine degrades during training, and PG and SC lose reward together.
- Resets hold at every noise level.
Pulling the trainer towards the sampler is not enough
We keep score centering and add a penalty that pulls the trainer towards the sampler: a KL term on the output distributions, or an MSE term on the residual stream. Like score centering, the KL term only acts at the last layer; neither penalty changes the point at which the earlier layers’ Jacobians are evaluated. With $\mathcal{L}_{SC}$ the score-centering objective of Section 2 and $\lambda$ the penalty coefficient, we minimize
$$ \mathcal{L}{SC+KL} = -\mathcal{L}{SC} + \lambda \cdot \frac{1}{T}\sum_{t=1}^{T} \mathrm{KL}!\left(\operatorname{sg}(\mu_\theta(\cdot \mid x, y_{<t})) ,\Vert, \pi_\theta(\cdot \mid x, y_{<t})\right) $$
$$ \mathcal{L}{SC+MSE} = -\mathcal{L}{SC} + \lambda \cdot \frac{1}{L,P,d}\sum_{\ell=1}^{L}\sum_{p=1}^{P} \left\Vert h_{\ell,p}^{\pi} - \operatorname{sg}!\left(h_{\ell,p}^{\mu}\right) \right\Vert_2^2 $$ where $h_{\ell,p}$ is the residual stream after block $\ell$ at position $p$ (prompt and answer tokens), of width $d$. Both penalties are computed on the rollouts of the batch, and the stop-gradient $\operatorname{sg}$ makes the sampler a fixed target: only the trainer is pulled. Noise 0.1, 10 seeds.
- The best penalty closes about half of the gap to resets, without improving the cosine.
- A penalty strong enough to close the KL does so by destroying the policy.
- The matched and reset runs keep a higher KL than the collapsed ones: what they share is a cosine near 1, not a low KL.
A2. Qwen2.5-0.5B with NVFP4 weights
Setup
We train Qwen2.5-0.5B-Instruct (24 blocks, hidden size 896) on the GSM8K train set (7,473 problems), with reward 1 if the last boxed number in the response equals the answer. Each step samples 8 responses for each of 64 prompts at temperature 1, up to 512 new tokens. The loss for a response $y$ of $T$ tokens to prompt $x$, in a group of $G = 8$ responses with rewards $r_1, \dots, r_G$, is the advantage times the token-mean log-probability:
$$ \mathcal{L} = -,A \cdot \frac{1}{T}\sum_{t=1}^{T} \log \pi_\theta(y_t \mid x, y_{<t}), \qquad A = r - \frac{1}{G}\sum_{g=1}^{G} r_g $$ There are no importance weights, no KL term and no normalisation of the advantage by its standard deviation. We take one AdamW step per batch at learning rate $10^{-6}$, with gradient clipping at 1.0, on fp32 master weights under bf16 autocast. Each configuration runs for 700 steps with 4 seeds, and is evaluated every 20 steps on the full GSM8K test set (1,319 problems), sampled at temperature 0.7.
NVFP4 is emulated in PyTorch and applied to the weights of the Linear layers inside the blocks only: FP4 (E2M1) values, one FP8 (E4M3) scale per 16 consecutive inputs and one fp32 scale per matrix, rounded to nearest without calibration. Activations and the KV cache are not quantized. In the NVFP4 trainer the rounding is straight-through. Residual resets replace the output of every block straight-through by the sampler’s decode-time output, at every position except the last token of the response.
Where the mismatch is for Qwen2.5-0.5B
- NVFP4 rounding perturbs every block, so the mismatch builds up with depth and has no single entry point (unlike the INT4 KV-cache case of Section 6).
- Training amplifies it only in the upper half of the network: most with PG, least with resets.
A3. Can we scale up? additional experiments
Setup
We train Qwen3-8B-Base (36 layers, hidden size 4096) on Big-Math, with reward 1 if the last boxed number in the response equals the answer. Each step samples 8 responses for each of 64 prompts at temperature 1, up to 2048 new tokens. The loss computation follows that in Appendix A2.
There are no importance weights, no KL term and no normalisation of the advantage by its standard deviation. We take one AdamW step per batch at a constant learning rate of $3 \times 10^{-6}$, with gradient clipping at 1.0, on fp32 master weights under bf16 autocast. Each configuration runs for 400 steps with 5 seeds. MATH-500 runs with 4 samples per problem at temperature 1, up to 2048 tokens.
INT4 KV is emulated in SGLang: after RoPE, each token’s keys and values are rounded to a symmetric 4-bit integer grid (−7 to 7). There is one scale per 64 values of a head (its largest magnitude / 7), rounded to nearest without calibration. Weights and activations are not quantized. In the INT4 KV trainer the same rounding is straight-through. Residual resets replace the output of layers 0–34 straight-through by the sampler’s output, at every position except the last token. Because SGLang cannot backpropagate and integer rounding has zero derivative almost everywhere, we compute the reference sampler gradient in Megatron by injecting the sampler’s residual stream after every layer while differentiating through INT4 KV rounding straight-through.
Where the mismatch is for Qwen3-8B-Base
To locate the mismatch, we measure the relative hidden activations error between the trainer and the INT4 KV sampler, after each layer at step 0.
Because the sampler uses an INT4 KV cache, a bf16 KV trainer is already off by 0.27 after layer 0. Switching to an INT4 KV trainer closes most of this gap, though a small mismatch remains: tiny bf16 differences between the two engines occasionally push a borderline value across an INT4 rounding threshold.
The error spike at layer 16, driven by a minority of tokens (spaces after =, <, or == in math expressions). Such tokens occur only ~5 in 10,000 tokens with a bf16 KV trainer and ~2 in 10,000 with an INT4 KV trainer, yet they account for over 90% of the layer-16 activation mismatch. Resetting after layer 15 removes these disagreements, making L15 the single most effective reset.
The INT4 sampler is noisy on its own. Even when the sampler rescores its own answers in a new batch, the log-probs change:
| Log-prob diff (nats / token) | bf16 KV sampler | INT4 KV sampler |
|---|---|---|
| Same batch, rescored | 0 (exact) | 0 (exact) |
| Different batch vs. sampled (mean / mean abs.) | −0.0001 / 0.008 | −0.012 / 0.062 |
| Two recomputations vs. each other (mean / mean abs.) | −0.0001 / 0.008 | −0.013 / 0.115 |
| Trainer vs. sampled (mean abs.) | bf16 KV trainer: 0.0085 | bf16 KV trainer: 0.32 INT4 KV trainer: 0.13 INT4 KV trainer + Residual Resets: 0.023 |
The INT4 KV sampler disagrees with itself ~14× more than with bf16 KV, and recomputing lowers sampled tokens’ log-probabilities on average. Matching the trainer’s KV precision cuts the mismatch from 0.32 to 0.13 (close to the sampler’s own batch-to-batch noise 0.115). Only residual resets push the INT4 KV trainer’s mismatch lower, down to 0.023.
Training dynamics
Both per-token KL (sampler ‖ trainer) and average hidden activation mismatch (average across layers 9, 18, 27, and 34) stays largely flat:
- Without residual resets: INT4 KV / bf16 KV KL roughly doubles over training, implying that the mismatch still exists. Matching the KV precision (INT4 KV / INT4 KV) lowers KL but rounding differences still compound across layers.
- With residual resets: Reusing the sampler’s activations drops residual error to ~$10^{-3}$ bf16 KV or ~$5 \times 10^{-5}$ INT4 KV (matching the bf16 KV / bf16 KV KL baseline). Because errors can no longer build up across layers, only tiny differences remain at the LM head.
Matching INT4 KV better aligns computation, but irreducible rounding noise can’t be mitigated; residual resets stop this error accumulation, keeping KL and activation mismatches low.
How Much Data Do Residual Resets Move?
Each reset layer stores one residual-stream vector per token: hidden size 4096, in bf16 (2 bytes). That’s 4096 × 2 B = 8 KiB per token per layer, so a set of k reset layers costs $8 \times k$ KiB per token.
| Number of Resets | Layers | Transfer per token | Per step (~1k tok/sample) | (NVIDIA GB300) KV pool left |
|---|---|---|---|---|
| 0 | — | 0 | 0 | 100% |
| 1 | 15 | 8 KiB | 4 GiB | 95% |
| 4 | 9, 15, 27, 34 | 32 KiB | 16 GiB | 82% |
| 12 | 2,5,9,12,15,18,21,24,27,30,32,34 | 96 KiB | 48 GiB | 60% |
| 35 | 0–34 | 280 KiB | 140 GiB | 34% |
Storage and transfer costs scale linearly with $k$, making full-network resets expensive:
- Full resets ($k = 35$): Recording every layer produces ~140 GiB per step, too large to hold in GPU memory, requiring off to host RAM or local disk. At 280 KiB per token, this is nearly twice the size of the KV cache.
- Single reset ($k = 1$): Resetting only after layer 15 cuts the footprint by $35\times$, down to 8 KiB per token (4 GiB per step).
The KV pool left column reflects our simple implementation (storing residual states in the sampler’s KV-cache pool), which leaves less room for active sequences. Sampler Replay3 keeps GPU memory constant by asynchronously draining fixed-size GPU buffers to node-local RAM or disk and prefetching during training. Their released implementation requires the sampler and trainer to be colocated on a single node, with multi-node replay left to future work. We left such engineering optimizations aside to focus on the potential of selective resets with matched trainer and sampler quantization.