Skip to content

[no-ci] [DTensor][DCP] BlockShard placement and multi-chunk checkpointing (copy of #199232 and #199235, AI-assisted) - #204900

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

weifengpy wants to merge 2 commits into
gh/weifengpy/244/basefrom
gh/weifengpy/244/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. A copy of the author's drafts #199232 and #199235, so that #204901 (BlockShard in fully_shard) can stack on the FlexShard engine stack. Not for review or landing: review and land #199232 and #199235.

BC-breaking?

No. Adds the BlockShard DTensor placement and multi-chunk DCP checkpointing of BlockShard DTensors.

Summary (human written only)

Placeholder for the author.

Agent details (AI-generated)

A copy of #199232 and #199235 (the author's drafts 825ea582ac2 and 330bd32e9bf, written on main from Oct 6), rebased onto this stack and squashed into one commit, without their ghstack trailers. Main moved under two hunks of #199232, and its test linter asks one addition of the new test file; the rest applied as is:

  • _dispatch.py: random ops now take their RNG offsets from first_spec, the spec the local op runs on (the redistribute schema's first spec when the op redistributes its input, e.g. multinomial), rather than from args[0]._spec. _lower_block_shard_spec now wraps first_spec at both call sites (_distribute_region and _compute_rng_offsets). A BlockShard operand's redistribute schema comes back from _propagate_block_shard mapped to BlockShard, Replicate or Partial, and the lowering leaves specs without BlockShard unchanged, so random ops on other DTensors behave as on main.
  • _sharding_prop.py: [DTensor] Add BlockShard placement #199232 sends ops with BlockShard operands to _propagate_block_shard where main had early returns for aten._local_scalar_dense and aten._assert_async.msg. Main's [DTensor] Reduce sharded any/all locally instead of all-gathering #204895 has since replaced those with replicate-only strategies, so the BlockShard dispatch is the only early return left there. any on a BlockShard tensor (used by trunc_normal_ init) now stays local, as on Shard.
  • test_block_shard.py declares hw_classification = HardwareClassification.GENERIC on its test classes, which main's TEST_LINTER now requires of new test files (the DTensor test bases fall back to CPU).

Test Plan

python -m pytest test/distributed/tensor/test_block_shard.py
python -m pytest test/distributed/checkpoint/test_dtensor_checkpoint.py test/distributed/checkpoint/test_state_dict_utils.py test/distributed/checkpoint/test_planner.py
spin lint -- --take RUFF,PYFMT,FLAKE8,PYREFLY <changed files>
spin lint -- --take TEST_LINTER,TESTOWNERS,TEST_HAS_MAIN test/distributed/tensor/test_block_shard.py

On 4 GB300s, main bba8f39: test_block_shard.py 15 passed (the tests of both drafts), test_dtensor_checkpoint.py 1 passed, test_state_dict_utils.py 9 passed, test_planner.py 23 passed, and test_dtensor.py 112 passed, 4 expected failures. spin lint -- --take RUFF,PYFMT,FLAKE8,PYREFLY is clean for the changed files, and TEST_LINTER,TESTOWNERS,TEST_HAS_MAIN for the test file.

The two drafts' descriptions

[DTensor] Add BlockShard placement

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.

[DCP] Checkpoint BlockShard DTensors as multiple chunks per rank

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

A BlockShard rank owns a contiguous row range of the merged view
(prod(shape[:k]), *shape[k:]) (of its expert-parallel Shard(0) slice,
if any). When that range crosses a boundary inside shape[:k], it is up to
2k - 1 boxes of the global tensor, not one, so the single-chunk DTensor
checkpoint path can't describe it. Checkpoints keep using the global
(unmerged) coordinates, so the serialized format doesn't depend on the
placement.

The DCP core already handles several chunks per tensor per rank
(ShardedTensor and CheckpointableTensor use it): write items carry
MetadataIndex(fqn, offset, index), and find_tensor_shard resolves each
chunk on load. Only the DTensor hooks assume one chunk. For BlockShard,
__create_chunk_list__ and __create_write_items__ now emit one chunk per
box (BlockShard._local_boxes, offset by the EP slice), and
__get_tensor_shard__ returns local[row_start:row_stop].view(box_size).
The rows are contiguous in the local tensor, so the view is writable and
loads land in place. Other placements keep the single-chunk path. Replicated
mesh dims (HSDP) produce identical MetadataIndex entries, which the global
save plan already dedups.

Two helpers bypassed the hooks and are fixed:
_create_default_metadata_only_plan now goes through
DTensor.__create_write_items__, and _distribute_tensors (used by
set_model_state_dict(..., broadcast_from_rank0=True)) takes the
merged-row chunk (of the EP slice) for BlockShard instead of slicing the
full tensor by one offset.

CheckpointableTensor can't be used for this directly: its validation
requires the local tensor to have as many dims as the global tensor, while a
BlockShard local tensor has the merged-view shape.

Test Plan

python test/distributed/tensor/test_block_shard.py
python test/distributed/checkpoint/test_dtensor_checkpoint.py
python test/distributed/checkpoint/test_state_dict_utils.py
python test/distributed/checkpoint/test_planner.py

The new tests check box decomposition, chunk lists and write items (1D and
expert-parallel layouts), saving BlockShard tensors with rows crossing
expert boundaries and loading them as BlockShard (1D, HSDP, EP),
Replicate, and Shard(1), loading a Shard(1) checkpoint into
BlockShard, and _distribute_tensors.

[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/204900

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

❌ 4 New Failures, 1 Unclassified Failure

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

NEW FAILURES - The following jobs have failed:

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

  • dtensor / get-label-type / runner-determinator (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    CI is disabled by the [no-ci] PR title prefix. Remove the prefix and push a new commit to run CI.

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

[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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant