Skip to content

Average GRPO gradients across DDP ranks, and keep MiniCPM3's pre-head scaling - #12193

Merged
danielhanchen merged 6 commits into
mainfrom
grpo-minicpm3-ddp-head
Sep 29, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
grpo-minicpm3-ddp-head

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

Summary

Two GRPO defects on main, both in the hidden-state loss path:

  1. Multi-GPU GRPO never averages gradients. zoo's grpo_accumulated_loss runs the gradient-bearing forward on unwrapped_model(...), which bypasses DistributedDataParallel.forward. The reducer is never armed, so backward never all-reduces and every rank trains its own copy of the model on its own data. Nothing errors.
  2. MiniCPM3 trains a different objective when its forward is not compiled. MiniCPM3ForCausalLM.forward divides the hidden states by config.logits_scaling right before lm_head. The compiled forward returns them after that line and is correct, but the uncompiled hidden-state wrapper returns outputs.hidden_states[-1], which is before the division. The policy and reference log-probs were then computed from logits logits_scaling times too large. This path is used for a plain transformers model, a reference model, or UNSLOTH_COMPILE_DISABLE=1.

Changes (unsloth/models/rl.py)

  • _wrap_grpo_ddp_gradient_sync: wraps the generated GRPO trainer's training_step. After the step, when the model is DDP-wrapped, the world size is above 1, ddp.require_backward_grad_sync is set (the micro-step where DDP itself would reduce; it is False inside no_sync()), and DDP.forward did 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 through DDP.forward is left alone, so nothing is averaged twice.
  • Hidden-state wrapper: for model_type == "minicpm3" it now divides by logits_scaling, as the model's own forward does.
  • Hidden-state wrapper: on the first call per model it checks that the head applied to the returned hidden states reproduces the forward's own last-position logits, using the transforms from 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 not hidden_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_sync and the max abs difference of per-parameter sums across ranks after training:

cell main this branch
full fine-tuning, gradient checkpointing off False, 65.1 True, 0.0
full fine-tuning, gradient checkpointing on False, 65.1 True, 0.0
LoRA False, 0.113 True, 0.0
LoRA, ddp_find_unused_parameters=False False, 0.113 True, 0.0
LoRA, ddp_find_unused_parameters=False, gradient accumulation 2 False, 0.141 True, 0.0

Control: 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 dense log_softmax(model(...).logits) computed under the same bf16 autocast:

main this branch
max abs per-token logp error 17.54 0.016 (bf16 rounding at logits up to 28)
tiny Qwen3 control 5.2e-4 5.2e-4

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:

run main this branch
full finetuning out of sync, 410.5 in sync, 0.0
LoRA out of sync, 0.068 in sync, 0.0
full finetuning, gradient checkpointing in sync, 0.0

Gradient values: on fixed inputs, Unsloth's GRPO gradients match stock TRL's compute_loss to 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 through DDP.forward is not averaged twice, and a no_sync micro-step keeps local grads.
  • The GRPO / RL / GKD test files together: 114 passed, 6 skipped.

Notes

  • Single-GPU runs are unchanged: the sync only runs when the model is DDP-wrapped with world size above 1, and the MiniCPM3 division only runs in the uncompiled wrapper for that model type.
  • Not in this PR: Unsloth's SFTTrainer with LoRA under DDP raises Expected to mark a variable ready only once unless ddp_find_unused_parameters=False is set, which is the setting the multi-GPU docs already give.

@danielhanchen danielhanchen self-assigned this Sep 28, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-28T13:20:58.386274Z 4703b59 Manual request
🔒 Security Review ✅ Completed 2026-09-28T11:39:51.145367Z 7163ac6 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 7163ac610e

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth/models/rl.py
chunk[0].div_(world_size)
start = stop
continue
flat = torch.cat([g.reshape(-1) for g in chunk])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: ae7a8d5c8a

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 4703b59e3a

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 1c9bf9f into main Sep 29, 2026
22 of 32 checks passed
@danielhanchen
danielhanchen deleted the grpo-minicpm3-ddp-head branch September 29, 2026 12:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant