Three Key Fixes for Unstable RL Training in Large Language Models
This article examines why reinforcement learning post-training becomes unstable as scale increases and presents three practical fixes: an unbiased KL estimator to control gradient spikes, sequence-level stability filtering to discard unreliable samples, and consistency constraints that align training and inference objectives. It includes code examples, implementation guidance, and operational recommendations for keeping large-scale RL post-training stable.
1. Background: Why Post-Training Breaks When You Push Harder
During the reinforcement learning post-training stage of large language models, the industry commonly relies on Proximal Policy Optimization (PPO) and simplified variants such as Group Relative Policy Optimization (GRPO) as the core algorithms. The basic paradigm is straightforward: first sample a batch of responses using the current or a slightly older policy, then compute advantages from the reward signal, and finally update the parameters with a constrained objective function. In theory, this pipeline can push a model’s reasoning and alignment quality up a notch without damaging its language capabilities.
But once training scales up and the share of post-training compute relative to pretraining cost increases, two problems tend to surface at the same time.
The first is numerical instability. The objective function usually includes a KL regularization term that keeps the current policy from drifting too far from the reference policy. Common KL estimators expand over the log ratio, so when the current policy assigns a very small probability to a given token, the reciprocal of that ratio blows up quickly. Gradient magnitude then spirals out of control, showing up as loss spikes, sudden jumps in parameter norm, or outright divergence.
The second is growing policy drift (a deeper off-policy gap). Rollouts come from the old policy while updates apply to the current policy, and the two diverge further after multiple rounds of minibatch updates. On top of that, the inference engine and the training engine are not fully identical in operator implementations, numerical precision, or how batches are assembled, so the same text can produce systematically different probabilities on each side. Left unaddressed, the objective being optimized is no longer the objective you set out to optimize.
2. Fix 1: Unbiased KL Estimation to Suppress Gradient Explosions
The standard approach adds KL as a scalar penalty directly into the loss. The catch is that common estimators are a mathematically “biased but low-variance” compromise: their gradient form contains a log term over the ratio of reference-policy to current-policy probabilities, and the smaller the probability, the larger the gradient.
A more robust idea is to apply a correction using an importance sampling ratio, writing the sampling policy explicitly into the estimator:
KL ≈ (π_old / π_θ) * ( π_ref/π_θ - log(π_ref/π_θ) - 1 )
The roles of the three policies must be kept distinct:
- π_old: the behavior policy that produces the rollout data, a snapshot of the parameters at sampling time;
- π_θ: the current policy being updated by gradient descent;
- π_ref: the reference policy, typically a frozen initial alignment model that only serves as an anchor for “don’t drift too far.”
In practice, two implementation patterns are more common. One is to clip the ratio, bounding the correction term within a limited range. The other is to cap the KL contribution at the token level, which is equivalent to fitting the gradient with a fuse. Example code:
ratio = torch.exp(logp_old - logp_cur) # importance ratiokl_term = (logp_ref - logp_cur).exp() - (logp_ref - logp_cur) - 1kl_term = (ratio.detach() * kl_term).clamp(max=KL_CAP)loss = policy_loss + beta * kl_term.mean()
The point is that the goal here is not strict theoretical unbiasedness, but controllability under finite numerical precision. Events with extremely small probabilities contribute little to the final reward anyway; letting them generate huge gradients is a pure side effect.
3. Fix 2: Sequence-Level Stability Filtering to Avoid Wasted Learning
The second fix moves the granularity from the token to the full sequence. When the sampling policy and the current policy differ too much in distribution over a response, the importance ratio for that sample becomes distorted overall, and the gradient direction it produces is not trustworthy.
The approach is to set a sequence-level ratio threshold and mask out any sample outside that range so it does not participate in the current update:
seq_ratio = torch.exp((logp_old - logp_cur).sum(dim=-1))mask = (seq_ratio < SEQ_UPPER) & (seq_ratio > SEQ_LOWER)loss = (per_token_loss * mask.unsqueeze(-1)).sum() / mask.sum().clamp(min=1)
This yields three benefits. First, it prevents extreme samples from dominating the gradient. Second, it reduces memory spikes and numerical spikes caused by a few overly long sequences. Third, it keeps the distribution of the effective batch closer to on-policy, making the theoretical bound more credible. The cost is lower sample utilization, so dynamic sampling (continuously topping up until enough valid samples are collected) is needed to sustain throughput.
4. Fix 3: Consistency Constraints to Eliminate Training-Inference Objective Drift
The third fix targets a subtle problem: the same model producing inconsistent probabilities across two engines.
A. Keep Routing Consistent (for Sparse Expert Architectures)
If a sparse expert model uses different routing strategies on the inference side and the training side, the expert selection results differ and the output distribution shifts accordingly. The solution is to record the expert ID hit by each token during sampling and force the same routing to be reused during the update, rather than running argmax again.
B. Keep the Sampling Mask Consistent (for Truncated Sampling)
If the inference side uses top-p/top-k truncated sampling and the training side ignores that mask when recomputing probabilities, the probability mass of the truncated tokens gets misattributed. The approach is the same: cache the candidate set and mask from sampling time, then apply negative-infinity masking to the excluded tokens before computing the ratio during training.
logp_cur = masked_log_softmax(cur_logits, keep_mask) # reuse the sampling masklogp_old = stored_logp_old # reuse the value recorded at sampling time
5. Combined Effect and Implementation Recommendations
The three fixes each hold one line of defense: bounded numerics, trustworthy samples, and a consistent objective. Stacked together, the post-training stage can tolerate larger policy update steps and a higher share of compute without suffering unrecoverable collapse. This is also one of the infrastructure conditions behind the rapid gains in reasoning capability in recent years.
Practical recommendations:
- Fix consistency first, then tune hyperparameters. Until training-inference inconsistency is resolved, any adjustment to the KL coefficient or learning rate is optimization on top of noise.
- Monitoring comes first. It is advisable to build dashboards for the following metrics: quantiles of the sequence ratio distribution, the proportion of masked samples, the KL estimate, the gradient norm, and the magnitude of parameter updates. General-purpose logging services and monitoring/alerting capabilities can be used to set threshold alerts.
- Move in small, fast steps. Use small-scale controlled experiments to determine the threshold ranges, then scale up to full training.
- Keep rollback points. Periodically save parameter snapshots so you can quickly revert when a loss spike appears.
- Make compute elastic. Large-scale rollouts and training can be orchestrated on container platforms and elastic compute resource pools, decoupling sampling from updates to improve overall utilization.
Overall, the core tension in large-scale reinforcement learning post-training is not whether the algorithm theory is elegant, but controllability under the combination of three factors: finite numerical precision, heterogeneous execution environments, and long-running training. Building stability into the objective function and the data pipeline is the prerequisite for turning post-training investment into real capability gains.
