Practical Stability Optimizations for GRPO in Large-Scale RL Training

    Reinforcement learning (RL) training for large language models frequently suffers from divergence issues such as reward curve oscillation and gradient explosions. This article explores practical stability optimizations applied to the Group Relative Policy Optimization (GRPO) algorithm during the post-training phase. By examining three key dimensions—mathematical correction through unbiased KL estimation, stability filtering via off-policy sequence masking, and consistency constraints for routing and sampling—we uncover the underlying engineering philosophy: prioritizing numerical stability over theoretical accuracy to enable scalable and robust RL training.

    Practical Stability Optimizations for GRPO in Large-Scale RL Training

    Introduction: Why LLM RL Training Frequently Diverges

    In recent years, a leading industry team released a new generation of reasoning models. The most notable aspect of their technical report was not the model architecture itself, but the systematic stability improvements they made to the Group Relative Policy Optimization (GRPO) algorithm during the post-training phase. These improvements allowed the team to scale RL compute to over 10% of pretraining costs without training crashes, ultimately supporting the model’s state-of-the-art reasoning capabilities.

    In LLM RL training, a recurring pain point is that as training steps increase and model capabilities approach a certain threshold, the training process suddenly diverges—reward curves oscillate violently, outputs degrade into gibberish, and gradient norms explode. The root cause of such issues is often not poor reward function design, but structural defects in the optimization objective at the numerical level. This article breaks down the proposed improvements across three dimensions: mathematical correction (unbiased KL estimation), stability filtering (off-policy sequence masking), and consistency constraints (routing and sampling preservation). We also distill the core engineering philosophy behind them: in large-scale training scenarios, numerical stability takes precedence over theoretical accuracy.

    1. Mathematical Correction: Unbiased KL Estimation

    1.1 Problem Background

    In PPO/GRPO type algorithms, to prevent the policy from updating too aggressively and causing the model to “diverge,” a KL divergence regularization term is typically added to the objective function:

    $J = E[A(s,a)] - \beta \cdot D{KL}(\pi\theta | \pi_{ref})$

    Here, $\pi{ref}$ is the frozen reference model, and $\pi\theta$ is the current policy being optimized. The theoretical KL divergence cannot be calculated analytically, so in practice, estimators like K3 are often used for unbiased estimation:

    $D{KL} \approx \frac{\pi{ref}}{\pi\theta} - \log\frac{\pi{ref}}{\pi_\theta} - 1$

    The problem arises when the current policy’s predicted probability for a certain token is extremely small ($\pi\theta \ll \pi{ref}$). The $\pi_\theta$ in the denominator causes the value of this term to scale drastically, and its gradient tends toward infinity. In LLM training, where a single update contains tens of thousands of tokens, just a few tokens hitting this extreme condition are enough to pollute the gradient direction of the entire batch.

    1.2 Improvement Solution

    The improvement involves introducing an importance sampling correction ratio, rewriting the estimation as:

    $D{KL} \approx \frac{\pi\theta}{\pi{old}} \left( \frac{\pi{ref}}{\pi\theta} - \log\frac{\pi{ref}}{\pi_\theta} - 1 \right)$

    This involves three easily confused policy objects that must be clearly distinguished:

    • $\pi_{old}$ (Old Policy): Responsible for producing data. It is the policy snapshot when generating the current training batch (rollout data) and remains constant during one RL iteration.
    • $\pi_\theta$ (Current Policy): Being optimized, i.e., the model currently updating its parameters via gradient descent.
    • $\pi_{ref}$ (Reference Policy): Provides the KL anchor, typically the model frozen after SFT.

    By introducing $\frac{\pi\theta}{\pi{old}}$, when $\pi_\theta$ approaches zero, the overall product is effectively flattened at the gradient level, preventing the gradient explosion caused by the vanishing denominator. This modification sacrifices some theoretical “pure unbiasedness” but earns a stable and controllable gradient magnitude in engineering—this is the first manifestation of “numerical stability over theoretical accuracy.”

    2. Stability Filtering: Off-Policy Sequence Masking

    2.1 Problem Background

    Modern RL infrastructure widely adopts a decoupled architecture for training and inference: the inference cluster generates samples using a high-throughput engine, while the training cluster consumes samples to update parameters. Because the scheduling rhythms of the two clusters are not synchronized, the policy used during training is often several steps ahead of the sampling policy, creating a natural off-policy bias.

    When the bias is small (e.g., a few optimization steps), the importance sampling ratio can still correct it. However, when the bias accumulates to a certain extent, the sampling distribution of some sequences differs too much from the current policy distribution. The gradients provided by these samples are essentially “optimizing for another policy,” which is not only ineffective but also introduces variance explosions.

    2.2 Improvement Solution

    This solution introduces a masking mechanism at the sequence granularity: for each sequence, calculate a distribution difference metric between the new and old policies (such as the mean or quantile of the importance ratio). If it exceeds a threshold, the loss for the entire sequence is set to zero:

    1. # Pseudocode
    2. def sequence_mask(logp_new, logp_old, threshold):
    3. # Sequence-level importance ratio
    4. ratio = (logp_new - logp_old).exp()
    5. seq_ratio = ratio.mean(dim=-1) # Sequence average
    6. mask = (seq_ratio < threshold).float()
    7. return mask # 1 to keep, 0 to discard
    8. loss = (per_token_loss * sequence_mask(...)).mean()

    Unlike PPO’s token-level clipping, sequence-level masking discards the entire sequence: once a trajectory is deemed untrustworthy, it no longer contributes any gradient. The insight behind this design is that heavily off-policy samples are not objects for “discounted learning” but for “rejected learning.”

    3. Consistency Constraints: Keep Routing and Keep Sampling Mask

    3.1 Routing Consistency (For MoE Models)

    In the Mixture of Experts (MoE) architecture, each token is routed by a gating network to a few experts. If training and inference compute routing separately, even with identical inputs, differences in floating-point operation order and parallel partitioning methods can cause minor changes in gating scores. This might route the same token to different experts in the two environments. This means the gradients calculated during training act on Expert A, while Expert B is actually activated during inference—creating a systematic drift between the optimization target and actual behavior.

    The solution is Keep Routing: during the rollout phase, record the expert routing decision for each token, and during the training phase, force the reuse of that routing result rather than letting the training framework recompute it. This ensures that regardless of how the training framework’s parallel strategy changes, the gradients always act on the parameters actually used during inference.

    3.2 Sampling Mask Consistency (For Top-P/Top-K)

    To ensure generation quality, inference engines typically enable Top-P or Top-K truncation sampling, meaning they only sample within the highest-probability candidate set. However, if the training side does not align with this behavior when calculating loss, the model will calculate KL penalties and policy gradients for tokens that can never be sampled during inference, wasting gradients and interfering with the optimization direction.

    The Keep Sampling Mask approach works by recording the truncation mask from the inference phase (which tokens are in the candidate set) and applying the same mask when calculating loss on the training side, ensuring that the optimization space strictly matches the sampling space.

    1. # Pseudocode: Aligning with inference-time truncation behavior
    2. loss = kl_term * top_p_mask # Calculate regularization only for tokens that can be sampled during inference
    3. pg_loss = advantage * ratio * top_p_mask

    4. A Unified Perspective on the Three Improvements

    Looking at the three improvements together, we can see they correspond to three failure modes in large-scale RL systems:

    Improvement Targeted Problem Failure Mode
    Unbiased KL Estimation Denominator vanishing for low-probability tokens Gradient explosion
    Sequence Masking Excessive distribution divergence between new and old policies Invalid or harmful learning signals
    Routing/Sampling Consistency Inconsistency between training and inference environments Optimization target drift

    The shared methodology is: do not pursue the theoretical optimum of an algorithm under ideal assumptions; instead, investigate every deviation between the real distributed system and theoretical assumptions item by item, and align or mask them at minimum cost. This “defensive optimization” philosophy is consistent with engineering practices in large-scale pretraining, such as gradient clipping, loss spike detection, and data rollback.

    5. Engineering Implications

    For teams looking to implement RL post-training in their own business, the following experiences can be leveraged:

    1. Monitor First: Before deploying KL regularization, monitor the tail of the token-level KL values and gradient norm distributions. Extreme values often precede training crashes.
    2. Minimize Training-Inference Policy Gap: By increasing synchronization frequency and limiting data reuse epochs, keep off-policy bias within the masking threshold.
    3. Infrastructure Consistency Priority: If using MoE models, routing decisions must be reproducible; if inference uses truncation sampling, the training loss must be aware of the same candidate set. When building training pipelines on cloud platforms, you can leverage general container platforms, logging services, and monitoring/alerting infrastructure to observe training metrics in real-time and quickly pinpoint sources of instability.
    4. Scale RL Investment Gradually as Budget Allows: Industry practices show that scaling RL compute to over 10% of pretraining costs is feasible, provided the stability mechanisms have been thoroughly validated.

    Conclusion

    The competition in LLM reasoning capabilities is shifting from “pretraining data scale” to “post-training infrastructure robustness.” The three stability optimizations of GRPO may seem trivial, but they actually build the critical foundation that allows reinforcement learning to scale. For developers, understanding the trade-off philosophy behind these optimizations—decisively choosing numerical stability over theoretical elegance—is more valuable than memorizing any single formula.