Stabilizing Training in Large-Scale Reinforcement Learning for LLMs

    This article explores practical optimization strategies for stabilizing reinforcement learning (RL) during the post-training phase of large language models. It focuses on three core mechanisms—unbiased KL divergence estimation, sequence-level masking for filtering unreliable samples, and consistency constraints for routing and sampling—that jointly address gradient anomalies, invalid samples, and train-inference distribution mismatches. The discussion includes implementation considerations and monitoring metrics for large-scale training environments.

    Why Large-Scale RL Training for LLMs Becomes Unstable

    In the post-training phase of large models, reinforcement learning is commonly used to improve mathematical reasoning, code generation, complex instruction following, and multi-step decision-making. Unlike supervised fine-tuning, RL does not simply make the model reproduce standard answers. Instead, it continuously adjusts the generation policy using reward signals to steer the model toward producing high-quality, verifiable, and constraint-satisfying outputs.

    However, as training scale grows, generation sequences become longer, and reward models become more complex, several problems often emerge: sudden increases in loss, severe gradient fluctuations, over-concentration on a few modes, gradual mismatch between the training policy and the actual sampling policy, and even cases where training metrics improve while inference performance degrades.

    A practical class of solutions to these issues builds on group-relative advantage optimization methods by modifying the objective function and data filtering pipeline. The core idea is not to pursue an increasingly sophisticated theoretical objective, but to prioritize numerical stability, distribution consistency, and engineering controllability during large-scale training.

    This article highlights three general optimization mechanisms:

    1. Unbiased or low-bias KL divergence estimation.
    2. Sequence-level stability filtering and masking.
    3. Constraints that keep routing behavior and sampling behavior consistent.

    These three methods correspond to three critical risk areas in RL training: abnormal gradients, invalid samples, and inconsistency between the training environment and the inference environment.

    Understanding Why RL Training Can Become Unstable

    During RL training, the model generates responses according to its current policy. A reward function evaluates each response, and the results are used to update the model parameters. For a single prompt, the model may produce multiple candidate answers; the algorithm computes advantage values based on the relative performance of these candidates and adjusts the generation probabilities accordingly.

    A simplified objective can be expressed as:

    [
    L(\theta)=\mathbb{E}\left[\frac{1}{G}\sum_{i=1}^{G}\min\left(r_i(\theta)A_i,\operatorname{clip}(r_i(\theta),1-\epsilon,1+\epsilon)A_i\right)\right]
    ]

    Where:

    • (\theta) represents the policy being trained.
    • (G) is the number of candidates generated for the same prompt.
    • (A_i) is the relative advantage of the (i)-th candidate.
    • (r_i(\theta)) is the probability ratio between the current and old policies for the generated output.
    • (\epsilon) is the clipping threshold that limits the policy update magnitude.

    Theoretically, the probability ratio and clipping mechanism restrict the update step. In practice, issues often arise at a finer granularity.

    First, the probability of a single token can be extremely small, leading to very large differences in log-probabilities. Second, a sequence containing only a few anomalous tokens can amplify the training signal for the entire sequence. Third, mixture-of-experts architectures or truncated sampling strategies can cause the training and generation phases to use different computational paths. Fourth, the old policy generates data, but by the time the current policy is updated, the data distribution is naturally delayed.

    Therefore, stabilizing RL training cannot rely solely on one objective function. It requires addressing numerical, data, and system-level issues simultaneously.

    Unbiased KL Estimation: Avoiding Gradient Anomalies from Extremely Small Probabilities

    Role of the KL Regularization Term

    RL training typically includes a KL constraint to prevent the current policy from drifting too far from a reference policy. A common form is:

    [
    D{KL}(\pi\theta|\pi{ref})
    =
    \mathbb{E}
    {x\sim\pi\theta}
    \left[
    \log\frac{\pi
    \theta(x)}{\pi_{ref}(x)}
    \right]
    ]

    Here, (\pi\theta) is the current policy and (\pi{ref}) is the reference policy. The KL term acts as a “brake”: the reward function pushes the model toward better outcomes, while the KL regularization prevents the model from completely changing its language distribution to chase local rewards.

    At the token level, probabilities assigned by the current and reference policies can differ significantly. When a token has a near-zero probability under the current policy but a relatively high probability under the reference policy, directly computing the probability ratio or its gradient can lead to numerical instability.

    Risks in Common Estimators

    Some commonly used estimators rely on forms such as:

    [
    \log\frac{\pi\theta}{\pi{ref}}
    ]

    or further use the ratio:

    [
    \frac{\pi\theta}{\pi{ref}}
    ]

    When distributions differ significantly, the variance of these terms increases noticeably. In long sequences, multiplying or accumulating ratios across multiple tokens can easily produce extreme values, leading to:

    • Sudden amplification of gradients.
    • Overflow in mixed-precision computation.
    • A single anomalous sample dominating a batch update.
    • Severe oscillation in training loss between consecutive steps.

    These problems do not necessarily mean the model has learned incorrect knowledge; rather, the estimator may be overly sensitive to extreme probability regions.

    Importance Sampling Correction

    A general improvement is to introduce an importance sampling ratio between the old and current policies. The idea is that data is generated by the old policy, but the loss needs to reflect the current policy, so observations from the old policy distribution cannot be directly treated as coming from the current policy.

    The relevant estimate can be simplified as:

    [
    \hat{D}{KL}
    =
    \frac{\pi
    \theta}{\pi{old}}
    \left(
    \frac{\pi
    {ref}}{\pi\theta}
    -
    \log\frac{\pi
    {ref}}{\pi_\theta}
    -1
    \right)
    ]

    Where:

    • (\pi_{old}) is the old policy used to generate training samples.
    • (\pi_\theta) is the current policy being updated.
    • (\pi_{ref}) is the reference policy used to constrain drift.

    The main point is not the exact formula, but the use of importance sampling to connect the data generation distribution with the current optimization distribution, while improving the behavior of the KL estimate in extreme probability regions.

    Practical implementation considerations include:

    1. Use log-probabilities for calculations to avoid underflow from direct multiplication.
    2. Set reasonable numerical guards for probability ratios.
    3. In mixed-precision training, accumulate critical statistics in higher precision.
    4. Monitor unusually large KL values instead of silently clipping them.
    5. Distinguish between real distribution shift and numerical issues in the estimator.

    Validating the KL Estimator

    Evaluate the estimator from four angles:

    • Check the mean, quantiles, and maximum KL value per training batch.
    • Measure the contribution of extreme tokens to the total gradient.
    • Compare loss fluctuations across different sequence lengths.
    • Check whether the trained model exhibits repetition, degeneration, or over-conservative behavior.

    Note that smaller KL is not always better. Overly strong constraints limit the model’s ability to learn new policies and slow down reward improvement; overly weak constraints may cause the model to drift from its original language abilities. In practice, focus on the balance between KL trends and task gains.

    Sequence-Level Masking: Filtering Invalid Updates from Distribution Mismatches

    Why Sequence-Level Processing Is Needed

    RL samples are typically generated as complete responses, but the loss is often computed at the token level. This creates a problem: a response containing only a few anomalous segments can produce unstable gradients at multiple positions.

    For example, a long response may match the old policy well for the first part, then suddenly contain low-probability content later. Simply averaging over all tokens can cause the anomalous segment to disproportionately amplify the update signal for the entire sequence.

    Therefore, compared to token-level clipping, sequence-level masking is better suited for handling the question of whether the entire sample remains trustworthy.

    Basic Approach

    Compute a stability metric for each sample, such as the average absolute log-probability difference between the current and old policies:

    [
    \Deltas=
    \frac{1}{T_s}
    \sum
    {t=1}^{Ts}
    \left|
    \log\pi
    \theta(yt|x,y{<t})
    -
    \log\pi{old}(y_t|x,y{<t})
    \right|
    ]

    where (T_s) is the sequence length.

    When (\Delta_s) exceeds a threshold, the sequence is marked as unstable and its weight is reduced or it is masked entirely in the current update:

    [
    m_s=
    \begin{cases}
    1, & \Delta_s\leq \tau\
    0, & \Delta_s>\tau
    \end{cases}
    ]

    The final objective can be written as:

    [
    L’=\frac{\sum_s m_s L_s}{\sum_s m_s+\delta}
    ]

    where (\tau) is the stability threshold and (\delta) prevents division by zero when no valid samples remain.

    Masking Is Not About Removing All Difficult Samples

    Sequence masking does not aim to filter out low-reward samples, nor does it keep only simple answers that the model already knows. The goal is to filter out samples that cannot provide reliable gradients due to severe policy mismatch, extreme probability estimates, or abnormal generation processes.

    If all low-reward samples are excluded, the model loses exploration capability. If all high-reward samples are retained, a few anomalous samples may dominate training. Therefore, the masking condition should be based on policy consistency and numerical stability, not directly on task rewards.

    Safer Engineering Strategy

    In practice, use a tiered approach:

    • Mild shift: keep the sample but reduce its weight.
    • Moderate shift: only keep stable tokens.
    • Severe shift: mask the entire sequence.
    • Consecutive anomalies across multiple rounds: pause updates and inspect the sampling, reward, or data pipeline.

    Also record the valid sample ratio for each round. If the ratio stays too low for a long time, the problem may not be the masking itself, but an overly large learning rate, rapidly changing sampling policy, mis-scaled reward, or an outdated old policy.

    Maintaining Routing Consistency: Reducing Train-Inference Bias in Sparse Models

    In sparse models, an input token does not necessarily pass through the entire network. Instead, a routing module selects a subset of experts or computational branches. This reduces computational cost but introduces additional inconsistency risk.

    Routing Changes Affect Reward Signals

    Suppose a batch of samples is generated by the old policy. During generation, a token is assigned to a certain set of experts. When training the current policy, the same token may be assigned to a different set because parameters have been updated or routing scores have changed.

    This means the probabilities computed during training do not exactly correspond to the computational path that produced the token during generation. Even if the model parameters change slightly, routing changes can amplify policy differences and interfere with advantage estimation and KL estimation.

    Basic Idea of Maintaining Routing

    A generic approach is to reuse as much routing information from the generation phase as possible when computing old-policy statistics, or to record enough routing data so that the training process can reproduce the same computational path as during sampling.

    The goal is not to permanently fix routing, but to reduce additional routing noise within the effective time window of a policy update. This separates “policy changes caused by parameter updates” from “computational changes caused by routing changes.”

    Note that routing information increases storage and communication costs. Choose a recording method based on system scale, such as saving discrete routing indices, candidate branch information, or only necessary metadata for replay.

    Maintaining Sampling Consistency: Controlling Distribution Changes from Top-P and Top-K

    Generation often uses truncated sampling, where only a limited candidate set with high probabilities is considered. Common practices include truncating by the number of candidates or by cumulative probability.

    This helps reduce obviously unreasonable outputs, but it introduces an important issue: the full distribution computed during training is not the same as the truncated distribution actually used for sampling during generation.

    For example, the training objective assumes all tokens are part of the original distribution, while the generation process samples only from a limited candidate set. If the two are not aligned, the reward signal corresponds to one distribution while gradients are computed based on another, leading to an implicit objective shift.

    Consistency Handling Approaches

    Consider the following options:

    • Reproduce the candidate filtering rules from generation during training.
    • Apply a uniform mask to truncated tokens.
    • Compute relevant probabilities using the truncated, re-normalized distribution.
    • Save candidate sets or necessary sampling metadata when recording samples.
    • Ensure that reward evaluation and policy probability use the same effective token range.

    Trade-offs in Consistency Constraints

    Maintaining sampling consistency does not mean the training phase must replicate every detail of the generation phase. Over-replication increases system complexity and memory consumption, and may limit the model’s ability to explore low-probability but valuable answers.

    A more reasonable approach is to identify which differences significantly affect policy gradients and prioritize eliminating those with high impact. For example, large changes in candidate sets, inconsistencies in truncation thresholds between training and inference, and dynamic changes in sampling temperature should all be closely monitored.

    How the Three Optimization Methods Work Together

    These three methods address different problems but are usually combined in large-scale training.

    First, unbiased KL estimation improves the numerical properties of the regularization term and avoids gradient anomalies caused by extreme probabilities.

    Second, sequence-level masking identifies samples that do not provide reliable learning signals, reducing the impact of invalid updates on the overall training process.

    Third, routing and sampling consistency constraints narrow the gap between the training environment and the generation environment, preventing implicit drift of the optimization objective.

    The overall process can be summarized as:

    1. Generate multiple candidate responses using the old policy.
    2. Compute rewards, relative advantages, and old-policy probabilities.
    3. Record generation environment information based on routing and sampling configurations.
    4. Compute current-policy probabilities and reference-policy probabilities.
    5. Use stable KL estimation to compute distribution constraints.
    6. Generate sample masks based on sequence shift magnitude.
    7. Perform policy updates on valid samples.
    8. Monitor KL, rewards, valid sample ratio, and gradient norms.
    9. Adjust learning rate, sampling configuration, or update frequency when anomalies appear.

    Key Metrics to Monitor

    To judge whether the optimization is truly effective, do not only look at final rewards. Build a comprehensive training monitoring system.

    Policy Stability Metrics

    • Average log-probability difference between current and old policies.
    • KL mean, maximum, and high percentiles.
    • Ratio of policy ratios exceeding the clipping interval.
    • Gradient norms and number of gradient anomalies.

    Data Quality Metrics

    • Sequence mask ratio.
    • Valid sample ratio across different length intervals.
    • Retention ratio of high-reward versus low-reward samples.
    • Ratios of repeated answers, empty answers, and malformed answers.

    Task Performance Metrics

    • Mean task reward.
    • Pass rate under multiple sampling attempts.
    • Long-chain reasoning success rate.
    • Output format compliance rate.
    • Difference between training and validation sets.

    If rewards continue to increase while KL and gradient fluctuations expand simultaneously, the model is likely chasing rewards at the cost of stability. If the mask ratio keeps rising, the current policy may be updating too fast, or the sampling and training environments are clearly inconsistent.

    Conclusion

    The key challenge in large-scale RL for LLMs is not just designing a more complex optimization formula, but keeping the entire training loop controllable under large scale, long sequences, and dynamic sampling conditions.

    Unbiased KL estimation addresses extreme probability issues at the numerical level; sequence-level masking tackles contamination from anomalous samples; maintaining routing and sampling consistency resolves mismatches between the generation environment and the optimization environment.

    These three methods reflect an important engineering principle: in real large-scale training systems, theoretical objectives must be considered together with numerical stability, data validity, and system consistency. Only when reward functions, policy updates, sampling processes, routing mechanisms, and monitoring systems form a complete closed loop can RL-based post-training scale stably and continuously improve model performance on complex reasoning tasks.