Skip to content

[Kimi K2.7] Add DistributedMuon with all-to-all/compute overlap - #4060

Merged
weifengpy merged 1 commit into
mainfrom
gh/weifengpy/44/head
Aug 13, 2026
Merged

weifengpy merged 1 commit into
mainfrom
gh/weifengpy/44/head

Conversation

@weifengpy

@weifengpy weifengpy commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):


Profiler trace showing all-to-all overlapping during Muon: https://fburl.com/o7pyeuuy
Screenshot 2026-08-09 at 7 12 39 PM

Memory snapshot showing the expected sharded optimizer state dict.

ghstack (bottom to top):

Co-authored-by: Liangyu Wang [email protected]

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 4, 2026
weifengpy added a commit that referenced this pull request Aug 5, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #4060
* __->__ #4063

before: spmd_types exposes the dense DP axis as dp_shard, but Kimi 2.7
requested the legacy fsdp axis, causing Invalid mesh dim: 'fsdp' during
initialization

after: explicitly tells FSDP that dp_shard or efsdp is the data-parallel
shard axis
weifengpy added a commit that referenced this pull request Aug 6, 2026
ghstack-source-id: 42ce6ec
Pull-Request: #4060
weifengpy added a commit that referenced this pull request Aug 6, 2026
ghstack-source-id: 44cc6b7
Pull-Request: #4060
weifengpy added a commit that referenced this pull request Aug 6, 2026
ghstack-source-id: 4d37231
Pull-Request: #4060
weifengpy added a commit that referenced this pull request Aug 6, 2026
ghstack-source-id: 88f25a6
Pull-Request: #4060
weifengpy added a commit that referenced this pull request Aug 6, 2026
ghstack-source-id: 61606e5
Pull-Request: #4060
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Aug 6, 2026
weifengpy added a commit that referenced this pull request Aug 8, 2026
ghstack-source-id: 0120950
Pull-Request: #4060
@weifengpy weifengpy changed the title Add standalone distributed Muon optimizer [Kimi K2.7] Add DistributedMuon and flex_optimizer_reshard for all-to-all/compute overlap Aug 10, 2026
@weifengpy
weifengpy marked this pull request as ready for review August 10, 2026 01:08
@weifengpy
weifengpy marked this pull request as draft August 10, 2026 01:13
weifengpy added a commit that referenced this pull request Aug 10, 2026
…-all/compute overlap

* Add flex_optimizer_reshard to overlap packed all-to-all redistribution with optimizer compute: Separate parameter storage layout from Muon compute layout.
* Add DistributedMuon: per-head by default, enabled in Kimi K2.7, 2.5 and Moonlight recipes
* support FSDP2 + EP. Does not support TP and PP
* does not support oversharded QKV, eg single head get fragmented because of Shard(0). see future PRs in ghstack for support
* the packed all-to-all redistribution and optimizer-compute overlap ideas are informed by [FSDP-Canzona](https://github.com/liangyuwang/FSDP-Canzona) and [Canzona: A Unified, Asynchronous, and Load-Balanced Framework for Distributed Matrix-based Optimizers](https://arxiv.org/abs/2602.06079) (Wang et al., 2026).
* resolve #3353
* Co-authored with [Liangyu Wang (@liangyuwang)](https://github.com/liangyuwang).

[ghstack-poisoned]

ghstack-source-id: 201f5c1
Pull-Request: #4060
Co-authored-by: Liangyu Wang <[email protected]>
@weifengpy
weifengpy force-pushed the gh/weifengpy/44/base branch from 115aa99 to 81f44ea Compare August 10, 2026 01:18
@weifengpy
weifengpy force-pushed the gh/weifengpy/44/head branch from bd3cd8b to ef09899 Compare August 10, 2026 01:18
weifengpy added a commit that referenced this pull request Aug 10, 2026
…-all/compute overlap

* Add flex_optimizer_reshard to overlap packed all-to-all redistribution with optimizer compute: Separate parameter storage layout from Muon compute layout.
* Add DistributedMuon: per-head by default, enabled in Kimi K2.7, 2.5 and Moonlight recipes
* support FSDP2 + EP. Does not support TP and PP
* does not support oversharded QKV, eg single head get fragmented because of Shard(0). see future PRs in ghstack for support
* the packed all-to-all redistribution and optimizer-compute overlap ideas are informed by [FSDP-Canzona](https://github.com/liangyuwang/FSDP-Canzona) and [Canzona: A Unified, Asynchronous, and Load-Balanced Framework for Distributed Matrix-based Optimizers](https://arxiv.org/abs/2602.06079) (Wang et al., 2026).
* resolve #3353
* Co-authored with [Liangyu Wang (@liangyuwang)](https://github.com/liangyuwang).

[ghstack-poisoned]

ghstack-source-id: 396065d
Pull-Request: #4060
Co-authored-by: Liangyu Wang <[email protected]>
@weifengpy
weifengpy force-pushed the gh/weifengpy/44/head branch from bdf224f to 3880d70 Compare August 10, 2026 01:44
weifengpy added a commit that referenced this pull request Aug 10, 2026
…-all/compute overlap

* Add flex_optimizer_reshard to overlap packed all-to-all redistribution with optimizer compute: Separate parameter storage layout from Muon compute layout.
* Add DistributedMuon: per-head by default, enabled in Kimi K2.7, 2.5 and Moonlight recipes
* support FSDP2 + EP. Does not support TP and PP
* does not support oversharded QKV, eg single head get fragmented because of Shard(0). see future PRs in ghstack for support
* the packed all-to-all redistribution and optimizer-compute overlap ideas are informed by [FSDP-Canzona](https://github.com/liangyuwang/FSDP-Canzona) and [Canzona: A Unified, Asynchronous, and Load-Balanced Framework for Distributed Matrix-based Optimizers](https://arxiv.org/abs/2602.06079) (Wang et al., 2026).
* resolve #3353
* Co-authored with [Liangyu Wang (@liangyuwang)](https://github.com/liangyuwang).

[ghstack-poisoned]

ghstack-source-id: aa8daae
Pull-Request: #4060
Co-authored-by: Liangyu Wang <[email protected]>
@weifengpy
weifengpy force-pushed the gh/weifengpy/44/base branch from b9c5bb5 to 423b2e4 Compare August 10, 2026 01:48

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

didn't have time to dive into details, so my first review is mostly on UX

Comment on lines +92 to +94
# Run the GPU-only DistributedMuon test that CPU unit CI skips.
python -m pytest tests/unit_tests/test_distributed_muon.py \
--durations=20 -vv

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wwwjn we should set up GPU unit test in CI

Comment thread tests/integration_tests/models.py Outdated
"--parallelism.expert_parallel_degree 2",
"--training.steps 1",
"--checkpoint.enable",
"--checkpoint.enable_first_step_checkpoint",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need this?

@weifengpy weifengpy Aug 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removing first step checkpointing - but will chat more on checkpoint resume below

Comment thread tests/integration_tests/models.py Outdated
[
# Consolidate the former 2-GPU FSDP smoke and 8-GPU
# FSDP+TP+EP+PP test into one supported FSDP+EP path with
# checkpoint resume. Kimi DistributedMuon rejects TP because

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is checkpoint resumption worth extra testing for kimi?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed checkpoint resume from integration tests - there was optimizer-specific load logic (per-head view metadata), but it turns out to be redundant

DCP save/load is covered in test_distributed_muon.py now

Comment thread torchtitan/config/configurable.py Outdated
Comment on lines +53 to +60
# dataclasses.asdict() recursively flattens nested dataclasses
# before _convert can honor their custom to_dict(). For Muon
# sharding, json.dumps() would then fail with "Object of type
# Shard is not JSON serializable", while Owned becomes {}.
return {
f.name: _convert(getattr(val, f.name))
for f in dataclasses.fields(val)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we do

return _convert(dataclasses.asdict(val))

as in #4088

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I excluded the change from this PR - will comment directly in #4088

Comment thread torchtitan/models/kimi_k2_7/README.md Outdated
Comment on lines +39 to +41
| Tensor Parallelism (TP) | The model supports TP: token embeddings and vision activations remain replicated for vision scatter, decoder SP resumes at layer 0, and vision attention/linear layers are TP-sharded without vision SP. The default DistributedMuon recipes currently reject TP because it can produce unsupported `_StridedShard` parameter layouts |
| Expert Parallelism (EP) | DeepSeek-V3 routed + shared experts |
| Pipeline Parallel (PP) | Vision encoder folded into the first stage; 1F1B and Interleaved1F1B schedules |
| Pipeline Parallel (PP) | The model supports PP with the vision encoder folded into the first stage, but the default DistributedMuon recipes do not yet support stage-local optimizer groups |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe add to TODOs?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added a TODO section

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correction: the TODO section already existed; I did not add it. I kept these DistributedMuon limitations in the Supported Parallelisms table instead, with the concrete follow-ups linked there (#3353 for TP and #4102 for PP), so the current support status has a single source of truth rather than being duplicated in TODO.

Comment on lines +62 to +68
lr: float = 1e-3,
weight_decay: float = 0.1,
momentum: float = 0.95,
nesterov: bool = True,
ns_coefficients: tuple[float, float, float] = (3.4445, -4.7750, 2.0315),
eps: float = 1e-7,
ns_steps: int = 5,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why having these default, are they mimicking what core has?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, this is trying to be consistent with torch.optim.Muon in 1st PR

ns_steps_by_group=ns_steps_by_group,
),
)
self._plans = result.plans

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

may be more clear

Suggested change
self._plans = result.plans
self._bucket_plans = result.plans

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done



@dataclass(frozen=True, slots=True)
class BucketSpec:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

redundant to BucketConfig?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

refactored to make BucketConfig public facing - it's at trainer config layer and user should be aware of it

_BucketSpec is lower-level config for API flex_optimizer_reshard with resolved mesh. torchtitan user shouldn't be aware of it

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wasn't able to review internals in details

I feel this should be put in distributed/flex_shard/ and eventually go annex

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

created torchtitan/distributed/flex_shard

  • optimizer_reshard.py: public configuration/API
  • _optimizer_reshard_schedule.py: tensor routes, bucket plans, and packed all-to-all schedules
  • _optimizer_reshard_runtime.py: buffers, streams, collectives, and pipelining

once DistributedMuon gets sync into internal, we are on track to export flex_shard folder as an annex repo

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I may prefer to have this directly under components/
and later we can group optimizers.py, lr_schedulers.py, distributed_muon.py to be under components/optim

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done - distributed_muon.py remains directly under torchtitan/components/

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

distributed_muon.py gets moved into flex_shard folder becuase bucketing and muon math are coupled without introducing opmtizer parts (which needs delicated alignment on UX)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated. DistributedMuon now lives at torchtitan/distributed/flex_shard/distributed_muon.py, and the one-file optim/ package is gone. This placement is intentional because FlexShard is intended to become a standalone repo. The whole flex_shard/ package now imports only PyTorch/stdlib, and its public layout API accepts exact string DeviceMesh.mesh_dim_names, so dependencies flow TorchTitan -> FlexShard -> PyTorch.

@weifengpy
weifengpy marked this pull request as draft August 11, 2026 05:48
Comment thread torchtitan/components/optimizer.py Outdated
- more info: https://pytorch.org/docs/stable/optim.html
"""

optimizer_init_kwargs: dict[str, dict[str, Any]] = field(default_factory=dict)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this different from ParamGroupConfig.optimizer_kwargs?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good question! optimizer_init_kwargs is for distributed muon wrapper, with fqn-to-compute sharding, bucketing info, per-head view

optimizer_kwargs is like traditional optimizer constructor kwargs

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked again: optimizer_kwargs is for passed to param_group, eg

ParamGroupConfig(
      pattern=r".*\.weight$",
      optimizer_name="DistributedMuon",
      optimizer_kwargs={
          "lr": 2e-4,
          "momentum": 0.95,
          "ns_steps": 5,
      },
  )

I renamed to optimizer_factory_kwargs_by_name, "by_name" means "DistributedMuon". A full example e2e is

config = OptimizersContainer.Config(
      param_groups=[
          ParamGroupConfig(
              pattern=muon_pattern,
              optimizer_name="DistributedMuon",
              optimizer_kwargs={
                  "lr": 2e-4,
                  "momentum": 0.95,
                  "ns_steps": 5,
              },
          ),
      ],
      optimizer_factory_kwargs_by_name={
          "DistributedMuon": {
              "compute_sharding_by_fqn": compute_sharding_by_fqn,
              "bucket_configs": bucket_configs,
          },
      },
  )

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need this file?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not strictly required for imports - I just want flex_shard to be a formal python module

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a basic README, mentioning that we will annex this folder as a package.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will make sure to add README before landing, and mention annex as future plan

submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Aug 12, 2026
…-all/compute overlap

* Add flex_optimizer_reshard to overlap packed all-to-all redistribution with optimizer compute: Separate parameter storage layout from Muon compute layout.
* Add DistributedMuon: per-head by default, enabled in Kimi K2.7, 2.5 and Moonlight recipes
* support FSDP2 + EP. Does not support TP and PP yet, but is possible to extend
* oversharded QKV by Shard(0) will be supported later in the PR stack
* the packed all-to-all redistribution and optimizer-compute overlap ideas are informed by [FSDP-Canzona](https://github.com/liangyuwang/FSDP-Canzona) and [Canzona: A Unified, Asynchronous, and Load-Balanced Framework for Distributed Matrix-based Optimizers](https://arxiv.org/abs/2602.06079) (Wang et al., 2026).
* resolve pytorch/torchtitan#3353

Co-authored-by: Liangyu Wang <[email protected]>

**profiler trace** to showcase all-to-all overlapping during muon: https://fburl.com/o7pyeuuy
<img width="608" height="322" alt="Screenshot 2026-08-09 at 7 12 39 PM" src="https://github.com/user-attachments/assets/22e344bd-1459-432d-a023-cc71efe72da1" />

**memory snapshot** to showcase expected sharded optimizer state dict

ghstack (bottom to top):
* [#4060 — DistributedMuon and flex_optimizer_reshard (this PR)](pytorch/torchtitan#4060)
* [#4078 — Support oversharded QKV heads](pytorch/torchtitan#4078)
* [#4077 — Support explicit replicated Muon compute](pytorch/torchtitan#4077)

ghstack-source-id: 0c301d0
Pull-Request: pytorch/torchtitan#4060
Co-authored-by: Liangyu Wang <[email protected]>
Comment thread torchtitan/components/optimizer.py Outdated
Must include all required kwargs (e.g. ``lr``). No implicit defaults."""

@classmethod
def for_remaining_parameters(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems a syntactic sugar, but not absolutely necessary? I'd prefer keeping the api surface as succinct as possible and let user specify * pattern explicitly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed for_remaining_parameters and instead let user specify explicitly

param_groups=param_groups,
optimizer_init_kwargs={
"DistributedMuon": {
"bucket_configs": bucket_configs,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed offline, shall we error out if multiple param groups use DistributedMuon optimizer.

)
compute_sharding_by_fqn = {
fqn: compute_sharding
for layer_shardings in layer_compute_shardings

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

naming is confusing

compute placement.
"""

compute_placement: Owned | Shard

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
compute_placement: Owned | Shard
compute_sharding: Owned | Shard

to be consistent with titan convention https://github.com/pytorch/torchtitan/blob/main/torchtitan/protocols/sharding.py#L118

also since there's no mesh concept here, not clear how we are going to extend this to multi-mesh shardings



@dataclass(frozen=True, slots=True)
class BatchedMatrixComputeView:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The name is not suggestive of what it does. And it seems hard for me to think of any name that is.

How do you like / dislike the proposal in #4060 (comment)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AttentionPerHeadComputeView is very model specific, that's why I only improved docstring of BatchedMatrixComputeView.

But I admit only attention need this so far - I can use AttentionPerHeadComputeView as public facing name if it's reads more intuitive

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so it seems we won't have flex_optimizer_reshard and DistributedMuon itself covers the optimization

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i am brining back flex_optimizer_reshard - I lost it accidentally when prototyping to see what happens without optimizer factory

num_matrices=attention.n_heads,
),
)
per_expert = MuonComputeShardingConfig(compute_placement=Shard(0))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

experts params are on 2D storage mesh, so this compute_placement must be ambiguous?

BucketConfig(
name="layers." + "-".join(map(str, layer_ids)),
patterns=fqns,
mesh_axis="dp_shard",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where do we specify the efsdp axis?

submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Aug 12, 2026
…-all/compute overlap

* Add flex_optimizer_reshard to overlap packed all-to-all redistribution with optimizer compute: Separate parameter storage layout from Muon compute layout.
* Add DistributedMuon: per-head by default, enabled in Kimi K2.7, 2.5 and Moonlight recipes
* support FSDP2 + EP. Does not support TP and PP yet, but is possible to extend
* oversharded QKV by Shard(0) will be supported later in the PR stack
* the packed all-to-all redistribution and optimizer-compute overlap ideas are informed by [FSDP-Canzona](https://github.com/liangyuwang/FSDP-Canzona) and [Canzona: A Unified, Asynchronous, and Load-Balanced Framework for Distributed Matrix-based Optimizers](https://arxiv.org/abs/2602.06079) (Wang et al., 2026).
* resolve pytorch/torchtitan#3353

Co-authored-by: Liangyu Wang <[email protected]>

**profiler trace** to showcase all-to-all overlapping during muon: https://fburl.com/o7pyeuuy
<img width="608" height="322" alt="Screenshot 2026-08-09 at 7 12 39 PM" src="https://github.com/user-attachments/assets/22e344bd-1459-432d-a023-cc71efe72da1" />

**memory snapshot** to showcase expected sharded optimizer state dict

ghstack (bottom to top):
* [#4060 — DistributedMuon and flex_optimizer_reshard (this PR)](pytorch/torchtitan#4060)
* [#4078 — Support oversharded QKV heads](pytorch/torchtitan#4078)
* [#4077 — Support explicit replicated Muon compute](pytorch/torchtitan#4077)

ghstack-source-id: f8e162f
Pull-Request: pytorch/torchtitan#4060
Co-authored-by: Liangyu Wang <[email protected]>
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Aug 12, 2026
…-all/compute overlap

* Add flex_optimizer_reshard to overlap packed all-to-all redistribution with optimizer compute: Separate parameter storage layout from Muon compute layout.
* Add DistributedMuon: per-head by default, enabled in Kimi K2.7, 2.5 and Moonlight recipes
* support FSDP2 + EP. Does not support TP and PP yet, but is possible to extend
* oversharded QKV by Shard(0) will be supported later in the PR stack
* the packed all-to-all redistribution and optimizer-compute overlap ideas are informed by [FSDP-Canzona](https://github.com/liangyuwang/FSDP-Canzona) and [Canzona: A Unified, Asynchronous, and Load-Balanced Framework for Distributed Matrix-based Optimizers](https://arxiv.org/abs/2602.06079) (Wang et al., 2026).
* resolve pytorch/torchtitan#3353

Co-authored-by: Liangyu Wang <[email protected]>

**profiler trace** to showcase all-to-all overlapping during muon: https://fburl.com/o7pyeuuy
<img width="608" height="322" alt="Screenshot 2026-08-09 at 7 12 39 PM" src="https://github.com/user-attachments/assets/22e344bd-1459-432d-a023-cc71efe72da1" />

**memory snapshot** to showcase expected sharded optimizer state dict

ghstack (bottom to top):
* [#4060 — DistributedMuon and flex_optimizer_reshard (this PR)](pytorch/torchtitan#4060)
* [#4078 — Support oversharded QKV heads](pytorch/torchtitan#4078)
* [#4077 — Support explicit replicated Muon compute](pytorch/torchtitan#4077)

ghstack-source-id: 21c53bc
Pull-Request: pytorch/torchtitan#4060
Co-authored-by: Liangyu Wang <[email protected]>
MeshAxisName.DP: Shard(0),
MeshAxisName.DP_SHARD: Shard(0),
MeshAxisName.EFSDP: Shard(0),
MeshAxisName.EP: Shard(0),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what if there's not enough experts to shard?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there is a follow up PR that handle EP Shard(0) EFSDP Shard(1)

this first PR gate on EP and EFSDP both sharding on dim0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this first PR gate on EP and EFSDP both sharding on dim0

you mean the storage sharding should ALSO be dim0, dim0?

@weifengpy weifengpy Aug 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, in this PR, we only target storage sharding dim0, dim0

if EP dim0, EFSDP dim1, we would raise unimplemented error

raise NotImplementedError(
f"Muon parameter {fqn!r} cannot yet redistribute along "
f"mesh axis {redistribution_axis_name!r} while preserving "
f"non-replicated axis {mesh_axis_names[storage_mesh_axis]!r}"
)

then support storage dim0, dim1 in #4122

@weifengpy weifengpy Aug 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ignore bot reply. will reply later Made this explicit in #4060. The Kimi support table documents the initial requirement, and a dedicated four-GPU test constructs expert storage (EFSDP Shard(1), EP Shard(0)), requests compute (Shard(0), Shard(0)), and asserts the targeted constructor error. Correction to my previous reply: the one-axis orthogonal-shard support is #4122, not #4124.

per_expert = MuonComputeShardingConfig(
compute_layout=ComputeLayout(
axis_placements={
MeshAxisName.DP: Shard(0),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need this? DP should be a fwd-bwd compute axis

@weifengpy weifengpy Aug 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ignore this as it's from bot. will reply later Agreed. Removed MeshAxisName.DP from the expert compute layout. It now names only physical parameter-storage axes: dp_shard for the dense/no-EP storage variant and efsdp plus ep for the sparse storage mesh.

Comment on lines +63 to +73
Placements override the named axes; omitted axes preserve their storage
placement. Ownership axes assign each complete logical matrix to one
participant in their Cartesian group. Extra declarations may target mesh
variants not used by a particular parameter, but at least one declaration
must apply when the layout is resolved.
"""

axis_placements: Mapping[MeshAxisName, Replicate | Shard] = field(
default_factory=dict
)
owner_mesh_axis_names: tuple[MeshAxisName, ...] = ()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found them not easy to understand

submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Aug 12, 2026
…-all/compute overlap

* Add flex_optimizer_reshard to overlap packed all-to-all redistribution with optimizer compute: Separate parameter storage layout from Muon compute layout.
* Add DistributedMuon: per-head by default, enabled in Kimi K2.7, 2.5 and Moonlight recipes
* support FSDP2 + EP. Does not support TP and PP yet, but is possible to extend
* oversharded QKV by Shard(0) will be supported later in the PR stack
* the packed all-to-all redistribution and optimizer-compute overlap ideas are informed by [FSDP-Canzona](https://github.com/liangyuwang/FSDP-Canzona) and [Canzona: A Unified, Asynchronous, and Load-Balanced Framework for Distributed Matrix-based Optimizers](https://arxiv.org/abs/2602.06079) (Wang et al., 2026).
* resolve pytorch/torchtitan#3353

Co-authored-by: Liangyu Wang <[email protected]>

**profiler trace** to showcase all-to-all overlapping during muon: https://fburl.com/o7pyeuuy
<img width="608" height="322" alt="Screenshot 2026-08-09 at 7 12 39 PM" src="https://github.com/user-attachments/assets/22e344bd-1459-432d-a023-cc71efe72da1" />

**memory snapshot** to showcase expected sharded optimizer state dict

ghstack (bottom to top):
* [#4060 — DistributedMuon and flex_optimizer_reshard (this PR)](pytorch/torchtitan#4060)
* [#4078 — Support oversharded QKV heads](pytorch/torchtitan#4078)
* [#4077 — Support explicit replicated Muon compute](pytorch/torchtitan#4077)

ghstack-source-id: e690b71
Pull-Request: pytorch/torchtitan#4060
Co-authored-by: Liangyu Wang <[email protected]>
@weifengpy weifengpy changed the title [Kimi K2.7] Add DistributedMuon and flex_optimizer_reshard for all-to-all/compute overlap [Kimi K2.7] Add DistributedMuon with all-to-all/compute overlap Aug 12, 2026
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Aug 12, 2026
* Add DistributedMuon to overlap packed all-to-all redistribution with optimizer compute while separating parameter storage and Muon compute layouts.
* Use per-head Muon by default in Kimi K2.7, Kimi K2.5, and Moonlight recipes.
* Support FSDP2 + EP. TP and PP are not supported yet but can be extended later.
* Leave oversharded Shard(0) QKV support to a later PR in the stack.
* The packed all-to-all redistribution and optimizer-compute overlap ideas are informed by [FSDP-Canzona](https://github.com/liangyuwang/FSDP-Canzona) and [Canzona: A Unified, Asynchronous, and Load-Balanced Framework for Distributed Matrix-based Optimizers](https://arxiv.org/abs/2602.06079) (Wang et al., 2026).
* Resolve pytorch/torchtitan#3353.

**Profiler trace** showing all-to-all overlapping during Muon: https://fburl.com/o7pyeuuy
<img width="608" height="322" alt="Screenshot 2026-08-09 at 7 12 39 PM" src="https://github.com/user-attachments/assets/22e344bd-1459-432d-a023-cc71efe72da1" />

**Memory snapshot** showing the expected sharded optimizer state dict.

ghstack (bottom to top):
* [#4060 - DistributedMuon with all-to-all/compute overlap (this PR)](pytorch/torchtitan#4060)
* [#4078 - Support oversharded QKV heads](pytorch/torchtitan#4078)
* [#4077 - Support explicit replicated Muon compute](pytorch/torchtitan#4077)

ghstack-source-id: 8fce56e
Pull-Request: pytorch/torchtitan#4060
Co-authored-by: Liangyu Wang <[email protected]>
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Aug 12, 2026
* Add DistributedMuon to overlap packed all-to-all redistribution with optimizer compute while separating parameter storage and Muon compute layouts.
* Use per-head Muon by default in Kimi K2.7, Kimi K2.5, and Moonlight recipes.
* Support FSDP2 + EP. TP and PP are not supported yet but can be extended later.
* Leave oversharded Shard(0) QKV support to a later PR in the stack.
* The packed all-to-all redistribution and optimizer-compute overlap ideas are informed by [FSDP-Canzona](https://github.com/liangyuwang/FSDP-Canzona) and [Canzona: A Unified, Asynchronous, and Load-Balanced Framework for Distributed Matrix-based Optimizers](https://arxiv.org/abs/2602.06079) (Wang et al., 2026).
* Resolve pytorch/torchtitan#3353.

**Profiler trace** showing all-to-all overlapping during Muon: https://fburl.com/o7pyeuuy
<img width="608" height="322" alt="Screenshot 2026-08-09 at 7 12 39 PM" src="https://github.com/user-attachments/assets/22e344bd-1459-432d-a023-cc71efe72da1" />

**Memory snapshot** showing the expected sharded optimizer state dict.

ghstack (bottom to top):
* [#4060 - DistributedMuon with all-to-all/compute overlap (this PR)](pytorch/torchtitan#4060)
* [#4078 - Support oversharded QKV heads](pytorch/torchtitan#4078)
* [#4077 - Support explicit replicated Muon compute](pytorch/torchtitan#4077)

ghstack-source-id: 54fb071
Pull-Request: pytorch/torchtitan#4060
Co-authored-by: Liangyu Wang <[email protected]>
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Aug 12, 2026
* Add DistributedMuon to overlap packed all-to-all redistribution with optimizer compute while separating parameter storage and Muon compute layouts.
* Use per-head Muon by default in Kimi K2.7, Kimi K2.5, and Moonlight recipes.
* Support FSDP2 + EP. TP and PP are not supported yet but can be extended later.
* Leave oversharded Shard(0) QKV support to a later PR in the stack.
* The packed all-to-all redistribution and optimizer-compute overlap ideas are informed by [FSDP-Canzona](https://github.com/liangyuwang/FSDP-Canzona) and [Canzona: A Unified, Asynchronous, and Load-Balanced Framework for Distributed Matrix-based Optimizers](https://arxiv.org/abs/2602.06079) (Wang et al., 2026).
* Resolve pytorch/torchtitan#3353.

**Profiler trace** showing all-to-all overlapping during Muon: https://fburl.com/o7pyeuuy
<img width="608" height="322" alt="Screenshot 2026-08-09 at 7 12 39 PM" src="https://github.com/user-attachments/assets/22e344bd-1459-432d-a023-cc71efe72da1" />

**Memory snapshot** showing the expected sharded optimizer state dict.

ghstack (bottom to top):
* [#4060 - DistributedMuon with all-to-all/compute overlap (this PR)](pytorch/torchtitan#4060)
* [#4078 - Support oversharded QKV heads](pytorch/torchtitan#4078)
* [#4077 - Support explicit replicated Muon compute](pytorch/torchtitan#4077)

ghstack-source-id: e09970f
Pull-Request: pytorch/torchtitan#4060
Co-authored-by: Liangyu Wang <[email protected]>
Comment on lines +221 to +229
per_expert = MuonComputeShardingConfig(
compute_layout=ComputeLayout(
placements_by_mesh_axis={
MeshAxisName.DP_SHARD.value: Shard(0),
MeshAxisName.EFSDP.value: Shard(0),
MeshAxisName.EP.value: Shard(0),
},
)
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems routed experts are put in the same bucket as other params in a transformer block -- would DistributedMuon runtime take care of this when performing a2a? Would two a2a per layer be issued? Would it be more straightforward to users if we require two buckets for each block, like FSDP2?

@weifengpy weifengpy Aug 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

routed experts + dense params is in the same bucket only becuase there is no redistribution for routed experts, because we gate on EP Shard(0) and EFSDP Shard(0) in this PR for now

in future PRs, when routed experts require actual redistribution, it's only possible via a separate bucket, like FSDP2

  • routed experts in a bucket with 2D mesh, EP + EFSDP
  • dense params in a bucket with 1D mesh, DP-only

Comment on lines +78 to +82

placements_by_mesh_axis: Mapping[str, Replicate | Shard] = field(
default_factory=dict
)
matrix_ownership_axes: tuple[str, ...] = ()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you plan to consolidate these two fields later by introducing Owned placement?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yep - they are merging into one in this PR

Comment on lines +51 to +53
ParamGroupConfig(pattern=r"\\.bias$", ...),
ParamGroupConfig(pattern=r"\\.router\\.", ...),
ParamGroupConfig(pattern=r".*", ...),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shall we error out when multiple ParamGroups use DistributedMuon optimizer?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, we raise error for multiple ParamGroups at init time

raise ValueError("DistributedMuon requires exactly one parameter group")

I was tracking all your comment locally and whether they are resolved. should be able to save your time to repeat things

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh sorry I didn't realize we can do that inside distributed muon because all param groups under the same optimizer is grouped together by https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/optimizer.py#L213

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no worries

)
"""

distribution_by_mesh_axis: Mapping[str, SingleParticipant | Replicate | Shard]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to be consistent
https://github.com/pytorch/torchtitan/blob/main/torchtitan/protocols/sharding.py#L117

Suggested change
distribution_by_mesh_axis: Mapping[str, SingleParticipant | Replicate | Shard]
shardings_by_mesh_axis: Mapping[str, SingleParticipant | Replicate | Shard]


@dataclass(frozen=True, slots=True)
class SingleParticipant:
"""Assign the complete subgroup-local logical tensor to one participant.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is a "participant"?

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no other major feedback on UX / structure from me, other than this minor point https://github.com/pytorch/torchtitan/pull/4060/changes#r3771755149

Thanks a lot!

* Add DistributedMuon to overlap packed all-to-all redistribution with optimizer compute while separating parameter storage and Muon compute layouts.
* Use per-head Muon by default in Kimi K2.7, Kimi K2.5, and Moonlight recipes.
* Support FSDP2 + EP. TP and PP are not supported yet but can be extended later.
* Leave oversharded Shard(0) QKV support to a later PR in the stack.
* The packed all-to-all redistribution and optimizer-compute overlap ideas are informed by [FSDP-Canzona](https://github.com/liangyuwang/FSDP-Canzona) and [Canzona: A Unified, Asynchronous, and Load-Balanced Framework for Distributed Matrix-based Optimizers](https://arxiv.org/abs/2602.06079) (Wang et al., 2026).
* Resolve #3353.

**Profiler trace** showing all-to-all overlapping during Muon: https://fburl.com/o7pyeuuy
<img width="608" height="322" alt="Screenshot 2026-08-09 at 7 12 39 PM" src="https://github.com/user-attachments/assets/22e344bd-1459-432d-a023-cc71efe72da1" />

**Memory snapshot** showing the expected sharded optimizer state dict.

ghstack (bottom to top):
* [#4060 - DistributedMuon with all-to-all/compute overlap (this PR)](#4060)
* [#4078 - Support oversharded QKV heads](#4078)
* [#4077 - Support explicit replicated Muon compute](#4077)

ghstack-source-id: ed9a849
Pull-Request: #4060
Co-authored-by: Liangyu Wang <[email protected]>
@weifengpy
weifengpy force-pushed the gh/weifengpy/44/head branch from 11e8d15 to 909b0a4 Compare August 13, 2026 06:55
@weifengpy
weifengpy changed the base branch from gh/weifengpy/44/base to main August 13, 2026 06:55
@weifengpy
weifengpy marked this pull request as ready for review August 13, 2026 06:57
@weifengpy
weifengpy merged commit bb90ff9 into main Aug 13, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu 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.

Proposal: async and load-balanced Muon/SOAP-style optimizers for TorchTitan

2 participants