Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/204901
Note: Links to docs will display an error until the docs builds have been completed. ❌ 7 New FailuresAs of commit f727397 with merge base bba8f39 ( NEW FAILURES - The following jobs have failed:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This was referenced Nov 14, 2026
[FSDP2] Run fully_shard on the FlexShard engine runtime; delete FSDPParamGroup (AI-assisted)
#203764
Draft
Draft
weifengpy
added a commit
that referenced
this pull request
Nov 16, 2026
…n on the shared engine (AI-assisted) - [x] Passes lint (`spin fixlint`) - [x] Added/updated tests - [x] Updated documentation where applicable - [ ] Included benchmark results ## Linked issue or supporting maintainer > No linked issue; the author has write access. Ports #199234 onto the engine stack. ## BC-breaking? > No. `shard_placement_fn` may also return `BlockShard`, which raised before. ## Summary (human written only) > _Placeholder for the author._ ## Agent details (AI-generated) Drafted with an AI assistant at the author's request. A draft for discussion, not ready for review or merge. **Problem.** MoE expert weights `[E, O, I]` with fewer (local) experts than FSDP ranks either pad whole experts with `Shard(0)`, which leaves ranks empty, or use `Shard(1)`, which needs `O % W == 0` and reorders on every all-gather and reduce-scatter. #199234 let `shard_placement_fn` return `BlockShard` (added by the previous commit): FSDP shards, gathers and reduces `Shard(0)` of the merged view `(prod(shape[:k]), *shape[k:])`, and only the DTensors carry `BlockShard`. It was written against FSDP2's own `FSDPParam` storage and `foreach_reduce`, which this stack deleted: a `fully_shard` group is now an engine bucket that stores, gathers and reduces each parameter's `ParamSource.data` with the engine's `Shard`, and `FSDPParam` is only the parameter's DTensor representation. **What.** The merged view lives in FSDP2's frontend; the engine (`torch/distributed/fsdp/_flex_shard`) is unchanged. In review order: 1. `_fsdp_param.py`, `FSDPParam._init_sharded_param`: a `BlockShard` from `shard_placement_fn` is kept in `_block_shard`, and the bucket gets `Shard(0)` (`fsdp_placement`) of the merged view of the parameter's data (the local tensor of a DTensor parameter): `shard_source`, the `ParamSource.data` that the bucket chunks, is that view, `_merged_size` its size and `sharded_size` its chunk. The sharded spec has `BlockShard` on the DP shard mesh dim where `Shard(0)` or `_StridedShard` would be, on the plain, TP/EP-mesh and spmd-mesh paths, and is validated with `_validate_block_shard_placements`, so unsupported compositions raise `NotImplementedError` as in #199234: TP's `Shard(1)`, several DP shard mesh dims, DDP, spmd_types parameters and parameters with all-gather extensions. 2. `_fsdp_engine.py`, `FSDPParamRepresentation`: the hooks through which the engine hands a parameter's data to and from modules map between the merged view and the parameter's shape. `unsharded_param` views the gathered merged rows as the parameter's (local) shape before wrapping them; `unsharded_grad` and `unsharded_local` give the reduce the merged view of the gradient and of the unsharded parameter, whose shape the zeros of a missing gradient take. So the reduce-scatter pads merged rows, not whole experts. 3. `_fsdp_common.py` and `_fully_shard.py`: `resolve_shard_placement` accepts `BlockShard`; the `shard_placement_fn` docs. **Why this layer.** `Shard(0)` of the merged view is a layout that the engine's `Shard` already implements. Handing the bucket the merged view as the parameter's data, and mapping it back in the representation hooks, which already convert between the bucket's tensors and what modules see, needs no new engine contract and no `BlockShard` case in the engine: chunking and padding, the all-gather copy-out, the reduce-scatter copy-in, `reshard_after_forward=int` (a flat chunk of the gathered bytes), HSDP's all-reduce and accumulation, and re-homing after `to_empty()` take the dim-0 path as for any `Shard(0)` parameter. The engine's own `BlockShard` placement (a count of whole blocks per rank) is a different layout, outside FSDP2's collectives. #199234's post-forward `(Replicate(), BlockShard)` DTensor has no counterpart here: after forward, the engine registers the sharded parameters again, which carry `BlockShard`. ### Test Plan ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_block_shard.py python -m pytest test/distributed/_composable/fsdp/test_fully_shard_init.py python -m pytest test/distributed/_composable/fsdp/test_fully_shard_training.py -k "ShardPlacementFn or 1DTrainingCore" python -m pytest test/distributed/_composable/fsdp/test_fully_shard_state_dict.py python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py python -m pytest test/distributed/_composable/fsdp/test_fully_shard_engine.py python -m pytest test/distributed/_composable/fsdp/test_fully_shard_dtensor.py spin lint -- --take RUFF,PYFMT,FLAKE8,PYREFLY <changed files> spin lint -- --take TEST_LINTER,TESTOWNERS,TEST_HAS_MAIN test/distributed/_composable/fsdp/test_fully_shard_block_shard.py ``` `test_fully_shard_block_shard.py` ports #199234's tests. 1D, with 3 experts over 4 ranks so that merged rows cross expert boundaries and the last rank is short: init (each rank holds its chunk of the merged rows); meta-device init (`trunc_normal_` after `fully_shard` draws the values of `Shard(0)` on the merged view, and the next forward uses them); training parity (AdamW `foreach=True`, `clip_grad_norm_`) for `reshard_after_forward` in {True, False, 2} and HSDP, against an unsharded reference and, bit for bit (losses, local gradients and parameters, norms), against a model that stores each expert weight as its merged view with the default `Shard(0)`; the dim-0 collectives (all-gather outer sizes of 1, reduce-scatter inputs that are merged-row gradients with shard dim 0); state dict, DCP and full-state-dict broadcast round trips; HSDP accumulation without the all-reduce while an expert weight is unused; and the errors for blocks that are not trailing dims, TP's `Shard(1)` and several DP shard dims. Expert parallelism, with 6 experts over 2 EP ranks so that the 15 merged rows of each EP rank's `w1` split 8 and 7 over 2 efsdp ranks, in both of torchtitan's layouts (EP DTensors on the `(efsdp, ep)` mesh with `dp_mesh_dims=DataParallelMeshDims(shard="efsdp")`, and EP DTensors on the ep mesh with FSDP on the efsdp mesh): init, training parity for `reshard_after_forward` in {True, False}, and DCP and full-state-dict broadcast. Without the merged view in `unsharded_grad`, the parity tests fail (88 of `w1`'s 120 gradient elements differ); without it in `unsharded_local`, the HSDP accumulation test fails (the reduce-scatter output of the zeros does not match the size of the accumulated output). Results on 4 GB300s, main bba8f39, one file at a time (the whole FSDP2 suite at this revision: 479 passed, with the same `alloc_from_pg` failure): `test_fully_shard_block_shard.py` 20 passed; `test_fully_shard_init.py` 46 passed; `test_fully_shard_training.py -k "ShardPlacementFn or 1DTrainingCore"` 14 passed; `test_fully_shard_state_dict.py` 11 passed; `test_fully_shard_engine.py` 7 passed; `test_fully_shard_dtensor.py` 10 passed; `test_fully_shard_comm.py` 202 passed and 1 failed, `test_fully_shard_alloc_from_pg`, which asserts that NCCL logs no buffer registrations and fails the same way without this commit (the NCCL on this host logs them). Lint is clean. The whole FSDP2 suite at this commit (4x GB300): 478 passed, 8 deselected (they need 8 GPUs), and the same `test_fully_shard_alloc_from_pg` failure. This PR was authored with an AI assistant (Claude). ghstack-source-id: c7591f1 Pull-Request: #204901
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
spin fixlint)Linked issue or supporting maintainer
BC-breaking?
Summary (human written only)
Agent details (AI-generated)
Drafted with an AI assistant at the author's request. A draft for discussion, not ready for review or merge.
Problem. MoE expert weights
[E, O, I]with fewer (local) experts than FSDP ranks either pad whole experts withShard(0), which leaves ranks empty, or useShard(1), which needsO % W == 0and reorders on every all-gather and reduce-scatter. #199234 letshard_placement_fnreturnBlockShard(added by the previous commit): FSDP shards, gathers and reducesShard(0)of the merged view(prod(shape[:k]), *shape[k:]), and only the DTensors carryBlockShard. It was written against FSDP2's ownFSDPParamstorage andforeach_reduce, which this stack deleted: afully_shardgroup is now an engine bucket that stores, gathers and reduces each parameter'sParamSource.datawith the engine'sShard, andFSDPParamis only the parameter's DTensor representation.What. The merged view lives in FSDP2's frontend; the engine (
torch/distributed/fsdp/_flex_shard) is unchanged. In review order:_fsdp_param.py,FSDPParam._init_sharded_param: aBlockShardfromshard_placement_fnis kept in_block_shard, and the bucket getsShard(0)(fsdp_placement) of the merged view of the parameter's data (the local tensor of a DTensor parameter):shard_source, theParamSource.datathat the bucket chunks, is that view,_merged_sizeits size andsharded_sizeits chunk. The sharded spec hasBlockShardon the DP shard mesh dim whereShard(0)or_StridedShardwould be, on the plain, TP/EP-mesh and spmd-mesh paths, and is validated with_validate_block_shard_placements, so unsupported compositions raiseNotImplementedErroras in [FSDP2] Support BlockShard in shard_placement_fn #199234: TP'sShard(1), several DP shard mesh dims, DDP, spmd_types parameters and parameters with all-gather extensions._fsdp_engine.py,FSDPParamRepresentation: the hooks through which the engine hands a parameter's data to and from modules map between the merged view and the parameter's shape.unsharded_paramviews the gathered merged rows as the parameter's (local) shape before wrapping them;unsharded_gradandunsharded_localgive the reduce the merged view of the gradient and of the unsharded parameter, whose shape the zeros of a missing gradient take. So the reduce-scatter pads merged rows, not whole experts._fsdp_common.pyand_fully_shard.py:resolve_shard_placementacceptsBlockShard; theshard_placement_fndocs.Why this layer.
Shard(0)of the merged view is a layout that the engine'sShardalready implements. Handing the bucket the merged view as the parameter's data, and mapping it back in the representation hooks, which already convert between the bucket's tensors and what modules see, needs no new engine contract and noBlockShardcase in the engine: chunking and padding, the all-gather copy-out, the reduce-scatter copy-in,reshard_after_forward=int(a flat chunk of the gathered bytes), HSDP's all-reduce and accumulation, and re-homing afterto_empty()take the dim-0 path as for anyShard(0)parameter. The engine's ownBlockShardplacement (a count of whole blocks per rank) is a different layout, outside FSDP2's collectives. #199234's post-forward(Replicate(), BlockShard)DTensor has no counterpart here: after forward, the engine registers the sharded parameters again, which carryBlockShard.Test Plan
test_fully_shard_block_shard.pyports #199234's tests. 1D, with 3 experts over 4 ranks so that merged rows cross expert boundaries and the last rank is short: init (each rank holds its chunk of the merged rows); meta-device init (trunc_normal_afterfully_sharddraws the values ofShard(0)on the merged view, and the next forward uses them); training parity (AdamWforeach=True,clip_grad_norm_) forreshard_after_forwardin {True, False, 2} and HSDP, against an unsharded reference and, bit for bit (losses, local gradients and parameters, norms), against a model that stores each expert weight as its merged view with the defaultShard(0); the dim-0 collectives (all-gather outer sizes of 1, reduce-scatter inputs that are merged-row gradients with shard dim 0); state dict, DCP and full-state-dict broadcast round trips; HSDP accumulation without the all-reduce while an expert weight is unused; and the errors for blocks that are not trailing dims, TP'sShard(1)and several DP shard dims. Expert parallelism, with 6 experts over 2 EP ranks so that the 15 merged rows of each EP rank'sw1split 8 and 7 over 2 efsdp ranks, in both of torchtitan's layouts (EP DTensors on the(efsdp, ep)mesh withdp_mesh_dims=DataParallelMeshDims(shard="efsdp"), and EP DTensors on the ep mesh with FSDP on the efsdp mesh): init, training parity forreshard_after_forwardin {True, False}, and DCP and full-state-dict broadcast. Without the merged view inunsharded_grad, the parity tests fail (88 ofw1's 120 gradient elements differ); without it inunsharded_local, the HSDP accumulation test fails (the reduce-scatter output of the zeros does not match the size of the accumulated output).Results on 4 GB300s, main bba8f39, one file at a time (the whole FSDP2 suite at this revision: 479 passed, with the same
alloc_from_pgfailure):test_fully_shard_block_shard.py20 passed;test_fully_shard_init.py46 passed;test_fully_shard_training.py -k "ShardPlacementFn or 1DTrainingCore"14 passed;test_fully_shard_state_dict.py11 passed;test_fully_shard_engine.py7 passed;test_fully_shard_dtensor.py10 passed;test_fully_shard_comm.py202 passed and 1 failed,test_fully_shard_alloc_from_pg, which asserts that NCCL logs no buffer registrations and fails the same way without this commit (the NCCL on this host logs them). Lint is clean. The whole FSDP2 suite at this commit (4x GB300): 478 passed, 8 deselected (they need 8 GPUs), and the sametest_fully_shard_alloc_from_pgfailure.This PR was authored with an AI assistant (Claude).