Repository navigation
Conversation
[ghstack-poisoned]
This was referenced Nov 19, 2026
Draft
[ghstack-poisoned]
[ghstack-poisoned]
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_trainerrejects DistMuon, so a FlexShard run can't trainwith Muon. DistMuon (
torchtitan/distributed/flex_shard/) plans each step from itsparameters' 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_singlecalls on its buckets' process groups, not DTensor redistributes,and its Newton-Schulz math runs on
to_local()views. A DTensor parameter onlysupplies the layout DistMuon plans from. This PR gives DistMuon that layout for a
plain parameter:
StorageLayout(new, intorchtitan/distributed/flex_shard/) declares a plainparameter's mesh, placements (
ShardorReplicateper 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.DistMuontakes 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
paramnow comes from astorageobject, theDTensor itself or a small read-only view of the layout and the local tensor
(
_LocalShardStorage); grads and momentum go through_local(). DTensor parameterstake the same code paths as before, and the package still depends only on PyTorch.
DistMuonpasses the layouts of its FlexShard parameters, from thenew
dist_muon_storage_layoutsinflex_shard_backend.py: each bucket'sShard(dim)on the bucket's mesh, which is FSDP2's DTensor spec for the parameter (the same mesh
object, also
dp_shard_cpunder context parallelism). Under expert parallelism, arouted expert's layout is on the
(edp_shard, ep)mesh, sharded byepfirst andthen 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-dimensionaledp_shardbucket mesh doesn'thold, so
FlexShardConfig.apply_to_decoderrecords that mesh, unflattened, withrecord_expert_mesh. The grad norm doesn't use it: its meshes still come from theexpert-parallelism PR's
FlexShardConfig._reduce_meshes. Withmax_nccl_ctas_for_comms, the wrapper takes a bucket's storage mesh from the layout.declare_optimizer_state_layoutsregisters a state-dict hook that declares theparameter's layout on each momentum, through the EMA PR's
declare_param_layouts,as flex_shard's
register_optimizer_checkpoint_hookdoes for Adam's states. Thathook 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.
FlexShardConfig.validate_trainerno longer rejects DistMuon, exceptunder tensor parallelism, which it reads from a new
parallelismargument, added toStorageConfig.validate_trainerand passed byTrainingEngine.Config.__post_init__. There, a dense FlexShard parameter is its tprank's shard, and
dist_muon_storage_layoutsgives only its bucket's split, soDistMuon 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
_StridedShardlayouts). Lifting it needs DistMuon's TP support and aStorageLayouton the
(dp_shard, tp)mesh, which the tensor-parallelism PR already records for thegrad norm.
dist_muon_storage_layoutsasserts that only routed experts have an outerlayout.
FLEX_SHARD_FSDP.mdmoves DistMuon to the supported training features, liststhe 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_layoutsanddeclare_optimizer_state_layoutsreturn at oncewithout flex_shard imported. The earlier revision of this PR gave DistMuon
persistent DTensor views of FlexShard's parameters (
as_fsdp2_dtensor, which #5842deleted), wrapped the grads in DTensors in
step(), and kept the momentum as aDTensor in FSDP2's layout.
The parity test file gains three methods and a helper,
_dist_muon_optimizers, thatputs 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'smatrices 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, twomicrobatches. 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_fsdp2withDistMuon, on Qwen3 MoE debug with
ep=2. FlexShard loads FSDP2's checkpoint of themodel, 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_sizeset to 2 (22 s, 23 s and 34 s), andso does
test_matches_fsdp2. At 2 ranks,ep=2leavesedp_shard=1; in CI's 4GPUs, 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], foroptimizer.state.layers.0.attention.qkv_linear.wqkv.weight.momentum_buffer. Withoutrecord_expert_mesh, the expert-parallelism test fails building DistMuon, atdist_muon_storage_layouts's assertion forlayers.0.feed_forward.routed_experts.w13.weight. With the experts' layouts on theirbucket mesh instead (the assertion removed too), DistMuon's planner raises in
_compute_ready_costs(tuple.index(x): x not in tuple), since the otherdp_shardranks 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_traineraccepts a Llama 3 debug config with DistMuon andrejects 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, acceleratorgraphs off:
scripts/loss_compare.pywith FSDP2 against FlexShard, both from loss_compare'sseed checkpoint: loss and grad norm bitwise equal at every step (step-50 loss
4.62512).
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_commswith FlexShard, and aresume-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.pyand torchtitan'sDistMuonwrapper, so whichever lands secondrebases. Once DistMuon supports TP's layouts, FlexShard's rejection of DistMuon under
TP can go with a
StorageLayouton the(dp_shard, tp)mesh.Co-authored-by: Wei Feng [email protected]