Skip to content

FSDP2: initialize the root unit before a gathered generate runs the blocks - #17875

Merged
danielhanchen merged 3 commits into
mainfrom
fsdp2-root-lazy-init-before-gather
Nov 16, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
fsdp2-root-lazy-init-before-gather

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

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_unsharded initialises the real root unit (_lazy_init_root) before it gathers. It does nothing once a forward has already gone through the root.

Results

Check main This PR
tests/test_fsdp2_native_unsharded_block_calls_gloo.py (2 CPU ranks: blocks called inside the gathered context, then one training step) "already been lazily initialized for layers.0" passes; loss and grad norm match one process
Kaggle 2xT4, shrunk Gemma3_(1B)-GRPO.py, UNSLOTH_FSDP2_LAYOUT=sharded crashes in training (all_gather_copy_in_stream) fixed: all 4 steps train (with unslothai/unsloth-zoo#2540)
Kaggle 2xT4, Llama3.2 SFT, sharded layout passes, loss matches single GPU

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=DETAIL the ranks sat in different collectives (rank 0 in a block all-gather, rank 1 already in backward).

_unsloth_grpo_refuse_rank_local_forwards turns 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_collective from 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):

Run main This PR
Gemma3 1B GRPO, FSDP2 default layout 4 steps, then rank 1 fails in tokenizer.save_pretrained (#17862) passes; grad norm [0.9363, 0.6525] identical to main; packing stays on
Gemma3 1B GRPO, sharded layout step 1 AttributeError passes, all 4 steps; peak 3032 MiB
Llama3.2 SFT, default / sharded max loss diff vs 1 GPU 9e-5 / 6e-5 3e-5 / 5e-5

Both 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.py fails without the change and passes with it; all 491 tests/test_grpo*.py pass.

Merge after unslothai/unsloth-zoo#2540 (without it the new check reads False and behaviour is unchanged).

…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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T23:48:05.879216Z 2bb9a36 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 review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: b664e8ccb4

ℹ️ 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 marked this pull request as draft November 15, 2026 20:42
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]
@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: 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)

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

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.

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.

@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: 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".

[skip ci]
@danielhanchen
danielhanchen merged commit fea5cc8 into main Nov 16, 2026
@danielhanchen
danielhanchen deleted the fsdp2-root-lazy-init-before-gather branch November 16, 2026 01:11
danielhanchen added a commit to danielhanchen/unsloth-zoo-staging that referenced this pull request Nov 16, 2026
…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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant