Skip to content

[no-ci] [FSDP2] Support BlockShard in fully_shard's shard_placement_fn on the shared engine (AI-assisted) - #204901

Draft
weifengpy wants to merge 2 commits into
gh/weifengpy/245/basefrom
gh/weifengpy/245/head
Draft

weifengpy wants to merge 2 commits into
gh/weifengpy/245/basefrom
gh/weifengpy/245/head

Conversation

@weifengpy

@weifengpy weifengpy commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):


  • Passes lint (spin fixlint)
  • Added/updated tests
  • 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 [FSDP2] Support BlockShard in shard_placement_fn #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-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

🔗 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 Failures

As of commit f727397 with merge base bba8f39 (image):

NEW FAILURES - The following jobs have failed:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

[ghstack-poisoned]
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

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant