Three Key Fixes for Unstable RL Training in Large Language Models

    This article examines three common failure modes that destabilize reinforcement learning post-training of large language models—regularization gradient explosions, invalid samples polluting gradients, and objective drift from training-inference mismatch—and explains three practical corrections: an unbiased KL estimator with importance sampling reweighting, sequence-level stability filtering for off-policy rollouts, and consistency constraints that preserve expert routing and sampling masks. It includes code snippets, engineering cautions, and a staged rollout plan for keeping large-scale RL training observable, clip-safe, and reproducible.

    1. Background: Why Large-Scale RL Post-Training Tends to Collapse

    During the reinforcement learning post-training stage of large language models, the industry commonly relies on Proximal Policy Optimization (PPO) and its simplified variants, such as GRPO-style methods that remove the value network and replace the critic with group-relative advantages. These methods are very lightweight from an engineering standpoint, but once training scales up and sampling is decoupled from updates, three typical instability patterns emerge: numerical explosion of the regularization term’s gradients, gradient pollution from invalid samples, and objective drift caused by inconsistent training and inference paths. Combined, these effects lead to sudden collapses in the reward curve, output degenerating into repeated fragments, and violent KL oscillations, eventually forcing a rollback to an earlier checkpoint.

    It is worth stressing that the root cause is not that “the algorithm is theoretically incorrect.” Rather, it is the deeper off-policy behavior introduced by large-scale parallel sampling, the frequent touching of low-probability tokens, and the amplified implementation differences between training and inference for mixture-of-experts routing and sampling operators. Consequently, the core of any improvement is not absolute precision in the formulas, but prioritizing numerical stability and controllable distributions.

    2. Fix 1: Unbiased KL Estimation to Suppress Gradient Explosions in Low-Probability Regions

    The standard approach uses a sampled estimate of the KL divergence as a regularization term, constraining the current policy from drifting too far from the reference policy. Common third-order-style estimators have a low-variance advantage when the probability ratio is large, but when the current policy assigns an extremely small probability to a token while the reference policy’s probability is not small, the ratio blows up sharply, the gradient magnitude tends toward infinity, and a single update step can destroy the parameters.

    A widely adopted correction introduces an importance sampling ratio into the estimator, reweighting the current policy probability with the policy probability at sampling time. This keeps the estimate unbiased in expectation while pulling extreme ratios back into a controllable range. A schematic form can be written as:

    1. # ratio: current policy / sampling policy; log_ratio_ref: log(pi_ref/pi_theta)
    2. term = log_ratio_ref.exp() - log_ratio_ref - 1.0
    3. kl_est = ratio * term
    4. kl_est = torch.clamp(kl_est, max=CLIP_MAX) # engineering safeguard against outliers

    There are three engineering points. First, the ratio must undergo numerical clipping and probability lower-bound protection (for example, applying clamp_min to probabilities) to avoid division by zero and overflow. Second, the KL term should be computed per token and then normalized by the effective length, preventing accumulation from amplifying over long sequences. Third, monitor quantiles of the KL rather than the mean; a normal mean with tail outliers is often a warning sign before a collapse.

    3. Fix 2: Stability Filtering with Off-Policy Sequence Masking

    When the sampling policy and the current policy differ too much, a given response no longer “represents” the current policy’s distribution, and continuing to update parameters with its gradients is ineffective or even harmful learning. Sequence-level masking works as follows: for each rollout, compute the importance ratio or average log ratio over the entire sequence; if the deviation exceeds a threshold, set the loss of the whole sample to zero so it does not participate in this update.

    1. seq_log_ratio = log_pi_theta_sum - log_pi_old_sum
    2. keep = (seq_log_ratio.abs() <= SEQ_TOL) & (response_len > 0)
    3. loss = (per_token_loss * keep).sum() / keep.sum().clamp_min(1)

    Compared with per-token clipping, sequence-level filtering is “coarser” but more stable: it acknowledges that a trajectory is an indivisible unit of learning and avoids the bias caused by updating half a sequence while discarding the other half. In practice, the filtering ratio is usually kept small (for example, a single-digit percentage), and the length and reward distribution of discarded samples are logged to help determine whether the sampling temperature is too high, the number of update steps is too large, or the data itself is noisy.

    4. Fix 3: Consistency Constraints to Preserve Routing and Sampling Masks

    Mixture-of-experts models often use different routing implementations in training and inference (such as batched grouped computation versus per-token dispatch), so Top-K expert selection results can differ subtly. The sampling side has a similar issue, where Top-P/Top-K operators are implemented inconsistently across the two paths. Together, these make “the probabilities seen during training” inconsistent with “the probabilities actually used during sampling,” causing the objective function to drift.

    The consistency constraint has two parts. First, preserve routing: when recomputing the current policy probabilities, reuse the expert assignments determined at sampling time so the forward and backward computation paths stay aligned. Second, preserve the sampling mask: record the set of candidates that were truncated or masked during sampling, and apply the same mask to that set in the training forward pass, guaranteeing that the probabilities of excluded tokens are strictly zero.

    1. # cache routing and candidate mask during sampling
    2. cache = {"expert_ids": expert_ids, "sample_mask": sample_mask}
    3. # reuse them in the training forward pass
    4. logits = router_recompute(hidden, expert_ids=cache["expert_ids"])
    5. logits = logits.masked_fill(~cache["sample_mask"], NEG_INF)
    6. log_pi_theta = logits.log_softmax(-1).gather(-1, token_ids)

    This step may look trivial, but it is key infrastructure for pushing RL compute from a single-digit percentage of pre-training cost toward much higher levels without collapsing: it keeps the “environment” and the “optimized object” strictly aligned and removes unnecessary sources of variance.

    5. How the Three Fixes Work Together and How to Roll Them Out

    The three improvements govern gradient magnitude, sample validity, and environment consistency respectively, and they complement one another: the unbiased KL controls single-point risk, sequence masking controls sample risk, and the consistency constraint controls systemic bias. For deployment, a staged rollout is recommended: first enable the probability lower bound and KL clipping, then turn on sequence filtering and observe the discard rate, and finally complete the routing and sampling mask caching. If a container platform is used to host distributed sampling and training, dashboards can be built on top of logging services and monitoring alerts for KL quantiles, filtering rates, and routing consistency rates, with automatic pause and checkpoint rollback on anomalies. Overall, stability in large-scale RL post-training comes from three things—observability, clippability, and reproducibility—rather than more complex theoretical corrections.