Skip to content

[no-ci] [FSDP] flex_shard: global gradient norm, HSDP meshes and an int reshard_after_forward (AI-assisted) - #204899

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

weifengpy wants to merge 2 commits into
gh/weifengpy/243/basefrom
gh/weifengpy/243/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. Stacked on #204334.

BC-breaking?

No. Adds torch.distributed.fsdp.experimental.flex_shard.clip_grad_norm_, set_outer_shard_groups/get_outer_shard_groups and FlexShardModule.set_requires_all_reduce, and dtensor_to_global_layout also declares the outer shard groups; BucketSpec.mesh also takes a 2D mesh and BucketSpec.reshard_after_forward an int, both of 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.

Three things fully_shard users have that flex_shard lacked. The engine already runs the last two for fully_shard; flex_shard only had no way to ask for them.

1. Global gradient norm. flex_shard parameters are plain local tensors, so torch.nn.utils.clip_grad_norm_ computes each rank's norm of its own shard and clips each rank by a different factor; with fully_shard, DTensor gradients make the stock function reduce over the mesh. (With two equal halves, each rank sees 1/sqrt(2) of the true norm.) clip_grad_norm_(parameters, max_norm, norm_type=2.0, error_if_nonfinite=False, foreach=None) has torch.nn.utils.clip_grad_norm_'s signature and result. A flex_shard parameter's local gradient is this rank's part of the full gradient, disjoint from the other ranks' parts on its bucket's mesh (as Shard, BlockShard, BucketedOwned and the other placements lay them out), so each mesh's norm is the local norm combined by one all-reduce over that mesh: sum of p-th powers, max for the infinity norm, sum of counts for p = 0. Parameters that flex_shard does not shard count once. The gradients are then scaled with torch.nn.utils.clip_grads_with_norm_. A rank that holds no part of a gradient (e.g. one it does not own) contributes zero but still joins the all-reduce. Replicas of an HSDP mesh hold the same parts, so the shard mesh's all-reduce is the whole norm there too. A parameter that is itself a part of a bigger one (tensor or expert parallelism, declared with set_global_layout) is combined over the groups that split it too: set_outer_shard_groups(tensor, groups) declares them before flex_shard(), one group per mesh dim that shards the parameter, and dtensor_to_global_layout declares the groups of a DTensor's Shard dims. flex_shard keeps them on the parameters it installs, and the norm reduces over the bucket's mesh and then each of them. A layout that covers the full parameter (a replicated one) needs none; a partial layout without them raises ValueError, naming set_outer_shard_groups. Parameters with the same groups share their all-reduces.

2. HSDP. A 2D BucketSpec.mesh with mesh_dim_names shards over dim 1 and replicates over dim 0, as fully_shard does. placement_fn and the parameters' sharding metadata see the 1D shard mesh; the replicate group goes to the engine's build_bucket, which all-reduces each reduce-scatter's output over the replicas and counts them in the default divide factor, as FSDP2 does. FlexShardModule.set_requires_all_reduce exposes the engine's switch for gradient accumulation without the all-reduce, like FSDP2's. An unnamed 2D mesh raises, as in fully_shard.

3. An int reshard_after_forward. An int that divides the shard mesh size gives each rank a group of that many consecutive shard-mesh ranks, which build_bucket uses as fully_shard's post-forward group: the rank keeps its group's part of the unsharded parameters after forward, and the group all-gathers them before backward. Only the members create a group (new_group(..., use_local_synchronization=True)), so buckets on meshes over some of the ranks work too, and buckets with the same ranks share one. The shard mesh size reshards as True and 1 as False, as in FSDP2.

HSDP and the post-forward group need the reduce and post-forward paths that the engine's Shard implements, so flex_shard and relayout_bucket raise for placements that do not declare matches_fsdp2_collectives, with the check that fsdp2_compatible already used. relayout_bucket keeps a bucket's replicate and post-forward groups.

Review order: clip_grad.py and set_outer_shard_groups (placement_contract.py, kept through ParamInfo and FlexShardRepresentation, declared by the DTensor adapter); flex_shard.py (_resolve_bucket_meshes, the shared placement check, build_flex_bucket and relayout_bucket passing the groups) and the BucketSpec docs; then the tests.

Test Plan

python -m pytest test/distributed/_composable/flex_shard/test_flex_shard_clip_grad.py
python -m pytest test/distributed/_composable/flex_shard/test_flex_shard_fsdp2_parity.py -k HSDPAndReshard
python -m pytest test/distributed/_composable/flex_shard/test_flex_shard_buckets.py -k multi_dim_mesh
spin lint -- --take RUFF,PYFMT,FLAKE8,PYREFLY,TEST_LINTER,TESTOWNERS,TEST_HAS_MAIN <changed files>
  • test_flex_shard_clip_grad.py checks the total norm and every rank's clipped gradients against torch.nn.utils.clip_grad_norm_ on an unsharded copy, for Shard, BucketedBlockShard and whole-parameter BucketedOwned buckets with uneven sizes and a parameter outside flex_shard, for the 2-, 1- and infinity norms. test_matches_unsharded_reference_with_outer_layouts does the same on 4 ranks with tensor and expert parallelism over one dim of a 2x2 mesh and flex_shard over the other (column- and row-wise weights, stacked experts and a replicated bias, as DTensors through dtensor_to_global_layout), each rank's gradients set to its parts of known full gradients; test_outer_layout_needs_its_shard_groups checks the error.
  • TestFlexShardHSDPAndReshardToSmallerGroup: fsdp2_compatible buckets match fully_shard bit for bit (losses, local grads and parameters over 3 AdamW steps, and every all-gather and reduce-scatter input) on a (2, 2) HSDP mesh, with and without accumulation that all-reduces only the last microbatch, and with the layers' reshard_after_forward=2 on a 4-rank mesh, for fp32 and bf16/fp32 mixed precision; plus the errors for an owner placement on an HSDP mesh or with an int reshard, an unnamed 2D mesh and an int that does not divide the mesh size.

Results on main bba8f39 (4x GB300): test_flex_shard_clip_grad.py 3 passed; TestFlexShardHSDPAndReshardToSmallerGroup 3 passed; the whole flex_shard suite 157 passed and the FSDP2 suite 479 passed (1 failure, test_fully_shard_alloc_from_pg, from this host's NCCL) at the top of the stack. Lint is clean.

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/204899

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

❌ 4 New Failures

As of commit 92aca25 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]

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant