Repository navigation
Average GRPO gradients across DDP ranks, and keep MiniCPM3's pre-head scaling - #12193
Conversation
…scaling in the hidden-state fallback
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex security review |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
…er tests the new helpers
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ec47de1f6e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| chunk[0].div_(world_size) | ||
| start = stop | ||
| continue | ||
| flat = torch.cat([g.reshape(-1) for g in chunk]) |
There was a problem hiding this comment.
Handle sparse gradients before flattening buckets
When a GRPO model has a trainable Embedding(..., sparse=True) or another parameter producing a sparse gradient, this flattening path calls reshape on a sparse tensor and raises instead of synchronizing it. If that gradient exists on only some ranks, the zero-filled ranks may even proceed with a dense gradient while another rank raises, leaving peers blocked in the collective. DDP supports sparse embedding gradients, so these gradients need a layout-aware reduction path rather than the dense torch.cat bucket.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reachable: sparse gradients only come from nn.Embedding(sparse=True), and no transformers model, unsloth or unsloth_zoo module constructs one, so GRPO never sees a sparse grad.
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Summary
Two GRPO defects on main, both in the hidden-state loss path:
grpo_accumulated_lossruns the gradient-bearing forward onunwrapped_model(...), which bypassesDistributedDataParallel.forward. The reducer is never armed, sobackwardnever all-reduces and every rank trains its own copy of the model on its own data. Nothing errors.MiniCPM3ForCausalLM.forwarddivides the hidden states byconfig.logits_scalingright beforelm_head. The compiled forward returns them after that line and is correct, but the uncompiled hidden-state wrapper returnsoutputs.hidden_states[-1], which is before the division. The policy and reference log-probs were then computed from logitslogits_scalingtimes too large. This path is used for a plain transformers model, a reference model, orUNSLOTH_COMPILE_DISABLE=1.Changes (
unsloth/models/rl.py)_wrap_grpo_ddp_gradient_sync: wraps the generated GRPO trainer'straining_step. After the step, when the model is DDP-wrapped, the world size is above 1,ddp.require_backward_grad_syncis set (the micro-step where DDP itself would reduce; it is False insideno_sync()), andDDP.forwarddid not run with grad during the step, it averages every trainable gradient over the DDP process group. The ranks first agree on which parameters have a gradient, and a parameter that has one on any rank is zero-filled elsewhere, as DDP does. The grads are all-reduced in 64 MiB buckets per device and dtype. A step that did go throughDDP.forwardis left alone, so nothing is averaged twice.model_type == "minicpm3"it now divides bylogits_scaling, as the model's own forward does.detect_logit_transforms. If they do not match, the model is marked unsafe, a warning is printed once, and every later call returns real logits. This catches any other architecture whose head input is nothidden_states[-1], instead of training on the wrong objective.Evidence
GRPO under DDP: 2 gloo ranks on one B200, tiny untied Qwen3, 3 steps, run on main and on this branch. The table shows
ranks_in_syncand the max abs difference of per-parameter sums across ranks after training:ddp_find_unused_parameters=Falseddp_find_unused_parameters=False, gradient accumulation 2Control: Unsloth's SFTTrainer run through the same launcher ends with the ranks identical (difference 0.0), so the harness does reduce when training goes through DDP.
MiniCPM3: tiny MiniCPM3 with
logits_scaling = 0.25, loaded with plain transformers into the Unsloth GRPO trainer, compared against denselog_softmax(model(...).logits)computed under the same bf16 autocast:On 2 real GPUs (Kaggle, 2 x Tesla T4, NCCL, fp16 autocast over fp32 weights, 3 steps), max difference of per-parameter sums across ranks after training:
Gradient values: on fixed inputs, Unsloth's GRPO gradients match stock TRL's
compute_lossto about 1e-6 (fp32) for grpo, bnpo, dr_grpo and dapo, and a batch split over micro-batches x gradient accumulation x ranks gives the same gradient as the whole batch on one GPU (bnpo additionally needs unslothai/unsloth-zoo#1498). Float32 GRPO on a T4 / V100 needs unslothai/unsloth-zoo#1499.Related: #3901.
Tests:
tests/python/test_grpo_hidden_states_pre_head.py: 2 tests, both fail on main and pass here.tests/python/test_grpo_ddp_gradient_sync.py: 2 spawned gloo ranks. It checks that a bypassing step leaves every rank with the exact mean of the local grads, a step throughDDP.forwardis not averaged twice, and ano_syncmicro-step keeps local grads.Notes
Expected to mark a variable ready only onceunlessddp_find_unused_parameters=Falseis set, which is the setting the multi-GPU docs already give.