Repository navigation
Conversation
|
@claude review this pr - theres likely room to make this cleaner, so focus on that the most for this round of review |
|
Claude finished @anshul-si's task in 4m 0s —— View job Request changes: review. The main cleanup items are that the FlexShard path copies FSDP2's decoder grouping instead of sharing it, and that the parity test never runs in CI because |
There was a problem hiding this comment.
Verdict: Request changes -- The FlexShard path copies FSDP2's decoder grouping instead of sharing it, and the bitwise-parity test never runs in CI because flex_shard isn't a pinned dependency. A future change to either backend could break parity with nothing to catch it.
What this PR does. It adds parallelism.fsdp_backend: Literal["fsdp2", "flex_shard"]. With flex_shard, Decoder._apply_fsdp hands each group that apply_fsdp_to_decoder would pass to fully_shard to the external flex_shard package as one fsdp2_compatible bucket. FlexShard parameters and grads are plain local shards, so two places turn them into the DTensor views FSDP2 would have produced: parameter init (Module._init_param) and clip_grad_norm_. Unsupported combinations are rejected at config time, and four models reject the backend in _apply_fsdp.
Example.
llama3 debugmodel, dp_shard=4, CE loss, accelerator graphs off
fsdp_backend="fsdp2" -> fully_shard(tok_emb), fully_shard([norm, lm_head]), fully_shard(layer_i), fully_shard(root)
fsdp_backend="flex_shard" -> flex_shard(model, buckets=[tok_emb], [norm, lm_head], [layers.i], [leftover root fqns])
claimed: identical loss / grad_norm / params at every step
Must fix
tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:30: the dependency is unpinned, so the test always skips. Also, the description has no loss comparison and no testing section.torchtitan/distributed/flex_shard_fsdp.py:132: duplicatesapply_fsdp_to_decoder's grouping. Have both backends use one group description.torchtitan/distributed/flex_shard_fsdp.py:175: three functions should be one. The shim also uses a private torch API and checkssys.moduleswith no upstreamTODO.torchtitan/distributed/fsdp.py:165: the opt-out guard missesexperiments/transformers_modeling_backend, which falls back to FSDP2 without any error.torchtitan_recipes/tests/models/llama3.py:238: two recipes with no consumer.tests/unit_tests/cpu/config/test_parallelism_config.py:107: a test that only asserts a constant.
Should consider
flex_shard_fsdp.py:54: droppp_enabled(PP is banned) and the duplicated"default"default.flex_shard_fsdp.py:81: the mesh check can't be reached through config, so use anassert.fsdp.py:146:set_requires_gradient_syncbranches onhasattr, and its name overlaps theFSDPModulemethod while it changes three flags.training_engine.py:168: move the FlexShard-specific validation out of core and use plainifs.- Placement: the new
torchtitan/distributed/flex_shard_fsdp.pysits next to the existing in-tree packagetorchtitan/distributed/flex_shard/(optimizer reshard and DistMuon)..github/area_reviewers.ymlalready routes that directory to the FSDP owner. Two different "FlexShard"s, one in-tree and one externalflex_shard, are confusing. If they are the same project, put this integration inside the package (e.g.distributed/flex_shard/fsdp.py).
Questions
- How does the in-tree
torchtitan.distributed.flex_shardrelate tometa-pytorch/flex_shard? Is the in-tree one moving out? The answer decides where this file belongs, and whetherDistMuon(rejected here because it needs DTensor params) should come from the external package.
Details
- Gate: this is the first step of a stated FSDP2 replacement, and FlexShard is a meta-pytorch library, so principle 3 allows the dependency. The design question is whether parity is enforced structurally or only by a test. Today the parity test cannot run in CI, so the duplication in
apply_flex_shard_to_decoderis the main risk. - Smaller alternative for the grouping: a helper in
fsdp.pythat yields(module_fqns, reshard_after_forward, placements)for the embedding, norm/head, each block and the root.apply_fsdp_to_decoderloopsfully_shardover it; the FlexShard path maps each entry to aBucketSpec. FSDP2-only extras (set_unshard_in_backward, the EP>1 per-param mesh, prefetch) stay where they are. This is about -40 lines inflex_shard_fsdp.pyand a small net change infsdp.py. clip_grad_norm_correctness: it clipsparams_by_meshthroughp.grad, which stays the plain local shard, whiletotal_normcomes from the DTensor views afterfull_tensor(). That is consistent.
Not verified: the bitwise-parity claim (needs 4 GPUs with flex_shard installed), and whether MoE decoders other than llama3 (qwen3 MoE, gpt_oss, kimi) match FSDP2 under this backend.
A maintainer still needs to review, since the PR touches core code.
parallelism.fsdp_backend="flex_shard" trains with FlexShard (meta-pytorch/flex_shard) in place of FSDP2's fully_shard; "fsdp2" stays the default. This is the first step of replacing FSDP2: data parallelism over dp_shard for decoders, with training bitwise identical to FSDP2. Both backends now take a decoder's groups from decoder_fsdp_groups: the embedding (with the norm and output projection when weights are tied), the norm with the output projection, and each transformer block, each with its reshard_after_forward policy and its stacked-linear and routed-expert placements. apply_fsdp_to_decoder passes each group to fully_shard, as before. apply_flex_shard_to_decoder gives FlexShard one fsdp2_compatible bucket per group, plus one for the parameters left to the root, with the same mixed precision as mixed_precision_policy (preserved parameters keep the wider dtype). Gradients are summed without division, as disable_fsdp_gradient_division makes FSDP2 do. FSDP2 skips the embedding's backward all-gather, which FlexShard can't yet; values are unaffected. FlexShard stores parameters as plain local shards, while torchtitan relies on FSDP2's DTensor parameters in two places. Module._init_param and clip_grad_norm_ go through as_fsdp2_dtensor, the DTensor FSDP2 would give a parameter or its grad, so initialization matches FSDP2's, and each rank clips with the global norm rather than its local one. Gradient accumulation with fsdp_defer_gradient_reduction goes through set_is_last_accumulation_step, which covers both backends. FlexShard is imported only when selected. Config validation rejects what the flex_shard backend does not support yet: HSDP; tensor, context, expert and pipeline parallelism; symmetric-memory communication; CPU offloading; accelerator graphs; ChunkedLossWrapper; checkpointing; EMA; DistMuon; SPMD typechecking; and any model that overrides Decoder._apply_fsdp (multimodal models, DeepSeek V3 and V4, Flux and the transformers modeling backend). The multi-GPU unit-test job installs flex_shard at a pinned commit, so the parity test runs in CI. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 59b2c74 Pull-Request: #5842
parallelism.fsdp_backend="flex_shard" trains with FlexShard (meta-pytorch/flex_shard) in place of FSDP2's fully_shard; "fsdp2" stays the default. This is the first step of replacing FSDP2: data parallelism over dp_shard for decoders, with training bitwise identical to FSDP2. Both backends now take a decoder's groups from decoder_fsdp_groups: the embedding (with the norm and output projection when weights are tied), the norm with the output projection, and each transformer block, each with its reshard_after_forward policy and its stacked-linear and routed-expert placements. apply_fsdp_to_decoder passes each group to fully_shard, as before. apply_flex_shard_to_decoder gives FlexShard one fsdp2_compatible bucket per group, plus one for the parameters left to the root, with the same mixed precision as mixed_precision_policy (preserved parameters keep the wider dtype). Gradients are summed without division, as disable_fsdp_gradient_division makes FSDP2 do. FSDP2 skips the embedding's backward all-gather, which FlexShard can't yet; values are unaffected. FlexShard stores parameters as plain local shards, while torchtitan relies on FSDP2's DTensor parameters in two places. Module._init_param and clip_grad_norm_ go through as_fsdp2_dtensor, the DTensor FSDP2 would give a parameter or its grad, so initialization matches FSDP2's, and each rank clips with the global norm rather than its local one. Gradient accumulation with fsdp_defer_gradient_reduction goes through set_is_last_accumulation_step, which covers both backends. FlexShard is imported only when selected. Config validation rejects what the flex_shard backend does not support yet: HSDP; tensor, context, expert and pipeline parallelism; symmetric-memory communication; CPU offloading; accelerator graphs; ChunkedLossWrapper; checkpointing; EMA; DistMuon; SPMD typechecking; and any model that overrides Decoder._apply_fsdp (multimodal models, DeepSeek V3 and V4, Flux and the transformers modeling backend). The multi-GPU unit-test job installs flex_shard at a pinned commit, so the parity test runs in CI. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 0171f5b Pull-Request: #5842
|
@claude review this pr |
|
Claude finished @anshul-si's task in 4m 57s —— View job Request changes: review. The design issues from the last round are fixed, but GraphTrainer models get past the new |
There was a problem hiding this comment.
Verdict: Request changes -- The design problems from the last round are fixed. The remaining blocker: GraphTrainer models get through the new _apply_fsdp guard and train with SimpleFSDP without any error. The description is also out of date and has no numerics proof for the refactored FSDP2 main path.
What this PR does. It adds parallelism.fsdp_backend: Literal["fsdp2", "flex_shard"]. The new decoder_fsdp_groups describes the decoder's sharding groups once: embedding, norm+head, each block, and the root leftovers, each with its reshard policy and non-Shard(0) placements. With FSDP2, apply_fsdp_to_decoder calls fully_shard on each group. With FlexShard, apply_flex_shard_to_decoder makes one fsdp2_compatible bucket per group. as_fsdp2_dtensor turns FlexShard's plain local shards into DTensor views, for init and for grad-norm clipping. Unsupported features are rejected in ParallelismConfig.__post_init__, in validate_flex_shard_training, and in validate_model_training_config, which rejects any model whose _apply_fsdp is not Decoder._apply_fsdp.
Example.
recipe: graph_trainer llama3 debugmodel, --override parallelism.fsdp_backend=flex_shard
validate_model_training_config: GraphTrainerLlama3Model._apply_fsdp is Decoder._apply_fsdp -> passes
GraphTrainerModel.parallelize -> apply_simple_fsdp(...) # _apply_fsdp is never called
result: trains with SimpleFSDP; fsdp_backend is ignored without any error
Resolved since the last review: the grouping is no longer duplicated (decoder_fsdp_groups), the GPU test now runs in CI against a pinned commit, the three DTensor helpers are now one, the guard is opt-in and covers transformers_modeling_backend, the recipes are down to one, the constant-assert test is gone, the mesh check is now an assert, set_is_last_accumulation_step replaces the hasattr branch, and the FlexShard validation has moved out of training_engine.py.
Must fix
- The description is out of date and missing its required sections. It still says accumulation goes through
set_requires_gradient_sync(nowset_is_last_accumulation_step) and that models "reject it in_apply_fsdp" (the check is now inconfig/validation.py). It doesn't say thatapply_fsdp_to_decoder, the main FSDP2 training path, was rewritten on top ofdecoder_fsdp_groups. Per CLAUDE.md, a refactor needs identical loss/grad_norm before vs. after (seed 42, deterministic), and a FlexShard vs. FSDP2 comparison fromscripts/loss_compare.py. There is no Testing or Numerics section, and the "Summary (human-written)" template section is missing. torchtitan/config/validation.py:52-- GraphTrainer models get past the guard (see inline comment).torchtitan/distributed/flex_shard_fsdp.py:160-- the TODO has no upstream issue link (see inline comment).
Should consider
torchtitan/distributed/fsdp.py:126--routed_expert_param_placementsis single-use now. Inline it.- Still open from last round:
apply_flex_shard_to_decoderkeepspp_enabled, which is alwaysFalsebecause PP is banned. Passpp_enabled=Falsetodecoder_fsdp_groupsand drop the parameter. tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.pycovers only the dense llama3 debug model. The riskiest new code is the MoE path, which isn't exercised: routed-expertShard(1/2)placements whendp_shard > num_experts, and theparam_dtype_overridesfor preserved router params. Adding an MoE debug flavor to the existingproduct(...)would cover it without a new test.
Questions
- RL:
push_model_state_dictpublishesmodel_part.state_dict()(rl/trainer/trainer.py:502). Under FSDP2 these are DTensors. What does FlexShard'sstate_dict()return? If it's the plain local shards (checkpointing is banned, presumably for this reason), every rank would put a shard under the full-weight key. Either rejectflex_shardin the RL trainer config or confirm it works. Unverified. - From last round, still unanswered in the PR: how does the in-tree
torchtitan/distributed/flex_shard/, the optimizer-reshard package that holds DistMuon, relate tometa-pytorch/flex_shard? Having two different "FlexShard"s next to each other (flex_shard/andflex_shard_fsdp.py) is confusing.
Details
- Refactor equivalence, checked by reading the code. Dense blocks:
placements = linear_param_shard_placements(block), which is unchanged. MoE with EP=1: the stacked placements updated with the expert placements, the same as the oldparam_placements. EP>1: the old code checked expert placements first and then fell back to stacked. The new code merges them with the expert placements winning, and picks the mesh by membership inrouted_experts.parameters(), which is equivalent.expert_sharding_sizenow readsdp_meshinstead offsdp_config["mesh"], which is the same object (fsdp.py:516).set_unshard_in_backwardis still applied only in the untied case, as before. - The DSv3 MTP path calls
apply_fsdp_to_decoderwith an unchanged signature, so it is unaffected. clip_grad_norm_: the norm is computed fromgrads_by_mesh(the DTensor views), and the clipping usesparams_by_meshthroughp.grad. Both are grouped by the same mesh key, so they stay consistent.
Not verified: the bitwise-parity claim (needs 4 GPUs with flex_shard); that fully_shard([block]) registers the same hooks as fully_shard(block) (FSDP2 source not inspectable here; the FSDP2 before/after loss comparison asked for above would settle it); what FlexShard's state_dict() returns.
A maintainer still needs to review, since the PR touches core code.
parallelism.fsdp_backend=FlexShardConfig() trains with FlexShard (meta-pytorch/flex_shard) in place of FSDP2's fully_shard; None, the default, keeps FSDP2. This is the first step of replacing FSDP2: data parallelism over dp_shard for decoders, with training bitwise identical to FSDP2. Both backends now take a decoder's groups from decoder_fsdp_groups: the embedding (with the norm and output projection when weights are tied), the norm with the output projection, and each transformer block, each with its reshard_after_forward policy and its stacked-linear and routed-expert placements. apply_fsdp_to_decoder passes each group to fully_shard, as before. apply_flex_shard_to_decoder gives FlexShard one fsdp2_compatible bucket per group, plus one for the parameters left to the root, with the same param_dtype and reduce_dtype as mixed_precision_policy. Gradients are summed without division, as disable_fsdp_gradient_division makes FSDP2 do. FSDP2 skips the embedding's backward all-gather, which FlexShard can't yet; values are unaffected. FlexShard stores parameters as plain local shards, while torchtitan relies on FSDP2's DTensor parameters in two places. Module._init_param and clip_grad_norm_ go through as_fsdp2_dtensor, the DTensor FSDP2 would give a parameter or its grad, so initialization matches FSDP2's, and each rank clips with the global norm rather than its local one. Gradient accumulation with fsdp_defer_gradient_reduction goes through set_is_last_accumulation_step, which covers both backends. FlexShard is imported only when selected. Config validation rejects what it does not support yet, in the trainer config's __post_init__, which the config loader runs again after recipes assign fields: HSDP; tensor, context, expert and pipeline parallelism; symmetric-memory communication; CPU offloading; accelerator graphs; ChunkedLossWrapper; checkpointing; EMA; DistMuon; SPMD typechecking; any model that overrides Decoder._apply_fsdp (multimodal models, DeepSeek V3 and V4, Flux and the transformers modeling backend); and tied weights, which parallelization unties until init_states ties them again, too late for FlexShard. GraphTrainer (SimpleFSDP), FaultTolerantTrainer (whose replica all-reduce hooks FSDP2) and the RL trainer (which would publish FlexShard's local shards as full weights) reject it too. apply_flex_shard_to_decoder rejects preserve_dtype_params and quantized MXFP8/NVFP4 weights, which FlexShard would compute differently. The multi-GPU unit-test job installs flex_shard at a pinned commit, so the parity test runs in CI. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 40c04b7 Pull-Request: #5842
parallelism.fsdp_backend=FlexShardConfig() trains with FlexShard (meta-pytorch/flex_shard) in place of FSDP2's fully_shard; None, the default, keeps FSDP2. This is the first step of replacing FSDP2: data parallelism over dp_shard for decoders, with training bitwise identical to FSDP2. Both backends now take a decoder's groups from decoder_fsdp_groups: the embedding (with the norm and output projection when weights are tied), the norm with the output projection, and each transformer block, each with its reshard_after_forward policy and its stacked-linear and routed-expert placements. apply_fsdp_to_decoder passes each group to fully_shard, as before. apply_flex_shard_to_decoder gives FlexShard one fsdp2_compatible bucket per group, plus one for the parameters left to the root, with the same param_dtype and reduce_dtype as mixed_precision_policy. Gradients are summed without division, as disable_fsdp_gradient_division makes FSDP2 do. FSDP2 skips the embedding's backward all-gather, which FlexShard can't yet; values are unaffected. FlexShard stores parameters as plain local shards, while torchtitan relies on FSDP2's DTensor parameters in two places. Module._init_param and clip_grad_norm_ go through as_fsdp2_dtensor, the DTensor FSDP2 would give a parameter or its grad, so initialization matches FSDP2's, and each rank clips with the global norm rather than its local one. Gradient accumulation with fsdp_defer_gradient_reduction goes through set_is_last_accumulation_step, which covers both backends. FlexShard is imported only when selected. Config validation rejects what it does not support yet, in the trainer config's __post_init__, which the config loader runs again after recipes assign fields: HSDP; tensor, context, expert and pipeline parallelism; symmetric-memory communication; CPU offloading; accelerator graphs; ChunkedLossWrapper; checkpointing; EMA; DistMuon; SPMD typechecking; any model that overrides Decoder._apply_fsdp (multimodal models, DeepSeek V3 and V4, Flux and the transformers modeling backend); and tied weights, which parallelization unties until init_states ties them again, too late for FlexShard. GraphTrainer (SimpleFSDP), FaultTolerantTrainer (whose replica all-reduce hooks FSDP2) and the RL trainer (which would publish FlexShard's local shards as full weights) reject it too. apply_flex_shard_to_decoder rejects preserve_dtype_params and quantized MXFP8/NVFP4 weights, which FlexShard would compute differently. The multi-GPU unit-test job installs flex_shard at a pinned commit, so the parity test runs in CI. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: f7e0e2e Pull-Request: #5842
|
@claude review this pr |
|
Claude finished @anshul-si's task in 2m 41s —— View job Request changes: review. The numerics results for the refactored FSDP2 path are still |
There was a problem hiding this comment.
Verdict: Request changes -- The design is in good shape now. What blocks it: the description's numerics results are still <fill in>, even though apply_fsdp_to_decoder (the main FSDP2 path) was rewritten. The PR also lands two TODOs with no link, one of them a literal placeholder.
What this PR does. It adds parallelism.fsdp_backend: FlexShardConfig | None. decoder_fsdp_groups describes the decoder's FSDP groups once: embedding, norm+head, each block (with non-Shard(0) and routed-expert placements), and the root leftovers. FSDP2 calls fully_shard on each group. FlexShard maps each group to an fsdp2_compatible bucket. as_fsdp2_dtensor gives the DTensor view used for init and for grad-norm clipping. Unsupported features raise in validate_flex_shard_training, validate_model_training_config, the GraphTrainer, FT and RL trainers, and apply_flex_shard_to_decoder (preserve_dtype_params, MXFP8/NVFP4).
Example.
llama3 debugmodel, dp_shard=4, CE loss, accelerator graphs off
fsdp_backend=None -> fully_shard([tok_emb]), fully_shard([norm, lm_head]), fully_shard([layer_i]), fully_shard(root)
fsdp_backend=FlexShardConfig() -> flex_shard(model, buckets=[tok_emb], [norm, lm_head], [layers.i], [root leftovers])
claim: identical loss / grad_norm / grads / params at every step
Resolved since the last review: GraphTrainer, FT and RL trainers now reject the backend; routed_expert_param_placements is inlined; the parity test covers an MoE model (qwen3 debugmodel_moe); the description is up to date apart from its results.
Must fix
- Description: both results are
<fill in>. Before merge, it needs (a) FSDP2 before vs. after this PR with seed 42 and deterministic mode, fromscripts/loss_compare.py --assert-equal, because the main training path was refactored; and (b) a link to the CI run showing thattest_flex_shard_fsdp.py::test_matches_fsdp2ran and passed.importorskipstays in, so a broken flex_shard install would show up as a green skip (tests rules: verify the intended test actually ran). torchtitan/config/validation.py:60-- theTODO(<re-tie PR>)placeholder (inline).torchtitan/distributed/flex_shard_fsdp.py:183-- still open from the last round: theTODOneeds the meta-pytorch/flex_shard issue link. This shim is whyModule._init_paramandclip_grad_norm_know about FlexShard.
Should consider
torchtitan/config/parallelism.py:78-- an emptyFlexShardConfig, withNonemeaning FSDP2, misuses theX.Config | Noneconvention (inline).torchtitan/distributed/fsdp.py:239-- checkisinstance(model_part, FSDPModule)instead of passingfsdp_backendinto the core training loop (inline).- Still open:
apply_flex_shard_to_decoder'spp_enabled(flex_shard_fsdp.py:62) is alwaysFalsebecause PP is rejected. Passpp_enabled=Falsetodecoder_fsdp_groupsand drop the parameter and the caller's argument. test_flex_shard_fsdp.py: qwen3debugmodel_moehas 64 experts ondp_shard=4, so the routed-expert row-sharding branch (expert_sharding_size > num_experts,fsdp.py:~196) is still not exercised under FlexShard. A flavor with fewer experts than 4 would cover it, if one exists.
Questions
- Still unanswered from both earlier rounds: how does the in-tree
torchtitan/distributed/flex_shard/package (optimizer reshard, DistMuon) relate tometa-pytorch/flex_shard?flex_shard/andflex_shard_fsdp.pysitting side by side is confusing.
Details
- Overrides of
parallelizein gpt_oss, qwen3_5, kimi_k2_7 and muse_glimmer all callsuper().parallelize, so they reachDecoder._apply_fsdp. kimi_k3 and flux are rejected through their_apply_fsdpoverrides, and GraphTrainer is now rejected in its config. I found no other way past the backend guard. - qwen3_5 sets
preserve_dtype_params, so with FlexShard it passes config validation and then raises inapply_flex_shard_to_decoderat parallelize time. That is still an explicit error, just a later one. - EP>1 refactor: placements are now merged with the routed-expert ones winning, and the mesh is chosen by membership in
routed_experts.parameters(). This is equivalent to the old two-dict lookup.
Not verified: the bitwise-parity claim (needs 4 GPUs with flex_shard), and that fully_shard([block]) registers the same hooks as fully_shard(block) (the FSDP2 before/after comparison above would settle it).
A maintainer still needs to review, since the PR touches core code.
parallelism.fsdp_backend=FlexShardConfig() trains with FlexShard (meta-pytorch/flex_shard) in place of FSDP2's fully_shard; None, the default, keeps FSDP2. This is the first step of replacing FSDP2: data parallelism over dp_shard for decoders, with training bitwise identical to FSDP2. Both backends now take a decoder's groups from decoder_fsdp_groups: the embedding (with the norm and output projection when weights are tied), the norm with the output projection, and each transformer block, each with its reshard_after_forward policy and its stacked-linear and routed-expert placements. apply_fsdp_to_decoder passes each group to fully_shard, as before. apply_flex_shard_to_decoder gives FlexShard one fsdp2_compatible bucket per group, plus one for the parameters left to the root, with the same param_dtype and reduce_dtype as mixed_precision_policy. Gradients are summed without division, as disable_fsdp_gradient_division makes FSDP2 do. FSDP2 skips the embedding's backward all-gather, which FlexShard can't yet; values are unaffected. FlexShard stores parameters as plain local shards, while torchtitan relies on FSDP2's DTensor parameters in two places. Module._init_param and clip_grad_norm_ go through as_fsdp2_dtensor, the DTensor FSDP2 would give a parameter or its grad, so initialization matches FSDP2's, and each rank clips with the global norm rather than its local one. Gradient accumulation with fsdp_defer_gradient_reduction goes through set_is_last_accumulation_step, which covers both backends. FlexShard is imported only when selected. Config validation rejects what it does not support yet, in the trainer config's __post_init__, which the config loader runs again after recipes assign fields: HSDP; tensor, context, expert and pipeline parallelism; symmetric-memory communication; CPU offloading; accelerator graphs; ChunkedLossWrapper; checkpointing; EMA; DistMuon; SPMD typechecking; any model that overrides Decoder._apply_fsdp (multimodal models, DeepSeek V3 and V4, Flux and the transformers modeling backend); and tied weights, which parallelization unties until init_states ties them again, too late for FlexShard. GraphTrainer (SimpleFSDP), FaultTolerantTrainer (whose replica all-reduce hooks FSDP2) and the RL trainer (which would publish FlexShard's local shards as full weights) reject it too. apply_flex_shard_to_decoder rejects preserve_dtype_params and quantized MXFP8/NVFP4 weights, which FlexShard would compute differently. The multi-GPU unit-test job installs flex_shard at a pinned commit, so the parity test runs in CI. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: f7e0e2e Pull-Request: #5842
| @@ -0,0 +1,204 @@ | |||
| # Copyright (c) Meta Platforms, Inc. and affiliates. | |||
There was a problem hiding this comment.
flex_shard is not a FSDP; they are parallel to each other.
flex_shard.py is good enough I think.
I know we have a flex_shard/ folder for DistMuon, but that will be moved to flex_shard repo.
…ackend.Config() Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the checkpointing PR, the Hugging Face load PR, the tensor- and context-parallelism PR, the DeepSeek V3 PR, the accelerator-graphs PR, the integration-tests-and-docs PR, the EMA PR, the DistMuon PR, the DeepSeek V3 DistMuon recipe PR and the DeepSeek V3 MTP PR. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Description `FlexShardBackend.validate_model` rejects `pipeline_parallel_degree > 1`. Deleting the rejection alone would train differently from FSDP2: - **Pipeline schedules don't recognize FlexShard stages.** PyTorch's pipeline stages and schedules treat a stage module as data parallel only if it is an `FSDPModule`. They would never unshard a FlexShard stage ahead of its compute, defer its gradient reduction across microbatches, or finalize it at the end of the step. - **The chunked loss reduce-scatters every microbatch.** On the last stage, `flex_shard_partial_backwards` turned `lm_head`'s bucket's gradient sync on for the last chunk of each microbatch, while the schedule keeps sync off until the end of the step. With the schedules fixed, Llama 3 debug under 1F1B at `pp=2, dp_shard=2` (8 microbatches) runs 12 reduce-scatters per step on the last stage instead of FSDP2's 4, and its loss leaves FSDP2's at step 6. - **ZBV loses the final norm's grad.** After the chunks, `flex_shard_partial_backwards` resharded `lm_head`'s bucket, which also holds the final norm. A zero-bubble schedule's input pass then takes the sharded `norm.weight`, so its weight pass never computes that grad: with the other fixes, Llama 3 debug under ZBV at `pp=2` on 2 GPUs has a step-1 grad norm of 1.4159 with FlexShard and 1.4189 with FSDP2. - **Grads accumulate in bf16 across microbatches.** With bf16 parameters, FlexShard sums the grads of no-sync backwards in bf16, where FSDP2 sums them in fp32. The fixes are in three repositories. As in #5842, nothing on the FlexShard path creates a DTensor. - **PyTorch:** pytorch/pytorch#205659, "[pipelining] Treat any module with FSDP2's stage methods as sharded data parallel" (not merged yet). Pipeline stages and schedules check for the six methods they call, which FlexShard modules have, instead of for `FSDPModule`. - **flex_shard** (not merged yet): - "Sum the grads of a module called more than once per backward as FSDP2 does", the fix the DeepSeek V3 MTP PR needs, also sums the Linear weights' grads across no-sync backwards in fp32. - "Run the end-of-backward pass for no-sync buckets under manual backward finalization, as FSDP2 does" does the same for the embedding. - "Add requires_gradient_sync and manual_backward_finalization getters to bucket storages". - **This PR:** - `flex_shard_partial_backwards` reads the caller's gradient sync and whether backward finalization is manual through those getters. Under manual finalization, i.e. a pipeline schedule, every chunk keeps its grads and the bucket stays unsharded after the chunks, as FSDP2's `fsdp_partial_backwards` leaves reductions and parameter residency to the schedule. Otherwise the last chunk takes the caller's setting, and the caller's settings are restored instead of set to True. That's no change today: validation rejects deferred gradient reduction, so sync is on outside. - `FlexShardBackend.validate_model` no longer rejects pipeline parallelism. It rejects it with a PyTorch whose pipelining lacks pytorch/pytorch#205659, which would neither defer nor finalize FlexShard's reductions (a TODO to drop the check once torchtitan's minimum PyTorch has it). `FlexShardBackend.validate_trainer` rejects `checkpointer.initial_load_in_hf` with pipeline parallelism: `load_hf_into_local_shards` groups and broadcasts over all ranks, which assumes every rank holds the same keys, and pipeline stages don't (a TODO, and a note at that assumption). - Accelerator graphs with pipeline parallelism stay allowed: they match FSDP2 bitwise (below). - The TODO on deferred gradient reduction now says what's left there: FSDP2's `fsdp_partial_backwards` leaves the last chunk's reduction to the outer backward when earlier microbatches kept grads. - `FLEX_SHARD_FSDP.md` lists pipeline parallelism as supported (with a PyTorch that has pytorch/pytorch#205659), replaces its rejection with the Hugging Face load's, and lists the new integration test. Before this lands, torchtitan's CI pin of flex_shard (`.github/scripts/install_flex_shard.sh`, `d6bb546`) has to move to a commit with the three flex_shard changes, and CI's PyTorch nightly has to include pytorch/pytorch#205659. Without that PyTorch, validation rejects pipeline parallelism with FlexShard. The new pin is needed without pipeline parallelism too: `flex_shard_partial_backwards` now reads the getters for every chunked loss. **Tests.** - `test_config_validation.py` gains `test_flex_shard_pipeline_parallelism`: FlexShard with `pipeline_parallel_degree=2` is accepted when pipelining recognizes FlexShard modules and rejected when it doesn't (pytorch/pytorch#205659's helper removed), and a Hugging Face load with pipeline parallelism is rejected. The file passes (26). - `deepseek_v3_flex_shard+cp+pp+ep` in the models suite is a Real PG FlexShard twin of `deepseek_v3_fsdp+cp+pp+ep` (DeepSeek V3 debug, `dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`, 8 GPUs), as the integration-tests PR's twins are: the same config with `fsdp_backend=FlexShardBackend.Config()`, checked bitwise against the FSDP2 entry's golden, from the same seed checkpoint (`deepseek_v3_debugmodel`). ROCm skips it (`hardware_skips/skipped_tests.toml`), and release validation's `--exclude` list gains it. `test_integration_test_definitions.py` and `test_context_parallel_validation.py` pass (52 passed, 40 subtests). - No GPU unit parity test: `_check_matches_fsdp2` builds models with `model.parallelize` and runs its own microbatch loop, while a pipeline schedule owns the step, the loss and the reductions, so a pipeline case would need a second harness around `model.pipeline`. The twin and the runs below check pipeline parallelism end to end. - With the three flex_shard changes, `test_matches_fsdp2_with_tied_weights_and_chunked_loss` and `test_matches_fsdp2_with_tensor_parallelism`, whose chunked losses go through `flex_shard_partial_backwards` without pipeline parallelism, pass on 2 GB200 GPUs with `world_size` set to 2. - flake8 and ufmt pass on the changed files. **FlexShard matches FSDP2.** All runs use torch with pytorch/pytorch#205659, flex_shard with the three changes, seed 42, deterministic, 8 microbatches, flex attention (FA4 isn't installed on the test machine) and the recipes' `ChunkedLossWrapper`. Both backends load the same seed checkpoint, made without pipeline parallelism on one GPU. - On 2 GB200 GPUs at `pp=2`, `scripts/loss_compare.py --assert-equal --metrics loss,grad_norm` over 20 steps reports equal loss and grad norm at every step (step-20 loss and grad norm): | Config | Step 20 | | --- | --- | | Llama 3 debug, 1F1B | 3.11325 / 0.7644 | | Llama 3 debug, Interleaved1F1B | 3.11325 / 0.7644 | | Llama 3 debug, ZBV | 3.11323 / 0.7642 | | DeepSeek V3 debug, 1F1B | 3.13358 / 0.5802 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.11325 / 0.7644 | The graphs run records the forward-backward graph on both backends. At `dp_shard=1` no reduce-scatter runs, which the runs below add. - On 4 GB300 GPUs at `pp=2, dp_shard=2` (MAST), one training per backend for 20 steps, TensorBoard scalars compared exactly: loss, max loss and grad norm are bitwise identical at every step, and so is the load-balance loss for DeepSeek V3: | Config | Step 20 | | --- | --- | | Llama 3 debug, Interleaved1F1B | 3.14708 / 0.7182 | | DeepSeek V3 debug, `ep=2`, 1F1B | 3.18157 / 0.5915 | | DeepSeek V3 debug, `ep=2`, ZBV | 3.18201 / 0.6053 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.14708 / 0.7182 | On 8 GB300 GPUs, the twin's config and its FSDP2 counterpart (`dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`) are bitwise identical in the same scalars over 20 steps (step-20 loss 3.18164, grad norm 0.6002). MAST's PyTorch build lacks pytorch/pytorch#205659. Its pipelining files are those of the PR's base, so the jobs loaded the PR's three changed files (`torch/distributed/pipelining/_utils.py`, `stage.py` and `schedules.py`) in their place through an import hook in `sitecustomize`, checked at startup. - The 2-GPU runs and the 4-GPU runs without graphs started before the PyTorch check in validation and the twin's definition were added. Their FlexShard and pipeline code is this commit's. - ZBV needs workarounds on both backends, so it's out of scope here: functorch's `donated_buffer=False`, since compiled flex attention's backward donates buffers that the split backward's `retain_graph` needs; full activation remat for Llama 3; and no remat for DeepSeek V3, whose default remat unpacks a saved input twice in the split backward and whose full remat's MoE routing placeholder fails. **FSDP2 is unchanged.** FSDP2's code doesn't change. `scripts/loss_compare.py <the DeepSeek V3 MTP PR> <this PR>` with FSDP2 on Llama 3 debug at `pp=2`, Interleaved1F1B, the chunked loss, 20 steps, without a seed checkpoint (both start from seed 42 with the same parallelism), 2 GB200 GPUs, reports equal loss and grad norm at every step (step-20 loss 3.13296, grad norm 0.7869). **Not covered:** deferred gradient reduction, with or without pipeline parallelism (it needs flex_shard's equivalent of FSDP2's `set_is_last_backward`); Hugging Face loads with pipeline parallelism; and MTP layers with pipeline parallelism, which torchtitan rejects for both backends. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 751f488 Pull-Request: #6243
…ackend.Config() Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the checkpointing PR, the Hugging Face load PR, the tensor- and context-parallelism PR, the DeepSeek V3 PR, the accelerator-graphs PR, the integration-tests-and-docs PR, the EMA PR, the DistMuon PR, the DeepSeek V3 DistMuon recipe PR and the DeepSeek V3 MTP PR. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Description `FlexShardBackend.validate_model` rejects `pipeline_parallel_degree > 1`. Deleting the rejection alone would train differently from FSDP2: - **Pipeline schedules don't recognize FlexShard stages.** PyTorch's pipeline stages and schedules treat a stage module as data parallel only if it is an `FSDPModule`. They would never unshard a FlexShard stage ahead of its compute, defer its gradient reduction across microbatches, or finalize it at the end of the step. - **The chunked loss reduce-scatters every microbatch.** On the last stage, `flex_shard_partial_backwards` turned `lm_head`'s bucket's gradient sync on for the last chunk of each microbatch, while the schedule keeps sync off until the end of the step. With the schedules fixed, Llama 3 debug under 1F1B at `pp=2, dp_shard=2` (8 microbatches) runs 12 reduce-scatters per step on the last stage instead of FSDP2's 4, and its loss leaves FSDP2's at step 6. - **ZBV loses the final norm's grad.** After the chunks, `flex_shard_partial_backwards` resharded `lm_head`'s bucket, which also holds the final norm. A zero-bubble schedule's input pass then takes the sharded `norm.weight`, so its weight pass never computes that grad: with the other fixes, Llama 3 debug under ZBV at `pp=2` on 2 GPUs has a step-1 grad norm of 1.4159 with FlexShard and 1.4189 with FSDP2. - **Grads accumulate in bf16 across microbatches.** With bf16 parameters, FlexShard sums the grads of no-sync backwards in bf16, where FSDP2 sums them in fp32. The fixes are in three repositories. As in #5842, nothing on the FlexShard path creates a DTensor. - **PyTorch:** pytorch/pytorch#205659, "[pipelining] Treat any module with FSDP2's stage methods as sharded data parallel" (not merged yet). Pipeline stages and schedules check for the six methods they call, which FlexShard modules have, instead of for `FSDPModule`. - **flex_shard** (not merged yet): - "Sum the grads of a module called more than once per backward as FSDP2 does", the fix the DeepSeek V3 MTP PR needs, also sums the Linear weights' grads across no-sync backwards in fp32. - "Run the end-of-backward pass for no-sync buckets under manual backward finalization, as FSDP2 does" does the same for the embedding. - "Add requires_gradient_sync and manual_backward_finalization getters to bucket storages". - **This PR:** - `flex_shard_partial_backwards` reads the caller's gradient sync and whether backward finalization is manual through those getters. Under manual finalization, i.e. a pipeline schedule, every chunk keeps its grads and the bucket stays unsharded after the chunks, as FSDP2's `fsdp_partial_backwards` leaves reductions and parameter residency to the schedule. Otherwise the last chunk takes the caller's setting, and the caller's settings are restored instead of set to True. That's no change today: validation rejects deferred gradient reduction, so sync is on outside. - `FlexShardBackend.validate_model` no longer rejects pipeline parallelism. It rejects it with a PyTorch whose pipelining lacks pytorch/pytorch#205659, which would neither defer nor finalize FlexShard's reductions (a TODO to drop the check once torchtitan's minimum PyTorch has it). `FlexShardBackend.validate_trainer` rejects `checkpointer.initial_load_in_hf` with pipeline parallelism: `load_hf_into_local_shards` groups and broadcasts over all ranks, which assumes every rank holds the same keys, and pipeline stages don't (a TODO, and a note at that assumption). - Accelerator graphs with pipeline parallelism stay allowed: they match FSDP2 bitwise (below). - The TODO on deferred gradient reduction now says what's left there: FSDP2's `fsdp_partial_backwards` leaves the last chunk's reduction to the outer backward when earlier microbatches kept grads. - `FLEX_SHARD_FSDP.md` lists pipeline parallelism as supported (with a PyTorch that has pytorch/pytorch#205659), replaces its rejection with the Hugging Face load's, and lists the new integration test. Before this lands, torchtitan's CI pin of flex_shard (`.github/scripts/install_flex_shard.sh`, `d6bb546`) has to move to a commit with the three flex_shard changes, and CI's PyTorch nightly has to include pytorch/pytorch#205659. Without that PyTorch, validation rejects pipeline parallelism with FlexShard. The new pin is needed without pipeline parallelism too: `flex_shard_partial_backwards` now reads the getters for every chunked loss. **Tests.** - `test_config_validation.py` gains `test_flex_shard_pipeline_parallelism`: FlexShard with `pipeline_parallel_degree=2` is accepted when pipelining recognizes FlexShard modules and rejected when it doesn't (pytorch/pytorch#205659's helper removed), and a Hugging Face load with pipeline parallelism is rejected. The file passes (26). - `deepseek_v3_flex_shard+cp+pp+ep` in the models suite is a Real PG FlexShard twin of `deepseek_v3_fsdp+cp+pp+ep` (DeepSeek V3 debug, `dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`, 8 GPUs), as the integration-tests PR's twins are: the same config with `fsdp_backend=FlexShardBackend.Config()`, checked bitwise against the FSDP2 entry's golden, from the same seed checkpoint (`deepseek_v3_debugmodel`). ROCm skips it (`hardware_skips/skipped_tests.toml`), and release validation's `--exclude` list gains it. `test_integration_test_definitions.py` and `test_context_parallel_validation.py` pass (52 passed, 40 subtests). - No GPU unit parity test: `_check_matches_fsdp2` builds models with `model.parallelize` and runs its own microbatch loop, while a pipeline schedule owns the step, the loss and the reductions, so a pipeline case would need a second harness around `model.pipeline`. The twin and the runs below check pipeline parallelism end to end. - With the three flex_shard changes, `test_matches_fsdp2_with_tied_weights_and_chunked_loss` and `test_matches_fsdp2_with_tensor_parallelism`, whose chunked losses go through `flex_shard_partial_backwards` without pipeline parallelism, pass on 2 GB200 GPUs with `world_size` set to 2. - flake8 and ufmt pass on the changed files. **FlexShard matches FSDP2.** All runs use torch with pytorch/pytorch#205659, flex_shard with the three changes, seed 42, deterministic, 8 microbatches, flex attention (FA4 isn't installed on the test machine) and the recipes' `ChunkedLossWrapper`. Both backends load the same seed checkpoint, made without pipeline parallelism on one GPU. - On 2 GB200 GPUs at `pp=2`, `scripts/loss_compare.py --assert-equal --metrics loss,grad_norm` over 20 steps reports equal loss and grad norm at every step (step-20 loss and grad norm): | Config | Step 20 | | --- | --- | | Llama 3 debug, 1F1B | 3.11325 / 0.7644 | | Llama 3 debug, Interleaved1F1B | 3.11325 / 0.7644 | | Llama 3 debug, ZBV | 3.11323 / 0.7642 | | DeepSeek V3 debug, 1F1B | 3.13358 / 0.5802 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.11325 / 0.7644 | The graphs run records the forward-backward graph on both backends. At `dp_shard=1` no reduce-scatter runs, which the runs below add. - On 4 GB300 GPUs at `pp=2, dp_shard=2` (MAST), one training per backend for 20 steps, TensorBoard scalars compared exactly: loss, max loss and grad norm are bitwise identical at every step, and so is the load-balance loss for DeepSeek V3: | Config | Step 20 | | --- | --- | | Llama 3 debug, Interleaved1F1B | 3.14708 / 0.7182 | | DeepSeek V3 debug, `ep=2`, 1F1B | 3.18157 / 0.5915 | | DeepSeek V3 debug, `ep=2`, ZBV | 3.18201 / 0.6053 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.14708 / 0.7182 | On 8 GB300 GPUs, the twin's config and its FSDP2 counterpart (`dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`) are bitwise identical in the same scalars over 20 steps (step-20 loss 3.18164, grad norm 0.6002). MAST's PyTorch build lacks pytorch/pytorch#205659. Its pipelining files are those of the PR's base, so the jobs loaded the PR's three changed files (`torch/distributed/pipelining/_utils.py`, `stage.py` and `schedules.py`) in their place through an import hook in `sitecustomize`, checked at startup. - The 2-GPU runs and the 4-GPU runs without graphs started before the PyTorch check in validation and the twin's definition were added. Their FlexShard and pipeline code is this commit's. - ZBV needs workarounds on both backends, so it's out of scope here: functorch's `donated_buffer=False`, since compiled flex attention's backward donates buffers that the split backward's `retain_graph` needs; full activation remat for Llama 3; and no remat for DeepSeek V3, whose default remat unpacks a saved input twice in the split backward and whose full remat's MoE routing placeholder fails. **FSDP2 is unchanged.** FSDP2's code doesn't change. `scripts/loss_compare.py <the DeepSeek V3 MTP PR> <this PR>` with FSDP2 on Llama 3 debug at `pp=2`, Interleaved1F1B, the chunked loss, 20 steps, without a seed checkpoint (both start from seed 42 with the same parallelism), 2 GB200 GPUs, reports equal loss and grad norm at every step (step-20 loss 3.13296, grad norm 0.7869). **Not covered:** deferred gradient reduction, with or without pipeline parallelism (it needs flex_shard's equivalent of FSDP2's `set_is_last_backward`); Hugging Face loads with pipeline parallelism; and MTP layers with pipeline parallelism, which torchtitan rejects for both backends. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 751f488 Pull-Request: #6243
|
@claude review this pr and make sure tianyu's feedback has been addressed |
|
Claude finished @anshul-si's task in 2m 39s —— View job Approve, with items to fix before merging. 10 of @tianyu-l's 11 comments are resolved at HEAD; the split of the validation call is only partly done and needs his confirmation. There is one new issue: the sharding backend comes from two sources that can disagree. review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. At HEAD, 10 of @tianyu-l's 11 comments are fixed in code or answered by the author. The validation-placement comment is only partly done and needs @tianyu-l to confirm. One new issue: the backend now has two sources that can disagree.
What this PR does. parallelism.fsdp_backend holds a ShardingBackend.Config (FullyShardBackend by default, or FlexShardBackend). The backend owns validate_model, validate_trainer, apply_to_decoder and clip_grad_norm_, so no caller branches on which backend is in use. Both backends get their units from the shared decoder_sharding_units. FSDP2 calls fully_shard on each unit, and FlexShard makes one bucket per unit plus a root bucket.
Example.
parallelism.fsdp_backend = FlexShardBackend.Config()
validate_model_training_config -> backend.validate_model(...) # model/parallelism/training
TrainingEngine.Config.__post_init__ -> backend.validate_trainer(...) # loss/ckpt/optim/trainer
Decoder._apply_fsdp -> parallelism.fsdp_backend.build().apply_to_decoder(...)
GradientClipper -> parallelism_context.sharding_backend.clip_grad_norm_(...)
@tianyu-l's comments, checked at HEAD
| Comment | Status |
|---|---|
training_engine.py: call validation in validate_model_training_config |
Partly. The model/parallelism/training checks moved there (validation.py:253). The loss/checkpointer/optim/trainer-class checks still run in core, now in TrainingEngine.Config.__post_init__ (training_engine.py:252), because validate_model_training_config doesn't receive those configs. The reason is valid, but it leaves two hooks on the ABC and a backend call in core. @tianyu-l should confirm this split, or ask for those four configs to be passed to validate_model_training_config. |
parallelism.py: StrEnum, or make it object-oriented with no if-else on the backend |
Resolved: ShardingBackend Configurable with sibling configs. There are no isinstance(..., FlexShard*) branches left outside the backend modules. |
parallelism_context.py: why translate to a bool? |
Resolved: the context holds the built backend. This introduces the issue below. |
utils.py: top-level if-else or separate clip_grad_norm_ |
Resolved: each backend has its own clip_grad_norm_, and the shared tail is clip_grads_with_mesh_norms_. |
File name: flex_shard.py |
Answered: the file is kept as flex_shard_backend.py until DistMuon leaves distributed/flex_shard/. No pushback so far. |
apply_fsdp_to_decoder: kwargs after model |
Resolved (fsdp.py:1582), with all callers updated. |
head name |
Resolved: norm_and_lm_head. |
_apply_flex_shard: at most one positional arg |
Resolved. |
FlexShardShard name |
Resolved: custom_placements.Shard. |
_apply_fsdp2 -> _apply_fully_shard |
Resolved. |
FSDPGroup name shared with FlexShard |
Resolved: ShardingUnit / decoder_sharding_units. |
Must fix
torchtitan/distributed/parallelism_context.py:120-- the backend has two sources (parallelism.fsdp_backendfor sharding,parallelism_context.sharding_backend, which defaults to FSDP2, for clipping). The GPU parity test relies on them disagreeing and skipsGradientClipper's path (inline).- Still open from the last round:
flex_shard_backend.py:78-- the grad-norm reduction copied from flex_shard's example has noTODO(<flex_shard issue link>)to say it goes away once flex_shard provides it.
Should consider
torchtitan/config/parallelism.py:94-- the field isfsdp_backend, but the class and the context field aresharding_backend(inline).- Still open:
test_flex_shard_fsdp.py:31keepsimportorskip, even though CI now pins flex_shard. GPU Unit Tests for this revision is still queued. Please confirm from its log thattest_matches_fsdp2showsPASSED, notSKIPPED. - Following @tianyu-l's point that FlexShard will have its own knobs:
FullyShardBackendstill reads thefsdp_*fields onParallelismConfig, andFlexShardBackendsharesfsdp_reshard_after_forward. The description defers moving them to each backend'sConfig. A TODO atsharding_backend.py'sFullyShardBackendwould record that.
Details
parallelism.fsdp_backend.build()is called in four places (validation.py,training_engine.py,decoder.py,ParallelismContext.from_config). The backends are stateless, so building it repeatedly is harmless, but the_apply_fsdpcall site is the one that should read from the context.- Paths that construct
ParallelismContextdirectly (RL generator, graph_trainer precompile) belong to trainers thatvalidate_trainerrejects. No production config reaches the mismatch today, so this is a must-fix to lock in, not a live bug. - The FSDP2 refactor is unchanged in substance since the last round, and the description carries
loss_compare.py --assert-equalresults against base.
Not verified: bitwise parity on GPU (CI still queued).
A maintainer still needs to review, since the PR touches core code, and @tianyu-l's CHANGES_REQUESTED still stands.
| enable_sequence_parallel: bool | ||
| # Built from parallelism.fsdp_backend: how the data-parallel parameters are | ||
| # sharded, and what depends on it, e.g. clipping their grads. | ||
| sharding_backend: ShardingBackend = field(default_factory=_default_sharding_backend) |
There was a problem hiding this comment.
There are now two independent sources for the backend. Decoder._apply_fsdp (decoder.py:203) builds it from parallelism.fsdp_backend. GradientClipper uses this field, and this field silently defaults to FullyShardBackend whenever ParallelismContext is constructed directly instead of through from_config. Direct construction happens in the RL generator, graph_trainer's precompile_main.py, and about 20 tests. If the two disagree, the model is sharded by FlexShard but clipped by dist_utils.clip_grad_norm_ on plain local shards. Each rank then clips by its own local norm, with no error. Today only the rejected trainers construct contexts directly, so production can't hit this. The new GPU test does hit it, though: it builds a default context, shards with FlexShard, and calls parallelism.fsdp_backend.build().clip_grad_norm_ directly, so it never exercises GradientClipper's path.
Smallest fix: make this field the single source. _apply_fsdp calls parallelism_context.sharding_backend.apply_to_decoder(...), and the GPU test passes sharding_backend=FlexShardBackend.Config().build() and clips through parallelism_context.sharding_backend. Ideally also drop the default_factory, since a required field shouldn't silently pick a backend (config rules: required fields have no default). If updating the direct constructors is too much churn for this PR, keep the default, but make _apply_fsdp read from the context so sharding and clipping can't disagree.
## Summary (human-written) Our goal is to fully replace FSDP2 with FlexShard. This PR is the first step: it adds FlexShard as an experimental, opt-in backend while keeping FSDP2 as the default. This lets us test new FlexShard features and close feature gaps while users on FSDP2 see no change. ## Description torchtitan can shard data-parallel parameters only with FSDP2's `fully_shard`. This PR adds `parallelism.fsdp_backend`, the config of a `ShardingBackend` (`torchtitan/distributed/sharding_backend.py`). A `ShardingBackend` is a `Configurable` that owns the operations that depend on how the parameters are sharded: validating the config, sharding a decoder and clipping grad norms. Callers build it from its config and call it, so no code checks which backend is in use. The default, `FullyShardBackend.Config()`, keeps FSDP2. Setting it to `FlexShardBackend.Config()` shards the model with FlexShard (meta-pytorch/flex_shard) instead. FSDP2's existing `fsdp_*` options stay on `ParallelismConfig` for now, so the FSDP2 path is unchanged. This is the first step of replacing FSDP2. It covers the case where the two backends can be compared bit for bit: decoders with data parallelism over `dp_shard` only. `Decoder._apply_fsdp` calls the backend's `apply_to_decoder`, and `flex_shard` is imported only when it is selected. Later PRs in the stack add the operations they need to `ShardingBackend` rather than checking the backend. `FullyShardBackend.apply_to_decoder` runs what `Decoder._apply_fsdp` ran before: it calls `apply_fsdp_to_decoder`, which calls `fully_shard` on the embedding, on the norm with the output projection, on each transformer block, and finally on the root model for any leftover parameters. `FlexShardBackend.apply_to_decoder` (`torchtitan/distributed/flex_shard_backend.py`) takes the same units from `decoder_sharding_units`, which `apply_fsdp_to_decoder` also uses, and gives FlexShard one bucket for each. Each bucket uses its unit's mesh, shard dims and reshard-after-forward policy, the same param and reduce dtypes, `gradient_divide_factor=1.0` (gradients are summed, as `disable_fsdp_gradient_division` makes FSDP2 do) and `fsdp2_compatible=True`. The leftover root bucket, like FSDP2's root unit, isn't resharded after forward. As a result the two backends issue the same collectives, and training from the same parameters is bitwise identical. To keep the two backends from drifting apart, the grouping moved out of the FSDP2 loop into `decoder_sharding_units` in `fsdp.py`, and the rest of FSDP2's code into `_apply_fully_shard`. `decoder_sharding_units` returns each unit's modules, reshard policy, and stacked-linear and routed-expert placements. `apply_fsdp_to_decoder` now takes every argument but `model` by keyword, so its callers pass `dp_mesh` by name. The FSDP2 path's behavior doesn't change. It now passes each unit to `fully_shard` as a list (`fully_shard([block])`), and FSDP2 gives a one-module list the same per-module hooks as the module itself. The embedding's `set_unshard_in_backward(False)` condition and the EP > 1 per-parameter mesh logic are the same as before. FlexShard parameters and their grads stay plain local shards: nothing on the FlexShard path creates a DTensor. torchtitan relied on FSDP2's DTensor parameters in two places, which now handle plain shards: - **Initialization.** Right after sharding, `_apply_flex_shard` wraps each FlexShard parameter's `param_init` function with flex_shard's `init_from_full` and the layout flex_shard reports for it (`get_flex_shard_global_layouts`). The wrapped function runs the init function on a full-size tensor and keeps this rank's part, so each shard is its slice of one device's initialization. `to_empty()` rebuilds FlexShard's parameters but keeps the modules, so the wrapped functions survive it, and `models/base` doesn't change. FSDP2's DTensor init draws each shard's values separately, so the two backends start from different, equally valid, weights. A module without `param_init` falls back to `reset_parameters()`, which would draw each FlexShard shard as the whole parameter, with the same values on every rank, so such modules are rejected (below). With tied weights, which pytorch#6144 keeps tied through parallelization, flex_shard reports the shared parameter under both names. `lm_head`'s function initializes it, and `tok_embeddings`' `skip_param_init` stays a no-op rather than being wrapped. Wrapped, it would copy an uninitialized full tensor into the shard, which `lm_head`'s function overwrites only because `tok_embeddings` initializes first. - **Grad-norm clipping.** `ParallelismContext` holds the built backend, and `GradientClipper` clips with its `clip_grad_norm_`. `FullyShardBackend`'s calls `dist_utils.clip_grad_norm_`, as `GradientClipper` did before. `FlexShardBackend`'s groups the grads by their bucket's mesh (`flex_shard.get_mesh`) instead of by DTensor mesh. `flex_shard_grad_norm` reduces each group's norm over its mesh in DTensor's order (each grad's local norm, all-reduced, then the norm of those norms), ported from flex_shard's DeepSeek V3 example, so the norm matches FSDP2's bit for bit. Combining the groups' norms, the PP reduction and clipping moved out of `dist_utils.clip_grad_norm_` into `clip_grads_with_mesh_norms_`, which both backends call. FlexShard differs from FSDP2 in one way that affects memory and communication: FSDP2 skips the embedding's backward all-gather, and FlexShard can't yet, so it gathers the embedding again in backward. Anything FlexShard doesn't support yet raises a `ValueError` when the config is validated, after recipes and overrides and before distributed init. `validate_model_training_config` calls the backend's `validate_model`, which checks the model, parallelism and training options. The checks of the loss, checkpointer, optimizers and trainer read configs that `validate_model_training_config` doesn't receive, so `TrainingEngine.Config.__post_init__` calls the backend's `validate_trainer`, for every trainer. Both do nothing for `FullyShardBackend`. FlexShard's checks are temporary: each goes once FlexShard supports the feature. - **Parallelism:** HSDP, tensor, context, expert and pipeline parallelism. - **FSDP2 options:** symmetric-memory communication, CPU offloading, unsharding in the current stream (`fsdp_unshard_in_current_stream`), and deferred gradient reduction (`fsdp_defer_gradient_reduction`), since FlexShard has no `set_is_last_backward`. - **Model:** any model that overrides `_apply_fsdp` (multimodal models, DeepSeek V3 and V4, Flux and the transformers modeling backend); `preserve_dtype_params`; modules without `param_init` that have a `reset_parameters()`; and MXFP8/NVFP4 weights. All are read from the model config, so the `param_init` check also rejects modules that have no parameters to initialize, such as the `RMSNorm(elementwise_affine=False)` QK norms of muse_glimmer and muse_spark. - **Training features:** accelerator graphs, `ChunkedLossWrapper`, checkpointing, EMA, DistMuon, gradient clippers other than `GradientClipper` (only it is known to clip with the backend's `clip_grad_norm_`) and SPMD typechecking. - **Trainers:** any trainer other than `torchtitan.trainer.Trainer`, including GraphTrainer, FaultTolerantTrainer and the RL trainer. `FlexShardBackend.validate_model` then raises an `ImportError` if flex_shard isn't installed, rather than failing when the model is sharded, after distributed init. The multi-GPU unit-test job installs flex_shard at a pinned commit (`d6bb546`), so the new parity test runs in CI. That test, `test_flex_shard_fsdp.py::test_matches_fsdp2`, runs on 4 GPUs. It builds each model with both backends and checks that each FlexShard shard equals its slice of one device's initialization from the same seed. It then copies FSDP2's initial parameters into the FlexShard model and requires bitwise-equal per-microbatch losses, grad norms, gradients and parameters over three AdamW steps. It covers llama3 `debugmodel` with `fsdp_reshard_after_forward` set to default, qwen3 `debugmodel_moe` with always, and llama3 `debugmodel` with tied weights, set up as the tied Llama 3 flavors (1B, 3B) do, with default, each with two microbatches. A CPU test checks that `validate_model_training_config` rejects a model with its own `_apply_fsdp` (DeepSeek V4) instead of letting it silently shard with FSDP2, and a module without `param_init`. The existing `test_fsdp.py` covers the refactored FSDP2 path; its only edit is mechanical: it now expects `fully_shard([block])`. The optimizer and trainer unit tests that stub `clip_grad_norm_` now give their fake parallelism contexts a `FullyShardBackend`. This revision passes the parity test on 2 GB200 GPUs with `world_size` set to 2. An earlier revision also passed it, except the tied case, on 4 GB300 GPUs. On an earlier revision of this PR, based on `4122eafc0`, the FSDP2 path matched its base bit for bit: `scripts/loss_compare.py 4122eaf <that revision> --assert-equal --metrics loss,grad_norm` (seed 42, deterministic, 50 steps, 2 GB200 GPUs, `dp_shard=2`) reports equal loss and grad norm at every step for llama3 `debugmodel` (step-50 loss 2.86823), for llama3 `debugmodel` with two microbatches per step and `fsdp_defer_gradient_reduction=True` (2.83577), and for qwen3 `moe_debug` (3.71935). These runs use flex attention because the environment has no FA4, and skip the seed checkpoint, since both runs of each pair start from seed 42 with the same parallelism. Expert parallelism is the next PR in the stack. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: b9a77fb Pull-Request: pytorch#5842
…er override; agent self-review; rl/transport (#6407) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it approved, 30 then got a formal "request changes" from a maintainer, and about 20 more got substantive inline asks. In nearly all of them the bot either saw the problem and approved anyway, or never asked the questions maintainers ask most ("does the repo already do this?", "who should own this?"). The opposite failure, the bot blocking something a maintainer was fine with, is rare: in the PRs we sampled, 2 of its 81 must-fix items were wrong and about a third were minor (the empty human-written summary was the biggest source). **Example** (#6112, controller sizes the rollout worker pool): ``` before: bot approved 10 times; tianyu-l then blocked: "the controller reads rollouter.rollouts_per_worker to compute a count it hands back to the Rollouter -- violates encapsulation" after: same commit, new skill -> Request changes, must-fix #1: "controller.py:589 -- wrong owner for the worker count ..." ``` There was also no way for a code owner to overrule the bot except dismissing its review in the GitHub UI, and a later `@claude review again` would block again. ## What changed **Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`): - Verdict rules: Approve only when every remaining item is an edit the bot could write itself. Anything the author still owes (a design change, an unexplained golden change, evidence the PR rests on) is Request changes; anything only a maintainer can decide is Needs discussion. A hedge like "a maintainer should decide" can't come with Approve. - Always must-fix: a violated written rule, a silent wrong result, a second definition of an existing concept, a gate finding. - Design gate: new questions for the existing counterpart, in-repo ownership, and the design behind a bug; "ban only what doesn't work on main"; read the numbers behind a claim. The overlapping-PR search is mandatory and reported. - Re-review covers every commit since the last full review, including code taken from the bot's own suggestions. A scoped question gets a `COMMENT`, not a whole-PR verdict. - The bot fact-checks its own proposed fixes, and cites a source for claims about external tools or marks them unverified (never must-fix). - An empty "Summary (human-written)" is a one-line "Before merge" note that never affects the verdict. - Checklist: config ownership direction, general shared wrappers, dead code the PR creates, model variants as flavors, a mechanical pass over every new or changed function. **Code owner override** (`SKILL.md`, `claude-code.yml`, `CONTRIBUTING.md`): a code owner comments `@claude override` (optionally `@claude override 2,3: <reason>`); the bot approves if nothing else is open and doesn't re-raise the overridden items. A code owner's GitHub approval or "LGTM" is not an override, so a teammate can approve without the bot dropping its findings. Dismissing the bot's review still unblocks the PR, but isn't an override: the bot can't tell who dismissed it. **Agent self-review** (`CLAUDE.md`, `pr-description`): an agent preparing a PR runs `pr-review` in branch mode first and records unaddressed items in an optional "Self-review" section. PRs written without an agent are unaffected; a missing section is never a finding. Where each new rule comes from (maintainer asks the bot missed): | Change | PRs | | --- | --- | | No Approve with open design/evidence items or a "maintainer should decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 | | Author waiver can't clear a must-fix | #6201, #6202, #6203 | | Existing counterpart; one source of truth | #5228, #6169, #5881, #5823, #5824, #6059, #5812 | | Responsibility owner; config ownership direction | #6112, #6332, #5802, #5803, #6325 | | Fix the design behind the bug; a TODO doesn't justify a workaround | #5572, #5689, #5657 | | Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819, #5543 | | Re-review covers all new commits; scoped asks don't approve | #5824, #5842 | | Mandatory overlap search | #5885, #6248 | | Ban only what doesn't work on main | #5543 | | Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868 | **Rules**: `design.md` gets the one-general-wrapper rule (moved from `models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the consumer owning its values; `config.md` gets ownership direction and "a Config doesn't read runtime state"; `direction.md` calls all-to-all the MoE reference implementation, so a new vendor-specific dispatch path (e.g. #6242) needs a reason the existing backends can't serve. **Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/` -> d4l3k. **Mechanical, skim**: `torchtitan/rl/transport/` holds data movement between RL actors. - `rl/model_state_dict_transport.py` -> `rl/transport/model_state_dict.py` - `rl/MODEL_STATE_DICT_TRANSPORT.md` -> `rl/transport/MODEL_STATE_DICT_TRANSPORT.md` - `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py` - tests: `tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py` -> `tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py` - imports, READMEs and `scripts/install_rl_env.sh` updated; no code changes. ## User-facing changes | Before | After | | --- | --- | | Overrule the bot: dismiss its review in the UI, and it blocks again on the next run | `@claude override [items]: <reason>`; the bot approves and doesn't re-raise them | | Empty human-written summary: bot must-fix | One "Before merge" line, no effect on the verdict | | `from torchtitan.rl.model_state_dict_transport import ...` | `from torchtitan.rl.transport.model_state_dict import ...` | | `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from torchtitan.rl.transport.rdma_microbatch import ...` | ## Testing Backtest: the new skill run locally (nothing posted) on each PR at the commit and thread state the bot originally saw. | PR | Bot then | New skill | What the maintainer asked | | --- | --- | --- | --- | | #6112 | Approve | Request changes | worker-count ownership (caught) | | #5837 | Approve | Request changes | apply to `dp_shard` too (caught) | | #5572 | Approve | Request changes | delete the injection design (caught) | | #6201 | Approve after author waived pins | Request changes, waiver ignored | pins broke GPU tests after merge (caught) | | #6007 | Approve | Request changes | fold K3.1 into K3 (caught) | | #5543 | Request changes: "ban it" | Request changes: keep main's path | don't break gpt-oss + DeepEP (fixed) | | #6144, #5905 (controls) | Approve | Approve | -- | | #6137 (control) | Approve | Needs discussion | -- (merge gate on an upstream API) | Code owner override, simulated on #6201: override by a code owner lifts the named item; `@claude override` from the author changes nothing; a code owner's "LGTM" approval followed by "review again" keeps Request changes. Transport move: 83 RL CPU unit tests pass locally (`transport/test_model_state_dict.py`, `test_trainer.py`, `test_engine_loop.py`). `transport/test_rdma_microbatch.py`, `test_generator.py` and `test_batcher_actor.py` fail to collect in my env on `origin/main` too (stale attention-gym / Monarch), so CI is the check for those. ## Known issues / follow-ups - Open PRs that edit the moved files rebase cleanly (git follows the renames), but new imports of the old module paths will break: #6309 (adds a delta transport that should live in `rl/transport/`), #6237, #6176, #6177, #5862, and drafts #6127, #6393, #6163, #5764. - The Actions bot can't read dependency source (e.g. SGLang); follow-up for the workflow. ## Self-review pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch mode diffs against `origin/main` and skips description findings before a description exists; the "Config doesn't read runtime state" rule no longer contradicts hardware validation; dismissal dropped as an override form (the bot can't tell who dismissed); `test_rdma_microbatch.py` added to the transport area. Not addressed: - One concern per PR -- the five changes ship together at the maintainer's request. - Open PRs touching the moved files -- listed above; the maintainer will coordinate.
tianyu-l
left a comment
There was a problem hiding this comment.
Great progress! Some more comments.
Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the checkpointing PR, the Hugging Face load PR, the tensor- and context-parallelism PR, the DeepSeek V3 PR, the accelerator-graphs PR, the integration-tests-and-docs PR, the EMA PR, the DistMuon PR, the DeepSeek V3 DistMuon recipe PR and the DeepSeek V3 MTP PR. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Description `FlexShardConfig.validate_model` rejects `pipeline_parallel_degree > 1`. Deleting the rejection alone would train differently from FSDP2: - **Pipeline schedules don't recognize FlexShard stages.** PyTorch's pipeline stages and schedules treat a stage module as data parallel only if it is an `FSDPModule`. They would never unshard a FlexShard stage ahead of its compute, defer its gradient reduction across microbatches, or finalize it at the end of the step. - **The chunked loss reduce-scatters every microbatch.** On the last stage, `FlexShardConfig._partial_backwards` turned `lm_head`'s bucket's gradient sync on for the last chunk of each microbatch, while the schedule keeps sync off until the end of the step. With the schedules fixed, Llama 3 debug under 1F1B at `pp=2, dp_shard=2` (8 microbatches) runs 12 reduce-scatters per step on the last stage instead of FSDP2's 4, and its loss leaves FSDP2's at step 6. - **ZBV loses the final norm's grad.** After the chunks, `_partial_backwards` resharded `lm_head`'s bucket, which also holds the final norm. A zero-bubble schedule's input pass then takes the sharded `norm.weight`, so its weight pass never computes that grad: with the other fixes, Llama 3 debug under ZBV at `pp=2` on 2 GPUs has a step-1 grad norm of 1.4159 with FlexShard and 1.4189 with FSDP2. - **Grads accumulate in bf16 across microbatches.** With bf16 parameters, FlexShard sums the grads of no-sync backwards in bf16, where FSDP2 sums them in fp32. The fixes are in three repositories. As in #5842, nothing on the FlexShard path creates a DTensor. - **PyTorch:** pytorch/pytorch#205659, "[pipelining] Treat any module with FSDP2's stage methods as sharded data parallel" (not merged yet). Pipeline stages and schedules check for the six methods they call, which FlexShard modules have, instead of for `FSDPModule`. - **flex_shard** (not merged yet): - "Sum the grads of a module called more than once per backward as FSDP2 does", the fix the DeepSeek V3 MTP PR needs, also sums the Linear weights' grads across no-sync backwards in fp32. - "Run the end-of-backward pass for no-sync buckets under manual backward finalization, as FSDP2 does" does the same for the embedding. - "Add requires_gradient_sync and manual_backward_finalization getters to bucket storages". - **This PR:** - `_partial_backwards` reads the caller's gradient sync and whether backward finalization is manual through those getters. Under manual finalization, i.e. a pipeline schedule, every chunk keeps its grads and the bucket stays unsharded after the chunks, as FSDP2's `fsdp_partial_backwards` leaves reductions and parameter residency to the schedule. Otherwise the last chunk takes the caller's setting, and the caller's settings are restored instead of set to True. That's no change today: validation rejects deferred gradient reduction, so sync is on outside. - `FlexShardConfig.validate_model` no longer rejects pipeline parallelism. It rejects it with a PyTorch whose pipelining lacks pytorch/pytorch#205659, which would neither defer nor finalize FlexShard's reductions (a TODO to drop the check once torchtitan's minimum PyTorch has it). `FlexShardConfig.validate_trainer` rejects `checkpointer.initial_load_in_hf` with pipeline parallelism: `load_hf_into_local_shards` groups and broadcasts over all ranks, which assumes every rank holds the same keys, and pipeline stages don't (a TODO, and a note at that assumption). - Accelerator graphs with pipeline parallelism stay allowed: they match FSDP2 bitwise (below). - The TODO on deferred gradient reduction now says what's left there: FSDP2's `fsdp_partial_backwards` leaves the last chunk's reduction to the outer backward when earlier microbatches kept grads. - `FLEX_SHARD_FSDP.md` lists pipeline parallelism as supported (with a PyTorch that has pytorch/pytorch#205659), replaces its rejection with the Hugging Face load's, and lists the new integration test. Before this lands, torchtitan's CI pin of flex_shard (`.github/scripts/install_flex_shard.sh`, `d6bb546`) has to move to a commit with the three flex_shard changes, and CI's PyTorch nightly has to include pytorch/pytorch#205659. Without that PyTorch, validation rejects pipeline parallelism with FlexShard. The new pin is needed without pipeline parallelism too: `_partial_backwards` now reads the getters for every chunked loss. **Tests.** - `test_config_validation.py` gains `test_flex_shard_pipeline_parallelism`: FlexShard with `pipeline_parallel_degree=2` is accepted when pipelining recognizes FlexShard modules and rejected when it doesn't (pytorch/pytorch#205659's helper removed), and a Hugging Face load with pipeline parallelism is rejected. The file passes (26). - `deepseek_v3_flex_shard+cp+pp+ep` in the models suite is a Real PG FlexShard twin of `deepseek_v3_fsdp+cp+pp+ep` (DeepSeek V3 debug, `dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`, 8 GPUs), as the integration-tests PR's twins are: the same config with `storage=FlexShardConfig()`, checked bitwise against the FSDP2 entry's golden, from the same seed checkpoint (`deepseek_v3_debugmodel`). ROCm skips it (`hardware_skips/skipped_tests.toml`), and release validation's `--exclude` list gains it. `test_integration_test_definitions.py` and `test_context_parallel_validation.py` pass (52 passed, 40 subtests). - No GPU unit parity test: `_check_matches_fsdp2` builds models with `model.parallelize` and runs its own microbatch loop, while a pipeline schedule owns the step, the loss and the reductions, so a pipeline case would need a second harness around `model.pipeline`. The twin and the runs below check pipeline parallelism end to end. - With the three flex_shard changes, `test_matches_fsdp2_with_tied_weights_and_chunked_loss` and `test_matches_fsdp2_with_tensor_parallelism`, whose chunked losses go through `_partial_backwards` without pipeline parallelism, pass on 2 GB200 GPUs with `world_size` set to 2. - flake8 and ufmt pass on the changed files. **FlexShard matches FSDP2.** All runs use torch with pytorch/pytorch#205659, flex_shard with the three changes, seed 42, deterministic, 8 microbatches, flex attention (FA4 isn't installed on the test machine) and the recipes' `ChunkedLossWrapper`. Both backends load the same seed checkpoint, made without pipeline parallelism on one GPU. - On 2 GB200 GPUs at `pp=2`, `scripts/loss_compare.py --assert-equal --metrics loss,grad_norm` over 20 steps reports equal loss and grad norm at every step (step-20 loss and grad norm): | Config | Step 20 | | --- | --- | | Llama 3 debug, 1F1B | 3.11325 / 0.7644 | | Llama 3 debug, Interleaved1F1B | 3.11325 / 0.7644 | | Llama 3 debug, ZBV | 3.11323 / 0.7642 | | DeepSeek V3 debug, 1F1B | 3.13358 / 0.5802 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.11325 / 0.7644 | The graphs run records the forward-backward graph on both backends. At `dp_shard=1` no reduce-scatter runs, which the runs below add. - On 4 GB300 GPUs at `pp=2, dp_shard=2` (MAST), one training per backend for 20 steps, TensorBoard scalars compared exactly: loss, max loss and grad norm are bitwise identical at every step, and so is the load-balance loss for DeepSeek V3: | Config | Step 20 | | --- | --- | | Llama 3 debug, Interleaved1F1B | 3.14708 / 0.7182 | | DeepSeek V3 debug, `ep=2`, 1F1B | 3.18157 / 0.5915 | | DeepSeek V3 debug, `ep=2`, ZBV | 3.18201 / 0.6053 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.14708 / 0.7182 | On 8 GB300 GPUs, the twin's config and its FSDP2 counterpart (`dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`) are bitwise identical in the same scalars over 20 steps (step-20 loss 3.18164, grad norm 0.6002). MAST's PyTorch build lacks pytorch/pytorch#205659. Its pipelining files are those of the PR's base, so the jobs loaded the PR's three changed files (`torch/distributed/pipelining/_utils.py`, `stage.py` and `schedules.py`) in their place through an import hook in `sitecustomize`, checked at startup. - The 2-GPU runs and the 4-GPU runs without graphs started before the PyTorch check in validation and the twin's definition were added. Their FlexShard and pipeline code is this commit's. - ZBV needs workarounds on both backends, so it's out of scope here: functorch's `donated_buffer=False`, since compiled flex attention's backward donates buffers that the split backward's `retain_graph` needs; full activation remat for Llama 3; and no remat for DeepSeek V3, whose default remat unpacks a saved input twice in the split backward and whose full remat's MoE routing placeholder fails. **FSDP2 is unchanged.** FSDP2's code doesn't change. `scripts/loss_compare.py <the DeepSeek V3 MTP PR> <this PR>` with FSDP2 on Llama 3 debug at `pp=2`, Interleaved1F1B, the chunked loss, 20 steps, without a seed checkpoint (both start from seed 42 with the same parallelism), 2 GB200 GPUs, reports equal loss and grad norm at every step (step-20 loss 3.13296, grad norm 0.7869). **Not covered:** deferred gradient reduction, with or without pipeline parallelism (it needs flex_shard's equivalent of FSDP2's `set_is_last_backward`); Hugging Face loads with pipeline parallelism; and MTP layers with pipeline parallelism, which torchtitan rejects for both backends. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 78fc5a7 Pull-Request: #6243
Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the checkpointing PR, the Hugging Face load PR, the tensor- and context-parallelism PR, the DeepSeek V3 PR, the accelerator-graphs PR, the integration-tests-and-docs PR, the EMA PR, the DistMuon PR, the DeepSeek V3 DistMuon recipe PR and the DeepSeek V3 MTP PR. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Description `FlexShardConfig.validate_model` rejects `pipeline_parallel_degree > 1`. Deleting the rejection alone would train differently from FSDP2: - **Pipeline schedules don't recognize FlexShard stages.** PyTorch's pipeline stages and schedules treat a stage module as data parallel only if it is an `FSDPModule`. They would never unshard a FlexShard stage ahead of its compute, defer its gradient reduction across microbatches, or finalize it at the end of the step. - **The chunked loss reduce-scatters every microbatch.** On the last stage, `FlexShardConfig._partial_backwards` turned `lm_head`'s bucket's gradient sync on for the last chunk of each microbatch, while the schedule keeps sync off until the end of the step. With the schedules fixed, Llama 3 debug under 1F1B at `pp=2, dp_shard=2` (8 microbatches) runs 12 reduce-scatters per step on the last stage instead of FSDP2's 4, and its loss leaves FSDP2's at step 6. - **ZBV loses the final norm's grad.** After the chunks, `_partial_backwards` resharded `lm_head`'s bucket, which also holds the final norm. A zero-bubble schedule's input pass then takes the sharded `norm.weight`, so its weight pass never computes that grad: with the other fixes, Llama 3 debug under ZBV at `pp=2` on 2 GPUs has a step-1 grad norm of 1.4159 with FlexShard and 1.4189 with FSDP2. - **Grads accumulate in bf16 across microbatches.** With bf16 parameters, FlexShard sums the grads of no-sync backwards in bf16, where FSDP2 sums them in fp32. The fixes are in three repositories. As in #5842, nothing on the FlexShard path creates a DTensor. - **PyTorch:** pytorch/pytorch#205659, "[pipelining] Treat any module with FSDP2's stage methods as sharded data parallel" (not merged yet). Pipeline stages and schedules check for the six methods they call, which FlexShard modules have, instead of for `FSDPModule`. - **flex_shard** (not merged yet): - "Sum the grads of a module called more than once per backward as FSDP2 does", the fix the DeepSeek V3 MTP PR needs, also sums the Linear weights' grads across no-sync backwards in fp32. - "Run the end-of-backward pass for no-sync buckets under manual backward finalization, as FSDP2 does" does the same for the embedding. - "Add requires_gradient_sync and manual_backward_finalization getters to bucket storages". - **This PR:** - `_partial_backwards` reads the caller's gradient sync and whether backward finalization is manual through those getters. Under manual finalization, i.e. a pipeline schedule, every chunk keeps its grads and the bucket stays unsharded after the chunks, as FSDP2's `fsdp_partial_backwards` leaves reductions and parameter residency to the schedule. Otherwise the last chunk takes the caller's setting, and the caller's settings are restored instead of set to True. That's no change today: validation rejects deferred gradient reduction, so sync is on outside. - `FlexShardConfig.validate_model` no longer rejects pipeline parallelism. It rejects it with a PyTorch whose pipelining lacks pytorch/pytorch#205659, which would neither defer nor finalize FlexShard's reductions (a TODO to drop the check once torchtitan's minimum PyTorch has it). `FlexShardConfig.validate_trainer` rejects `checkpointer.initial_load_in_hf` with pipeline parallelism: `load_hf_into_local_shards` groups and broadcasts over all ranks, which assumes every rank holds the same keys, and pipeline stages don't (a TODO, and a note at that assumption). - Accelerator graphs with pipeline parallelism stay allowed: they match FSDP2 bitwise (below). - The TODO on deferred gradient reduction now says what's left there: FSDP2's `fsdp_partial_backwards` leaves the last chunk's reduction to the outer backward when earlier microbatches kept grads. - `FLEX_SHARD_FSDP.md` lists pipeline parallelism as supported (with a PyTorch that has pytorch/pytorch#205659), replaces its rejection with the Hugging Face load's, and lists the new integration test. Before this lands, torchtitan's CI pin of flex_shard (`.github/scripts/install_flex_shard.sh`, `d6bb546`) has to move to a commit with the three flex_shard changes, and CI's PyTorch nightly has to include pytorch/pytorch#205659. Without that PyTorch, validation rejects pipeline parallelism with FlexShard. The new pin is needed without pipeline parallelism too: `_partial_backwards` now reads the getters for every chunked loss. **Tests.** - `test_config_validation.py` gains `test_flex_shard_pipeline_parallelism`: FlexShard with `pipeline_parallel_degree=2` is accepted when pipelining recognizes FlexShard modules and rejected when it doesn't (pytorch/pytorch#205659's helper removed), and a Hugging Face load with pipeline parallelism is rejected. The file passes (26). - `deepseek_v3_flex_shard+cp+pp+ep` in the models suite is a Real PG FlexShard twin of `deepseek_v3_fsdp+cp+pp+ep` (DeepSeek V3 debug, `dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`, 8 GPUs), as the integration-tests PR's twins are: the same config with `storage=FlexShardConfig()`, checked bitwise against the FSDP2 entry's golden, from the same seed checkpoint (`deepseek_v3_debugmodel`). ROCm skips it (`hardware_skips/skipped_tests.toml`), and release validation's `--exclude` list gains it. `test_integration_test_definitions.py` and `test_context_parallel_validation.py` pass (52 passed, 40 subtests). - No GPU unit parity test: `_check_matches_fsdp2` builds models with `model.parallelize` and runs its own microbatch loop, while a pipeline schedule owns the step, the loss and the reductions, so a pipeline case would need a second harness around `model.pipeline`. The twin and the runs below check pipeline parallelism end to end. - With the three flex_shard changes, `test_matches_fsdp2_with_tied_weights_and_chunked_loss` and `test_matches_fsdp2_with_tensor_parallelism`, whose chunked losses go through `_partial_backwards` without pipeline parallelism, pass on 2 GB200 GPUs with `world_size` set to 2. - flake8 and ufmt pass on the changed files. **FlexShard matches FSDP2.** All runs use torch with pytorch/pytorch#205659, flex_shard with the three changes, seed 42, deterministic, 8 microbatches, flex attention (FA4 isn't installed on the test machine) and the recipes' `ChunkedLossWrapper`. Both backends load the same seed checkpoint, made without pipeline parallelism on one GPU. - On 2 GB200 GPUs at `pp=2`, `scripts/loss_compare.py --assert-equal --metrics loss,grad_norm` over 20 steps reports equal loss and grad norm at every step (step-20 loss and grad norm): | Config | Step 20 | | --- | --- | | Llama 3 debug, 1F1B | 3.11325 / 0.7644 | | Llama 3 debug, Interleaved1F1B | 3.11325 / 0.7644 | | Llama 3 debug, ZBV | 3.11323 / 0.7642 | | DeepSeek V3 debug, 1F1B | 3.13358 / 0.5802 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.11325 / 0.7644 | The graphs run records the forward-backward graph on both backends. At `dp_shard=1` no reduce-scatter runs, which the runs below add. - On 4 GB300 GPUs at `pp=2, dp_shard=2` (MAST), one training per backend for 20 steps, TensorBoard scalars compared exactly: loss, max loss and grad norm are bitwise identical at every step, and so is the load-balance loss for DeepSeek V3: | Config | Step 20 | | --- | --- | | Llama 3 debug, Interleaved1F1B | 3.14708 / 0.7182 | | DeepSeek V3 debug, `ep=2`, 1F1B | 3.18157 / 0.5915 | | DeepSeek V3 debug, `ep=2`, ZBV | 3.18201 / 0.6053 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.14708 / 0.7182 | On 8 GB300 GPUs, the twin's config and its FSDP2 counterpart (`dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`) are bitwise identical in the same scalars over 20 steps (step-20 loss 3.18164, grad norm 0.6002). MAST's PyTorch build lacks pytorch/pytorch#205659. Its pipelining files are those of the PR's base, so the jobs loaded the PR's three changed files (`torch/distributed/pipelining/_utils.py`, `stage.py` and `schedules.py`) in their place through an import hook in `sitecustomize`, checked at startup. - The 2-GPU runs and the 4-GPU runs without graphs started before the PyTorch check in validation and the twin's definition were added. Their FlexShard and pipeline code is this commit's. - ZBV needs workarounds on both backends, so it's out of scope here: functorch's `donated_buffer=False`, since compiled flex attention's backward donates buffers that the split backward's `retain_graph` needs; full activation remat for Llama 3; and no remat for DeepSeek V3, whose default remat unpacks a saved input twice in the split backward and whose full remat's MoE routing placeholder fails. **FSDP2 is unchanged.** FSDP2's code doesn't change. `scripts/loss_compare.py <the DeepSeek V3 MTP PR> <this PR>` with FSDP2 on Llama 3 debug at `pp=2`, Interleaved1F1B, the chunked loss, 20 steps, without a seed checkpoint (both start from seed 42 with the same parallelism), 2 GB200 GPUs, reports equal loss and grad norm at every step (step-20 loss 3.13296, grad norm 0.7869). **Not covered:** deferred gradient reduction, with or without pipeline parallelism (it needs flex_shard's equivalent of FSDP2's `set_is_last_backward`); Hugging Face loads with pipeline parallelism; and MTP layers with pipeline parallelism, which torchtitan rejects for both backends. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 78fc5a7 Pull-Request: #6243
|
@claude review the updated pr |
|
Claude finished @anshul-si's task in 4m 30s —— View job Approve, with small items to fix before merging. All of @tianyu-l's latest comments are fixed, and |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. All of @tianyu-l's comments from 2026-11-27 are fixed at HEAD. Both of my must-fix items from the last round are done, apart from one TODO link. test_matches_fsdp2 now runs and passes in CI.
What this PR does. parallelism.storage is a stateless StorageConfig dataclass: FullyShardConfig (the default) or FlexShardConfig. Each one owns validate_model, validate_trainer, apply_to_decoder and clip_grad_norm_. ParallelismContext.from_config keeps the same object, so Decoder._apply_fsdp shards with parallelism_context.storage, and GradientClipper clips with that same object. apply_fsdp_to_decoder and dist_utils.clip_grad_norm_ are gone, and their bodies moved into FullyShardConfig.
Example.
config.parallelism.storage = FlexShardConfig()
validate_model_training_config -> parallelism.storage.validate_model(...)
TrainingEngine.Config.__post_init__ -> parallelism.storage.validate_trainer(...)
ParallelismContext.from_config -> context.storage is parallelism.storage
Decoder._apply_fsdp -> parallelism_context.storage.apply_to_decoder(...) # shard
GradientClipper -> parallelism_context.storage.clip_grad_norm_(...) # clip, same object
@tianyu-l's 2026-11-27 comments, checked at HEAD
| Comment | Status |
|---|---|
Rename ShardingBackend; make it a dataclass |
Resolved: StorageConfig (ABC dataclass, no Configurable) |
Rename fsdp_backend |
Resolved: parallelism.storage |
Move dist_utils.clip_grad_norm_ into the backend |
Resolved: FullyShardConfig.clip_grad_norm_, and its test moved to test_storage.py |
Drop the apply_fsdp_to_decoder indirection |
Resolved: inlined into FullyShardConfig.apply_to_decoder |
clip_grads_with_mesh_norms_ as a private base method |
Resolved: StorageConfig._clip_grads_with_mesh_norms_ |
Drop the _apply_flex_shard indirection; look for others |
Resolved: inlined; apply_fsdp_to_mtp_decoder takes configs |
Validation on the config, no build() |
Resolved in validation.py, training_engine.py and decoder.py |
| Private static method | Resolved: _raise_if_unsupported and _grad_norm |
My last round: the two-backend-sources issue is fixed (decoder.py:204 reads the context, and the GPU test clips through GradientClipper), and the field rename is done.
Must fix
- Still open from the last two rounds:
flex_shard_backend.py:406copies flex_shard's example norm reduction, including the privatetorch._foreach_norm. Replace the provenance comment with# TODO(<flex_shard issue link>): use flex_shard's grad-norm API once it has oneso the copy doesn't drift from upstream (principle 3).
Should consider
torchtitan/distributed/fsdp.py:104--ShardingUnit/decoder_sharding_unitskeep the "sharding" name that was dropped for the storage concept (inline).torchtitan/config/parallelism.py:102-- stray line break in the docstring (inline suggestion).- Still open:
storage.py:153saysFullyShardConfigis "configured by thefsdp_*fields ofParallelismConfig", and no PR in the stack moves them. Moving those fields ontoFullyShardConfigwould also delete four ofFlexShardConfig.validate_model's rejections (symm-mem, CPU offload, unshard-in-current-stream, deferred reduction), because the knobs would no longer exist on the FlexShard path. ATODOthere would record this.
Details
- FSDP2 path equivalence, checked by reading: tied/untied grouping, the
set_unshard_in_backwardcondition, the EP>1 per-param mesh (merged placements with expert placements winning, mesh chosen by membership inrouted_experts.parameters()), the root unit and prefetching all match the removedapply_fsdp_to_decoder. A one-module list given tofully_shardregisters per-module hooks, as the description says. The description'sloss_compare.py --assert-equalresults cover this. - Overrides can't bypass
validate_trainer:apply_overridesre-runsconfig_root.__post_init__()after swapping nodes (override.py:521). FullyShardConfiglives instorage.pyand notfsdp.pybecauseconfig/parallelism.pyneeds it as the default, andfsdp.pyimportsconfig.parallelismat module top. The asymmetry withflex_shard_backend.pyis forced by that import.- No in-repo callers of the removed
apply_fsdp_to_decoderordist_utils.clip_grad_norm_remain. - CI:
test_flex_shard_fsdp.py::TestFlexShardDecoder::test_matches_fsdp2 PASSEDin the multi-GPU job. The red checks come from files this PR doesn't touch: Lint and CPU Unit Test fail inobservability/profiler.py(CuspyConfig), and multi-GPU fails intest_dist_muon.py::TestDistMuonCpuOffload("No backend type associated with device type cpu"). Please confirm the DistMuon failure also happens on the base branch.
A maintainer still needs to review, since the PR touches core code, and @tianyu-l's CHANGES_REQUESTED still stands.
| return placements | ||
|
|
||
|
|
||
| class ShardingUnit(NamedTuple): |
There was a problem hiding this comment.
@tianyu-l's naming objection to ShardingBackend ("could be confused with other fwd-bwd sharding like TP / EP") also applies here. ShardingUnit and decoder_sharding_units are the only names left in this PR that use "sharding" for the storage concept, and they sit next to the model-side ShardingConfig. The docstring already calls it "Modules that a StorageConfig shards together", so StorageUnit / decoder_storage_units would give the concept one name across parallelism.storage, StorageConfig and these units. It's a mechanical rename across fsdp.py, storage.py and flex_shard_backend.py.
There was a problem hiding this comment.
if it's FSDP only let's call it
| class ShardingUnit(NamedTuple): | |
| class FSDPShardingUnit(NamedTuple): |
o/w if it's general let's call it
| class ShardingUnit(NamedTuple): | |
| class StorageShardingUnit(NamedTuple): |
| bucket per unit FSDP2 would shard, so training from the same parameters is | ||
| bitwise identical | ||
| to FSDP2. It rejects what it doesn't support yet. |
There was a problem hiding this comment.
Nit: the rename left a stray line break in the middle of this sentence.
| bucket per unit FSDP2 would shard, so training from the same parameters is | |
| bitwise identical | |
| to FSDP2. It rejects what it doesn't support yet. | |
| bucket per unit FSDP2 would shard, so training from the same parameters is | |
| bitwise identical to FSDP2. It rejects what it doesn't support yet. |
## Summary (human-written) Our goal is to fully replace FSDP2 with FlexShard. This PR is the first step: it adds FlexShard as an experimental, opt-in backend while keeping FSDP2 as the default. This lets us test new FlexShard features and close feature gaps while users on FSDP2 see no change. ## Description torchtitan can shard parameters' storage only with FSDP2's `fully_shard`. This PR adds `parallelism.storage`, a `StorageConfig` (`torchtitan/distributed/storage.py`): how parameters are stored, sharded across ranks and gathered for compute. Tensor and expert parallelism also store parameters sharded, but they compute on the shards (`ShardingConfig`). A `StorageConfig` is a dataclass that owns the operations that depend on how the parameters are stored: validating the config, sharding a decoder and clipping grad norms. It holds no state, so callers use the config object itself, with no `build()`, and no code checks which one is in use. The default, `FullyShardConfig()`, keeps FSDP2. Setting it to `FlexShardConfig()` shards the model with FlexShard (meta-pytorch/flex_shard) instead. FSDP2's existing `fsdp_*` options stay on `ParallelismConfig` for now, so the FSDP2 path is unchanged. This is the first step of replacing FSDP2. It covers the case where the two backends can be compared bit for bit: decoders with data parallelism over `dp_shard` only. `ParallelismContext.from_config` keeps the config object itself. `Decoder._apply_fsdp` shards with it (`apply_to_decoder`) and `GradientClipper` clips with it, so grads are always clipped by the storage config that sharded them. `flex_shard` is imported only when it is selected. Later PRs in the stack add the operations they need to `StorageConfig` rather than checking which one is in use. `FullyShardConfig.apply_to_decoder` does what `Decoder._apply_fsdp` did before, through `apply_fsdp_to_decoder`: it calls `fully_shard` on the embedding, on the norm with the output projection, on each transformer block, and finally on the root model for any leftover parameters. `FlexShardConfig.apply_to_decoder` (`torchtitan/distributed/flex_shard_backend.py`) takes the same units from `decoder_sharding_units` and gives FlexShard one bucket for each. Each bucket uses its unit's mesh, shard dims and reshard-after-forward policy, the same param and reduce dtypes, `gradient_divide_factor=1.0` (gradients are summed, as `disable_fsdp_gradient_division` makes FSDP2 do) and `fsdp2_compatible=True`. The leftover root bucket, like FSDP2's root unit, isn't resharded after forward. As a result the two backends issue the same collectives, and training from the same parameters is bitwise identical. To keep the two backends from drifting apart, the grouping moved out of the FSDP2 loop into `decoder_sharding_units` in `fsdp.py`, which returns each unit's modules, reshard policy, and stacked-linear and routed-expert placements. The rest of `apply_fsdp_to_decoder` moved into `FullyShardConfig.apply_to_decoder`, which resolves the meshes and reads the dtypes and `fsdp_*` options from the configs it's given, and `apply_fsdp_to_decoder` is gone. Its embedding check, `_fsdp_unit_holds_only_embedding_weights`, which nothing else used, moved with it as `FullyShardConfig._unit_holds_only_embedding_weights`. `MTPDecoder._apply_fsdp`, which DeepSeek V3 and V4 share, already calls `Decoder._apply_fsdp`, so it shards through the storage config too. The FSDP2 path's behavior doesn't change. It now passes each unit to `fully_shard` as a list (`fully_shard([block])`), and FSDP2 gives a one-module list the same per-module hooks as the module itself. The embedding's `set_unshard_in_backward(False)` condition and the EP > 1 per-parameter mesh logic are the same as before. FlexShard parameters and their grads stay plain local shards: nothing on the FlexShard path creates a DTensor. torchtitan relied on FSDP2's DTensor parameters in two places, which now handle plain shards: - **Initialization.** Right after sharding, `FlexShardConfig.apply_to_decoder` wraps each FlexShard parameter's `param_init` function with flex_shard's `init_from_full` and the layout flex_shard reports for it (`get_flex_shard_global_layouts`). The wrapped function runs the init function on a full-size tensor and keeps this rank's part, so each shard is its slice of one device's initialization. `to_empty()` rebuilds FlexShard's parameters but keeps the modules, so the wrapped functions survive it, and `models/base` doesn't change. FSDP2's DTensor init draws each shard's values separately, so the two backends start from different, equally valid, weights. A module without `param_init` falls back to `reset_parameters()`, which would draw each FlexShard shard as the whole parameter, with the same values on every rank, so such modules are rejected (below). With tied weights, which #6144 keeps tied through parallelization, flex_shard reports the shared parameter under both names. `lm_head`'s function initializes it, and `tok_embeddings`' `skip_param_init` stays a no-op rather than being wrapped. Wrapped, it would copy an uninitialized full tensor into the shard, which `lm_head`'s function overwrites only because `tok_embeddings` initializes first. - **Grad-norm clipping.** `ParallelismContext` holds the storage config, and `GradientClipper` clips with its `clip_grad_norm_`. `FullyShardConfig`'s is `dist_utils.clip_grad_norm_`, moved there unchanged: FSDP2's clipping now lives with FSDP2, and `distributed/utils.py` no longer has the function. Both configs' methods keep its `norm_type` (L2 by default, so callers pass nothing) and `error_if_nonfinite`. `FlexShardConfig`'s groups the grads by their bucket's mesh (`flex_shard.get_mesh`) instead of by DTensor mesh. Its `_grad_norm` reduces each group's norm over its mesh in DTensor's order (each grad's local norm, all-reduced, then the norm of those norms), ported from flex_shard's DeepSeek V3 example, so the norm matches FSDP2's bit for bit. Combining the groups' norms, the PP reduction and clipping are in `StorageConfig._clip_grads_with_mesh_norms_`, which both configs call. FlexShard differs from FSDP2 in one way that affects memory and communication: FSDP2 skips the embedding's backward all-gather, and FlexShard can't yet, so it gathers the embedding again in backward. Anything FlexShard doesn't support yet raises a `ValueError` when the config is validated, after recipes and overrides and before distributed init. `validate_model_training_config` calls the storage config's `validate_model`, which checks the model, parallelism and training options. The checks of the loss, checkpointer, optimizers and trainer read configs that `validate_model_training_config` doesn't receive, so `TrainingEngine.Config.__post_init__` calls the storage config's `validate_trainer`, for every trainer. Both do nothing for `FullyShardConfig`. FlexShard's checks are temporary: each goes once FlexShard supports the feature. - **Parallelism:** HSDP, tensor, context, expert and pipeline parallelism. - **FSDP2 options:** symmetric-memory communication, CPU offloading, unsharding in the current stream (`fsdp_unshard_in_current_stream`), and deferred gradient reduction (`fsdp_defer_gradient_reduction`), since FlexShard has no `set_is_last_backward`. - **Model:** any model that overrides `_apply_fsdp` (multimodal models, DeepSeek V3 and V4, Flux and the transformers modeling backend); `preserve_dtype_params`; modules without `param_init` that have a `reset_parameters()`; and MXFP8/NVFP4 weights. All are read from the model config, so the `param_init` check also rejects modules that have no parameters to initialize, such as the `RMSNorm(elementwise_affine=False)` QK norms of muse_glimmer and muse_spark. - **Training features:** accelerator graphs, `ChunkedLossWrapper`, checkpointing, EMA, DistMuon, gradient clippers other than `GradientClipper` (only it is known to clip with the storage config's `clip_grad_norm_`) and SPMD typechecking. - **Trainers:** any trainer other than `torchtitan.trainer.Trainer`, including GraphTrainer, FaultTolerantTrainer and the RL trainer. `FlexShardConfig.validate_model` then raises an `ImportError` if flex_shard isn't installed, rather than failing when the model is sharded, after distributed init. The multi-GPU unit-test job installs flex_shard at a pinned commit (`d6bb546`), so the new parity test runs in CI. That test, `test_flex_shard_fsdp.py::test_matches_fsdp2`, runs on 4 GPUs. It builds each model with both backends and checks that each FlexShard shard equals its slice of one device's initialization from the same seed. It then copies FSDP2's initial parameters into the FlexShard model and requires bitwise-equal per-microbatch losses, grad norms, gradients and parameters over three AdamW steps, clipping through `GradientClipper`. It covers llama3 `debugmodel` with `fsdp_reshard_after_forward` set to default, qwen3 `debugmodel_moe` with always, and llama3 `debugmodel` with tied weights, set up as the tied Llama 3 flavors (1B, 3B) do, with default, each with two microbatches. A CPU test checks that `validate_model_training_config` rejects a model with its own `_apply_fsdp` (DeepSeek V4) instead of letting it silently shard with FSDP2, and a module without `param_init`. The existing FSDP2 tests cover the moved FSDP2 code, and their edits are mechanical. `test_fsdp.py` now expects `fully_shard([block])`. The tests that called `apply_fsdp_to_decoder` (`test_fsdp.py`, `test_parallelism_context.py`, `test_fsdp_cpu_offload.py` and `test_fsdp_moe_sharding.py`) call `FullyShardConfig().apply_to_decoder` with configs, and patch mesh resolution to return their meshes. The optimizer and trainer unit tests that stub `clip_grad_norm_` now give their fake parallelism contexts a `FullyShardConfig`, and `test_distributed_utils.py`'s test of it moved to `test_storage.py`. This revision passes the parity test on 2 GB200 GPUs with `world_size` set to 2, and `test_fsdp_cpu_offload.py` on GB200; `test_fsdp_moe_sharding.py` needs 4 to 8 GPUs and wasn't rerun. An earlier revision also passed the parity test, except the tied case, on 4 GB300 GPUs. On an earlier revision of this PR, based on `4122eafc0`, the FSDP2 path matched its base bit for bit: `scripts/loss_compare.py 4122eaf <that revision> --assert-equal --metrics loss,grad_norm` (seed 42, deterministic, 50 steps, 2 GB200 GPUs, `dp_shard=2`) reports equal loss and grad norm at every step for llama3 `debugmodel` (step-50 loss 2.86823), for llama3 `debugmodel` with two microbatches per step and `fsdp_defer_gradient_reduction=True` (2.83577), and for qwen3 `moe_debug` (3.71935). These runs use flex attention because the environment has no FA4, and skip the seed checkpoint, since both runs of each pair start from seed 42 with the same parallelism. Expert parallelism is the next PR in the stack. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 074a693 Pull-Request: #5842
## Summary (human-written) Our goal is to fully replace FSDP2 with FlexShard. This PR is the first step: it adds FlexShard as an experimental, opt-in backend while keeping FSDP2 as the default. This lets us test new FlexShard features and close feature gaps while users on FSDP2 see no change. ## Description torchtitan can shard parameters' storage only with FSDP2's `fully_shard`. This PR adds `parallelism.storage`, a `StorageConfig` (`torchtitan/distributed/storage.py`): how parameters are stored, sharded across ranks and gathered for compute. Tensor and expert parallelism also store parameters sharded, but they compute on the shards (`ShardingConfig`). A `StorageConfig` is a dataclass that owns the operations that depend on how the parameters are stored: validating the config, sharding a decoder and clipping grad norms. It holds no state, so callers use the config object itself, with no `build()`, and no code checks which one is in use. The default, `FullyShardConfig()`, keeps FSDP2. Setting it to `FlexShardConfig()` shards the model with FlexShard (meta-pytorch/flex_shard) instead. FSDP2's existing `fsdp_*` options stay on `ParallelismConfig` for now, so the FSDP2 path is unchanged. This is the first step of replacing FSDP2. It covers the case where the two backends can be compared bit for bit: decoders with data parallelism over `dp_shard` only. `ParallelismContext.from_config` keeps the config object itself. `Decoder._apply_fsdp` shards with it (`apply_to_decoder`) and `GradientClipper` clips with it, so grads are always clipped by the storage config that sharded them. `flex_shard` is imported only when it is selected. Later PRs in the stack add the operations they need to `StorageConfig` rather than checking which one is in use. `FullyShardConfig.apply_to_decoder` does what `Decoder._apply_fsdp` did before, through `apply_fsdp_to_decoder`: it calls `fully_shard` on the embedding, on the norm with the output projection, on each transformer block, and finally on the root model for any leftover parameters. `FlexShardConfig.apply_to_decoder` (`torchtitan/distributed/flex_shard_backend.py`) takes the same units from `decoder_sharding_units` and gives FlexShard one bucket for each. Each bucket uses its unit's mesh, shard dims and reshard-after-forward policy, the same param and reduce dtypes, `gradient_divide_factor=1.0` (gradients are summed, as `disable_fsdp_gradient_division` makes FSDP2 do) and `fsdp2_compatible=True`. The leftover root bucket, like FSDP2's root unit, isn't resharded after forward. As a result the two backends issue the same collectives, and training from the same parameters is bitwise identical. To keep the two backends from drifting apart, the grouping moved out of the FSDP2 loop into `decoder_sharding_units` in `fsdp.py`, which returns each unit's modules, reshard policy, and stacked-linear and routed-expert placements. The rest of `apply_fsdp_to_decoder` moved into `FullyShardConfig.apply_to_decoder`, which resolves the meshes and reads the dtypes and `fsdp_*` options from the configs it's given, and `apply_fsdp_to_decoder` is gone. Its embedding check, `_fsdp_unit_holds_only_embedding_weights`, which nothing else used, moved with it as `FullyShardConfig._unit_holds_only_embedding_weights`. `MTPDecoder._apply_fsdp`, which DeepSeek V3 and V4 share, already calls `Decoder._apply_fsdp`, so it shards through the storage config too. The FSDP2 path's behavior doesn't change. It now passes each unit to `fully_shard` as a list (`fully_shard([block])`), and FSDP2 gives a one-module list the same per-module hooks as the module itself. The embedding's `set_unshard_in_backward(False)` condition and the EP > 1 per-parameter mesh logic are the same as before. FlexShard parameters and their grads stay plain local shards: nothing on the FlexShard path creates a DTensor. torchtitan relied on FSDP2's DTensor parameters in two places, which now handle plain shards: - **Initialization.** Right after sharding, `FlexShardConfig.apply_to_decoder` wraps each FlexShard parameter's `param_init` function with flex_shard's `init_from_full` and the layout flex_shard reports for it (`get_flex_shard_global_layouts`). The wrapped function runs the init function on a full-size tensor and keeps this rank's part, so each shard is its slice of one device's initialization. `to_empty()` rebuilds FlexShard's parameters but keeps the modules, so the wrapped functions survive it, and `models/base` doesn't change. FSDP2's DTensor init draws each shard's values separately, so the two backends start from different, equally valid, weights. A module without `param_init` falls back to `reset_parameters()`, which would draw each FlexShard shard as the whole parameter, with the same values on every rank, so such modules are rejected (below). With tied weights, which #6144 keeps tied through parallelization, flex_shard reports the shared parameter under both names. `lm_head`'s function initializes it, and `tok_embeddings`' `skip_param_init` stays a no-op rather than being wrapped. Wrapped, it would copy an uninitialized full tensor into the shard, which `lm_head`'s function overwrites only because `tok_embeddings` initializes first. - **Grad-norm clipping.** `ParallelismContext` holds the storage config, and `GradientClipper` clips with its `clip_grad_norm_`. `FullyShardConfig`'s is `dist_utils.clip_grad_norm_`, moved there unchanged: FSDP2's clipping now lives with FSDP2, and `distributed/utils.py` no longer has the function. Both configs' methods keep its `norm_type` (L2 by default, so callers pass nothing) and `error_if_nonfinite`. `FlexShardConfig`'s groups the grads by their bucket's mesh (`flex_shard.get_mesh`) instead of by DTensor mesh. Its `_grad_norm` reduces each group's norm over its mesh in DTensor's order (each grad's local norm, all-reduced, then the norm of those norms), ported from flex_shard's DeepSeek V3 example, so the norm matches FSDP2's bit for bit. Combining the groups' norms, the PP reduction and clipping are in `StorageConfig._clip_grads_with_mesh_norms_`, which both configs call. FlexShard differs from FSDP2 in one way that affects memory and communication: FSDP2 skips the embedding's backward all-gather, and FlexShard can't yet, so it gathers the embedding again in backward. Anything FlexShard doesn't support yet raises a `ValueError` when the config is validated, after recipes and overrides and before distributed init. `validate_model_training_config` calls the storage config's `validate_model`, which checks the model, parallelism and training options. The checks of the loss, checkpointer, optimizers and trainer read configs that `validate_model_training_config` doesn't receive, so `TrainingEngine.Config.__post_init__` calls the storage config's `validate_trainer`, for every trainer. Both do nothing for `FullyShardConfig`. FlexShard's checks are temporary: each goes once FlexShard supports the feature. - **Parallelism:** HSDP, tensor, context, expert and pipeline parallelism. - **FSDP2 options:** symmetric-memory communication, CPU offloading, unsharding in the current stream (`fsdp_unshard_in_current_stream`), and deferred gradient reduction (`fsdp_defer_gradient_reduction`), since FlexShard has no `set_is_last_backward`. - **Model:** any model that overrides `_apply_fsdp` (multimodal models, DeepSeek V3 and V4, Flux and the transformers modeling backend); `preserve_dtype_params`; modules without `param_init` that have a `reset_parameters()`; and MXFP8/NVFP4 weights. All are read from the model config, so the `param_init` check also rejects modules that have no parameters to initialize, such as the `RMSNorm(elementwise_affine=False)` QK norms of muse_glimmer and muse_spark. - **Training features:** accelerator graphs, `ChunkedLossWrapper`, checkpointing, EMA, DistMuon, gradient clippers other than `GradientClipper` (only it is known to clip with the storage config's `clip_grad_norm_`) and SPMD typechecking. - **Trainers:** any trainer other than `torchtitan.trainer.Trainer`, including GraphTrainer, FaultTolerantTrainer and the RL trainer. `FlexShardConfig.validate_model` then raises an `ImportError` if flex_shard isn't installed, rather than failing when the model is sharded, after distributed init. The multi-GPU unit-test job installs flex_shard at a pinned commit (`d6bb546`), so the new parity test runs in CI. That test, `test_flex_shard_fsdp.py::test_matches_fsdp2`, runs on 4 GPUs. It builds each model with both backends and checks that each FlexShard shard equals its slice of one device's initialization from the same seed. It then copies FSDP2's initial parameters into the FlexShard model and requires bitwise-equal per-microbatch losses, grad norms, gradients and parameters over three AdamW steps, clipping through `GradientClipper`. It covers llama3 `debugmodel` with `fsdp_reshard_after_forward` set to default, qwen3 `debugmodel_moe` with always, and llama3 `debugmodel` with tied weights, set up as the tied Llama 3 flavors (1B, 3B) do, with default, each with two microbatches. A CPU test checks that `validate_model_training_config` rejects a model with its own `_apply_fsdp` (DeepSeek V4) instead of letting it silently shard with FSDP2, and a module without `param_init`. The existing FSDP2 tests cover the moved FSDP2 code, and their edits are mechanical. `test_fsdp.py` now expects `fully_shard([block])`. The tests that called `apply_fsdp_to_decoder` (`test_fsdp.py`, `test_parallelism_context.py`, `test_fsdp_cpu_offload.py` and `test_fsdp_moe_sharding.py`) call `FullyShardConfig().apply_to_decoder` with configs, and patch mesh resolution to return their meshes. The optimizer and trainer unit tests that stub `clip_grad_norm_` now give their fake parallelism contexts a `FullyShardConfig`, and `test_distributed_utils.py`'s test of it moved to `test_storage.py`. This revision passes the parity test on 2 GB200 GPUs with `world_size` set to 2, and `test_fsdp_cpu_offload.py` on GB200; `test_fsdp_moe_sharding.py` needs 4 to 8 GPUs and wasn't rerun. An earlier revision also passed the parity test, except the tied case, on 4 GB300 GPUs. On an earlier revision of this PR, based on `4122eafc0`, the FSDP2 path matched its base bit for bit: `scripts/loss_compare.py 4122eaf <that revision> --assert-equal --metrics loss,grad_norm` (seed 42, deterministic, 50 steps, 2 GB200 GPUs, `dp_shard=2`) reports equal loss and grad norm at every step for llama3 `debugmodel` (step-50 loss 2.86823), for llama3 `debugmodel` with two microbatches per step and `fsdp_defer_gradient_reduction=True` (2.83577), and for qwen3 `moe_debug` (3.71935). These runs use flex attention because the environment has no FA4, and skip the seed checkpoint, since both runs of each pair start from seed 42 with the same parallelism. Expert parallelism is the next PR in the stack. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 074a693 Pull-Request: #5842
| return placements | ||
|
|
||
|
|
||
| class ShardingUnit(NamedTuple): |
There was a problem hiding this comment.
if it's FSDP only let's call it
| class ShardingUnit(NamedTuple): | |
| class FSDPShardingUnit(NamedTuple): |
o/w if it's general let's call it
| class ShardingUnit(NamedTuple): | |
| class StorageShardingUnit(NamedTuple): |
| multimodal encoders, and for Flux. | ||
| """ | ||
|
|
||
| storage: StorageConfig = field(default_factory=FullyShardConfig) |
There was a problem hiding this comment.
| storage: StorageConfig = field(default_factory=FullyShardConfig) | |
| storage_sharding: StorageShardingConfig = field(default_factory=FullyShardConfig) |
| only `data_parallel_shard_degree` can be negative. 1 means disabled. | ||
| """ | ||
|
|
||
| fsdp_reshard_after_forward: Literal["default", "always", "never"] = "default" |
There was a problem hiding this comment.
These fsdp_ configs should belong to StorageShardingConfig
| routed_experts: nn.Module | None = None | ||
|
|
||
|
|
||
| def decoder_sharding_units( |
There was a problem hiding this comment.
| def decoder_sharding_units( | |
| def decoder_storage_sharding_units( |
| return parallelism_context.storage.clip_grad_norm_( | ||
| parameters, | ||
| max_norm, | ||
| foreach=True, | ||
| pp_mesh=parallelism_context.get_optional_mesh("pp"), | ||
| parallelism_context=parallelism_context, | ||
| ) |
There was a problem hiding this comment.
sending parallelism_context into an object owned by itself is bad design -- here I think we only needs to send parallelism_context.get_optional_mesh("pp")
| edp_mesh_dims=edp_mesh_dims, | ||
| symm_mem_scope=parallelism.fsdp_symm_mem_scope, | ||
| unshard_in_current_stream=parallelism.fsdp_unshard_in_current_stream, | ||
| parallelism_context=parallelism_context, |
There was a problem hiding this comment.
similarly, here we only need to send pp_enabled
|
|
||
|
|
||
| @dataclass(kw_only=True, slots=True) | ||
| class StorageConfig(ABC): |
There was a problem hiding this comment.
| class StorageConfig(ABC): | |
| class StorageShardingConfig(ABC): |
|
|
||
|
|
||
| @dataclass(kw_only=True, slots=True) | ||
| class FullyShardConfig(StorageConfig): |
There was a problem hiding this comment.
let's create a folder
distributed/storage_sharding/
- protocol.py
- fsdp.py
- flex_shard.py
| *, | ||
| parallelism_context: ParallelismContext, | ||
| precision: PrecisionConfig, | ||
| parallelism: ParallelismConfig, |
There was a problem hiding this comment.
I don't think we need to send in all parallelism, after we put fsdp_-related configs in the StorageConfig
Stack from ghstack (oldest at bottom):
Summary (human-written)
Our goal is to fully replace FSDP2 with FlexShard. This PR is the first step: it adds FlexShard as an experimental, opt-in backend while keeping FSDP2 as the default. This lets us test new FlexShard features and close feature gaps while users on FSDP2 see no change.
Description
torchtitan can shard parameters' storage only with FSDP2's
fully_shard. This PR addsparallelism.storage, aStorageConfig(torchtitan/distributed/storage.py): howparameters are stored, sharded across ranks and gathered for compute. Tensor and expert
parallelism also store parameters sharded, but they compute on the shards
(
ShardingConfig). AStorageConfigis a dataclass that owns the operations thatdepend on how the parameters are stored: validating the config, sharding a decoder and
clipping grad norms. It holds no state, so callers use the config object itself, with no
build(), and no code checks which one is in use. The default,FullyShardConfig(),keeps FSDP2. Setting it to
FlexShardConfig()shards the model with FlexShard(meta-pytorch/flex_shard) instead. FSDP2's existing
fsdp_*options stay onParallelismConfigfor now, so the FSDP2 path is unchanged. This is the first step ofreplacing FSDP2. It covers the case where the two backends can be compared bit for bit:
decoders with data parallelism over
dp_shardonly.ParallelismContext.from_configkeeps the config object itself.
Decoder._apply_fsdpshards with it(
apply_to_decoder) andGradientClipperclips with it, so grads are always clipped bythe storage config that sharded them.
flex_shardis imported only when it is selected.Later PRs in the stack add the operations they need to
StorageConfigrather thanchecking which one is in use.
FullyShardConfig.apply_to_decoderdoes whatDecoder._apply_fsdpdid before, throughapply_fsdp_to_decoder: it callsfully_shardon the embedding, on the norm with theoutput projection, on each transformer block, and finally on the root model for any
leftover parameters.
FlexShardConfig.apply_to_decoder(
torchtitan/distributed/flex_shard_backend.py) takes the same units fromdecoder_sharding_unitsand gives FlexShard one bucket for each. Each bucket uses itsunit's mesh, shard dims and reshard-after-forward policy, the same param and reduce
dtypes,
gradient_divide_factor=1.0(gradients are summed, asdisable_fsdp_gradient_divisionmakes FSDP2 do) andfsdp2_compatible=True. Theleftover root bucket, like FSDP2's root unit, isn't resharded after forward. As a result
the two backends issue the same collectives, and training from the same parameters is
bitwise identical.
To keep the two backends from drifting apart, the grouping moved out of the FSDP2 loop
into
decoder_sharding_unitsinfsdp.py, which returns each unit's modules, reshardpolicy, and stacked-linear and routed-expert placements. The rest of
apply_fsdp_to_decodermoved intoFullyShardConfig.apply_to_decoder, which resolvesthe meshes and reads the dtypes and
fsdp_*options from the configs it's given, andapply_fsdp_to_decoderis gone. Its embedding check,_fsdp_unit_holds_only_embedding_weights, which nothing else used, moved with it asFullyShardConfig._unit_holds_only_embedding_weights.MTPDecoder._apply_fsdp, whichDeepSeek V3 and V4 share, already calls
Decoder._apply_fsdp, so it shards through thestorage config too. The FSDP2 path's behavior doesn't change.
It now passes each unit to
fully_shardas a list (fully_shard([block])), and FSDP2gives a one-module list the same per-module hooks as the module itself. The embedding's
set_unshard_in_backward(False)condition and the EP > 1 per-parameter mesh logic arethe same as before.
FlexShard parameters and their grads stay plain local shards: nothing on the FlexShard
path creates a DTensor. torchtitan relied on FSDP2's DTensor parameters in two places,
which now handle plain shards:
FlexShardConfig.apply_to_decoderwrapseach FlexShard parameter's
param_initfunction with flex_shard'sinit_from_fulland the layout flex_shard reports for it (
get_flex_shard_global_layouts). Thewrapped function runs the init function on a full-size tensor and keeps this rank's
part, so each shard is its slice of one device's initialization.
to_empty()rebuildsFlexShard's parameters but keeps the modules, so the wrapped functions survive it, and
models/basedoesn't change. FSDP2's DTensor init draws each shard's valuesseparately, so the two backends start from different, equally valid, weights. A module
without
param_initfalls back toreset_parameters(), which would draw eachFlexShard shard as the whole parameter, with the same values on every rank, so such
modules are rejected (below). With tied weights, which [decoder] Keep tok_embeddings and lm_head tied through _parallelize #6144 keeps tied through
parallelization, flex_shard reports the shared parameter under both names.
lm_head'sfunction initializes it, and
tok_embeddings'skip_param_initstays a no-op ratherthan being wrapped. Wrapped, it would copy an uninitialized full tensor into the
shard, which
lm_head's function overwrites only becausetok_embeddingsinitializesfirst.
ParallelismContextholds the storage config, andGradientClipperclips with itsclip_grad_norm_.FullyShardConfig's isdist_utils.clip_grad_norm_, moved there unchanged: FSDP2's clipping now lives withFSDP2, and
distributed/utils.pyno longer has the function. Both configs' methodskeep its
norm_type(L2 by default, so callers pass nothing) anderror_if_nonfinite.FlexShardConfig's groups the grads by their bucket's mesh(
flex_shard.get_mesh) instead of by DTensor mesh. Its_grad_normreduceseach group's norm over its mesh in DTensor's order (each grad's local norm,
all-reduced, then the norm of those norms), ported from flex_shard's DeepSeek V3
example, so the norm matches FSDP2's bit for bit. Combining the groups' norms, the PP
reduction and clipping are in
StorageConfig._clip_grads_with_mesh_norms_, which bothconfigs call.
FlexShard differs from FSDP2 in one way that affects memory and communication: FSDP2
skips the embedding's backward all-gather, and FlexShard can't yet, so it gathers the
embedding again in backward.
Anything FlexShard doesn't support yet raises a
ValueErrorwhen the config isvalidated, after recipes and overrides and before distributed init.
validate_model_training_configcalls the storage config'svalidate_model, whichchecks the model, parallelism and training options. The checks of the loss,
checkpointer, optimizers and trainer read configs that
validate_model_training_configdoesn't receive, so
TrainingEngine.Config.__post_init__calls the storage config'svalidate_trainer, for every trainer. Both do nothing forFullyShardConfig.FlexShard's checks are temporary: each goes once FlexShard supports the feature.
the current stream (
fsdp_unshard_in_current_stream), and deferred gradientreduction (
fsdp_defer_gradient_reduction), since FlexShard has noset_is_last_backward._apply_fsdp(multimodal models, DeepSeek V3 andV4, Flux and the transformers modeling backend);
preserve_dtype_params; moduleswithout
param_initthat have areset_parameters(); and MXFP8/NVFP4 weights. Allare read from the model config, so the
param_initcheck also rejects modules thathave no parameters to initialize, such as the
RMSNorm(elementwise_affine=False)QKnorms of muse_glimmer and muse_spark.
ChunkedLossWrapper, checkpointing, EMA,DistMuon, gradient clippers other than
GradientClipper(only it is known to clipwith the storage config's
clip_grad_norm_) and SPMD typechecking.torchtitan.trainer.Trainer, includingGraphTrainer, FaultTolerantTrainer and the RL trainer.
FlexShardConfig.validate_modelthen raises anImportErrorif flex_shard isn'tinstalled, rather than failing when the model is sharded, after distributed init.
The multi-GPU unit-test job installs flex_shard at a pinned commit (
d6bb546), so thenew parity test runs in CI. That test,
test_flex_shard_fsdp.py::test_matches_fsdp2,runs on 4 GPUs. It builds each model with both backends and checks that each FlexShard
shard equals its slice of one device's initialization from the same seed. It then copies
FSDP2's initial parameters into the FlexShard model and requires bitwise-equal
per-microbatch losses, grad norms, gradients and parameters over three AdamW steps,
clipping through
GradientClipper. It covers llama3debugmodelwithfsdp_reshard_after_forwardset to default, qwen3debugmodel_moewith always, andllama3
debugmodelwith tied weights, set up as the tied Llama 3 flavors (1B, 3B) do,with default, each with two microbatches. A CPU test checks that
validate_model_training_configrejects a model with its own_apply_fsdp(DeepSeekV4) instead of letting it silently shard with FSDP2, and a module without
param_init.The existing FSDP2 tests cover the moved FSDP2 code, and their edits are mechanical.
test_fsdp.pynow expectsfully_shard([block]). The tests that calledapply_fsdp_to_decoder(test_fsdp.py,test_parallelism_context.py,test_fsdp_cpu_offload.pyandtest_fsdp_moe_sharding.py) callFullyShardConfig().apply_to_decoderwith configs, and patch mesh resolution to returntheir meshes. The optimizer and trainer unit tests that stub
clip_grad_norm_now give their fake parallelism contexts aFullyShardConfig, andtest_distributed_utils.py's test of it moved totest_storage.py. This revisionpasses the parity test on 2 GB200 GPUs with
world_sizeset to 2, andtest_fsdp_cpu_offload.pyon GB200;test_fsdp_moe_sharding.pyneeds 4 to 8 GPUs andwasn't rerun. An earlier revision also passed the parity test, except the tied case, on
4 GB300 GPUs.
On an earlier revision of this PR, based on
4122eafc0, the FSDP2 path matched its basebit for bit:
scripts/loss_compare.py 4122eafc0 <that revision> --assert-equal --metrics loss,grad_norm(seed 42, deterministic, 50 steps, 2 GB200 GPUs,dp_shard=2) reportsequal loss and grad norm at every step for llama3
debugmodel(step-50 loss 2.86823),for llama3
debugmodelwith two microbatches per step andfsdp_defer_gradient_reduction=True(2.83577), and for qwen3moe_debug(3.71935).These runs use flex attention because the environment has no FA4, and skip the seed
checkpoint, since both runs of each pair start from seed 42 with the same parallelism.
Expert parallelism is the next PR in the stack.
Co-authored-by: Wei Feng [email protected]