Skip to content

[DTensor] Add BlockShard placement - #199232

Draft
weifengpy wants to merge 5 commits into
gh/weifengpy/203/basefrom
gh/weifengpy/203/head
Draft

weifengpy wants to merge 5 commits into
gh/weifengpy/203/basefrom
gh/weifengpy/203/head

Conversation

@weifengpy

@weifengpy weifengpy commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review.

FSDP2 shards each parameter with one Shard(dim). For MoE expert weights
[E, O, I] with more FSDP ranks than experts, Shard(0) leaves ranks empty,
and the Shard(1) fallback used by torchtitan needs O % W == 0 and pays a
chunk-cat copy on every all-gather and reduce-scatter. The layout we want is
Shard(0) of w.view(E * O, I) without flattening the parameter, which no
existing placement expresses.

BlockShard(block_numels, block_repeats=None) shards the tensor's row-major
elements in contiguous blocks assigned to ranks with torch.chunk
semantics. Only a single block equal to the product of the trailing dims
shape[k:] with k >= 2 is supported, which is exactly Shard(0) on the
merged view (prod(shape[:k]), *shape[k:]); the local tensor has the
merged-view shape [local_rows, *shape[k:]]. It can be combined with
Replicate, Partial, and Shard(0) on at most one other mesh dim; with
Shard(0) (expert parallelism), BlockShard applies to the local tensor
left by it, whatever the mesh dim order. The order is part of the placement
rule rather than DTensorSpec.shard_order because many specs are built
without a shard order, and the default order would be wrong for torchtitan's
(efsdp, ep) mesh.

This PR only adds what FSDP2 storage and DCP need, and lowers BlockShard
to Shard(0) wherever possible: _lower_block_shard_spec rewrites a spec
onto the merged view (_StridedShard(0, split_factor=ep) when the EP mesh
dim comes later, the same layout FSDP2+EP uses for Shard(0) today).

Review order:

  1. placement_types.py: the placement, _split_dim (the supported
    pattern), and _validate_block_shard_placements. It subclasses the C++
    Placement base, not Shard, so no existing rule mistakes it for
    Shard(0).
  2. _dtensor_spec.py: _lower_block_shard_spec.
  3. _sharding_prop.py: ops on BlockShard operands run as the lowered spec
    and map back. Only pointwise and foreach/fused ops are supported, plus
    the six other ops that FSDP2 storage reaches in the tests: zeros_like
    (optimizer state), detach and copy_ (state dicts), and empty_like,
    normal_, and any (trunc_normal_ init). Every non-scalar operand
    must be on the same BlockShard spec. Other ops raise
    NotImplementedError.
  4. _redistribute.py: a BlockShard source all-gathers its merged view and
    hands off to the regular planner (full_tensor()); redistributing to
    BlockShard raises.
  5. _dispatch.py: random ops use the lowered spec for RNG offsets, so
    parameter init draws the same values per element as Shard(0) on the
    merged view instead of repeating values across ranks.

Test Plan

python test/distributed/tensor/test_block_shard.py

The tests cover 1D, HSDP, and expert-parallel layouts (both mesh dim
orders) with shapes whose rank rows cross expert boundaries or are uneven:
local tensors, full_tensor/redistribute, elementwise and foreach ops with
no communication, AdamW (foreach=True) and clip_grad_norm_ parity,
trunc_normal_ matching Shard(0) on the merged view, torch.compile, and
that unsupported ops raise.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/199232

Note: Links to docs will display an error until the docs builds have been completed.

❌ 1 New Failure

As of commit 83726e2 with merge base 381cc3e (image):

NEW FAILURE - The following job has failed:

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

[ghstack-poisoned]
weifengpy added a commit to pytorch/torchtitan that referenced this pull request Oct 1, 2026
…t FSDP ranks

This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review.

> Routed-expert weights `[num_experts, rows, cols]` used `Shard(0)` when the
> expert FSDP degree is at most the number of local experts, and `Shard(1)`
> otherwise. `Shard(0)` pads whenever the local experts don't divide evenly
> (e.g. 12 local experts over 8 ranks hold 2, 2, 2, 2, 2, 2, 0, 0 experts), and
> `Shard(1)` needs `rows % fsdp_degree == 0` and costs a chunk-cat copy on every
> all-gather and reduce-scatter.
>
> `_expert_shard_placement` now picks:
> - `Shard(0)` when the local experts divide evenly over the expert FSDP
>   ranks: each rank holds whole experts, with no padding;
> - otherwise `BlockShard.split_leading(shape, 2)`, which shards the merged
>   `num_local_experts * rows` dim like `Shard(0)` of the flattened weight: no
>   padding and no reorder copies, for any FSDP degree. With EP > 1 the expert
>   params become `(R, BlockShard, Shard(0))` on the sparse mesh.
>
> Two cases keep the old `Shard(1)` / padded `Shard(0)` rule until they support
> `BlockShard` storage:
> - DistMuon: its storage-placement handling only understands `Replicate`,
>   `Shard`, and `_StridedShard`. `TrainingEngine.Config` turns off the new
>   `parallelism.expert_fsdp_block_shard` flag when an optimizer param group uses
>   DistMuon.
> - Tensor subclasses with FSDP extensions (float8/MXFP8 grouped experts):
>   FSDP2 raises `NotImplementedError` for `BlockShard` with them.
>
> `BlockShard` is imported unconditionally, following torchtitan's
> latest-nightly requirement, so this needs a nightly that includes the PyTorch
> stack (pytorch/pytorch#199232 -> #199235 -> #199234).
>
> Test Plan
>
> `_expert_shard_placement` returns `Shard(0)` for evenly divisible local
> experts, `BlockShard` otherwise, and the old rule for subclasses and with
> `use_block_shard=False`. Not yet validated end to end: the deepseek_v3 debug
> model run needs the `grain` data loader, and importing `TrainingEngine` fails
> in the local env (`spmd_types` version mismatch), so the DistMuon flag flip
> is untested here.

ghstack-source-id: fcdb8a2
Pull-Request: #4989
weifengpy added a commit to pytorch/torchtitan that referenced this pull request Oct 1, 2026
…t FSDP ranks

This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review.

> Routed-expert weights `[num_experts, rows, cols]` used `Shard(0)` when the
> expert FSDP degree is at most the number of local experts, and `Shard(1)`
> otherwise. `Shard(0)` pads whenever the local experts don't divide evenly
> (e.g. 12 local experts over 8 ranks hold 2, 2, 2, 2, 2, 2, 0, 0 experts), and
> `Shard(1)` needs `rows % fsdp_degree == 0` and costs a chunk-cat copy on every
> all-gather and reduce-scatter.
>
> Expert placements are now:
> - `Shard(0)` when the local experts divide evenly over the expert FSDP
>   ranks: each rank holds whole experts, with no padding;
> - otherwise `BlockShard.split_leading(shape, 2)`, which shards the merged
>   `num_local_experts * rows` dim like `Shard(0)` of the flattened weight: no
>   padding and no reorder copies, for any FSDP degree. With EP > 1 the expert
>   params become `(R, BlockShard, Shard(0))` on the sparse mesh.
>
> Two cases keep the old `Shard(1)` / padded `Shard(0)` rule until they support
> `BlockShard` storage:
> - DistMuon: its storage-placement handling only understands `Replicate`,
>   `Shard`, and `_StridedShard`. `TrainingEngine.Config` turns off the new
>   `parallelism.expert_fsdp_block_shard` flag when an optimizer param group uses
>   DistMuon.
> - Tensor subclasses with FSDP extensions (float8/MXFP8 grouped experts):
>   FSDP2 raises `NotImplementedError` for `BlockShard` with them.
>
> `BlockShard` is imported unconditionally, following torchtitan's
> latest-nightly requirement, so this needs a nightly that includes the PyTorch
> stack (pytorch/pytorch#199232 -> #199235 -> #199234).
>
> Test Plan
>
> The placement rule picks `Shard(0)` for evenly divisible local
> experts, `BlockShard` otherwise, and the old rule for subclasses and with
> `expert_fsdp_block_shard=False`. Not yet validated end to end: the deepseek_v3 debug
> model run needs the `grain` data loader, and importing `TrainingEngine` fails
> in the local env (`spmd_types` version mismatch), so the DistMuon flag flip
> is untested here.

ghstack-source-id: a71e080
Pull-Request: #4989
weifengpy added a commit to pytorch/torchtitan that referenced this pull request Oct 1, 2026
…t FSDP ranks

This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review.

> Routed-expert weights `[num_experts, rows, cols]` used `Shard(0)` when the
> expert FSDP degree is at most the number of local experts, and `Shard(1)`
> otherwise. `Shard(0)` pads whenever the local experts don't divide evenly
> (e.g. 12 local experts over 8 ranks hold 2, 2, 2, 2, 2, 2, 0, 0 experts), and
> `Shard(1)` needs `rows % fsdp_degree == 0` and costs a chunk-cat copy on every
> all-gather and reduce-scatter.
>
> Expert placements are now `Shard(0)` when the local experts divide evenly
> over the expert FSDP ranks (each rank holds whole experts, with no padding),
> and otherwise `BlockShard.split_leading(shape, 2)`, which shards the merged
> `num_local_experts * rows` dim like `Shard(0)` of the flattened weight: no
> padding and no reorder copies, for any FSDP degree. With EP > 1 the expert
> params become `(R, BlockShard, Shard(0))` on the sparse mesh.
>
> Known limitations when the local experts don't divide evenly (evenly
> divisible runs are unchanged):
> - float8/MXFP8 grouped experts (tensor subclasses with FSDP extensions):
>   FSDP2 raises `NotImplementedError` for `BlockShard` with them;
> - DistMuon: it raises `NotImplementedError` for `BlockShard` storage when the
>   optimizer is built.
> Both used `Shard(1)` or padded `Shard(0)` before. Supporting `BlockShard` in
> FSDP2 extensions (torchao) and in DistMuon's storage handling are follow-ups.
>
> `BlockShard` is imported unconditionally, following torchtitan's
> latest-nightly requirement, so this needs a nightly that includes the PyTorch
> stack (pytorch/pytorch#199232 -> #199235 -> #199234).
>
> Test Plan
>
> Not yet validated end to end: the deepseek_v3 debug model run needs the
> `grain` data loader, and importing the trainer fails in the local env
> (`spmd_types` version mismatch). `torchtitan.distributed.fsdp` imports.

ghstack-source-id: d7a9b6b
Pull-Request: #4989
weifengpy added a commit to pytorch/torchtitan that referenced this pull request Oct 1, 2026
…t FSDP ranks

This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review.

> Routed-expert weights `[num_experts, rows, cols]` used `Shard(0)` when the
> expert FSDP degree is at most the number of local experts, and `Shard(1)`
> otherwise. `Shard(0)` pads whenever the local experts don't divide evenly
> (e.g. 12 local experts over 8 ranks hold 2, 2, 2, 2, 2, 2, 0, 0 experts), and
> `Shard(1)` needs `rows % fsdp_degree == 0` and costs a chunk-cat copy on every
> all-gather and reduce-scatter.
>
> Expert placements are now `Shard(0)` when the local experts divide evenly
> over the expert FSDP ranks (each rank holds whole experts, with no padding),
> and otherwise `BlockShard.split_leading(shape, 2)`, which shards the merged
> `num_local_experts * rows` dim like `Shard(0)` of the flattened weight: no
> padding and no reorder copies, for any FSDP degree. With EP > 1 the expert
> params become `(R, BlockShard, Shard(0))` on the sparse mesh.
>
> Known limitations when the local experts don't divide evenly (evenly
> divisible runs are unchanged):
> - float8/MXFP8 grouped experts (tensor subclasses with FSDP extensions):
>   FSDP2 raises `NotImplementedError` for `BlockShard` with them;
> - DistMuon: it raises `NotImplementedError` for `BlockShard` storage when the
>   optimizer is built.
> Both used `Shard(1)` or padded `Shard(0)` before. Supporting `BlockShard` in
> FSDP2 extensions (torchao) and in DistMuon's storage handling are follow-ups.
>
> `BlockShard` is imported unconditionally, following torchtitan's
> latest-nightly requirement, so this needs a nightly that includes the PyTorch
> stack (pytorch/pytorch#199232 -> #199235 -> #199234).
>
> Test Plan
>
> Not yet validated end to end: the deepseek_v3 debug model run needs the
> `grain` data loader, and importing the trainer fails in the local env
> (`spmd_types` version mismatch). `torchtitan.distributed.fsdp` imports.

ghstack-source-id: 07efce1
Pull-Request: #4989
weifengpy added a commit to pytorch/torchtitan that referenced this pull request Oct 1, 2026
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review.

> When the expert FSDP degree is larger than the number of local experts,
> routed-expert weights `[num_experts, rows, cols]` used `Shard(1)` to avoid
> padding. That needs `rows % fsdp_degree == 0` and costs a chunk-cat copy on
> every all-gather and reduce-scatter. They now use
> `BlockShard.split_leading(shape, 2)`, which shards the merged
> `num_local_experts * rows` dim like `Shard(0)` of the flattened weight: no
> padding and no reorder copies, for any FSDP degree. With EP > 1 the expert
> params become `(R, BlockShard, Shard(0))` on the sparse mesh. All other
> cases keep `Shard(0)` as before.
>
> Known limitations in the cases that used `Shard(1)`:
> - float8/MXFP8 grouped experts (tensor subclasses with FSDP extensions):
>   FSDP2 raises `NotImplementedError` for `BlockShard` with them;
> - DistMuon: it raises `NotImplementedError` for `BlockShard` storage when the
>   optimizer is built.
> Supporting `BlockShard` in FSDP2 extensions (torchao) and in DistMuon's
> storage handling are follow-ups.
>
> `BlockShard` is imported unconditionally, following torchtitan's
> latest-nightly requirement, so this needs a nightly that includes the PyTorch
> stack (pytorch/pytorch#199232 -> #199235 -> #199234).
>
> Test Plan
>
> Not yet validated end to end: the deepseek_v3 debug model run needs the
> `grain` data loader, and importing the trainer fails in the local env
> (`spmd_types` version mismatch). `torchtitan.distributed.fsdp` imports.

ghstack-source-id: a09fd85
Pull-Request: #4989
weifengpy added a commit to pytorch/torchtitan that referenced this pull request Oct 1, 2026
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review.

> When the expert FSDP degree is larger than the number of local experts,
> routed-expert weights `[num_experts, rows, cols]` used `Shard(1)` to avoid
> padding. That needs `rows % fsdp_degree == 0` and costs a chunk-cat copy on
> every all-gather and reduce-scatter. They now use
> `BlockShard.split_leading(shape, 2)`, which shards the merged
> `num_local_experts * rows` dim like `Shard(0)` of the flattened weight: no
> padding and no reorder copies, for any FSDP degree. With EP > 1 the expert
> params become `(R, BlockShard, Shard(0))` on the sparse mesh. All other
> cases keep `Shard(0)` as before.
>
> Known limitations in the cases that used `Shard(1)`:
> - float8/MXFP8 grouped experts (tensor subclasses with FSDP extensions):
>   FSDP2 raises `NotImplementedError` for `BlockShard` with them;
> - DistMuon: it raises `NotImplementedError` for `BlockShard` storage when the
>   optimizer is built.
> Supporting `BlockShard` in FSDP2 extensions (torchao) and in DistMuon's
> storage handling are follow-ups.
>
> `BlockShard` is imported unconditionally, following torchtitan's
> latest-nightly requirement, so this needs a nightly that includes the PyTorch
> stack (pytorch/pytorch#199232 -> #199235 -> #199234).
>
> Test Plan
>
> Not yet validated end to end: the deepseek_v3 debug model run needs the
> `grain` data loader, and importing the trainer fails in the local env
> (`spmd_types` version mismatch). `torchtitan.distributed.fsdp` imports.

ghstack-source-id: 4380d7b
Pull-Request: #4989
weifengpy added a commit to pytorch/torchtitan that referenced this pull request Oct 1, 2026
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review.

> When the expert FSDP degree is larger than the number of local experts,
> routed-expert weights `[num_experts, rows, cols]` used `Shard(1)` to avoid
> padding. That needs `rows % fsdp_degree == 0` and costs a chunk-cat copy on
> every all-gather and reduce-scatter. They now use
> `BlockShard.split_leading(shape, 2)`, which shards the merged
> `num_local_experts * rows` dim like `Shard(0)` of the flattened weight: no
> padding and no reorder copies, for any FSDP degree. With EP > 1 the expert
> params become `(R, BlockShard, Shard(0))` on the sparse mesh. All other
> cases keep `Shard(0)` as before.
>
> Known limitations in the cases that used `Shard(1)`:
> - float8/MXFP8 grouped experts (tensor subclasses with FSDP extensions):
>   FSDP2 raises `NotImplementedError` for `BlockShard` with them;
> - DistMuon: it raises `NotImplementedError` for `BlockShard` storage when the
>   optimizer is built.
> Supporting `BlockShard` in FSDP2 extensions (torchao) and in DistMuon's
> storage handling are follow-ups.
>
> `BlockShard` is imported unconditionally, following torchtitan's
> latest-nightly requirement, so this needs a nightly that includes the PyTorch
> stack (pytorch/pytorch#199232 -> #199235 -> #199234).
>
> Test Plan
>
> Not yet validated end to end: the deepseek_v3 debug model run needs the
> `grain` data loader, and importing the trainer fails in the local env
> (`spmd_types` version mismatch). `torchtitan.distributed.fsdp` imports.

ghstack-source-id: 4349a67
Pull-Request: #4989
weifengpy added a commit to pytorch/torchtitan that referenced this pull request Oct 1, 2026
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review.

> When the expert FSDP degree is larger than the number of local experts,
> routed-expert weights `[num_experts, rows, cols]` used `Shard(1)` to avoid
> padding. That needs `rows % fsdp_degree == 0` and costs a chunk-cat copy on
> every all-gather and reduce-scatter. They now use
> `BlockShard.split_leading(shape, 2)`, which shards the merged
> `num_local_experts * rows` dim like `Shard(0)` of the flattened weight: no
> padding and no reorder copies, for any FSDP degree. With EP > 1 the expert
> params become `(R, BlockShard, Shard(0))` on the sparse mesh. All other
> cases keep `Shard(0)` as before.
>
> Known limitations in the cases that used `Shard(1)`:
> - float8/MXFP8 grouped experts (tensor subclasses with FSDP extensions):
>   FSDP2 raises `NotImplementedError` for `BlockShard` with them;
> - DistMuon: it raises `NotImplementedError` for `BlockShard` storage when the
>   optimizer is built.
> Supporting `BlockShard` in FSDP2 extensions (torchao) and in DistMuon's
> storage handling are follow-ups.
>
> `BlockShard` is imported unconditionally, following torchtitan's
> latest-nightly requirement, so this needs a nightly that includes the PyTorch
> stack (pytorch/pytorch#199232 -> #199235 -> #199234).
>
> Test Plan
>
> Not yet validated end to end: the deepseek_v3 debug model run needs the
> `grain` data loader, and importing the trainer fails in the local env
> (`spmd_types` version mismatch). `torchtitan.distributed.fsdp` imports.

ghstack-source-id: 4349a67
Pull-Request: #4989
weifengpy added a commit to pytorch/torchtitan that referenced this pull request Oct 1, 2026
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review.

> When the expert FSDP degree is larger than the number of local experts,
> routed-expert weights `[num_experts, rows, cols]` used `Shard(1)` to avoid
> padding. That needs `rows % fsdp_degree == 0` and costs a chunk-cat copy on
> every all-gather and reduce-scatter. They now use
> `BlockShard.split_leading(shape, 2)`, which shards the merged
> `num_local_experts * rows` dim like `Shard(0)` of the flattened weight: no
> padding and no reorder copies, for any FSDP degree. With EP > 1 the expert
> params become `(R, BlockShard, Shard(0))` on the sparse mesh. All other
> cases keep `Shard(0)` as before.
>
> Known limitations in the cases that used `Shard(1)`:
> - float8/MXFP8 grouped experts (tensor subclasses with FSDP extensions):
>   FSDP2 raises `NotImplementedError` for `BlockShard` with them;
> - DistMuon: it raises `NotImplementedError` for `BlockShard` storage when the
>   optimizer is built.
> Supporting `BlockShard` in FSDP2 extensions (torchao) and in DistMuon's
> storage handling are follow-ups.
>
> `BlockShard` is imported unconditionally, following torchtitan's
> latest-nightly requirement, so this needs a nightly that includes the PyTorch
> stack (pytorch/pytorch#199232 -> #199235 -> #199234).
>
> Test Plan
>
> Not yet validated end to end: the deepseek_v3 debug model run needs the
> `grain` data loader, and importing the trainer fails in the local env
> (`spmd_types` version mismatch). `torchtitan.distributed.fsdp` imports.

ghstack-source-id: f432bbf
Pull-Request: #4989
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]

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/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (dtensor) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant