Skip to content

Support DistMuon with parallelism.storage=FlexShardConfig() - #6213

Draft
anshul-si wants to merge 5 commits into
gh/anshul-si/31/basefrom
gh/anshul-si/31/head
Draft

anshul-si wants to merge 5 commits into
gh/anshul-si/31/basefrom
gh/anshul-si/31/head

Conversation

@anshul-si

@anshul-si anshul-si commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the
checkpointing PR, the Hugging Face load PR, the tensor- and context-parallelism PR,
the DeepSeek V3 PR, the accelerator-graphs PR, the integration-tests-and-docs PR
and the EMA PR.

Summary (human-written)

Description

FlexShardConfig.validate_trainer rejects DistMuon, so a FlexShard run can't train
with Muon. DistMuon (torchtitan/distributed/flex_shard/) plans each step from its
parameters' DTensor layouts, that is their mesh, placements and global shape, and it
keeps its momentum as a DTensor. FlexShard parameters, grads and optimizer states are
plain local shards, and the FlexShard path must not build DTensor views of them. This PR
lets DistMuon step FlexShard's plain local shards, bitwise equal to DistMuon on FSDP2,
checkpoints included, without creating a DTensor.

DistMuon already computes on local tensors. Its collectives are packed
all_to_all_single calls on its buckets' process groups, not DTensor redistributes,
and its Newton-Schulz math runs on to_local() views. A DTensor parameter only
supplies the layout DistMuon plans from. This PR gives DistMuon that layout for a
plain parameter:

  • StorageLayout (new, in torchtitan/distributed/flex_shard/) declares a plain
    parameter's mesh, placements (Shard or Replicate per mesh axis) and global shape,
    as a DTensor with that mesh and those placements would hold its local shard, plus an
    optional shard order, as in ComputeLayout. DistMuon takes one per plain parameter
    (storage_layout_by_fqn). It plans from the layout as from a DTensor's placements,
    checks that the layout gives the parameter's local shape on this rank, and keeps the
    parameter's grad and momentum as plain tensors with the parameter's local layout.
    The metadata DistMuon read from param now comes from a storage object, the
    DTensor itself or a small read-only view of the layout and the local tensor
    (_LocalShardStorage); grads and momentum go through _local(). DTensor parameters
    take the same code paths as before, and the package still depends only on PyTorch.
  • torchtitan's DistMuon passes the layouts of its FlexShard parameters, from the
    new dist_muon_storage_layouts in flex_shard_backend.py: each bucket's Shard(dim)
    on the bucket's mesh, which is FSDP2's DTensor spec for the parameter (the same mesh
    object, also dp_shard_cp under context parallelism). Under expert parallelism, a
    routed expert's layout is on the (edp_shard, ep) mesh, sharded by ep first and
    then by edp_shard, which lowers to FSDP2's (_StridedShard(0, ep), Shard(0)).
    DistMuon's buckets balance the experts' compute against the dense parameters' over
    dp_shard's ranks, which the experts' one-dimensional edp_shard bucket mesh doesn't
    hold, so FlexShardConfig.apply_to_decoder records that mesh, unflattened, with
    record_expert_mesh. The grad norm doesn't use it: its meshes still come from the
    expert-parallelism PR's FlexShardConfig._reduce_meshes. With
    max_nccl_ctas_for_comms, the wrapper takes a bucket's storage mesh from the layout.
  • Checkpoints. DistMuon's momentum has its parameter's local shape, so
    declare_optimizer_state_layouts registers a state-dict hook that declares the
    parameter's layout on each momentum, through the EMA PR's declare_param_layouts,
    as flex_shard's register_optimizer_checkpoint_hook does for Adam's states. That
    hook raises for optimizers other than Adam and AdamW, so torchtitan registers its
    own for DistMuon, with a TODO to use flex_shard's once it accepts other optimizers
    whose states have their parameter's shape. DCP then saves the same chunks as for
    FSDP2's DTensor momentum, and either backend loads the other's checkpoint.
  • Validation. FlexShardConfig.validate_trainer no longer rejects DistMuon, except
    under tensor parallelism, which it reads from a new parallelism argument, added to
    StorageConfig.validate_trainer and passed by
    TrainingEngine.Config.__post_init__. There, a dense FlexShard parameter is its tp
    rank's shard, and dist_muon_storage_layouts gives only its bucket's split, so
    DistMuon would orthogonalize the tp ranks' slices instead of the whole matrices,
    without an error. DistMuon's recipes reject TP with FSDP2 too (Proposal: async and load-balanced Muon/SOAP-style optimizers for TorchTitan #3353, TP-produced
    _StridedShard layouts). Lifting it needs DistMuon's TP support and a StorageLayout
    on the (dp_shard, tp) mesh, which the tensor-parallelism PR already records for the
    grad norm. dist_muon_storage_layouts asserts that only routed experts have an outer
    layout. FLEX_SHARD_FSDP.md moves DistMuon to the supported training features, lists
    the TP rejection, and says how DistMuon sees FlexShard's parameters.

The FSDP2 path doesn't change: its parameters are DTensors, so DistMuon reads the
same layouts and creates the same DTensor momentum as before, and
dist_muon_storage_layouts and declare_optimizer_state_layouts return at once
without flex_shard imported. The earlier revision of this PR gave DistMuon
persistent DTensor views of FlexShard's parameters (as_fsdp2_dtensor, which #5842
deleted), wrapped the grads in DTensors in step(), and kept the momentum as a
DTensor in FSDP2's layout.

The parity test file gains three methods and a helper, _dist_muon_optimizers, that
puts DistMuon on each block's matrices and AdamW on the rest, as the DistMuon recipes
split them. Its compute layouts take each of DistMuon's paths: the fused QKV weight
per head in place, the other matrices gathered whole on an owner, the stacked w13's
matrices spread from their row shards, and the routed experts where they're stored.

  • test_dist_muon_matches_fsdp2: Llama 3 debug and Qwen3 MoE debug, two
    microbatches. It requires the same bitwise-equal losses, grad norms, grads and
    parameters over three steps, and the same reduce-scatter count, as the other
    parity cases.
  • test_dist_muon_matches_fsdp2_with_expert_parallelism: Qwen3 MoE debug, ep=2,
    ChunkedLossWrapper, the same checks.
  • test_dist_muon_checkpoints_match_fsdp2: _check_checkpoints_match_fsdp2 with
    DistMuon, on Qwen3 MoE debug with ep=2. FlexShard loads FSDP2's checkpoint of the
    model, DistMuon's momentum and AdamW's states, and saves it again chunk for chunk
    and bit for bit, also as a bf16 export.

All three pass on 2 GB200 GPUs with world_size set to 2 (22 s, 23 s and 34 s), and
so does test_matches_fsdp2. At 2 ranks, ep=2 leaves edp_shard=1; in CI's 4
GPUs, the routed experts' layouts are strided (edp_shard=2), which hasn't run here.
Without the momentum hook, the checkpoint test fails at the load: DCP reports a size
mismatch, saved [4096, 256] against current [2048, 256], for
optimizer.state.layers.0.attention.qkv_linear.wqkv.weight.momentum_buffer. Without
record_expert_mesh, the expert-parallelism test fails building DistMuon, at
dist_muon_storage_layouts's assertion for
layers.0.feed_forward.routed_experts.w13.weight. With the experts' layouts on their
bucket mesh instead (the assertion removed too), DistMuon's planner raises in
_compute_ready_costs (tuple.index(x): x not in tuple), since the other dp_shard
ranks aren't on that mesh. The CPU DistMuon, optimizer and config validation tests
(cpu/distributed/flex_shard, test_optimizer_param_groups.py,
test_deepseek_v4_dist_muon.py, test_config_validation.py) pass, 76 of 76. On CPU,
FlexShardConfig.validate_trainer accepts a Llama 3 debug config with DistMuon and
rejects it at tensor_parallel_degree=2. pre-commit passes on the changed files
(pyrefly isn't installed here).

An earlier revision of this change, on the checkpointing PR, with the same DistMuon
and optimizer files, also ran through the trainer, on 2 GB200 GPUs with flex
attention, seed 42 and deterministic, 50 steps, Llama 3 debug with DistMuon
(lr=2e-3) on the blocks' matrices and AdamW on the rest, dp_shard=2, accelerator
graphs off:

  • scripts/loss_compare.py with FSDP2 against FlexShard, both from loss_compare's
    seed checkpoint: loss and grad norm bitwise equal at every step (step-50 loss
    4.62512).
  • The same config under FSDP2, the checkpointing PR against that revision: bitwise
    equal at every step (step 50: 4.50664). The PRs between the checkpointing PR and
    this one don't touch DistMuon's files, so the FSDP2 path runs the same code here.

Not run: 4 GPUs, DistMuon under context parallelism (whose layouts are on
dp_shard_cp, as FSDP2's), max_nccl_ctas_for_comms with FlexShard, and a
resume-and-continue run across backends (the checkpoint test's chunk-for-chunk
equality covers the state).

Open #5678 (DistMuon TP storage-to-compute layouts) also changes dist_muon.py,
optimizer_reshard.py and torchtitan's DistMuon wrapper, so whichever lands second
rebases. Once DistMuon supports TP's layouts, FlexShard's rejection of DistMuon under
TP can go with a StorageLayout on the (dp_shard, tp) mesh.

Co-authored-by: Wei Feng [email protected]

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@anshul-si anshul-si changed the title Support DistMuon with parallelism.fsdp_backend=FlexShardConfig() Support DistMuon with parallelism.fsdp_backend=FlexShardBackend.Config() Nov 25, 2026
[ghstack-poisoned]
@anshul-si anshul-si changed the title Support DistMuon with parallelism.fsdp_backend=FlexShardBackend.Config() Support DistMuon with parallelism.storage=FlexShardConfig() Nov 30, 2026

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

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant