Three Fixes for Unstable RL Training of Large Language Models
This article explains why reinforcement learning post-training for large language models often becomes less stable as more compute is invested, and presents three correction mechanisms: an unbiased KL estimate with importance weighting to control gradient spikes, sequence-level off-policy masking to filter noisy samples, and consistency constraints that align the training and inference environments. It includes pseudocode, practical tuning guidance, and deployment recommendations for keeping large-scale post-training stable.
1. Background: Why Post-Training Breaks Under Heavier Investment
During the reinforcement learning post-training stage of large language models, engineering teams commonly run into a counterintuitive pattern: the more compute they put into training, the worse the model performs. The symptoms include a sudden collapse in the reward curve, degraded and repetitive output, sharp spikes in the gradient norm, and eventually a forced rollback to an earlier checkpoint. The industry usually attributes these failures to two coupled factors: numerical instability and policy shift (the distribution being optimized during training is no longer the same distribution the sampled data came from).
The standard approach is to add a KL regularization term relative to a reference policy and apply a correction based on a set of importance sampling ratios. But as training scales up, a single batch of data gets reused across many steps, and the inference engine and the training engine differ in implementation, this naive scheme exposes three structural weaknesses. The sections below break them down one by one and outline the corresponding fixes.
2. Fix 1: Unbiased KL Estimation to Suppress Gradient Explosions in Low-Probability Regions
2.1 Failure Mechanism
Common KL estimators (such as the low-variance K3 form) are unbiased in expectation, but their per-sample gradients are not controlled. When the current policy assigns a token a probability far lower than the reference policy does, the absolute value of the log ratio grows sharply. Combined with the importance weight, the gradient at a single point can be amplified by several orders of magnitude. One extreme sample is enough to contaminate the gradient of the entire batch, skew the optimizer state (first- and second-order momentum), and make the next several dozen steps hard to recover.
2.2 Correction Approach
Introduce an importance ratio with the sampling policy in the denominator and use it to reweight the KL term. This keeps the estimate unbiased under the sampling distribution while decoupling the weight from the log ratio. A sketch of the implementation:
# Pseudocode: KL regularization with importance correctionlog_r_ref = ref_logprob - cur_logprob # log(pi_ref / pi_theta)ratio_is = (cur_logprob - old_logprob).exp() # pi_theta / pi_oldkl_k3 = ratio_is * (log_r_ref.exp() - log_r_ref - 1.0)kl = kl_k3.clamp(max=KL_CLAMP) # upper-bound clamp as a spike safeguard
The key point is that pi_old is the policy that produced this batch of rollout data, while pi_theta is the policy currently being updated by gradients. Keeping the two separate is what makes the correction mathematically valid. On the engineering side, you also need a probability floor clamp and float32 accumulation for log probabilities to avoid underflow in half precision.
3. Fix 2: Off-Policy Sequence Masking to Filter Out Invalid Learning Signals
3.1 The Core Problem
A batch of sampled data is reused across multiple training steps. As updates proceed, the divergence between the current policy and the sampling policy (measurable via the geometric mean of sequence-level importance weights) keeps rising. Samples that have diverged too far carry extremely high weight variance, so the gradients they provide are essentially noise. Letting them participate in the update with equal weight amounts to letting noise override the real signal.
3.2 Masking Strategy
Compute divergence per sequence and zero out any sample that falls outside a reasonable range so it contributes to neither the loss nor the gradient statistics:
seq_log_ratio = (cur_logprob - old_logprob).sum(dim=-1)keep = (seq_log_ratio.exp() > LO) & (seq_log_ratio.exp() < HI)loss = (per_token_loss * keep.unsqueeze(-1)).sum() / keep.sum().clamp(min=1)
Compared with per-token clipping, sequence-level filtering better matches the semantics that “a response is either trustworthy or it is not,” and it noticeably reduces how much invalid samples distort the optimization direction. In practice, monitor the keep rate. If it stays below 70% for a long stretch, the batch is being reused for too many steps, so shorten the reuse window or increase sampling temperature diversity.
4. Fix 3: Consistency Constraints to Eliminate Objective Drift Between Training and Inference
In large-scale training, sampling is usually handled by a high-throughput inference engine while gradient computation is handled by the training engine. The two differ subtly in operator implementations, batch assembly, and numerical precision, so the probability of the same token is not strictly equal and the importance ratio picks up a systematic bias.
- Keep routing consistent (for sparse expert architectures): For expert layers under sharded parallelism, fix the expert selection on the training side and reuse the routing decisions made at sampling time, avoiding probability jumps caused by switching experts.
- Keep sampling masks consistent (for truncated sampling): The truncation thresholds and random-seed masks used during sampling must be recorded and replayed on the training side, so the probability of a truncated token is strictly zero rather than approximately zero.
Both constraints share the same goal: align “the distribution seen at inference time” and “the distribution computed at training time” under a single implementation semantics, cutting objective drift off at the source.
5. Overall Benefits and Deployment Recommendations
The three fixes address the numerical, sample, and environment layers respectively. Stacked together, they let post-training compute scale to a higher fraction of pre-training cost without destabilizing, which is key infrastructure for a leap in reasoning capability. For deployment:
- Enable them in stages: bring in the unbiased KL and sequence masking first, then add the consistency constraints, so rollback causes are easier to isolate.
- Build an observability dashboard tracking gradient norm percentiles, mean KL estimate, sequence keep rate, and routing consistency rate.
- Use a container platform to elastically schedule the sampling and training clusters, use a logging service with monitoring alerts to capture anomalous samples, and archive checkpoints in object storage.
- Keep reproducible records of randomness and hyperparameters; any change to a masking threshold should be backed by a controlled experiment.
In short, the core trade-off in large-scale post-training is this: in the right direction, numerical stability takes priority over theoretical precision.
