# Ten Bugs in RL Post-Training That Do Not Crash *What each one looks like in the metrics, why it happens, how to find it, and what the fix looks like in real code*
Draft. Every number here comes from a log or from source at a named commit, and every code block was run, but the text has not been read by anyone else yet. The page asks search engines not to index it.
A crash is the easy kind of bug. The stack trace names a file, you open the file, and an hour later it is fixed. The expensive kind is the other one, where every process stays alive, the loss keeps printing, the reward curve climbs for two hundred steps and then quietly stops climbing, and nothing in the log says why. Reinforcement learning on top of a language model collects an unusual number of the second kind, because of how the system is put together. A supervised run has one model and one forward pass, whereas an RL run has a model being trained in one framework and the same model generating text in another, which means two sets of kernels computing what is supposed to be the same number. On top of that it has a loss whose denominator is a choice that nobody writes down, and a reward signal weak enough that a one percent error in the gradient can hide inside it for a long time. So, what are the ways an RL post-training run can be wrong while it looks healthy, and how would you find each one? I will go through ten of them. Each one is a mechanism in a real framework rather than a category of mistake, and I will ask the same four questions of each: what you see, why it happens, how you would find it, and what the fix looks like in code. The code comes from four repositories read at a fixed commit, all from October 2026: Miles (`b7b2870daf`), prime-rl (`f3827c4ed`), Megatron-LM (`54f18cd21`) and SGLang (`d5d87899f9`). Where I needed a number that none of them could give me I measured it, in six small experiments with Qwen3-8B as the model, four on one B300 and two on a CPU. The snippets below assume `import torch` and were all run before publishing. Three large subjects are out of this article. The reward itself is one, since every bug below assumes the reward already measures what you want, and getting that right is a harder article than this one. Memory and throughput are another, because an out-of-memory error or a slow step announces itself. The third is the parallel layout, except for the one place in section 7 where a collective is the bug. ## 1. Three Log-Probabilities and One Ratio Before the bugs we need a little shared vocabulary, because nine of the ten come down to one of four things: which log-probability went where, what divided the loss, which rank did what, and how far the policy has moved since the data was generated. One turn of the loop looks like Figure 1 below. An inference engine samples responses to a batch of prompts, the responses come back as token ids, and the training side runs its own forward pass over those same tokens to get the numbers the loss needs. Then the loss is computed, the optimizer steps, and the new weights are pushed back into the engine for the next turn.  *Figure 1: One turn of the loop. The three rows in the accent colour are log-probabilities of the same tokens, produced in three different places.* As Figure 1 shows, the same token ends up carrying three log-probabilities. In Miles they are three separate keys on the batch, read at the top of the policy loss: ```python # excerpt, cut down from miles/backends/training_utils/loss/hub/losses.py # policy_loss_function @ b7b2870daf rollout_old_log_probs = batch.get("rollout_log_probs") # the engine's reference_log_probs = batch.get("ref_log_probs") # the frozen reference # ... old_log_probs = rollout_old_log_probs if args.use_rollout_logprobs \ else trainer_scored_log_probs # the trainer's own forward ``` The first is what the inference engine reported while it was sampling, and it is the only one of the three that the sampler actually used. The second is what the trainer gets when it runs its own forward pass over the same tokens. The third comes from a frozen copy of the model from before post-training started. In exact arithmetic the first two would agree forever, and all three would agree at step 0. They do not. Each pair of these makes a ratio, and each ratio has one job, which is what Figure 2 shows.  *Figure 2: Which pair of log-probabilities forms which ratio, and what each ratio is for.* It pays to get the three rows of Figure 2 straight now, since the rest of the article refers to them constantly. The policy-gradient ratio is the one the clip acts on, and Miles stores its logarithm under the name `ppo_kl`, which is the old log-probability minus the new one. The mismatch ratio compares the trainer with the engine, and it is what truncated importance sampling corrects. The reference ratio is what a KL penalty charges for. In code they are three subtractions of the same shape: ```python rollout_logp = torch.tensor([-0.21, -1.90, -0.05, -3.30]) # the engine old_logp = torch.tensor([-0.20, -1.92, -0.05, -3.31]) # trainer, last step new_logp = torch.tensor([-0.17, -2.05, -0.04, -3.10]) # trainer, this step ppo_kl = old_logp - new_logp # Miles's name for the log-ratio ratio = (-ppo_kl).exp() # what the PPO clip acts on mismatch = (old_logp - rollout_logp).exp() # what TIS corrects print([round(x, 4) for x in ratio.tolist()]) print([round(x, 4) for x in mismatch.tolist()]) ``` The last piece of vocabulary is the denominator. A policy loss is a sum over response tokens, and something has to divide it. Miles builds that reducer once per micro-batch and passes it into the loss function, and notice where that leaves it: the denominator is set by configuration in one file and used in another, so it is easy for nobody on a team to be sure which one a run used. With that in place, here is the single most useful check in an RL trainer, and it is one number. In a synchronous run at step 0, before any weight update has happened, the trainer is scoring the very samples it just generated, with the very weights that generated them. The importance log-ratio at that moment is not approximately zero. It is zero. Miles turns this into an assertion: > At step 0, `abs(train/ppo_kl) < 1e-9` and `train/pg_clipfrac < 1e-10`, and `train/kl_loss` is zero. MLA relaxes to `1e-8`. If that number is not zero on your run, find out why before looking at anything else, because the first three bugs below all show up there first. ## 2. Bug 1: The Trainer and the Engine Disagree About the Same Token The symptom is that `ppo_kl` is small but not zero at step 0, and then the gap between the trainer's log-probabilities and the engine's grows over the run, which drags the clipped fraction up with it. Reward improves for a while and then goes sideways. It happens because the trainer and the engine compute the same mathematical quantity with different code: a different attention kernel, a different fused activation, a different tensor-parallel reduction, and, most often of all, a different batch shape. I wanted to know what that is worth in practice, so I measured it with the smallest version of the experiment I could build: one model, one set of weights, one sequence, scored twice. The setup is Qwen3-8B in bf16 on a B300. I sampled a 256-token response, then scored it alone as the only sequence in the batch, and then again as one row of a left-padded batch of eight, with explicit `position_ids` so that the padded row sees exactly the positions it saw when it was alone. The two calls are mathematically identical. Figure 3 shows what came back.  *Figure 3: Per-token absolute log-probability difference between scoring one response alone and scoring it inside a padded batch of eight. Qwen3-8B in bf16 on one B300.* As Figure 3 shows, the median token is untouched, since 119 of the 256 tokens came back bitwise identical and the median absolute difference is 3 x 10^-7. The tail is where the trouble is: the 99th percentile is 0.116, the largest difference is 0.439, and 18.8% of tokens moved by more than 10^-3. An importance weight is the exponential of that difference, so the worst token in this response has a weight of 0.644 where the median token has 1.0, and nothing changed except the shape of the tensor it was sitting in. Be careful about the cause here, because the obvious explanation is the wrong one. The other seven sequences cannot influence this one, since attention is masked and each row of a batch is independent. To check, I ran two more comparisons, which are the three panels of Figure 4.  *Figure 4: The same response scored three ways. Only the shape of the tensor changes the answer.* Panel B in Figure 4 is the control. The same padded batch of eight, with a completely different set of neighbouring sequences, returns log-probabilities that are bitwise identical to the first batch of eight, all 256 of them. Panel C drops the batch entirely and just pads the single sequence out to the same width, and that alone reproduces most of the difference, at a mean of 6.6 x 10^-3 and a maximum of 0.223. So the neighbours' values do not matter and the shape does. That is what you would expect once you think about how a matrix multiplication is scheduled. A GEMM of a different size gets a different tile size, a different number of thread blocks, and sometimes a split along the reduction dimension that a smaller problem would not use, and each of those changes the order in which the partial sums are added. Floating-point addition is not associative, so a different order gives a different last bit. The output projection shows it on its own, with no transformer around it: ```python torch.manual_seed(0) hidden = torch.randn(1, 4096, device="cuda", dtype=torch.bfloat16) lm_head = torch.randn(151936, 4096, device="cuda", dtype=torch.bfloat16) * 0.02 alone = hidden @ lm_head.T # [1, 151936] padding = torch.randn(2047, 4096, device="cuda", dtype=torch.bfloat16) batched = (torch.cat([hidden, padding]) @ lm_head.T)[:1] print(torch.equal(alone, batched)) # False print((alone - batched).abs().max().item()) # one bf16 ulp at this magnitude ``` With the real Qwen3-8B weights and a real hidden state, the largest logit moves by 0.0625 when 2047 other rows are added underneath it. For a logit whose root-mean-square is 6.76 that is a relative error of about one percent, and it is exactly one bf16 unit in the last place at that magnitude. The reduction inside the log-softmax does the same thing on a smaller scale. Taking the same bf16 logits and reducing the log-softmax in fp32 rather than in bf16 moves the per-token log-probability by 2.4 x 10^-4 on average and 7.0 x 10^-3 at worst. That is smaller than the batch-shape effect, and it is also the one you get for free, so the frameworks upcast the logits before the softmax rather than after. To find this, log the difference directly. Miles computes two numbers for exactly that, on every step where the engine's log-probabilities are present: ```python # excerpt, cut down from miles/.../loss/hub/losses.py:policy_loss_function abs_diff = (train_scored_log_probs - rollout_log_probs).abs() train_rollout_logprob_abs_diff = sum_of_sample_mean(abs_diff) # KL(rollout || train) at the sampled tokens, Schulman k3, clamped to [-10, 10] rollout_train_kl = compute_approx_kl(rollout_log_probs, train_scored_log_probs, kl_loss_type="low_var_kl") train_rollout_kl = sum_of_sample_mean(rollout_train_kl) ``` The first is easy to read and the second is the one to alert on. Miles's debugging guide also gives the thresholds that turn the number into a diagnosis, and they are the kind of thing to memorize: below 10^-4 is kernel jitter and is fine, above 1 is a configuration error so check the parallelism and the precision, and about 0.8 per token on an instruct model is almost always a chat-template mismatch rather than anything numerical. There are three fixes, and they differ in how much they cost you. The weakest is to correct for the mismatch, which is what truncated importance sampling does: multiply the per-token loss by the ratio between the two policies, clamped so that one bad token cannot take over the batch. ```python train_logp = torch.tensor([-0.20, -1.92, -0.05, -3.31]) rollout_logp = torch.tensor([-0.21, -1.90, -2.05, -3.30]) # 3rd disagrees pg_loss = torch.tensor([0.4, -0.2, 0.9, 0.1]) tis = torch.exp(train_logp - rollout_logp) # the third token's ratio is 6.4 tis_weights = tis.clamp(min=0.0, max=2.0) # Miles's defaults tis_clipfrac = (tis_weights != tis).float().mean() corrected = pg_loss * tis_weights print([round(x, 3) for x in tis_weights.tolist()], float(tis_clipfrac)) print([round(x, 3) for x in corrected.tolist()]) ``` The middle option is to throw the bad tokens away instead of down-weighting them. Miles calls it `icepop_function` and prime-rl calls it `IcePopLoss`, and both replace the clamp with a band: a token whose ratio falls outside `[clip_low, clip_high]` contributes nothing at all. The difference matters more than it looks, because clamping keeps a biased contribution from a token that the two sides disagree about, while zeroing removes it and accepts a smaller effective batch. The strongest fix is to make the mismatch not exist, and reading the configuration for it is the best way I know to see how long the list of things that have to agree really is. Miles's true-on-policy contract pins deterministic inference and deterministic training, the same attention backend on both sides, Megatron's `local` transformer implementation instead of Transformer Engine's, batch-invariant matmuls, the rope and bias-swiglu fusions turned off, a tensor-parallel-invariant row linear, a deterministic tensor-parallel all-reduce, and three environment variables: `NCCL_ALGO=Ring`, `NVTE_ALLOW_NONDETERMINISTIC_ALGO=0` and `CUBLAS_WORKSPACE_CONFIG=:4096:8`. Under that mode the assertion changes from "within 0.03" to "exactly equal". The batch-invariant part of that list is a library of its own. SGLang ships `mm_batch_invariant`, `addmm_batch_invariant`, `bmm_batch_invariant`, `_log_softmax_batch_invariant`, `mean_batch_invariant` and `rms_norm_batch_invariant`, adapted from Thinking Machines' `batch_invariant_ops`, behind a `set_batch_invariant_mode` context manager. They are slower than the kernels they replace, so they are a mode rather than the default. Afterwards, watch `train_rollout_kl` as the headline number, `tis_clipfrac` to see how often the correction is saturating, and the effective sample size to see whether the weights have spread out. ## 3. Bug 2: The Router Picks Different Experts Than the Rollout Did The symptom here is specific enough to be a fingerprint: a dense model trains fine on the same code, and a mixture-of-experts model of similar size collapses after tens of steps. Miles's debugging guide lists the symptom and the cause on one line, as "MoE training collapses after tens of steps. Routing not preserved." It happens because a router scores every expert for every token and keeps the top k. With 256 experts and a k of 8, the decision that matters is whether a given expert lands in position 8 or position 9, and those two scores are usually almost the same. A difference of the size we measured in the last section is more than enough to swap them. I wanted the number rather than the argument, so I extended the same experiment. The two scorings from section 2 give two versions of the hidden state at each of Qwen3-8B's 36 layers. I pushed both versions through a real 256-expert router, took the top 8 with the correction bias the way the aux-loss-free designs do, and counted how often the chosen set differs. The routers are the real `mlp.gate.weight` and `mlp.gate.e_score_correction_bias` tensors of MiMo-V2.6-Flash-RL, which has 256 experts, a top-k of 8, and a hidden size of 4096, the same width as Qwen3-8B. The hidden states and the routers therefore come from two different models, so what this measures is how a real router responds to a difference of the size a real forward pass produces, and not anything about either model on its own. **709 of 10,044 token-and-layer pairs, or 7.06%, come out with a different set of experts.** The worst layer flips 11.1% of its tokens and the best flips 0.36%.  *Figure 5: Left, the gap between the eighth and ninth expert score. Right, the fraction of top-8 sets that change as the hidden state is perturbed by a known relative amount.* The left half of Figure 5 says why the number is that large. The median gap between the 8th and the 9th score, averaged over the layers, is 3.59 x 10^-3, on scores that live between 0 and 1. The right half calibrates it: perturbing a Gaussian hidden state by a relative 10^-6 changes nothing, 10^-4 changes 0.12% of the sets, 10^-3 changes 0.79%, and 10^-2 changes 8.83%. The two runs' hidden states differ by a median of 8.2 x 10^-4 at the first layer and by about 10^-2 from the middle of the network onward, so the measured 7.06% is close to what the sweep predicts. The reason this is worse than an ordinary log-probability difference is that the gradient goes somewhere else entirely. Miles's documentation puts the failure concretely: the rollout picks experts {2, 7} for a token, training picks {2, 8} for the same token, "the gradient is computed against the wrong expert", and over hundreds of layers and thousands of steps the policy diverges. The fix is to record the routing during the rollout and replay it during training. The mechanism is about fifteen lines, and the interesting part is the last one: ```python # excerpt, cut down from miles/utils/replay_base.py # BaseReplayManager.get_topk_fn @ b7b2870daf def new_topk_fn(scores, topk, *args, **kwargs): if stage == "record": probs, top_indices = old_topk_fn(scores, topk, *args, **kwargs) replay.record(top_indices) # copied to pinned CPU memory return probs, top_indices if stage == "replay_forward": top_indices = replay.pop_forward() return scores.gather(1, top_indices), top_indices return old_topk_fn(scores, topk, *args, **kwargs) ``` The replay branch takes the expert indices from the rollout but gathers their scores from the trainer's own router, so the expert assignment is fixed while the gradient still flows into the router's weights. Returning the recorded probabilities as well would be easier and would stop the router learning anything. We can check that the gradient really does survive the gather: ```python scores = torch.rand(4, 8, requires_grad=True) # 4 tokens, 8 experts recorded = torch.topk(torch.rand(4, 8), 2, dim=-1).indices # from the rollout probs = scores.gather(1, recorded) # replayed selection probs.sum().backward() print(int((scores.grad != 0).sum())) # 8: two live experts per token print(bool((scores.grad.gather(1, recorded) == 1).all())) # True ``` Recording is not free. The rollout has to carry an array of shape `(tokens - 1, layers, top_k)` in int32, which Miles puts at roughly 60 MB per sample for a 32K-token sequence with 60 layers and a top-k of 8. That is per sample, so a batch of a few hundred means tens of gigabytes of routing metadata moving from the engine to the trainer every step. To find this one without turning the fix on, Miles's CI checker recomputes the top-k in the trainer, compares it against the recorded indices token by token, and fails when too large a fraction has no overlap at all. Afterwards, watch that mismatch fraction, and watch `train_rollout_kl`, which on an MoE model should fall sharply when replay is turned on. If it does not fall, the mismatch was never the routing. ## 4. Bug 3: The Rollout Runs in a Lower Precision Than the Trainer This one looks like a mismatch that does not go away when you fix the kernels. `train_rollout_kl` settles at a floor instead of at zero, and the floor is larger than a bf16 engine would give you. It happens because serving a 4-bit or 8-bit copy of the model is how the rollout gets fast enough to be worth doing, and quantizing the weights changes the function. The question is by how much, relative to the kernel noise we have already measured, so I measured that too. The trainer keeps bf16 weights, the rollout gets the same weights rounded into a format and rounded back, which is what an online quantizer does to them, and both score the same 256-token response. The two formats are the ones the inference stacks actually use: FP8 in E4M3 with one fp32 scale per 128 x 128 block of the weight, which is the layout DeepSeek ships and SGLang loads, and NVFP4 in E2M1 with one FP8 scale per 16 values along the input dimension plus one fp32 scale for the tensor. The NVFP4 round trip is short enough to write out, and it is a good way to see where the error comes from, since E2M1 has only sixteen representable values: ```python torch.manual_seed(0) levels = torch.tensor([0, .5, 1, 1.5, 2, 3, 4, 6]) # E2M1, positive half w = torch.randn(64, 256) x = w.view(64, -1, 16) # one scale per 16 values gscale = x.abs().amax() / (6.0 * 448.0) # per tensor, fp32 bscale = (x.abs().amax(-1, keepdim=True) / 6.0 / gscale).to( torch.float8_e4m3fn).float() * gscale # per block, fp8 y = x / bscale.clamp_min(1e-12) idx = (y.abs().unsqueeze(-1) - levels).abs().argmin(-1) q = levels[idx] * y.sign() * bscale err = (q.view_as(w) - w).abs() print(round(float(err.max() / w.abs().max()), 4), # worst single weight round(float(err.pow(2).mean().sqrt() / w.std()), 4)) # typical weight # 0.1424 0.0954 ``` On Gaussian weights that comes out at about 10% of a standard deviation for a typical weight, with the worst one off by 14% of the largest weight in the tensor. Two things make it worse than the sixteen levels alone suggest: the block scale is itself stored in FP8, so it is rounded too, and a block whose largest value lands just above a representable scale loses its top values to clipping.  *Figure 6: Mean absolute per-token log-probability difference between a bf16 trainer and a quantized rollout, against the difference the batch shape alone produces.* As Figure 6 shows, FP8 block-wise over every linear layer gives a mean difference of 2.34 x 10^-2, which is 3.5 times the 6.6 x 10^-3 that the batch shape produced on its own, and NVFP4 gives 7.65 x 10^-2, which is 12 times. The tails move further than the means. Under FP8 the worst token's importance weight is 2.36 and 0.39% of tokens fall outside a band of 0.5 to 2.0, and under NVFP4 the worst is 2.72 and 2.73% of tokens fall outside that band. One token in forty is outside a 2x clip before a single optimizer step has happened. Two things keep those numbers a floor rather than a measurement of any shipping kernel. I quantized the weights only, and a real engine quantizes the activations too. And Qwen3-8B is dense, so nothing here says anything about what quantizing a router does, which section 3 suggests is the more dangerous place to do it. The fix is to match the two sides, or to budget for the gap. Miles publishes a compatibility matrix that reads as a statement of what is known to work: a BF16 rollout only pairs with BF16 training, an FP8 block-wise rollout pairs with BF16 or FP8 training, an MXFP8 rollout pairs with BF16 or MXFP8, and an NVFP4 rollout pairs only with NVFP4 training. The cheapest configuration of all, BF16 training with an FP8 engine, is the one the same page warns about, since "there is precision drift between the two paths; on MoE workloads, pair this with R3 (and optionally TIS)." To find it, compare `train_rollout_kl` between an otherwise identical bf16 rollout and the quantized one, and see whether the floor moves. Afterwards, keep watching the same metric but change the alert, because a quantized rollout has a floor and alerting on its absolute value will page you every step. Alert on a change in the floor instead. ## 5. Bug 4: Every Sequence Gets the Same Weight, However Long It Is Here the symptom is that response length drifts and nobody asked it to. Usually they get shorter, which on a reasoning task is the opposite of what you want. It happens because the loss is a sum over response tokens and the default reducer divides each response by its own token count before summing. Miles's version has exactly two branches: ```python # excerpt, cut down from miles/.../data/context_parallel.py # get_sum_of_sample_mean @ b7b2870daf def sum_of_sample_mean(x): # the default return sum((x_i * mask_i).sum() / torch.clamp_min(denom_i, 1) for x_i, mask_i, denom_i in zip(x.split(response_lengths), loss_masks, denominators)) def sum_of_token(x): # with --calculate-per-token-loss return sum((x_i * mask_i).sum() for x_i, mask_i in zip(x.split(response_lengths), loss_masks)) ``` The first gives every response the same total weight, and the second gives every token the same weight, with the division by the global token count happening outside. The difference is larger than it sounds, and the easiest way to see it is to put a realistic batch through both and take the gradient from autograd rather than reasoning about it. I used eight response lengths with the long tail a reasoning rollout produces, from 48 to 2,048 tokens, 3,733 tokens in total. ```python lengths = [48, 61, 95, 128, 240, 311, 802, 2048] logp = [torch.zeros(n, requires_grad=True) for n in lengths] sum(-z.sum() / n for z, n in zip(logp, lengths)).backward() # sample mean sample = [z.grad[0].item() for z in logp] for z in logp: z.grad = None (sum(-z.sum() for z in logp) / sum(lengths)).backward() # token mean token = [z.grad[0].item() for z in logp] print(round(sample[0] / sample[-1], 1)) # 42.7 print(round(token[0] / token[-1], 1)) # 1.0 ```  *Figure 7: The same batch of eight responses under the sample mean and under the token mean. In each panel the left bar is the token count and the right bar is the share of the gradient.* Figure 7 puts the same thing at the level of the whole batch. Under the sample mean, the 2,048-token response holds 54.9% of the batch's tokens and receives 12.5% of the gradient, because 12.5% is one eighth and there are eight responses. Under the token mean it receives 54.9%. Per token, as the snippet prints, one token of the shortest response carries 42.7 times the weight of one token of the longest. Neither reducer is wrong, since they are different objectives, and the literature disagrees about which to use. DAPO's paper states the case for the token mean directly: "Since all samples are assigned the same weight in the loss calculation, tokens within longer responses (which contain more tokens) may have a disproportionately lower contribution to the overall loss, which can lead to two adverse effects." Dr.GRPO identifies the same division as "an optimization bias in GRPO" that "artificially increases response length (especially for incorrect outputs) during training". What is wrong is not knowing which one your run uses, because the choice silently decides whether a long response is worth more or less than a short one. To find it, plot the response-length distribution rather than its mean and watch whether it drifts in the first few hundred steps, then go and read the reducer. The fix is to pick the one you meant. Miles exposes the token mean as a flag and ships Dr.GRPO's version as a plugin, which is a reducer that divides by a constant rather than by any token count at all: ```python # excerpt, cut down from miles/examples/experimental/DrGRPO/custom_reducer.py DIVISOR = 1000.0 def sum_of_sample_mean(x): return sum((x_i * loss_mask_i).sum() / DIVISOR for x_i, loss_mask_i in zip(x.split(response_lengths), loss_masks)) ``` Megatron applies the other half of whatever you chose, inside its pipeline schedule, and the comment there flags a third edge case that section 7 is about: `output_tensor /= torch.clamp(num_tokens, min=1)` exists to "protect against division by zero when all tokens are masked in a microbatch". Afterwards, watch the mean response length together with the length distribution and the fraction of responses that hit the generation limit. ## 6. Bug 5: Each Rank Divides by Its Own Token Count The symptom for this one is nothing at all. The loss looks the same, the gradient norm looks the same, and the run is slightly wrong forever. It happens because each data-parallel rank computes a loss over its own samples and data-parallel training then averages the ranks' gradients. If each rank divided by its own token count, a rank that happened to draw short responses has divided by a smaller number, so every one of its tokens pushes harder on the weights than a token on a rank that drew long ones. prime-rl's trainer says this in a comment above the fix, and it is the clearest statement of the bug I found in any of these repositories: > With a per-rank denominator, ranks with fewer loss tokens implicitly upweight their per-token gradient contribution after FSDP averaging. The size of the effect is whatever the imbalance is. I ran two gloo ranks holding 100 and 900 response tokens, which is an ordinary amount of skew when responses run from 48 to 2,048 tokens, and measured a token on the small rank being worth 9.0 times a token on the large one.  *Figure 8: The same two ranks under a per-rank denominator and under a global one.* The bottom row of Figure 8 is the fix, and the only thing it adds to the step is one collective of three scalars. Both ranks end up dividing by 1,000 instead of by 100 and 900, so a token is worth the same on both, and the ratio between them is exactly 1.0 rather than 9.0. ```python # excerpt, cut down from prime-rl/src/prime_rl/trainer/rl/train.py @ f3827c4ed local_rl_scale = sum(int(mb["loss_mask"].sum()) for mb in micro_batches) global_scales = torch.tensor( [local_rl_scale, local_ce_scale, local_ref_kl_scale], dtype=torch.float64, device="cuda") dist.all_reduce(global_scales, op=dist.ReduceOp.SUM, group=dp_cp_group) rl_scale, ce_scale, ref_kl_scale = ( s if s > 0 else 1 for s in global_scales.tolist()) ``` Two details in that snippet are the ones to copy. The three scales go into one tensor so that every rank issues the same collective whether or not its samples carry all three loss components, which is the same class of problem as the next section. And the reduction is in float64, because a token count summed over a thousand ranks is a number you want to be exact. Miles arrives at the same place from the other direction, by normalizing on the step's rollout count, which every rank already knows without a collective. To find it, log the per-rank response-token count every step and watch the ratio between the largest and the smallest. If that ratio is ever far from one and the denominator is local, the gradient is being reweighted by it. ## 7. Bug 6: A Rank With No Tokens Skips Backward This one hangs. Nothing is printed, and half an hour later the NCCL watchdog fires and the job dies with a timeout on a collective whose name looks unrelated to anything you changed. It happens because collectives are matched by the order in which every rank issues them, and not by name. A rank whose micro-batch is empty after masking, and whose loss function returns early because there is nothing to compute, never runs backward, so it never issues the gradient reduction that every other rank is already waiting at. Empty micro-batches are ordinary rather than exotic. A dynamic-sampling filter can remove every group a rank was holding, truncation can leave a sample with no response tokens inside the loss mask, and context parallelism splits a sequence across ranks, so a short sequence split eight ways leaves some of them with nothing. Miles's own type documentation says so directly: with context parallelism a sample's local length "can be zero and can differ across ranks". I reproduced it with two gloo processes and an eight-second group timeout, so that it fails in seconds rather than in half an hour. With the early return, rank 1 reported that it had returned without running backward and rank 0 died inside the gloo transport. With the fix below, both ranks finished and agreed on the gradient.  *Figure 9: Left, the rank with no tokens returns early and the other rank waits at a collective that will never be matched. Right, a zero-valued term keeps the empty rank in the graph.* The one thing my reproduction gets wrong is the failure mode in Figure 9. gloo runs over TCP, so when the other process exited the socket closed and rank 0 got an error straight away. NCCL has no equivalent signal, and the surviving ranks sit inside the collective until the watchdog timeout fires, which is the difference between an error you can read and a job that stops for half an hour. The fix is to give the empty rank a loss that is zero but still attached to the graph, so that backward runs and the collectives line up. Both frameworks do it in one line. In Miles the reducer is a Python `sum` over a list of per-sample terms, so an empty micro-batch makes the loss a plain integer with no graph behind it at all: ```python per_sample = [] # this rank's micro-batch is empty loss = sum(per_sample) # builtin sum of an empty list, so: int 0 print(type(loss).__name__, hasattr(loss, "backward")) # int False logits = torch.randn(4, 7, requires_grad=True) loss = loss + 0 * logits.sum(dtype=torch.float32) # the anchor loss.backward() # now this rank runs backward print(float(logits.grad.abs().sum())) # 0.0 ``` That is the whole mechanism, and both repositories explain their version in the comment above it. Miles writes "make sure the gradient could backprop correctly; fp32 sum avoids fp16 inf -> nan" in the loss, and "forces autograd to traverse the full graph on every rank to avoid hang" in the dispatcher where context parallelism is involved. prime-rl names the pattern: > Graph anchor: a micro batch whose components are all empty (e.g. a fully truncated distillation sample, whose stamped streams survive as all-zero prefixes) must still return a backward-able loss so every rank runs backward and FSDP collectives stay in sync. The `dtype=torch.float32` in Miles's version is not decoration. A sum over a vocabulary-sized fp16 tensor can overflow to infinity, and zero times infinity is a NaN, so the anchor meant to save the step would poison it instead. To find it, log the minimum number of loss-mask tokens over ranks per micro-batch. Once the hang has already happened, `NCCL_DEBUG=INFO` together with `RAY_DEDUP_LOGS=0` will show which ranks reached the collective and which did not. ## 8. Bug 7: The KL You Are Logging Is Not a KL The symptom is a KL metric that goes negative, or one that jumps around so much between steps that you cannot tell whether a change you made helped. It happens because a KL divergence is an expectation over a whole distribution and during training we have one sample from it per token. There are three standard estimators for that, all from Schulman's note on the subject, and the frameworks implement all three behind a string: ```python # excerpt, cut down from miles/.../loss/hub/math_utils.py:compute_approx_kl log_ratio = log_probs.float() - log_probs_base.float() if kl_loss_type == "k1": kl = log_ratio elif kl_loss_type == "k2": kl = log_ratio**2 / 2.0 elif kl_loss_type in ["k3", "low_var_kl"]: log_ratio = -log_ratio kl = log_ratio.exp() - 1 - log_ratio ``` k1 is the definition and it is unbiased. It is also negative about half the time, because for any individual sample the ratio can fall either way and only its average over the distribution has to be positive. k3 is the one to use, and the reason is visible in a single experiment. I sampled 20,000 tokens from a 16,384-way categorical whose logits have the scale of a real logit row, and from a second distribution made by nudging those logits, so that the true KL is known in closed form and every estimator can be scored against it.  *Figure 10: Mean and standard deviation of the three estimators over 20,000 samples, against the true KL marked by the dashed line.* As Figure 10 shows, with a true KL of 1.82 x 10^-4, k1's mean over 20,000 samples is 4.98 x 10^-4, so it is still off by a factor of nearly three, and its standard deviation is 1.90 x 10^-2, which is 104 times the quantity it is estimating. k3's mean is 1.808 x 10^-4, within one percent of the truth, with a standard deviation of 2.42 x 10^-4. k2 is just as tight here and is slightly biased by construction, and k3 is the one that stays unbiased as the two distributions move apart, so it is the default. The same comparison runs in a second on a smaller distribution, with the true KL again in closed form: ```python torch.manual_seed(0) logits = torch.randn(512) * 2.6 p = torch.softmax(logits, 0) q = torch.softmax(logits + torch.randn(512) * 0.5, 0) true_kl = (p * (p.log() - q.log())).sum() idx = torch.multinomial(p, 200_000, replacement=True) lr = p[idx].log() - q[idx].log() # one sample's log-ratio, drawn from p k1, k3 = lr, (-lr).exp() - 1 + lr print(round(float(true_kl), 4), round(float(k1.mean()), 4), round(float(k3.mean()), 4)) print(round(float(k1.std()), 3), round(float(k3.std()), 3), int((k1 < 0).sum()), int((k3 < 0).sum())) ``` On the measured Qwen3-8B pair from section 2 the difference is not subtle at all. Over the same 256 tokens, k1 sums to -1.03 and k3 sums to +0.156, from the same two vectors of numbers, and one of the two answers is negative. So the way to find this is to look at the sign: if your KL metric is ever negative, it is k1. The fix is to use k3 for anything you read, even where the loss uses something else, and to clamp it. Miles's `low_var_kl` is k3 with the log-ratio clamped before the exponential and the result clamped to [-10, 10] afterwards, which matters because `exp` of a large log-ratio is how a metric becomes an `inf` and then a NaN that propagates into the loss. There is one more wrinkle, which comes up as soon as you run off-policy: when the samples come from a different policy than the one you are measuring, the estimator needs an importance correction, and Miles has it behind `--use-unbiased-kl`, multiplying the per-token KL by `exp(log_probs - old_log_probs)` and attributing the idea in the code to DeepSeek-V3.2. ## 9. Bug 8: The Clip Is Symmetric, So Entropy Falls The symptom is that entropy falls steadily, the samples within a group become identical, and the reward curve flattens while more rollouts stop helping, because every rollout now says the same thing. It happens because the PPO clip is a brake that works on one direction at a time, depending on the sign of the advantage. For a token with a positive advantage the clip stops the loss from rewarding any ratio above `1 + eps`, so once that token's probability has risen twenty percent there is no more gradient pushing it up. For a token with a negative advantage the clip stops at `1 - eps` on the other side. Figure 11 draws both.  *Figure 11: The per-token surrogate loss against the importance ratio, for a positive and a negative advantage, with a symmetric clip, a raised upper bound, and a dual clip.* As Figure 11 shows, the asymmetry is in what the two sides are doing to the distribution. Suppressing a token that is already rare is unbounded work, since a token at ratio 0.1 still has somewhere to fall, while promoting a token that is already likely stops at `1 + eps`. DAPO's paper describes the same effect from the exploration side: "the upper clip can restrict the exploration of the policy, where making an 'exploitation' token more probable is much easier yet the probability of an unlikely 'exploration' token is too tightly bounded to be uplifted." The net effect of a symmetric clip is that it is easier to make the distribution narrower than wider, and narrower is where entropy collapse comes from. DAPO's answer is to raise the upper bound on its own, which the frameworks call clip-higher, and Miles exposes it as a second threshold: ```python # excerpt, cut down from miles/.../loss/hub/math_utils.py:compute_policy_loss pg_losses1 = -ratio * advantages pg_losses2 = -ratio.clamp(1 - eps_clip, 1 + eps_clip_high) * advantages clip_pg_losses1 = torch.maximum(pg_losses1, pg_losses2) if eps_clip_c is not None: # dual clip, for A < 0 only pg_losses3 = -eps_clip_c * advantages clip_pg_losses2 = torch.min(pg_losses3, clip_pg_losses1) pg_losses = torch.where(advantages < 0, clip_pg_losses2, clip_pg_losses1) ``` The default for `eps_clip` is 0.2 and `eps_clip_high` is unset, which leaves the clip symmetric unless you ask otherwise. Miles's shipped recipes do ask, and several of them, including the GPT-OSS and MiMo ones, run `--eps-clip 0.2 --eps-clip-high 0.28`, which is the pair DAPO's paper uses. What that buys is visible by differentiating the surrogate at a ratio the symmetric clip has already given up on: ```python def surrogate(ratio, adv, eps_low=0.2, eps_high=0.2): r = ratio.clone().requires_grad_() loss = torch.maximum(-r * adv, -r.clamp(1 - eps_low, 1 + eps_high) * adv) loss.sum().backward() return r.grad r = torch.tensor([1.25]) # already 25% above the old policy print(float(surrogate(r, adv=torch.tensor([1.0])))) # 0.0 print(float(surrogate(r, adv=torch.tensor([1.0]), eps_high=0.28))) # -1.0 ``` The third threshold in the Miles excerpt above, `eps_clip_c`, is the dual clip, and it fixes the other side. When an advantage is negative and the ratio has grown large, `-ratio * A` grows without bound and one token can take over the batch, so the dual clip caps the loss at `eps_clip_c` times the advantage, with an assertion that `eps_clip_c > 1.0` so that it only ever bites outside the ordinary clip range. There is a sequence-level version of the same idea in the same file: `compute_opsm_mask` drops a whole sequence when its mean log-ratio exceeds a threshold *and* its advantage is negative, which is a more surgical way of saying that a trajectory the policy has already moved away from should not be punished again. To find this, plot entropy. Miles's CI asserts that rollout entropy at the start of a run is in `(0, 0.7)`, which is a useful anchor for what normal looks like on an instruct model. Then plot `pg_clipfrac` split by the sign of the advantage, because the aggregate number hides which side is doing the clipping, and count the distinct responses per group. ## 10. Bug 9: The Group's Advantage Is Divided by the Group's Standard Deviation The symptom is a run that spends more of its gradient on prompts it has already settled, in either direction, than it would without the division, and correspondingly less on the ones it still gets right about half the time. It happens because GRPO takes a group of responses to the same prompt, subtracts the group's mean reward, and, in the published form, divides by the group's standard deviation. Miles does exactly that, behind a flag whose help text is a link to the Dr.GRPO paper: ```python # excerpt, cut down from miles/ray/rollout/train_data_conversion.py @ b7b2870daf normalized = rollout_rewards - rollout_rewards.mean() if args.advantage_estimator in ["grpo", "gspo"] \ and args.grpo_std_normalization and len(rollout_rewards) > 1: std = rollout_rewards.std() if std > 0: normalized = normalized / (std + 1e-6) ``` The division is what Dr.GRPO objects to, and the arithmetic is small enough to do once by hand. Take three groups of eight responses with binary rewards: one that got seven right, one that got four, and one that got one. ```python groups = {"7 of 8": [1.0] * 7 + [0.0] * 1, "4 of 8": [1.0] * 4 + [0.0] * 4, "1 of 8": [1.0] * 1 + [0.0] * 7} for name, r in groups.items(): g = torch.tensor(r) centred = g - g.mean() scaled = centred / (g.std() + 1e-6) print(name, round(float(g.std()), 3), round(float(centred.abs().sum()), 3), # the group's pull, raw round(float(scaled.abs().sum()), 3)) # and after the division ``` Without the division, the balanced group pulls 4.0 against 1.75 for either lopsided one, so it contributes 2.3 times as much, and that is the ordering you want, since the prompt the model solves half the time is the one a gradient can still move. After the division the gap closes to 7.48 against 4.95, or 1.5 times. What happened is that each group was multiplied by one over its own standard deviation, which is 1.87 for the balanced group and 2.83 for the lopsided ones, so the division moved weight away from the prompts the model is still learning and onto the ones it has already settled, in either direction. That is what Dr.GRPO means when it calls the division "an optimization bias in GRPO". The special case at the end of that excerpt is a second and smaller bug. A group where every response got the same reward has zero standard deviation, and also zero advantage once the mean is subtracted, so it contributes nothing to the gradient while having cost a full group of generation. Miles filters those out before training: ```python # excerpt, cut down from miles/rollout/filter_hub/common_filters.py @ b7b2870daf keep = torch.tensor(rewards, dtype=torch.float64).std() > 1e-8 return FilterOutput(keep=keep, reason=None if keep else f"zero_std_{rewards[0]}") ``` The reason string records whether the group was all-right or all-wrong, which is the more useful number of the two: a rising all-wrong fraction means the prompts are too hard, and a rising all-right fraction means they are too easy. So the way to find both of these is to plot the distribution of group accuracy rather than its mean, together with the fraction of groups the filter removed, split by which end they came from. The fix for the first is `--disable-grpo-std-normalization` if you want Dr.GRPO's version, keeping the mean subtraction either way, since that is what makes the estimator a baseline rather than a reward. ## 11. Bug 10: The Old Policy Is Not the Policy That Generated the Tokens The symptom is that a synchronous run is fine and an asynchronous one drifts, with the clipped fraction climbing as you let more generation stay in flight. It happens because in an asynchronous run a trajectory is generated under one set of weights and trained on under a later one, which is the whole point, since the engines never wait for a training step. The trap is that the ratio's denominator is computed by default from the *current* actor rather than from the weights that did the sampling, so the clip, which exists to keep the update inside a trust region around the behaviour policy, is anchored to a policy that never produced the data. Miles refuses to start an asynchronous PPO run without an explicit answer to this, and the assertion it raises is also the list of fixes, so here it is in full: > Async PPO training requires an explicit behavior-policy correction, because rollouts are generated before the current weight update while log probs are recomputed by the current actor by default. Pass one of: `--use-rollout-logprobs` (use the rollout engine's log probs as the ratio denominator), `--use-tis` (truncated importance sampling correction), or `--keep-old-actor` (recompute the denominator with the weights the rollout engines used). The docstring above it adds the part that makes this silent rather than loud. Doing nothing "silently anchor[s] clipping (and KL-shaped advantages) to a policy that never generated the trajectory; the recorded `weight_versions` are a metric, not an enforcement mechanism." The first of those three fixes is the one that connects this section back to the first. If the ratio's denominator is the engine's own log-probabilities, then the ratio is already a correct importance weight for the staleness and the kernel mismatch at the same time, which is why Miles makes `--use-rollout-logprobs` and `--use-tis` mutually exclusive: switching both on would apply the correction twice. To find it, bound the staleness and see whether the drift goes away. Staleness is the gap between a group's weight version and the engines' current version, and Miles reports it several ways, including a token-weighted average, because a long trajectory spans more weight versions than a short one. The bound, `--max-weight-staleness`, is unset by default, which means that out of the box nothing stops a group from being arbitrarily old. Afterwards, watch `token_weighted_staleness`, `pg_clipfrac`, and the effective sample size. The last of the three is the sharpest instrument, and Miles computes it from the per-token importance weights with the comment that a value of 1.0 is on-policy while a value near 0 means the weights have become concentrated on a few tokens. For reference, the batch-shape mismatch from section 2 on its own gives an effective sample size ratio of 0.9992, so anything meaningfully below 1 is staleness rather than kernels. ## 12. What to Put on the Dashboard Nine of the ten bugs above are visible in a number that the frameworks already compute, so here they are in one place. At step 0 of a synchronous run, assert rather than plot: `ppo_kl` is zero to 10^-9, `pg_clipfrac` is zero, `kl_loss` is zero, the trainer's log-probs match the reference's, and rollout entropy is in (0, 0.7). Miles turns all of these on with `--ci-test`, and each has an escape hatch for the case where your change makes it legitimately not hold. Every step after that, watch seven things: `train_rollout_kl` for the gap between the trainer and the engine, `ess_ratio` for how far off-policy you are, `pg_clipfrac` split by the sign of the advantage, `entropy_loss`, the response-length distribution, the per-rank token counts as a largest-over-smallest ratio, and the fraction of groups the filters removed. When one of them moves and you do not know why, cut the loop in half before doing anything else. Record a rollout with `--debug-rollout-only --save-debug-rollout-data`, then train from the recording with `--load-debug-rollout-data`. Miles's guide explains why that is the first step rather than a later one: it "removes sampling randomness from the loop, which is what makes a bisect or an A/B of a loss change trustworthy." Two more tools are the ones to learn about before you need them. `--ci-inject-rollout-data-path` keeps the engines running and compares their fresh generation against a recording, failing when the token match ratio drops below 0.9, which is how you catch engines holding the wrong weights after a sync; the same guide notes that "legitimate ulp-level drift only flips the occasional sampled token, so the ratio stays high when the sync is correct." And `--ci-save-model-hash` writes a SHA256 per layer including the name, shape and dtype, so that a weight mismatch names a layer instead of just saying that the model differs. What all ten have in common is that an RL trainer is two implementations of one model that have to agree, plus a sum whose denominator nobody wrote down. The measurements in this article took an afternoon on one GPU, and every one of them is a thing a trainer could be computing on every step. Most of the work of making a run trustworthy is making those two things observable, and most of these bugs were found by somebody who added the metric first. ## Sources - Miles, the RL post-training framework most of the code above comes from: https://github.com/radixark/miles - prime-rl: https://github.com/PrimeIntellect-ai/prime-rl - Megatron-LM: https://github.com/NVIDIA/Megatron-LM - SGLang: https://github.com/sgl-project/sglang - John Schulman, Approximating KL Divergence: http://joschu.net/blog/kl-approx.html - Thinking Machines' batch-invariant kernels, which SGLang's are adapted from: https://github.com/thinking-machines-lab/batch_invariant_ops - Understanding R1-Zero-Like Training, the Dr.GRPO paper: https://arxiv.org/abs/2503.20783 - DAPO: An Open-Source LLM Reinforcement Learning System at Scale: https://arxiv.org/abs/2503.14476 - Rollout Routing Replay: https://arxiv.org/abs/2510.11370 - Your Efficient RL Framework Secretly Brings You Off-Policy RL Training: https://fengyao.notion.site/off-policy-rl