Repository navigation
[distmuon] Isolate redistribution NCCL communicators - #5183
Conversation
| config: Config, | ||
| *, | ||
| params: Iterable[dict[str, Any]] | Iterable[Tensor], | ||
| process_group_cache: _DistMuonProcessGroupCache | None = None, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.meshAPI, 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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
There was a problem hiding this comment.
this is only for distmuon pg with a separate communicator. OK, let's be more future sighted and use separate device mesh contract.
01e8d71 to
41e27f2
Compare
d1f579a to
16d63cc
Compare
| lr=muon_lr, | ||
| weight_decay=0.1, | ||
| adjust_lr_fn="match_rms_adamw", | ||
| redistribution_max_ctas=8, |
There was a problem hiding this comment.
@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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
- 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.
- 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.
- 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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
no problem. let's do the separate device mesh.
weifengpy
left a comment
There was a problem hiding this comment.
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
f8c3e36 to
81f0de0
Compare
|
@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( |
There was a problem hiding this comment.
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,
)
There was a problem hiding this comment.
i was following this earlier suggestion to build a cache under distributed folder,
- Build the capped mesh in
torchtitan/distributed/(e.g. onParallelismContext, cached once per run): split the FSDP shard axes (dp_shard,edp_shard) withmax_ctasandsplit_share=0, keep the other axes' groups, and wrap them with the list formDeviceMesh.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.
There was a problem hiding this comment.
the instruction is clear, will update accordingly.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
86739fd to
da9a1f9
Compare
ddea7db to
6b614e4
Compare
| 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) |
There was a problem hiding this comment.
don't need this function, can just use constructor
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
maybe
| 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?
There was a problem hiding this comment.
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( |
| ) | ||
| return mesh | ||
|
|
||
| def build_redistribution_mesh( |
There was a problem hiding this comment.
seems ad hoc, need to discuss
There was a problem hiding this comment.
this is building a new device mesh and process groups for the the redistribution of distmuon, so it is needed for the current approach.
There was a problem hiding this comment.
- this method doesn't use
self-- so it should be a standalone function - The function name didn't mention FSDP at all, but the content assume FSDP, so maybe rename to
build_alternative_fsdp_mesh()? - maybe should be put under fsdp.py? as it has nothing to do with
ParallelismContext
I'll trigger claude for feedback.
|
@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 finished @tianyu-l's task in 1m 55s —— View job Making DistMuon communicator isolation backend-agnostic
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.
The problem underneathWhat 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
This also answers @shuhuayu's timing concern: the optimizer config is built before any meshes exist, but A problem with the current version worth fixing anyway
Another option to considerThe 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 |
de73cbb to
9ddd4d3
Compare
| weight_decay=0.1, | ||
| adjust_lr_fn="match_rms_adamw", | ||
| ns_device="accelerator", | ||
| max_nccl_ctas_for_comms=8, |
| ) | ||
| return mesh | ||
|
|
||
| def build_redistribution_mesh( |
There was a problem hiding this comment.
- this method doesn't use
self-- so it should be a standalone function - The function name didn't mention FSDP at all, but the content assume FSDP, so maybe rename to
build_alternative_fsdp_mesh()? - 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
@claude review my latest comments, especially on the naming + function location one |
|
Claude finished @tianyu-l's task in 1m 56s —— View job Review of @tianyu-l's latest comments
Review only, no code pushed. 1.
|
| 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), so0also disables. Either write<=0 disables, or reject0in__post_init__. - If no matched parameter has a
dp_shard/edp_shardaxis,replaced_groupstaysFalseand the knob does nothing without telling anyone. CLAUDE.md asks for a warning when config is skipped like this. for_commsreads 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(...)indistributed/utils.py, notfsdp.py, because of the import cycle. Then revert all theparallelism_contextchanges across optimizers, the container and torchft. - Document the non-NCCL behavior, the memory mechanism and the TODO on the field. Fix
<0vs<=0, and warn when the cap ends up applying to nothing. - Explain why 8 in the K3 recipe.
… 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.
Summary
BucketConfig, validated against the inferred storage-mesh axis, ranks, and rank orderDeviceMeshwithin each DistMuon instance, replacing onlydp_shardandedp_shardgroups with resource-independent NCCL childrenbuild_alternative_fsdp_meshintorchtitan/distributed/utils.py, keeping the existingConfig.build(params=...)API without extra optimizer context plumbingWhy
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
DeviceMeshcontract 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 supportsmax_ctasnow 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 standalonebuild_alternative_fsdp_meshutility on matched parameters' storage meshes. Adam, AdamW, and custom optimizer constructors remain unchanged; no newparallelism_contextforwarding 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
DeviceMeshand 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 withsplit_share=0, preserves every other storage-mesh axis group, and reconstructs the original storage layout withDeviceMesh.from_group. The defaultmax_nccl_ctas_for_commsvalue is-1; all values<= 0leave 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
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 reloadpre-commit run --all-files: all non-type hooks passed; the full Pyrefly hook was skipped in favor of focused checkstorch.distributed.pipelining.analyze_pipeline_activation_livenessThe change does not alter optimizer arithmetic or collective payloads.