Skip to content

[distmuon] Isolate redistribution NCCL communicators - #5183

Merged
shuhuayu merged 5 commits into
pytorch:mainfrom
shuhuayu:distmuon
Oct 29, 2026
Merged

shuhuayu merged 5 commits into
pytorch:mainfrom
shuhuayu:distmuon

Conversation

@shuhuayu

@shuhuayu shuhuayu commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • add an explicit redistribution mesh to FlexShard BucketConfig, validated against the inferred storage-mesh axis, ranks, and rank order
  • build one storage-shaped redistribution mesh per distinct runtime storage DeviceMesh within each DistMuon instance, replacing only dp_shard and edp_shard groups with resource-independent NCCL children
  • attach the same built mesh directly to every matched DistMuon bucket with that storage layout, without a run-wide mesh cache
  • build capped meshes with standalone build_alternative_fsdp_mesh in torchtitan/distributed/utils.py, keeping the existing Config.build(params=...) API without extra optimizer context plumbing
  • leave the FlexShard DistMuon constructor and planner unchanged
  • keep FSDP on its original communicator and configure the Kimi K3 DistMuon recipe to use eight redistribution CTAs

Why

DistMuon uses all-to-all redistribution. Letting that traffic initialize on the FSDP communicator can create direct peer/channel connection state for the whole group, while reducing channels globally would also constrain FSDP collectives.

The explicit DeviceMesh contract follows the parallelism API convention: callers own process-group construction and DistMuon consumes the named mesh axis selected by its storage-to-compute transition. This supports max_ctas now and other process-group initialization options later without creating communicators implicitly inside FlexShard.

Optimizer construction retains the normal Config.build(params=...) API. The TorchTitan DistMuon wrapper calls the standalone build_alternative_fsdp_mesh utility on matched parameters' storage meshes. Adam, AdamW, and custom optimizer constructors remain unchanged; no new parallelism_context forwarding is needed in the optimizer container or torchft.

During initialization of each DistMuon instance, TorchTitan constructs one capped redistribution mesh for each distinct runtime storage DeviceMesh and explicitly reuses it across matching buckets. This sharing stays within that optimizer instance; there is no run-wide cache. The builder splits only the FSDP shard axes with split_share=0, preserves every other storage-mesh axis group, and reconstructs the original storage layout with DeviceMesh.from_group. The default max_nccl_ctas_for_comms value is -1; all values <= 0 leave communication behavior unchanged.

A positive cap requires NCCL on the FSDP shard axes. Other backends raise ValueError; fake warns and keeps the storage groups without modeling the cap. A storage mesh without FSDP shard axes warns that the cap is not applied. The configuration documents the connection-memory savings, fixed communicator overhead, and bandwidth tradeoff, with a TODO identifying this as a temporary workaround pending lower-memory redistribution.

For a 64-rank all-peer group with 12 MiB of measured connection storage per peer/channel pair, reducing 32 channels to 8 changes the fan-out estimate from 23.625 GiB to 5.906 GiB per rank.

Validation

  • optimizer, FlexShard, and distributed utility CPU tests: 73 passed
  • two-GPU NCCL mesh/checkpoint tests: 3 passed; checks max_ctas=8, split_share=0, group isolation, rank membership, retained replicate groups, all-to-all results, and optimizer schedule ownership before and after checkpoint reload
  • focused Pyrefly checks for core production files: 0 errors
  • pre-commit run --all-files: all non-type hooks passed; the full Pyrefly hook was skipped in favor of focused checks
  • broader ParallelismContext tests are blocked locally during collection because the installed PyTorch lacks torch.distributed.pipelining.analyze_pipeline_activation_liveness

The change does not alter optimizer arithmetic or collective payloads.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 8, 2026
@shuhuayu shuhuayu changed the title [DistMuon] Isolate redistribution NCCL communicators [distmuon] Isolate redistribution NCCL communicators Oct 8, 2026
config: Config,
*,
params: Iterable[dict[str, Any]] | Iterable[Tensor],
process_group_cache: _DistMuonProcessGroupCache | None = None,

@weifengpy weifengpy Oct 8, 2026 •

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.

we need 2 steps

step 1: refactor DistMuon BucketConfig to accept mesh explicitly

4. **Add `mesh: DeviceMesh | None = None` to `BucketConfig`.** Contract: the mesh has a named axis matching the storage-mesh axis the bucket redistributes along, covering the same ranks in the same order; DistMuon communicates on `mesh[axis].get_group()`. It can be 1D or storage-shaped (e.g. `(dp_replicate, edp_shard, ep)`). `None` keeps today's behavior.
5. **Validate in `_bind_bucket_configs`**, the only place a `_BucketSpec` is built: a missing axis or a layout mismatch (`torch.equal(mesh[axis].mesh, inferred.mesh)`) raises `ValueError`; bind `mesh[axis]`, so `_BucketSpec.mesh` stays 1D. Order matters because the bucket mesh's rank order assigns compute shards (`shard_participants`). Warn if the bucket has nothing to redistribute.
6. **Revert the planner changes.** `get_redistribution_process_group` goes away from `DistMuon`, `_build_bucket_plans` and `_redistribution_group`. FlexShard's `DistMuon` constructor stays unchanged, and reloads reuse the bound mesh.

step 2: consturct mesh with max_cta pg and pass to DistMuon

8. **Build the capped mesh in `torchtitan/distributed/`** (e.g. on `ParallelismContext`, cached once per run): split the FSDP shard axes (`dp_shard`, `edp_shard`) with `max_ctas` and `split_share=0`, keep the other axes' groups, and wrap them with the list form `DeviceMesh.from_group(groups, device_type, mesh=storage_mesh.mesh, mesh_dim_names=...)` so the storage layout is preserved. Keep the fake-backend fallback and the NCCL-only check.
9. **TorchTitan wiring:** keep `redistribution_max_ctas` on `DistMuon.Config`. At build time, for each bucket, take a matched parameter's storage mesh and `dataclasses.replace(bucket, mesh=...)`. Because DistMuon selects the axis by name, the wrapper doesn't need to know which axis moves (routed experts name both `edp_shard` and `ep`). Pass `parallelism_context` (already on `Optim`) instead of `process_group_cache`, and drop `_DistMuonProcessGroupCache` and the `isinstance` branch.

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 iterated over it with codex, and i think it is more lightweight to simply use reconfigured child process groups instead of exposing new device mesh arg to bucket config, which i tried and some redundant work in generic scheduler and fqn matching showed up. can you check the current pr again? let me know wdyt.

from codex:

The capped communicator is an internal DistMuon transport policy, not bucket configuration. FlexShard already resolves every bucket to the exact 1D redistribution mesh, including its axis, ranks, and rank order, so deriving the child communicator from that bound mesh makes invalid layouts unrepresentable. This preserves all required functionality while avoiding a new public BucketConfig.mesh API, duplicate validation, changes to the generic scheduler, and FQN rematching in the TorchTitan wrapper. The result is smaller, safer, and keeps communicator ownership in the component that actually uses 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.

tis this setting max cta to across fsdp2 pg and distmuon pg? because they use the same pg. that's why i suggested passing a new device mesh to distmuon so the max_cta is only applied to distmuon

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 checked again - we are decoupling with fsdp pg by creating a new pg inside DistMuon. the convention of paralelsim api is not to create pg implicitly inside, but let user pass device mesh as api contract

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.

each pg creation means 2GB nccl workspace memory. we had similar mistake in fsdp2 reshard_after_forward=int, and we should avoid such mistake here

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.

this is only for distmuon pg with a separate communicator. OK, let's be more future sighted and use separate device mesh contract.

@shuhuayu
shuhuayu force-pushed the distmuon branch 2 times, most recently from 01e8d71 to 41e27f2 Compare October 9, 2026 06:16
@shuhuayu
shuhuayu force-pushed the distmuon branch 8 times, most recently from d1f579a to 16d63cc Compare October 21, 2026 08:58
@shuhuayu
shuhuayu marked this pull request as ready for review October 21, 2026 08:59
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 21, 2026
lr=muon_lr,
weight_decay=0.1,
adjust_lr_fn="match_rms_adamw",
redistribution_max_ctas=8,

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.

@fegin IIRC during your earlier spmd grad accum perf work, you had to adjust CTA for comms using an envvar?

anyway, I feel this is not a very user-friendly flag

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.

if we use an envvar it will also change the config for fsdp comms so would limit the fsdp comms, thus here we used a separate communicator.

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.

  1. This is the new way and recommended way to configure communication. The biggest problem of using an envvar is that it is going to affect all collectives not just this one. So this is the recommended way.
  2. Discussed with @shuhuayu. I think we have to expose this or we can infer this number based on the size of fsdp world size. What's the difference between this use case and our previous experiments on allgather is the collective type. This is alltoall and nccl will form the fully-connected pairs while allgather may use ring algorithm that doesn't require the full-connected pairs. So the memory usage of alltoall increase a lot while allgather doesn't.
  3. One optimization opportunity is to use symmetric memory pull pattern, but it is unclear if we can force nccl to use this implementation by allocating symmetric memory for the input -- nccl may not even implement this pattern at all or only support this in the latest version.

I remember that @weifengpy wants to create a communication kernel for this, iirc.

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.

talked with @fegin on using pull-based on the long-term solution. implementation-wise this involves NVL + inter-node so it need some work. prior case is NVL-only (distmoe) or inter-node only (cp)

for short-term, max_cta should be enough to unblock k3 perf run. when things get hard blocked on this, we can kick off the above long-term solution

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.

ok, based on the discussions, then i will stick to the current approach, but remove the build_optimizer dispatcher as Tianyu suggested, and make the nccl specific configs explicit.

eps: float = 1e-7,
ns_steps: int = 5,
adjust_lr_fn: str | None = None,
redistribution_max_ctas: int = -1,

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.

max_ctas is one of the pg init opts. as i said, the future proof way is passing device mesh so distmuon don't use param device mesh. pg is inside that device mesh

starting from fsdp2, we are using device mesh contract, where pg is from mesh internal

so my feedback stays the same: pass device mesh to DistMuon, just like why fsdp2 need a device mesh

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 problem. let's do the separate device mesh.

@weifengpy weifengpy 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.

see above. i want to make sure this device mesh contract is there, not only for max_ctas, but also for any future pg init opts

@shuhuayu
shuhuayu force-pushed the distmuon branch 3 times, most recently from f8c3e36 to 81f0de0 Compare October 22, 2026 23:11
@shuhuayu

Copy link
Copy Markdown
Contributor Author

@weifengpy updated as suggested, can you check again?

default_factory=dict, init=False, repr=False
)
# Buckets and optimizers with the same storage layout and CTA cap share one mesh.
_redistribution_meshes: dict[_RedistributionMeshCacheKey, DeviceMesh] = field(

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 need a cache for this? i would expect as to pass the max_ctas and contruct mesh. eg, following is a way to avoid such cache

1. torchtitan/distributed/parallelism_context.py — the builder and cache die

diff


-_RedistributionMeshCacheKey: TypeAlias = tuple[
-    tuple[dist.ProcessGroup, ...],
-    tuple[str, ...],
-    tuple[int, ...],
-    tuple[int, ...],
-    int,
-]
-
 class ParallelismContext:
-    # Buckets and optimizers with the same storage layout and CTA cap share one mesh.
-    _redistribution_meshes: dict[_RedistributionMeshCacheKey, DeviceMesh] = field(
-        default_factory=dict, init=False, repr=False
-    )
-
-    def get_redistribution_mesh(
-        self, storage_mesh: DeviceMesh, *, max_ctas: int
-    ) -> DeviceMesh:
-        """Return a cached storage-shaped mesh with isolated FSDP shard groups."""
-        ...  # entire method: cache lookup, split_group loop, from_group rebuild
2. torchtitan/components/optim/optimizer.py — the knob and the auto-build die

diff


 class DistMuon(FlexShardDistMuon, BaseOptimizer):
     @dataclass(...)
     class Config(BaseOptimizer.Config):
-        redistribution_max_ctas: int = -1  # Cap NCCL CTAs to save memory; <0 disables.
-
-        def build_optimizer(self, *, params, parallelism_context) -> Optimizer:
-            if parallelism_context is None:
-                raise ValueError("DistMuon requires a ParallelismContext")
-            return self.build(params=params, parallelism_context=parallelism_context)
 
     def __init__(
         self,
         config: Config,
         *,
         params: ...,
-        parallelism_context: ParallelismContext,
     ) -> None:
-        param_groups = tuple(...)
-        bucket_configs = config.bucket_configs
-        if config.redistribution_max_ctas > 0:
-            ...  # per-bucket: find matched param, get_redistribution_mesh(...),
-            ...  # replace(bucket_config, mesh=redistribution_mesh)
         super().__init__(
-            param_groups,
+            params,
-            bucket_configs=bucket_configs,
+            bucket_configs=config.bucket_configs,
             ...
         )
Plus the plumbing that only existed to feed this: build_optimizer on the base Config, the parallelism_context parameter on OptimizersContainer and its use in optim.py, and the torchft passthrough — all revert to plain optimizer_config.build(params=[param_group]).

3. Caller side — the recipe builds it once and hands it in

The split dance survives only as the caller's own code, next to where bucket configs are authored (shown for K3; kimi_k3.py already builds its bucket_configs list in _dist_muon_optimizer):

diff


+def _capped_redistribution_mesh(storage_mesh: DeviceMesh, *, max_ctas: int) -> DeviceMesh:
+    """Split the FSDP shard axes into CTA-capped child communicators."""
+    groups = []
+    for axis_name in storage_mesh.mesh_dim_names:
+        group = storage_mesh.get_group(axis_name)
+        if axis_name not in (MeshAxisName.DP_SHARD, MeshAxisName.EDP_SHARD):
+            groups.append(group)
+            continue
+        options = dist.ProcessGroupNCCL.Options()
+        options.config.max_ctas = max_ctas
+        options.config.split_share = 0
+        groups.append(
+            dist.split_group(
+                parent_pg=group,
+                split_ranks=[list(range(dist.get_world_size(group)))],
+                pg_options=options,
+                backend="nccl",
+            )
+        )
+    return DeviceMesh.from_group(
+        groups, storage_mesh.device_type,
+        mesh=storage_mesh.mesh, mesh_dim_names=storage_mesh.mesh_dim_names,
+    )
+
 # at optimizer build time, where the parameter storage mesh is live:
+redistribution_mesh = _capped_redistribution_mesh(storage_mesh, max_ctas=8)
 bucket_configs = [
-    BucketConfig(name=name, patterns=non_routed_fqns),
-    BucketConfig(name=f"{name}.routed-experts", patterns=routed_fqns),
+    BucketConfig(name=name, patterns=non_routed_fqns, mesh=redistribution_mesh),
+    BucketConfig(name=f"{name}.routed-experts", patterns=routed_fqns, mesh=redistribution_mesh),
 ]
 
 DistMuon.Config(
     ...
-    redistribution_max_ctas=8,
     bucket_configs=bucket_configs,
 )

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 was following this earlier suggestion to build a cache under distributed folder,

  1. Build the capped mesh in torchtitan/distributed/ (e.g. on ParallelismContext, cached once per run): split the FSDP shard axes (dp_shard, edp_shard) with max_ctas and split_share=0, keep the other axes' groups, and wrap them with the list form DeviceMesh.from_group(groups, device_type, mesh=storage_mesh.mesh, mesh_dim_names=...) so the storage layout is preserved. Keep the fake-backend fallback and the NCCL-only check.

now looks like we should move the construction to k3 folder. let me confirm with you tmr offline.

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.

the instruction is clear, will update accordingly.

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 think the lifecycle inconvenience is that, for _dist_muon_optimizer(), it has no mesh information. mesh information is only available in runtime after model is built and fsdp sharded parameters are available.

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 the run-wide ParallelismContext cache. now buckets using the same storage mesh explicitly during construction. The behavior difference with persistent cache we used earlier is that: if we use pp with vpp=2, the persistent cache will init one communicator, but the current approach will construct two.

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.

@weifengpy can you have another check?

@shuhuayu
shuhuayu force-pushed the distmuon branch 3 times, most recently from 86739fd to da9a1f9 Compare October 23, 2026 23:45
@shuhuayu
shuhuayu force-pushed the distmuon branch 2 times, most recently from ddea7db to 6b614e4 Compare October 24, 2026 00:13
Comment on lines +60 to +67
def build_optimizer(
self,
*,
params: Iterable[dict[str, Any]] | Iterable[Tensor],
parallelism_context: ParallelismContext | None,
) -> Optimizer:
"""Build with the runtime context required by this optimizer."""
return self.build(params=params)

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.

don't need this function, can just use constructor

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.

this is a dispatcher in that other optimizers will not use parallelism_context while distmuon requires parallelism_context. i also think this is ugly and did not think out a better way. Or all other optimizers accept parallelism_context but ignore it.

adjust_lr_fn: Literal[
"original", "match_rms_adamw", "spectral_unclamped"
] | None = None
redistribution_max_ctas: int = -1 # Cap NCCL CTAs to save memory; <0 disables.

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

Suggested change
redistribution_max_ctas: int = -1 # Cap NCCL CTAs to save memory; <0 disables.
max_nccl_ctas_for_comms: int = -1 # Cap NCCL CTAs to save memory; <0 disables.

also, how would it work with non-cuda accelerators?

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.

this is a config specific to nccl.

] | None = None
redistribution_max_ctas: int = -1 # Cap NCCL CTAs to save memory; <0 disables.

def build_optimizer(

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.

same

)
return mesh

def build_redistribution_mesh(

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.

seems ad hoc, need to discuss

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.

this is building a new device mesh and process groups for the the redistribution of distmuon, so it is needed for the current approach.

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.

  1. this method doesn't use self -- so it should be a standalone function
  2. The function name didn't mention FSDP at all, but the content assume FSDP, so maybe rename to build_alternative_fsdp_mesh()?
  3. maybe should be put under fsdp.py? as it has nothing to do with ParallelismContext

I'll trigger claude for feedback.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude I don't feel comfortable overfitting to a special NCCL CTA customization, which is certainly not friendly to other hardwares. Can we do better?

@claude

claude Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 55s —— View job


Making DistMuon communicator isolation backend-agnostic

  • Read the PR diff
  • Work out a backend-agnostic alternative
  • Post recommendation

I didn't push any code. Two reviewers have pulled this PR in different directions, so the three of you should agree on a direction before it gets rewritten again.

Short answer: yes. Only one piece of this PR is NCCL-specific, and it's the piece that's currently in core.

Piece Backend-agnostic? Recommendation
BucketConfig.mesh plus the validation in _bind_bucket_configs (_optimizer_reshard_schedule.py:90-108) Yes. It's a plain DeviceMesh contract, same idea as FSDP2's mesh Keep. It's what @weifengpy asked for, and it would fit well as its own small PR
DistMuon.Config.redistribution_max_ctas (optimizer.py:224) No Remove
ParallelismContext.build_redistribution_mesh (parallelism_context.py:494-560): ProcessGroupNCCL.Options, split_share, the backend != NCCL raise, the hard-coded DP_SHARD/EDP_SHARD No, and ad hoc Remove
BaseOptimizer.Config.build_optimizer, plus passing parallelism_context through OptimizersContainer and torchft It only exists to feed the NCCL path Remove, then use the plain config.build(params=...)

The problem underneath

What we need, without naming any backend, is: "optimizer redistribution runs on its own communicator, not FSDP's." The CTA cap is only how we'd tune that communicator on NCCL. Today the tuning is the API, and the isolation is a side effect of it.

Proposed shape

  1. FlexShard: BucketConfig.mesh as it is in this PR. No change.
  2. ParallelismContext: build an optional dedicated optimizer-comm view of the storage meshes once, when the meshes are built, next to full_dense_mesh_for_fsdp and the sparse mesh. Use the backend_override path unflatten_mesh already uses (parallelism_context.py:290-300), which also accepts per-axis (backend, Options) in upstream DeviceMesh.
    • It's PyTorch-native and contains no if nccl: branches in our code.
    • The backend options come from config as an opaque per-backend override, or the default options if none are given. So on non-CUDA accelerators you still get isolation without any NCCL knob. The fake backend works the same way backend_override already handles it.
    • It's created once per run, which fixes a problem in the current version (below).
  3. Optimizer config: a backend-neutral switch such as isolate_redistribution_comm: bool = False. The TorchTitan DistMuon wrapper then looks up the matching mesh with parallelism_context.get_mesh(...) by storage layout. There's no more fnmatch re-matching to find a parameter's mesh (optimizer.py:262-275).
  4. K3 recipe: turns isolation on and puts the NCCL tuning (max_ctas=8) in its own parallelism/backend config. That keeps the NCCL-specific number at the recipe level, where it's a hardware-specific tuning choice, and out of optimizer.py.

This also answers @shuhuayu's timing concern: the optimizer config is built before any meshes exist, but ParallelismContext already knows the storage layouts before the model is built.

A problem with the current version worth fixing anyway

DistMuon.__init__ builds its redistribution meshes per optimizer instance (optimizer.py:259, the per-instance dict). OptimizersContainer creates one instance per model part, so PP with VPP=2 creates two child communicators per FSDP axis. That's the extra roughly 2 GB per process group @weifengpy warned about (the same mistake as reshard_after_forward=int). @shuhuayu's last comment notes this. Building them once in ParallelismContext at mesh-init time removes it.

Another option to consider

The memory issue comes from all-to-all opening a connection to every peer. NCCL charges for that per peer per channel, and other backends have their own costs. Redistribution could instead use all-gather or reduce-scatter (ring patterns, no all-peer connection state), at the cost of moving more data. A rough bucketed comparison of throughput versus memory on K3 would show whether the communicator setting is worth exposing at all. Without that data, I'd go with the proposal above.

Suggested next step: land BucketConfig.mesh as its own PR now, then decide between items 2–4 above and the alternative. If you'd like me to implement this, tag me with the direction you've agreed on.

@shuhuayu
shuhuayu force-pushed the distmuon branch 2 times, most recently from de73cbb to 9ddd4d3 Compare October 27, 2026 21:55
@shuhuayu
shuhuayu requested a review from tianyu-l October 27, 2026 22:18
weight_decay=0.1,
adjust_lr_fn="match_rms_adamw",
ns_device="accelerator",
max_nccl_ctas_for_comms=8,

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.

add a comment on "why 8"

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.

sure, added.

)
return mesh

def build_redistribution_mesh(

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.

  1. this method doesn't use self -- so it should be a standalone function
  2. The function name didn't mention FSDP at all, but the content assume FSDP, so maybe rename to build_alternative_fsdp_mesh()?
  3. maybe should be put under fsdp.py? as it has nothing to do with ParallelismContext

I'll trigger claude for feedback.

Newton-Schulz there and copies the result back. Momentum, parameters,
gradients and the exchange between ranks stay where they are, so this only
changes anything when the parameters live on the host."""
max_nccl_ctas_for_comms: int = -1 # Cap NCCL CTAs to save memory; <0 disables.

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.

For non-NCCL, is it no-op in general? is it only no-op when set to -1?

Add more detailed comments on how it saves memory.

Add TODO so that people know that this is only a temporary solution.

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.

For non-NCCL, is it no-op in general? is it only no-op when set to -1?

If set to be a positive integer and not nccl, it will raise errors.

Add more detailed comments on how it saves memory. Add TODO so that people know that this is only a temporary solution.

sure, added.

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.

renamed to build_alternative_fsdp_mesh and moved to distributed/utils.py. As claude suggested, this is not applying fsdp but creating a fsdp related mesh, so putting it into utils.py makes better sense.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review my latest comments, especially on the naming + function location one

@claude

claude Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 56s —— View job


Review of @tianyu-l's latest comments

  • Read the PR diff
  • Naming and location of build_redistribution_mesh
  • max_nccl_ctas_for_comms on non-NCCL backends, comments, and TODO
  • "Why 8" in the K3 recipe
  • Post review

Review only, no code pushed.


1. build_redistribution_mesh (parallelism_context.py:494)

(a) Make it a standalone function: agreed, and it helps more than it looks. The method never touches self. It's also the only reason DistMuon needs a ParallelismContext. Once it's a free function, the wrapper calls it on matched_parameter.device_mesh, and all of the following can be reverted:

  • parallelism_context on DistMuon.__init__, Adam.__init__ and AdamW.__init__ (optimizer.py:142,180,235)
  • the new parallelism_context argument on OptimizersContainer and its use in optim.py:125
  • the torchft passthrough (experiments/torchft/optimizer.py)
  • the BaseOptimizer docstring saying custom optimizers must accept parallelism_context

The current version requires every custom BaseOptimizer subclass to accept a new constructor kwarg, which breaks user code. That goes away too, and optimizer_config.build(params=[param_group]) becomes plain again. This resolves your earlier "can just use constructor" comment cleanly.

(b) Name: agreed that it should mention FSDP, but I'd avoid build_alternative_fsdp_mesh.

  • "alternative" doesn't say how it differs.
  • "fsdp mesh" suggests FSDP runs on it, and the whole point is that FSDP doesn't.

What the function actually does is take a storage mesh and swap the dp_shard/edp_shard groups for new split_group children with capped CTAs. I'd use the upstream verb, since "split" also tells the reader it allocates new communicators and costs memory:

def split_fsdp_shard_groups(storage_mesh: DeviceMesh, *, max_nccl_ctas: int) -> DeviceMesh:
    """Return a mesh with the storage layout whose dp_shard/edp_shard groups are
    new NCCL communicators (split_share=0, max_ctas capped); other axes keep
    their original groups."""

build_mesh_with_capped_fsdp_shard_groups would also work if you want something more explicit.

(c) Location: fsdp.py would create an import cycle; I'd use torchtitan/distributed/utils.py. The chain is:

components/optim/optimizer.py → distributed/fsdp.py → models.common.moe (fsdp.py:26) → models/common/moe/moe.py:39 → models/common/aux_loss.py:37 → components.optim → optimizer.py

fsdp.py is also about applying FSDP to modules, which this function doesn't do. distributed/utils.py fits better:

  • it already holds backend-specific communicator helpers (configure_nccl_for_ulysses, set_pg_timeouts)
  • it only imports parallelism_context, so MeshAxisName is still available
  • it keeps the code in torchtitan/distributed/, as CLAUDE.md asks

The two tests that mock parallelism_context.build_redistribution_mesh (test_dist_muon.py:75, test_optimizer_param_groups.py:586-625) would switch to patching the function.

2. max_nccl_ctas_for_comms (optimizer.py:228)

Is it a no-op on non-NCCL backends? Only when it's disabled. Current behavior:

value NCCL fake other backends (gloo, xccl, …)
<= 0 no-op no-op no-op
> 0 split + cap warns, falls back to the storage group ValueError (parallelism_context.py:529)

Raising is the right call; a silent no-op on XPU would hide a missing memory cap. It should be documented on the field, though.

Smaller issues:

  • The inline comment says <0 disables, but the check is > 0 (optimizer.py:239), so 0 also disables. Either write <=0 disables, or reject 0 in __post_init__.
  • If no matched parameter has a dp_shard/edp_shard axis, replaced_group stays False and the knob does nothing without telling anyone. CLAUDE.md asks for a warning when config is skipped like this.
  • for_comms reads as "all comms", but only DistMuon redistribution is capped and FSDP is untouched. The docstring should say so.

Suggested replacement for the inline comment:

        max_nccl_ctas_for_comms: int = -1
        """Cap NCCL CTAs (channels) for DistMuon redistribution only; ``<= 0`` disables.

        Redistribution is an all-to-all, so NCCL keeps connection buffers for every
        peer on every channel: memory ~ num_peers * num_channels * per-pair size.
        A positive value runs redistribution on new child communicators of the
        ``dp_shard``/``edp_shard`` groups (``split_share=0``) with ``max_ctas``
        set, which reduces the channels and that buffer memory. FSDP collectives
        stay on the original communicators. Each child communicator adds fixed
        workspace memory and fewer channels may lower all-to-all bandwidth.
        Requires NCCL: raises ``ValueError`` on other backends and is ignored
        (with a warning) under the fake backend.

        TODO: Temporary workaround for all-to-all connection memory. Remove once
        redistribution uses a pull-based (symmetric memory) kernel that does not
        need all-peer NCCL connections.
        """

The TODO matches @weifengpy's and @fegin's long-term plan.

3. "Why 8" (kimi_k3.py:329)

The PR description already has the reasoning, so it can go in the recipe:

                # All-to-all over a 64-rank FSDP group keeps ~12 MiB per
                # peer/channel; capping 32 channels to 8 cuts this from ~23.6 GiB
                # to ~5.9 GiB per rank. 8 is the largest cap that fits K3 memory;
                # revisit if redistribution becomes bandwidth-bound.
                max_nccl_ctas_for_comms=8,

@shuhuayu: please check the "largest cap that fits" part. If 8 was a reasonable first guess rather than the result of a sweep, the comment should say that instead.

Summary

  • Move it, rename it, and drop the plumbing: a free function split_fsdp_shard_groups(...) in distributed/utils.py, not fsdp.py, because of the import cycle. Then revert all the parallelism_context changes across optimizers, the container and torchft.
  • Document the non-NCCL behavior, the memory mechanism and the TODO on the field. Fix <0 vs <=0, and warn when the cap ends up applying to nothing.
  • Explain why 8 in the K3 recipe.

@shuhuayu
shuhuayu requested a review from tianyu-l October 28, 2026 23:46
tianyu-l added a commit that referenced this pull request Oct 29, 2026
… route PRs to area experts (#5667)

## Why

PR volume has outgrown review capacity. Of the 1,429 PRs merged since
April, one maintainer approved 1,066 (75%), and October alone had 351
merged PRs. Many PRs are agent-generated, and the agents (and `@claude`)
follow `.claude/CLAUDE.md`, which in several places contradicts how PRs
are actually reviewed:

- Principle 5 says to flag BC breakage. The maintainers deliberately
don't promise BC.
- config.md says "emit a warning" when config is silently skipped.
Review comments almost always say "just error out".
- PR expectations say "new features need CPU unit tests at minimum". In
~1,000 reviews the maintainer almost never asked for a new unit test,
and often asked for tests to be removed or folded into existing ones.

The result: across 130 PRs, the current `@claude` cited CLAUDE.md at
least 38 times, mostly to escalate. That produced 16+ BC concerns, 9+
"add a warning" suggestions and 23+ test requests. It also missed the
most common real review question: should this change exist in this form
at all?

This PR rewrites the rules from what reviewers actually say. The source
data:
- 3,391 inline comments, 289 review bodies and 383 PR comments from
Jul-Oct 2026.
- 48 refactor PRs, used to extract structural preferences.
- A comparison of 196 `@claude` runs against the human review on the
same PRs.

It then adds a torchtitan review skill, builds on PyTorch's `pr-review`
skill, and routes PRs to area experts without making them blocking
owners.

**Example: one past PR, as reviewed by the new skill** (#5546, at the
commit that was originally reviewed; blind, with no access to the real
comments):

```
Verdict: Request changes -- The problem is real, but the fix swaps a hard error for a
warn-and-continue fallback to FA2 ... It also adds a head-dim hook to 9 call sites,
7 of which can never fire.
Must fix
1. torchtitan/tools/utils.py:95-104 -- a missing wheel on Hopper/Blackwell now means a
   warning plus a silent switch to a slower kernel with different numerics ...
   Smallest fix (~15 lines): ... raise a clear error that names the module to install.
```
The human review of that PR: "450 LoC PR for a safety check sounds
insane" and "can we error out -- we don't want people to implicitly get
bad perf".

## What changed

**1. Rules** (`.claude/CLAUDE.md`, `.claude/rules/`):
- Core principles rewritten:
  - start from the problem, not the patch;
  - minimal by default;
  - PyTorch-native and upstream first;
  - reuse, but don't bend shared code for one consumer;
  - keep core oblivious to features;
- no BC promises, but protect numerics, HF loading, metric keys and
main-path perf;
  - raise instead of warn;
  - hardware-agnostic.
- Naming additions: overloaded terms, one name per concept, `_private`.
- PR expectations: descriptions must convince a human; tests must earn
their cost; one concern per PR.
- `config.md` rewritten:
  - each component owns its `X.Config`;
  - select implementations by config type;
  - `X.Config | None` instead of `enable_*`;
  - no post-hoc config mutation;
  - few knobs;
  - validate in `__post_init__`.
- `distributed.md`: spmd_types first, parallelism combinations, hidden
D2H syncs, hardware.
- New rules files:
  - `design.md`: structural rules distilled from past refactors.
- `tests.md`: when to add tests, preferring extensions of existing
coverage, placement, golden files.
- `direction.md`: current migrations. This needs maintainers to keep it
current.

**2. `pr-review` skill** (`.claude/skills/pr-review/`):

| Step | What it does |
| --- | --- |
| Context | Applicable rules, maintainer comments addressed or not,
earlier bot findings, overlapping open PRs. |
| Necessity/design gate | Is the problem real on main? Root cause vs
symptom? Right layer, or upstream? Should torchtitan own this?
Superseded? Smallest alternative? Value evidence? |
| Deep review | A quick sweep of every hunk (scope, placement, new knobs
and tests), then the checklist, split by lens for large PRs. |
| Consolidate and fact-check | Dedupe by root cause and fix; drop BC,
"add a warning", generic "add tests", lint and praise; verify must-fix
items. |
| Output | Verdict first, plain-words summary, a concrete before/after
example, at most a few must-fix items, details collapsed, unverified
claims labeled. |
| Modes | Full review, "review again" (only the delta), "review my
review", or answer a specific question first. |
| Posting | Line-anchored findings as inline comments (with `suggestion`
blocks for small fixes, at most ~10, posted only by the main agent after
fact-check), then one formal review via `gh pr review` (`--approve` /
`--request-changes` / `--comment`) with the verdict and one-line
pointers. |

**3. PR descriptions:**
- `pr-description` skill and `.github/pull_request_template.md`: Why
(with a simple example) -> What changed -> user-facing before/after ->
numerics -> testing.
- CONTRIBUTING.md updated to match.

**4. `@claude` workflow** (`claude-code.yml`):
- Always uses the skill.
- Allows read-only `gh issue view` / `gh pr view` / `gh pr diff` / `gh
pr list`, plus `gh pr review` and the action's inline-comment tool (it
cannot approve). `gh api` stays blocked.
- `effort=low|max` and `fable` comment keywords; default effort `high`.
- 55-minute timeout.

**5. Review routing:**
- `CODEOWNERS`:
- `*`: `tianyu-l` `fegin` `wwwjn` `shuhuayu` `acisseJZhong`
`felipemello1`.
- graph_trainer paths: core plus `SherlockNoMad` `aditvenk`
`sanketpurandare`.
  - torchft paths: core plus `d4l3k`.
- Every path has an owner, so a bot approval can never satisfy branch
protection on its own.
- `.github/area_reviewers.yml` and `workflows/area_reviewers.yml`
request at most 3 area experts as non-blocking reviewers, based on which
areas the changed files touch. The workflow runs on
`pull_request_target`, reads only the file list through the API, and
never checks out PR code.

## Alternatives considered

- **Copy PyTorch's skill as-is.** Its "missing tests -> Request Changes"
and BC section are exactly what produced noise here.
- **PyTorch-style per-directory `REVIEW.md` files.** The existing
glob-scoped `.claude/rules/` already do this, without more `.md` sprawl.
- **Deterministic lint hooks** for `torch.cuda.*`, `isinstance(..,
DTensor)` and `enable_*` fields. Every pattern already has hits on main
(12, 15 and 7 files), so they would need allowlists. The skill checks
them on the diff instead.
- **Making area experts code owners.** That makes them blocking;
auto-requesting reviews routes PRs without adding gates.

## Testing

**Backtest.** The new skill reviewed 7 past PRs blind, each at the
commit that was originally reviewed, and the output was compared with
the real human review. The skill was then fixed for the misses, and the
affected cases were re-run.

| PR | Human review's main point | New skill |
| --- | --- | --- |
| #5546 | too big for a safety check; error out | Hit both |
| #5153 | does this happen on main? don't violate the `nn.Module`
contract | Hit; proposed the fix that eventually landed |
| #4754 | workaround, not a fix; move the test | Hit the root cause (the
same fix the author later proposed); missed the test move, now covered
by the sweep |
| #5463 | motivation first; `LocalCompileConfig` design | Hit the design
and unused kwargs; motivation is a must-fix after the re-run |
| #5183 | NCCL-specific knob in core; TODO; `<0` semantics | Hit |
| #4474 | approve; DSv4 should fix the model/loss | Approve; partly
raised the model point |
| #4421 | approve; "how much e2e?" | Originally requested changes;
approves with items after the re-run |

None of the 10 reviews raised BC or asked for a warning.

**Other checks:**
- **Reviewer routing:** the area-reviewer logic was replayed on 1,429
merged PRs. Peak load is about 50 requests/month per person (graph
trainer, PP, MoE).
- **Workflow script:** dry-run with mocked GitHub objects on a real PR's
file list. The author is excluded, existing reviewers are skipped, and a
non-collaborator failure doesn't fail the run.
- **YAML and lint:** all YAML parses, the inline JS passes `node
--check`, and `pre-commit` passes.

## Known issues / follow-ups

- Comment-triggered workflows run from `main`, so `claude-code.yml` and
the skill only take effect after merge. Try `@claude review` on a real
PR right after.
- Not verified: whether the Claude GitHub App has write access. If it
does, its approvals count toward the 1 required approval (but never as a
code-owner approval), and its REQUEST_CHANGES blocks merging until it
re-approves or someone dismisses it. If it doesn't, its reviews are
advisory. The first real review will show which.
- `direction.md` and `area_reviewers.yml` are only useful if they are
kept current.
- Not included:
- PyTorch's time-budget hook (reviews that hit the 55-minute limit are
lost);
- auto-review on every push, which needs the PyTorch CI owners' hardened
setup.
Add an opt-in NCCL CTA cap backed by an independent child process group, cache child groups across optimizer instances, and retain the resolver across optimizer state reloads. Configure Kimi K3 DistMuon redistribution for eight CTAs without changing the FSDP parent communicator.
@shuhuayu
shuhuayu merged commit 09c98e5 into pytorch:main Oct 29, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests 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.

4 participants