Debug a GRPO Training Loop and Explain Ratio Drift
Machine LearningModel answerLast updated
Walk through a GRPO policy-gradient loop, identify three subtle implementation bugs, and explain why the importance-sampling ratio drifts from 1 even in an on-policy setup.
Setting the Scene
You are working on a reinforcement-learning-from-human-feedback (RLHF) pipeline that fine-tunes a large language model. The optimization algorithm is GRPO (Group Relative Policy Optimization), a critic-free variant of PPO in which the advantage baseline is derived from a group of completions sampled for the same prompt, rather than from a learned value network.
The loop is intended to be strictly on-policy: the same policy that generates the rollouts is immediately updated on them. Despite that intention, training is unstable and the importance-sampling ratios are behaving unexpectedly. Your job is to reason through the loop, surface the bugs, and explain the anomaly.
This is a discussion question. There is no code to run. A strong answer reasons precisely about the GRPO objective, autoregressive log-probability mechanics, and the difference between behavior that is expected by design versus behavior caused by an actual implementation mistake.
Useful clarifying questions to consider
Before diving in, think about which of these you would want to know:
- Is the reward per-completion (one scalar at the end) or per-step (a reward at every token)? The answer affects how advantages are broadcast across tokens.
- How many optimizer steps are taken per rollout batch — one, or multiple minibatch epochs PPO-style? This fundamentally changes whether a ratio of exactly 1 is achievable.
- Is generation done through the same forward pass as the log-prob scoring, or through a separate fast-inference engine that recomputes log-probs in the trainer?
- Are the sampling hyperparameters (temperature, top-p, repetition penalty) identical between rollout generation and log-prob recomputation?
- Is there a frozen reference model for KL regularization, and is the KL penalty folded into the reward signal or kept as a standalone loss term?
- What numerical precision and attention backend is used on each path (bf16 vs. fp32, fused kernels vs. eager)?
Part 1 — The end-to-end GRPO training step
Describe one complete training iteration, touching on:
- Sampling prompts from the dataset.
- Generating a group of completions per prompt.
- Computing group-relative advantages (no value network involved).
- Forming the policy-gradient loss.
- Updating the model weights.
Part 2 — Three common, easy-to-miss bugs
Assume training is failing for implementation reasons. Name three bugs that are easy to overlook in a GRPO/PPO-style loop — drawn from areas such as log-prob computation, token masking, advantage normalization, or policy mixing.
For each bug, explain:
- how you would detect it in practice, and
- how you would fix it.
Part 3 — Why does the ratio drift from 1?
During debugging you observe that the importance-sampling ratio
$$ r_t = \exp!\bigl(\log \pi_\theta(a_t \mid s_t) - \log \pi_{\text{old}}(a_t \mid s_t)\bigr) $$
is not always 1, even though the setup is described as strictly on-policy.
List the most likely causes of this drift and, for each, describe what you would check in the pipeline to confirm it.
Hints
Hint 1
For Part 1, be precise about what 'group-relative' means: the advantage of a completion is its reward minus the mean reward of all completions for that same prompt, optionally normalized by their standard deviation. That normalization step is load-bearing — getting it wrong at the wrong granularity is one of the most common bugs.
Hint 2
For Part 2, think about the token-level mechanics of an autoregressive model. Log-probabilities are produced by the model over the full sequence, but only the *completion* tokens should contribute to the loss and to the advantage weighting. Prompt tokens leaking into the loss, or a shift-by-one indexing error when aligning logits to target token IDs, are both silent and damaging.
Hint 3
For Part 3, separate causes into two buckets: (a) things that make the ratio deviate 'by design' even in a correct implementation (e.g., multi-epoch updates), and (b) things that indicate a genuine mismatch bug (e.g., different sampling configs, precision differences, or accidentally using the updated weights to rescore old rollouts).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — One Full GRPO Training Step
Prompt sampling. Draw a batch of prompts from the dataset. Each prompt acts as the state s.
Rollout generation. For each prompt, sample G completions from the current policy using autoregressive decoding. These completions are stored along with the token IDs and, critically, the per-token log-probabilities produced at generation time — these become log π_old.
Group-relative advantage computation. Score each completion with the reward function (or reward model). For each prompt, compute the mean and standard deviation of its G rewards. The advantage of completion i is:
$$A_i = \frac{r_i - \text{mean}(r_{1..G})}{\text{std}(r_{1..G}) + \epsilon}$$
This is the "critic-free" core of GRPO: the group itself provides the baseline, so no value network is needed. The scalar advantage is then broadcast to every completion token in that response.
Loss computation. Re-score each stored completion with the current policy (the one about to be updated) to get log π_θ. Compute the per-token ratio r_t = exp(log π_θ - log π_old). The GRPO loss mirrors PPO's clipped objective:
$$\mathcal{L} = -\mathbb{E}_t!\left[\min!\left(r_t A_t,\ \text{clip}(r_t, 1-\epsilon, 1+\epsilon), A_t\right)\right]$$
Add a KL penalty against a frozen reference model if required, applied either as an extra loss term or folded into the reward before the advantage step.
Weight update. Back-propagate and step the optimizer. If only one optimizer step is taken per rollout batch, the ratio stays close to 1. Multiple epochs push it further from 1, which is fine as long as clipping is active.
Part 2 — Three Easy-to-Miss Bugs
Bug 1 — Prompt tokens included in the loss (masking error)
What goes wrong. The loss is computed over all tokens in the sequence, including the prompt. Because the prompt tokens are deterministic (the model didn't choose them), their gradients add noise and dilute the signal from the actual completion.
Detection. Log the per-token loss before reduction. You will see non-trivial loss on the first N_prompt tokens. Alternatively, check that the token mask zeros out everything before the first completion token.
Fix. Build a boolean mask that is 0 for prompt positions and 1 for completion positions. Apply it before summing the per-token loss and before summing log-probs for the ratio.
Bug 2 — Off-by-one in logit-to-token alignment
What goes wrong. An autoregressive model's forward pass returns one logit vector per input position. The logit at position t predicts the token at position t+1. A common mistake is computing log_softmax(logits) and then indexing it with the input token IDs rather than the target token IDs (shifted by one). This silently computes log-probabilities for the wrong tokens, making both log π_old and log π_θ wrong in a correlated way that is hard to catch without inspecting individual values.
Detection. On a trivially short sequence with a known token ID, manually verify that log_prob[t] equals log_softmax(logits[t])[token_id[t+1]]. Any mismatch exposes the shift error.
Fix. Use labels = input_ids[:, 1:] and logits = logits[:, :-1, :] before the gather step, and confirm the shapes are consistent throughout.
Bug 3 — Advantage normalization at the wrong granularity
What goes wrong. Normalizing advantages across the entire batch rather than within each prompt's group destroys the relative signal. If some prompts in the batch receive uniformly high rewards and others uniformly low rewards, batch-level normalization mixes those groups and the advantage no longer measures "how good was this completion relative to other completions for the same prompt."
Detection. Log the mean and std of rewards grouped by prompt. If you normalize after grouping, each group should have mean ≈ 0 and std ≈ 1. If you see groups where all advantages share the same sign after normalization, you are normalizing at the wrong level.
Fix. Compute mean and std per prompt (over its G completions), normalize within that group, and only then flatten into the batch for the loss computation.
Part 3 — Why the Ratio Drifts from 1
Expected by design: multiple update epochs
If more than one optimizer step is taken per rollout batch — a deliberate choice to amortize generation cost — the weights used to rescore the completions in later minibatches are already slightly different from the weights that generated them. The ratio will drift away from 1 proportionally to the number of gradient steps. This is intended; the clip in the objective exists precisely to handle it. Check: confirm the number of epochs per rollout; if it is > 1, ratio drift is expected and should be controlled by the clip range, not eliminated.
Separate generation and scoring paths with different configs
If rollouts are generated by a fast inference engine (e.g., vLLM, TGI) and log-probs are recomputed in a separate training process, any difference in sampling settings — temperature, top-p, fused vs. unfused attention kernels, even bf16 vs. fp32 accumulation — can produce different softmax outputs for the same weights. Check: log the raw logit values for the same prompt+token from both paths and compare them numerically. Any discrepancy with identical weights points to a config mismatch.
Weights have already been updated before rescoring
A subtle bug: the training code rescores the stored completions after calling optimizer.step() rather than before. The rescored log-probs are from π_θ_new, not π_old, so the ratio no longer measures anything meaningful. Check: assert that the rescoring forward pass runs before the optimizer step, or that the stored log π_old was written at generation time and is never recomputed.
Numerical precision differences
Even with identical weights and identical configs, recomputing log-probs in bf16 versus fp32 can shift softmax outputs enough to push ratios a fraction away from 1. This is typically benign but worth confirming. Check: run both paths in fp32 for a single batch and verify ratios collapse to 1 (up to floating-point rounding). If they do not, the issue is not precision — it is something structural from the causes above.
Common Mistakes to Avoid
- Treating a ratio that is "not exactly 1" as always a bug. Multi-epoch training should move the ratio; the clip keeps it safe.
- Normalizing advantages once globally and assuming that is correct.
- Forgetting that the KL term, if folded into the reward, changes the effective advantage values and should not also appear as a separate loss term — double-counting it biases the update.
- Using
suminstead ofmeanwhen reducing the per-token loss without accounting for variable sequence lengths, causing longer completions to dominate the gradient.