Repository navigation
FSDP2: initialize the root unit before a gathered generate runs the blocks - #17875
Conversation
…locks FSDP2 takes the first unit to run forward as its root. Under the sharded layout a GRPO rollout's decode loop calls the decoder blocks directly inside native_fsdp2_unsharded, so a block became its own root and the first training forward failed: 'FSDPCommContext' object has no attribute 'all_gather_copy_in_stream' on 2xT4 (Gemma3 1B GRPO, UNSLOTH_FSDP2_LAYOUT=sharded), or 'requires running forward through the root module first'. Lazily initialize the real root on entry; a no-op once a forward went through it.
Codex Review Summary: ✅ CompletedThis 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 review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
Every forward all-gathers there, so per-rank forward counts hang. Sequence packing and PrefixGrouper run self-verify forwards only on the rank whose packed length grew, and the no-grad padded loop sized its mini batch from the rank's own sequence length. On such a model turn packing and PrefixGrouper off and agree the mini batch (unsloth_zoo grpo_forwards_are_collective / grpo_agree_mini_batch). [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2bb9a36306
ℹ️ 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".
| if _grpo_collective_forwards: | ||
| # Sized from this rank's sequence length: agree, or the forward counts differ. | ||
| from unsloth_zoo.rl_replacements import grpo_agree_mini_batch | ||
| B = grpo_agree_mini_batch(B, input_ids.device) |
There was a problem hiding this comment.
Agree on row capacity before converting it to a chunk count
When ranks autotune different row capacities, the MIN agreement is applied to the inverse quantity: after B = total_rows // B, B represents the number of chunks, and the padded loop uses batch_size = ceil(total_samples / B). For example, with eight rows, capacities of one and four become chunk counts of eight and two; agreeing on two makes both ranks process four rows per forward, including the rank that could only accommodate one. This can turn otherwise viable sharded GRPO runs into OOM failures when completion lengths or available memory differ across ranks. Apply the MIN agreement to the autotuned row capacity before the conversion, or agree on the maximum chunk count instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right. The agreement lives in unsloth-zoo's grpo_agree_mini_batch, which this loop calls; unslothai/unsloth-zoo#2540 561facd2a switches it to the largest chunk count (MAX), so this rank never forwards more rows than it autotuned for.
|
@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". |
[skip ci]
…tive (FSDP2 sharded layout hang) (unslothai#2540) ## Problem GRPO under FSDP2's sharded layout (`UNSLOTH_FSDP2_LAYOUT=sharded`, or any model large enough that Unsloth shards the frozen base) hangs at step 2 on 2 GPUs. Under that layout every forward all-gathers, so every rank must run the same number of forwards. `grpo_accumulated_loss` sized its per-forward mini batch with `autotune_batch_and_chunks(total_rows, seq_len, ...)`, where `seq_len` is each rank's own completion length, so ranks could run a different number of chunked forwards and wait on each other's all-gather forever. With `TORCH_DISTRIBUTED_DEBUG=DETAIL` on Kaggle 2x T4, collective #424 showed rank 0 in an FSDP block all-gather inside the chunked loss forward while rank 1 was already in `accelerator.gather` past the loss. DDP and FSDP2's default fit layout issue no collectives inside a forward, so they were never affected. ## Fix - `grpo_forwards_are_collective(model)`: True when the world size is above 1 and some module re-shards after forward (`_unsloth_reshard_after_forward`, which Unsloth's FSDP2 sets per sharded unit). Cached on the model. - `grpo_agree_mini_batch(B, device)`: all-reduces the mini batch chunk count to the MAX across ranks, so no rank forwards more rows than it autotuned for. It runs only when forwards are collective, so DDP, the fit layout and single-process runs get no new collective. The unsloth side (unslothai/unsloth#17875) uses the same check to turn off GRPO sequence packing and PrefixGrouper, whose self-verify forwards ran only on the rank whose packed length grew, and to agree the no-grad scoring loop's mini batch the same way. ## Tests `tests/test_grpo_mini_batch_agree_gloo.py`: 2-rank gloo (chunk counts 4 and 2 agree on 4), sharded / fit / plain / single-process detection, and a source check that `grpo_accumulated_loss` agrees after autotuning. It fails on main and passes here. All `tests/test_*grpo*.py` pass (1062 passed, 19 skipped). Kaggle 2x T4 with unslothai/unsloth#17875: Gemma3 1B GRPO under the sharded layout crashes at step 1 on main, and with both PRs trains all 4 steps (83.5 s, single GPU 56.6 s, peak 3032 MiB). The probe on both ranks records collective forwards True and packing / PrefixGrouper off; the single-GPU run keeps packing on. Llama-3.2 SFT under the same layout stays at parity with one GPU (max loss diff 1.3e-4).
GRPO under the FSDP2 sharded layout crashed at its first loss forward with
AttributeError: 'FSDPCommContext' object has no attribute 'all_gather_copy_in_stream'.The sharded layout is chosen automatically once a model is larger than 40% of one GPU. A 16-bit Qwen3 4B GRPO run on T4s would likely land on it by default.
Root cause
FSDP2 makes whichever sharded unit runs a forward first the root. During the rollout, the model is gathered (
native_fsdp2_unsharded), and Unsloth's decode loop calls the decoder blocks directly, never the model's top-level forward. A block therefore initialised as its own root, and the next training forward through the real root failed. On CPU the same bug reads "FSDP requires running forward through the root module first".Fix
native_fsdp2_unshardedinitialises the real root unit (_lazy_init_root) before it gathers. It does nothing once a forward has already gone through the root.Results
tests/test_fsdp2_native_unsharded_block_calls_gloo.py(2 CPU ranks: blocks called inside the gathered context, then one training step)Gemma3_(1B)-GRPO.py,UNSLOTH_FSDP2_LAYOUT=shardedall_gather_copy_in_stream)Existing FSDP2 unsharded / units / optimizer re-entry tests: 42 passed, 5 skipped. The same 4
test_native_fsdp2_units_and_grads[Qwen2_5_VL|Qwen3VL-*]cases fail on main and with this PR.Step-2 hang under the sharded layout (second commit)
Under the sharded layout every forward all-gathers, so every rank must run the same number of forwards. GRPO broke that two ways: sequence packing and PrefixGrouper ran their no-grad self-verify forwards only on the rank whose packed length grew, and the padded scoring loop sized its mini batch from each rank's own sequence length. With
TORCH_DISTRIBUTED_DEBUG=DETAILthe ranks sat in different collectives (rank 0 in a block all-gather, rank 1 already in backward)._unsloth_grpo_refuse_rank_local_forwardsturns packing and PrefixGrouper off through the existing refusal flags, and the scoring loop agrees its chunk count across ranks (the largest, so no rank forwards more rows than it sized for), only when forwards are collective (grpo_forwards_are_collectivefrom unslothai/unsloth-zoo#2540: world > 1 and a unit re-shards after forward). DDP and FSDP2's default fit layout read False and are unchanged; the cost is that GRPO under the sharded layout uses the padded loop instead of packing.Kaggle 2x T4, main vs this PR + unslothai/unsloth-zoo#2540 (+ #17862 for the tokenizer save at the end of the notebook):
tokenizer.save_pretrained(#17862)AttributeErrorBoth ranks record collective forwards True with packing and PrefixGrouper off under the sharded layout, and False with packing on under the default layout.
tests/test_grpo_collective_forwards_nograd.pyfails without the change and passes with it; all 491tests/test_grpo*.pypass.Merge after unslothai/unsloth-zoo#2540 (without it the new check reads False and behaviour is unchanged).