Repository navigation
Conversation
|
@claude review this pr |
|
Claude finished @anshul-si's task in 2m 30s —— View job Approve -- please address the items before merging (empty human-written summary, unlinked flex_shard TODOs). See the review. A maintainer still needs to review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The fix is in the right layer: FlexShard gets the same partial-backward treatment of lm_head that FSDP2 has, the FSDP2 path is untouched, and the bitwise-parity evidence plus the reduce-scatter-count guard are convincing. This touches core code (training_engine.py, components/loss.py, distributed/fsdp*.py), so a maintainer still needs to review it.
What this PR does. ChunkedLossWrapper now passes the model to fsdp_partial_backwards as fsdp_root. When that root is a FlexShard module, the call goes to flex_shard_partial_backwards. That function turns off gradient sync and reshard-after-backward on lm_head's bucket for the duration of the chunks, then turns sync back on before the last chunk, unless grads kept from earlier microbatches should wait for the decoder backward. post_validate_fsdp_for_accelerator_graph also calls reshard() on the FlexShard root, which closes the bucket forward that forward-only validation leaves open. With all that in place, the config-time rejection of ChunkedLossWrapper is removed.
Example. Llama 3 debug model, 8 chunks, 1 microbatch, FlexShard:
before: config raises "does not support ChunkedLossWrapper"
(with the check lifted: each chunk does RS(lm_head) + AG -> 9 RS/step, not bitwise equal to FSDP2)
after: chunks 0-6 keep grads unsharded and unreduced; chunk 7 does RS(lm_head);
decoder backward does AG + RS(norm) -> 2 AG / 2 RS, same as FSDP2
Must fix
- PR description: the "Summary (human-written)" section is empty. The author needs to fill it in.
torchtitan/distributed/flex_shard_fsdp.py:347-- the new TODOs on private FlexShard state still have<flex_shard issue link>placeholders. File the issue and link it (inline comment).
Should consider
torchtitan/distributed/fsdp_lifecycle.py:84-- if a FlexShard caller leaves outfsdp_root, it silently falls back to the per-chunk RS/AG path. Raise there instead (inline comment).torchtitan/distributed/flex_shard_fsdp.py:338-- the frozen-decoder rejection fires during the first step. Move it tovalidate_flex_shard_trainingif the config can identify the case (inline comment).
Details
- Necessity: this is a real gap on the base. Stock recipes use
ChunkedLossWrapper, and FlexShard rejects it. Lifting the check alone gives per-chunk collectives and a different summation order. The fix lives in the distributed lifecycle helper, not in the trainer, so core stays oblivious to it. Other trainers (RL, graph_trainer, torchft) reject FlexShard outright, soTrainingEngineis the only consumer that needsfsdp_root. - Deferral check: FSDP2 defers when any group in any state has
_post_backward_pending. FlexShard checks only the head bucket'sneeds_sync. Under deferred accumulation, every bucket keeps grads after the first microbatch, so the two checks agree in every configuration FlexShard supports (no PP, no HSDP). - Import graph:
fsdp_lifecycle.pyandfsdp.pynow importflex_shard_fsdpat top level, butflex_shard_fsdpimports only torch at top level andtorchtitan.distributed.fsdplazily. No cycle, and nothing from flex_shard loads unless the backend is selected. - Tests: the EP test is extended rather than a new one added, which fits
tests.md. Comparing reduce-scatter counts guards the grouping, which values alone can't show.
Not verified: I didn't run the GPU parity tests, and couldn't confirm in this environment that c10d.reduce_scatter_single exists in the pinned torch, which the test's patch relies on.
|
@claude review this pr now |
|
Claude finished @anshul-si's task in 1m 27s —— View job Approve -- please address the items before merging (unlinked flex_shard TODOs; private |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The latest push fixes the silent fallback in the right place and the human-written summary is now filled in. What's left are small local edits. This touches core code (training_engine.py, components/loss.py, distributed/fsdp*.py), so a maintainer still needs to review it.
What this PR does. ChunkedLossWrapper.set_lm_head takes the model as fsdp_root. fsdp_partial_backwards sends FlexShard roots to flex_shard_partial_backwards, which turns off gradient sync and reshard-after-backward on lm_head's bucket during the chunks, then turns sync back on for the last chunk unless kept grads should wait for the decoder backward. FSDP2 goes through _fsdp2_partial_backwards, whose body is unchanged. The config-time rejection of ChunkedLossWrapper is removed.
Example. Llama 3 debug model, 8 chunks, 1 microbatch, FlexShard:
before: config raises "does not support ChunkedLossWrapper"
after: chunks 0-6: no collectives; chunk 7: RS(lm_head); decoder bwd: AG + RS(norm)
-> 2 AG / 2 RS per step, same as FSDP2
set_lm_head(model.lm_head) # FlexShard, no root -> ValueError (new)
set_lm_head(model.lm_head, fsdp_root=model) # what TrainingEngine does
Since the last review
- Resolved: the human-written summary is filled in.
- Resolved: leaving out
fsdp_rootunder FlexShard is no longer silent.set_lm_headraises while the params are still sharded, and the EP test asserts the raise. I agree with the reply: a check insidefsdp_partial_backwardswould see gathered params, so it could never fire. - Still open: frozen-decoder rejection fires at runtime, not at config time (
flex_shard_fsdp.py:352, earlier inline comment, no reply yet). Should-consider.
Must fix
torchtitan/distributed/flex_shard_fsdp.py:322,:362-- the three TODOs still say<flex_shard issue link>. File the meta-pytorch/flex_shard issue and link it (see the earlier inline comment).
Should consider
torchtitan/distributed/flex_shard_fsdp.py:376-- new in this push: imports the private_PartialBackwardHooksfromfsdp_lifecycle, through a lazy import that works around a cycle. Yield the callable as before, or make the name public (inline comment).
Details
holds_flex_shard_paramsusessys.modules.get("flex_shard")plusis_flex_shard_param, the same pattern asas_fsdp2_dtensor. Without FlexShard it costs nothing, and none of the ~20 existingset_lm_headcallers (CPU tests, graph_trainer, recipes) need changes, because they never shard with FlexShard.- In
TrainingEngine._initialize_model,set_lm_headruns afterparallelize,to_emptyandinit_weights, but before any forward. The params are still sharded there, so the guard can fire. post_validate_fsdp_for_accelerator_graph:model.modules()reaches the FlexShard root once, soreshard()runs once per model part. With FSDP2 it behaves exactly as before.- Import graph:
fsdp.pyandfsdp_lifecycle.pyimportflex_shard_fsdpat top level.flex_shard_fsdpimports torchtitan modules only lazily or underTYPE_CHECKING, so there's no cycle.
Not verified: GPU parity tests and the reduce-scatter counts. I also didn't confirm that FlexShard parameters are still marked as sharded when set_lm_head runs in the engine; that relies on the author's account.
| # fsdp_lifecycle imports this module. | ||
| from torchtitan.distributed.fsdp_lifecycle import _PartialBackwardHooks | ||
|
|
||
| try: | ||
| storage.set_requires_gradient_sync(False) | ||
| storage.set_reshard_after_backward(False) | ||
| yield _PartialBackwardHooks(before_last_forward, lambda output: output) |
There was a problem hiding this comment.
This push makes flex_shard_fsdp.py import _PartialBackwardHooks, a private name from fsdp_lifecycle, at runtime here and under TYPE_CHECKING at line 45. That breaks the CLAUDE.md rule against importing another module's _private names, and it needs a lazy import to dodge the fsdp_lifecycle -> flex_shard_fsdp cycle. The previous revision avoided this by having flex_shard_partial_backwards yield only before_last_forward and letting fsdp_lifecycle wrap it in _PartialBackwardHooks. Either go back to that (and drop the lazy import, the TYPE_CHECKING import and the quoted annotation), or, if the NamedTuple really is shared now, rename it to PartialBackwardHooks.
|
@claude review the pr's new changes |
|
Claude finished @anshul-si's task in 3m 4s —— View job Approve -- please address the items before merging (the PR description still describes the previous |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The new revision is smaller and cleaner than the last one: no private FlexShard state, no fsdp_root plumbing, and loss.py/training_engine.py are untouched. What remains is mostly the PR description, which still describes the previous design and a deferred-reduction mode that this revision rejects. This touches core distributed code (distributed/fsdp*.py), so a maintainer still needs to review it.
What this PR does (this revision). When apply_flex_shard_to_decoder shards the model, it records the bucket storage of every module whose FSDP2 group is a single bucket, including norm+lm_head (record_buckets). fsdp_partial_backwards(lm_head, ...) checks that record with has_flex_shard_bucket and, on a hit, hands off to flex_shard_partial_backwards. During the chunks, that function turns off gradient sync and reshard-after-backward on the bucket. It turns sync back on before the last chunk, then restores the policy and reshards. Sync is hardcoded to True rather than restored, which is only correct because validate_flex_shard_training still rejects fsdp_defer_gradient_reduction. post_validate_fsdp_for_accelerator_graph calls model.reshard() on recorded FlexShard models, and the ChunkedLossWrapper rejection is removed.
Example. Llama 3 debug model, 8 chunks, 1 microbatch, FlexShard:
loss_fn.set_lm_head(model.lm_head) # unchanged API; no fsdp_root
fsdp_partial_backwards(lm_head) # has_flex_shard_bucket(lm_head) -> True
chunks 0-6: sync off, no reshard -> no collectives
chunk 7: sync on -> RS(lm_head)
finally: restore, bucket.reshard()
decoder bwd: AG + RS(norm) -> 2 AG / 2 RS per step, as FSDP2
fsdp_defer_gradient_reduction=True -> still ValueError at config time
Since the last review
- Resolved: the private
_PartialBackwardHooksimport is gone, andflex_shard_partial_backwardsyields the callable again. - Resolved: the reads of private FlexShard state (
_requires_gradient_sync,_runtime()[1].needs_sync, theflex_shard.flex_shard.flex_shard.FlexShardModuleimport) are gone. The bucket is now captured when the model is sharded. - Resolved differently: the
fsdp_rootargument and itsset_lm_headguard are gone. The lookup is keyed bylm_headitself, so there's no caller argument to forget. - Still open (should-consider, no reply yet): the frozen-decoder
ValueErrorfires during the first step, not at config time (flex_shard_fsdp.py:199).
Must fix
-
PR description is stale. It still describes the previous revision:
fsdp_root,is_flex_shard_module,set_lm_head(fsdp_root=...)and the training-engine change;- the private-state reads, and the table row "last chunk: ... unless a group has
_post_backward_pendinggrads"; - the "Known issues: private FlexShard state" entry.
It also reports results for
fsdp_defer_gradient_reduction=True: two Numerics rows, two Collectives rows, the "2 with deferred reduction" test cases, and two of the four "Regressions caught". This revision rejects deferral, and the test runs 2 microbatches without it. Please rewrite "What changed" for the registry design, drop or relabel the deferred rows, and say which numbers come from this revision. The mechanism changed (sync forced on, unconditional reshard), so at least the 2-GPU Llama 3loss_comparerun and the GPU unit test should be repeated on this revision. -
torchtitan/distributed/flex_shard_fsdp.py:209-- the TODO for the missing FlexShard gradient-sync getter has no upstream issue link (inline comment).
Details
- Hardcoded sync / unconditional reshard. Under FlexShard, the engine's only callers of
set_requires_gradient_sync/set_reshard_after_backward(training_engine.py:827-831) run only with deferral, which is rejected. So the bucket's sync is alwaysTrueand itsreshard_after_backwardalways the default outside this context. SettingTrueand resharding unconditionally therefore matches FSDP2's "restore, then reshard ifreshard_after_backwardor forward-only". The TODO invalidate_flex_shard_trainingties the two together. - Registry.
_MODULE_BUCKETS/_FLEX_SHARD_MODELSfollow the module's existing_GRAD_NORM_MESHESpattern. Values are weakrefs, so the bucket -> model -> module chain doesn't keep keys alive. Blocks with an expert bucket (two storages) aren't recorded, and that's correct, becauseflex_shard_partial_backwardsassumes one bucket. - Silent fallback.
lm_headalways sits in a single-bucket group, sincevalidate_flex_shard_trainingrejects models that overrideDecoder._apply_fsdp. Sohas_flex_shard_bucket(lm_head)can't miss under FlexShard. fsdp.pymove. Moving the storage loop out ofif expert_mesh is not Nonedoesn't change non-EP runs: each group has one storage, sostorages_of_group[1:]is empty. Thelen(storages) == len(buckets)assert now also runs without EP, andtest_matches_fsdp2(ep=1) exercises it.- FSDP2 path. Unchanged apart from the
has_flex_shard_bucketcheck in front of it, which is a dict lookup that misses for FSDP2 modules.
Not verified: GPU parity tests, reduce-scatter counts, and whether c10d.reduce_scatter_single exists in the pinned torch (the test's patch relies on it).
| # TODO: Gradient sync is set to True, not restored, because FlexShard has | ||
| # no public getter for it, and validate_flex_shard_training rejects | ||
| # deferred gradient reduction, so it's always on outside. Allowing deferral | ||
| # needs the caller's setting restored, and FlexShard's state of grads kept | ||
| # without sync, to leave the last reduce-scatter to the decoder backward | ||
| # when earlier microbatches kept grads, as FSDP2 does. |
There was a problem hiding this comment.
This TODO works around a FlexShard gap: there's no public getter for a bucket's gradient sync setting, or for whether it holds grads kept without sync. Because of that, before_last_forward and the finally hardcode True instead of restoring the caller's setting. CLAUDE.md principle 3 asks for an upstream issue link on TODOs like this. Without one, nothing ties lifting the fsdp_defer_gradient_reduction rejection to fixing this function, apart from the cross-reference in validate_flex_shard_training. Please file the meta-pytorch/flex_shard issue and put its URL here, e.g. # TODO(https://github.com/meta-pytorch/flex_shard/issues/N): ....
[ghstack-poisoned]
[ghstack-poisoned]
Stacked on #5842 and the expert-parallelism PR. ## Summary (human-written) FlexShard couldn;t match FSDP2 numerics with ChunkedLossWrapper because the wrappe calls lm_head separately on each chunk and runs a backward for each one. FSDP2's fsdp_partial_backwards kept lm_head gathers and held its reduce scatter until the last chink, but it only recofnized FSDP2 modules. This meant that FlexShard reduce-scattered after every chunk, which added collectives and summed grads in a different order than FSDP2. Fixed by adding a Flexshard path to fsdp_partial_backwards, which finds lm_head's bucket and keeps bucket gathered with grad sync of until the last chunk. ## Description `ChunkedLossWrapper` is the loss of the stock recipes (the Llama 3, Qwen3 and DeepSeek V3 debug models among them), but `FlexShardConfig.validate_trainer` rejects it, so FlexShard runs have to swap in `CrossEntropyLoss`. Deleting the rejection alone isn't enough. The wrapper calls `lm_head` on its own on each chunk of the hidden states, with a backward per chunk. `fsdp_partial_backwards` (#5563) keeps FSDP2's norm and `lm_head` group unsharded and its grads unreduced across those backwards, and reduce-scatters them once, at the last chunk. It does nothing for FlexShard, because `lm_head` isn't an `FSDPModule`, so FlexShard's bucket for the same group reduce-scatters, reshards and gathers again at every chunk. On the Qwen3 MoE debug model (8 chunks, `ep=2`, 2 ranks), that is 18 reduce-scatters per step instead of FSDP2's 11, and the lm_head grads are summed in a different order. This PR deletes the rejection and gives the bucket FSDP2's treatment, so training is bitwise identical to FSDP2 with the recipes' loss. It creates no DTensor, as #5842 requires, and uses only FlexShard's public API. `FlexShardConfig.validate_trainer` loses its `loss` argument, which only the rejection read, and so does `StorageConfig.validate_trainer`. `StorageConfig` gains `partial_backwards(model, module_fqn)`: the context that keeps a submodule unsharded while it runs on its own, in several forwards and backwards. The training engine, which holds the model when it calls `ChunkedLossWrapper.set_lm_head`, now also passes it the storage config's `partial_backwards(model, "lm_head")`, and the wrapper runs its chunks in it. `FullyShardConfig`'s is `fsdp_partial_backwards` on `lm_head`, unchanged, which is also the wrapper's default. `FlexShardConfig`'s finds `lm_head`'s bucket with the new `FlexShardConfig._bucket(model, "lm_head")`, by name: FlexShard keeps the buckets on the model and names each bucket's parameters (the public `param_infos`), and one bucket holds `lm_head`'s, along with the final norm's. With tied weights the bucket also holds `tok_embeddings`, and `lm_head.weight` is a second name of the shared parameter (`shared_fqns`), which the lookup checks too. Creating a seed checkpoint doesn't shard the model, so the engine passes nothing then. The bucket goes to the new `FlexShardConfig._partial_backwards`, which maps FSDP2's steps onto the bucket with FlexShard's per-bucket setters. During the chunks, it turns off the bucket's gradient sync and its reshard after backward, so each chunk's backward keeps the grads on the unsharded parameters. Before the last chunk it turns sync back on, so that chunk's backward reduce-scatters the grads of all chunks and reshards, as FSDP2 does at its last chunk. The decoder backward then gathers the bucket again and reduce-scatters the norm's grad, as FSDP2 does. The rest of FSDP2's steps aren't needed: - `set_reshard_after_forward(False)` on `lm_head`: a call of a module on its own leaves its bucket's forward open, so FlexShard runs no post-forward for it. - `is_last_backward = False` and the policies of the other groups: a chunk's backward finishes its own bucket and no other. - The explicit `unshard()`: it avoids an eager all-gather event under CUDA graph capture, and FlexShard rejects accelerator graphs. The first chunk gathers the bucket. - Deferring the last reduce-scatter to the decoder backward when earlier microbatches left grads unreduced: that only happens with `fsdp_defer_gradient_reduction=True`, which #5842 rejects. Gradient sync is therefore always on outside the chunks, and the function turns it back on rather than reading FlexShard's private setting. Lifting the rejection (FlexShard's `set_is_last_backward`) needs the deferral back, as `TODO`s at the rejection and in `_partial_backwards` say. - Manual finalization: FlexShard rejects pipeline parallelism. `set_lm_head` raises if FlexShard sharded `lm_head` and no `partial_backwards` is passed, so a caller that leaves it out doesn't silently get a reduce-scatter per chunk. The new `holds_flex_shard_params` checks with FlexShard's public `is_flex_shard_param`, and only once flex_shard is imported. It runs in `set_lm_head` because the parameters are still sharded there: inside the chunks they're gathered, and the check couldn't fire. Handing the wrapper the backend's context keeps torchtitan free of module-level state: an earlier revision recorded each module's bucket and each FlexShard model in global tables when the model was sharded. Validation runs the chunked loss under `no_grad`, and the loss's `lm_head` calls leave the bucket's forward open, as they leave FSDP2's grouped forward open. For FSDP2, `post_validate_fsdp_for_accelerator_graph` completes that forward after every validation step, eager or captured. The validator now calls the backend's new `reshard_after_eval(model_parts)` there instead. `FullyShardConfig`'s calls `post_validate_fsdp_for_accelerator_graph`, and `FlexShardConfig`'s calls FlexShard's `reshard()` on each model part, which closes the bucket's forward and reshards every bucket. Without it, the next training forward continues the stale forward, the norm gets no post-backward trigger, and the bucket stays gathered until the end of the decoder backward, where it reduce-scatters last. The values don't change, only memory and the order of the reduce-scatters. A frozen decoder with a trainable `lm_head` (e.g. LoRA on `lm_head` alone) still raises with FlexShard, now from `_partial_backwards`, at the first loss call. The chunks' inputs then don't require grad, so FlexShard has no trigger to finish the bucket after each chunk, and `lm_head`'s grads would stay on the unsharded parameters without ever reaching the optimizer. FSDP2 completes each call's grouped forward instead. `FlexShardConfig.validate_trainer` can't tell this case from the config: it depends on which parameters the built model leaves trainable. `test_matches_fsdp2_with_expert_parallelism` now trains with `ChunkedLossWrapper`, as the Qwen3 MoE recipes do, set up as the training engine sets it up. It covers the Qwen3 MoE debug model with `ep=2`, with `fsdp_reshard_after_forward` set to default and to always (only default before), each with one and with two microbatches. Every case of both parity tests also requires both backends to issue the same number of reduce-scatters, and FSDP2 a nonzero number, so that the count can't pass because the patches miss the calls. Values alone can't show how grads are grouped into reduce-scatters when the sums are exact. `test_matches_fsdp2` keeps cross-entropy on the full logits. The new `test_matches_fsdp2_with_tied_weights_and_chunked_loss` runs the Llama 3 debug model with tied weights, set up as the tied Llama 3 flavors (1B, 3B) do, with `ChunkedLossWrapper` and two microbatches. The fake validator contexts of `test_validator.py` and `test_accelerator_graph_validation_config.py` get a `FullyShardConfig`. On 2 GB200 GPUs with `world_size` set to 2, the EP test, the tied test and `test_matches_fsdp2` pass. They haven't run at CI's 4 GPUs: this machine has 2, and FlexShard needs CUDA. Without FlexShard's `partial_backwards`, `set_lm_head` raises in the EP test, and without the lookup of shared names, the tied test fails at the start, with no bucket found for `lm_head`. On an earlier revision, without FlexShard's partial backwards, the EP test failed on the reduce-scatter count (54 against FSDP2's 33 over three steps, default policy, one microbatch). On an earlier revision of this PR, a one-off probe on 2 GPUs (not part of the PR) ran two validation steps of the chunked loss with the validation hook, then three training steps, on the Llama 3 debug model: the validation losses were bitwise identical to FSDP2's, the bucket's forward was closed after the hook, and training stayed bitwise identical. Without FlexShard's `reshard()` in the hook, the bucket's forward was still open after it. The FSDP2 path doesn't change: `FullyShardConfig` runs `fsdp_partial_backwards` and `post_validate_fsdp_for_accelerator_graph`, unchanged, where the wrapper and the validator called them before. On an earlier revision of this PR, which added FlexShard branches to those two functions instead, `scripts/loss_compare.py <expert-parallelism PR> <this PR> --assert-equal --metrics loss,grad_norm` (seed 42, deterministic, 50 steps, 2 GB200 GPUs) reports equal loss and grad norm at every step for llama3 `debugmodel` with the recipe's `ChunkedLossWrapper` and two validation steps every 5 steps (step-50 loss 2.86823). Both runs captured training and validation in CUDA graphs, and their logged validation losses are identical. It uses flex attention because the environment has no FA4, and skips the seed checkpoint, since both runs start from seed 42 with the same parallelism. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: f29cbd5 Pull-Request: pytorch/torchtitan#6011
Stack from ghstack (oldest at bottom):
Stacked on #5842 and the expert-parallelism PR.
Summary (human-written)
FlexShard couldn;t match FSDP2 numerics with ChunkedLossWrapper because the wrappe calls lm_head separately on each chunk and runs a backward for each one. FSDP2's fsdp_partial_backwards kept lm_head gathers and held its reduce scatter until the last chink, but it only recofnized FSDP2 modules. This meant that FlexShard reduce-scattered after every chunk, which added collectives and summed grads in a different order than FSDP2. Fixed by adding a Flexshard path to fsdp_partial_backwards, which finds lm_head's bucket and keeps bucket gathered with grad sync of until the last chunk.
Description
ChunkedLossWrapperis the loss of the stock recipes (the Llama 3, Qwen3 and DeepSeekV3 debug models among them), but
FlexShardConfig.validate_trainerrejects it, soFlexShard runs have to swap in
CrossEntropyLoss. Deleting the rejection alone isn'tenough. The wrapper calls
lm_headon its own on each chunk of the hidden states, witha backward per chunk.
fsdp_partial_backwards(#5563) keeps FSDP2's norm andlm_headgroup unsharded and its grads unreduced across those backwards, and reduce-scatters them
once, at the last chunk. It does nothing for FlexShard, because
lm_headisn't anFSDPModule, so FlexShard's bucket for the same group reduce-scatters, reshards andgathers again at every chunk. On the Qwen3 MoE debug model (8 chunks,
ep=2, 2 ranks),that is 18 reduce-scatters per step instead of FSDP2's 11, and the lm_head grads are
summed in a different order. This PR deletes the rejection and gives the bucket FSDP2's
treatment, so training is bitwise identical to FSDP2 with the recipes' loss. It creates
no DTensor, as #5842 requires, and uses only FlexShard's public API.
FlexShardConfig.validate_trainerloses itslossargument, which only the rejectionread, and so does
StorageConfig.validate_trainer.StorageConfiggainspartial_backwards(model, module_fqn): the context that keeps asubmodule unsharded while it runs on its own, in several forwards and backwards. The
training engine, which holds the model when it calls
ChunkedLossWrapper.set_lm_head,now also passes it the storage config's
partial_backwards(model, "lm_head"), and thewrapper runs its chunks in it.
FullyShardConfig's isfsdp_partial_backwardsonlm_head, unchanged, which is also the wrapper's default.FlexShardConfig's findslm_head's bucket with the newFlexShardConfig._bucket(model, "lm_head"), by name:FlexShard keeps the buckets on the model and names each bucket's parameters (the public
param_infos), and one bucket holdslm_head's, along with the final norm's. With tiedweights the bucket also holds
tok_embeddings, andlm_head.weightis a second name ofthe shared parameter (
shared_fqns), which the lookup checks too. Creating a seedcheckpoint doesn't shard the model, so the engine passes nothing then. The bucket goes
to the new
FlexShardConfig._partial_backwards, which maps FSDP2's steps onto thebucket with FlexShard's per-bucket setters. During the chunks, it turns off the bucket's
gradient sync and its reshard after backward, so each chunk's backward keeps the grads
on the unsharded parameters. Before the last chunk it turns sync back on, so that
chunk's backward reduce-scatters the grads of all chunks and reshards, as FSDP2 does at
its last chunk. The decoder backward then gathers the bucket again and reduce-scatters
the norm's grad, as FSDP2 does. The rest of FSDP2's steps aren't needed:
set_reshard_after_forward(False)onlm_head: a call of a module on its ownleaves its bucket's forward open, so FlexShard runs no post-forward for it.
is_last_backward = Falseand the policies of the other groups: a chunk's backwardfinishes its own bucket and no other.
unshard(): it avoids an eager all-gather event under CUDA graphcapture, and FlexShard rejects accelerator graphs. The first chunk gathers the
bucket.
left grads unreduced: that only happens with
fsdp_defer_gradient_reduction=True,which Add parallelism.storage to shard decoders with FlexShard #5842 rejects. Gradient sync is therefore always on outside the chunks, and
the function turns it back on rather than reading FlexShard's private setting.
Lifting the rejection (FlexShard's
set_is_last_backward) needs the deferral back,as
TODOs at the rejection and in_partial_backwardssay.set_lm_headraises if FlexShard shardedlm_headand nopartial_backwardsispassed, so a caller that leaves it out doesn't silently get a reduce-scatter per chunk.
The new
holds_flex_shard_paramschecks with FlexShard's publicis_flex_shard_param,and only once flex_shard is imported. It runs in
set_lm_headbecause the parametersare still sharded there: inside the chunks they're gathered, and the check couldn't
fire. Handing the wrapper the backend's context keeps torchtitan free of module-level
state: an earlier revision recorded each module's bucket and each FlexShard model in
global tables when the model was sharded.
Validation runs the chunked loss under
no_grad, and the loss'slm_headcalls leavethe bucket's forward open, as they leave FSDP2's grouped forward open. For FSDP2,
post_validate_fsdp_for_accelerator_graphcompletes that forward after every validationstep, eager or captured. The validator now calls the backend's new
reshard_after_eval(model_parts)there instead.FullyShardConfig's callspost_validate_fsdp_for_accelerator_graph, andFlexShardConfig's calls FlexShard'sreshard()on each model part, which closes the bucket's forward and reshards everybucket. Without it, the next training forward continues the stale forward, the norm gets
no post-backward trigger, and the bucket stays gathered until the end of the decoder
backward, where it reduce-scatters last. The values don't change, only memory and the
order of the reduce-scatters.
A frozen decoder with a trainable
lm_head(e.g. LoRA onlm_headalone) still raiseswith FlexShard, now from
_partial_backwards, at the first loss call. Thechunks' inputs then don't require grad, so FlexShard has no trigger to finish the bucket
after each chunk, and
lm_head's grads would stay on the unsharded parameters withoutever reaching the optimizer. FSDP2 completes each call's grouped forward instead.
FlexShardConfig.validate_trainercan't tell this case from the config: it depends onwhich parameters the built model leaves trainable.
test_matches_fsdp2_with_expert_parallelismnow trains withChunkedLossWrapper, asthe Qwen3 MoE recipes do, set up as the training engine sets it up. It covers the Qwen3
MoE debug model with
ep=2, withfsdp_reshard_after_forwardset to default and toalways (only default before), each with one and with two microbatches. Every case of
both parity tests also requires both backends to issue the same number of
reduce-scatters, and FSDP2 a nonzero number, so that the count can't pass because the
patches miss the calls. Values alone can't show how grads are grouped into
reduce-scatters when the sums are exact.
test_matches_fsdp2keeps cross-entropy on thefull logits. The new
test_matches_fsdp2_with_tied_weights_and_chunked_lossruns theLlama 3 debug model with tied weights, set up as the tied Llama 3 flavors (1B, 3B) do,
with
ChunkedLossWrapperand two microbatches. The fake validator contexts oftest_validator.pyandtest_accelerator_graph_validation_config.pyget aFullyShardConfig.On 2 GB200 GPUs with
world_sizeset to 2, the EP test, the tied test andtest_matches_fsdp2pass. They haven't run at CI's 4 GPUs: this machine has 2, andFlexShard needs CUDA. Without FlexShard's
partial_backwards,set_lm_headraises inthe EP test, and without the lookup of shared names, the tied test fails at the start,
with no bucket found for
lm_head. On an earlier revision, without FlexShard's partialbackwards, the EP test failed on the reduce-scatter count (54 against FSDP2's 33 over
three steps, default policy, one microbatch). On an earlier revision of this PR, a
one-off probe on 2 GPUs (not part of the PR) ran two validation steps of the chunked
loss with the validation hook, then three training steps, on the Llama 3 debug model:
the validation losses were bitwise identical to FSDP2's, the bucket's forward was closed
after the hook, and training stayed bitwise identical. Without FlexShard's
reshard()in the hook, the bucket's forward was still open after it.
The FSDP2 path doesn't change:
FullyShardConfigrunsfsdp_partial_backwardsandpost_validate_fsdp_for_accelerator_graph, unchanged, where the wrapper and thevalidator called them before. On an earlier revision of this PR, which added FlexShard
branches to those two functions instead,
scripts/loss_compare.py <expert-parallelism PR> <this PR> --assert-equal --metrics loss,grad_norm(seed 42, deterministic, 50steps, 2 GB200 GPUs) reports equal loss and grad norm at every step for llama3
debugmodelwith the recipe'sChunkedLossWrapperand two validation steps every 5steps (step-50 loss 2.86823). Both runs captured training and validation in CUDA graphs,
and their logged validation losses are identical. It uses flex attention because the
environment has no FA4, and skips the seed checkpoint, since both runs start from seed
42 with the same parallelism.
Co-authored-by: Wei Feng [email protected]