Repository navigation
Conversation
7a0a2c2 to
4d1206a
Compare
22542f5 to
792b82a
Compare
| return ComputeLayout( | ||
| shardings_by_mesh_axis={ | ||
| MeshAxisName.DP_SHARD.value: Shard(0), | ||
| MeshAxisName.TP.value: Shard(0), |
There was a problem hiding this comment.
this line is magically working, but maybe worth change 2 things
following ep coding convention (set MeshAxisName.EP.value only when ep > 2)
- when tp > 2, set MeshAxisName.TP.value: Shard(0)
- else, don't set
- this magically works now because DistMuon silently ignores MeshAxisName.TP when tp == 1
add code comment that TP applies to routed experts for EP1, but never does it for EP2+. That explains why ep > 2 never have MeshAxisName.TP
There was a problem hiding this comment.
add code comment that TP applies to routed experts for EP1, but never does it for EP2+. That explains why ep > 2 never have MeshAxisName.TP
yeah, that's what i was thinking, make sense to add some comments for that.
There was a problem hiding this comment.
Updated. For EP=1, the layout now always declares dp_shard: Shard(0) and adds tp: Shard(0) only when tensor_parallel_degree > 1. For EP>1 it continues to use only the (efsdp, ep) sparse mesh. I also added the comment explaining that routed experts use TP only when EP is disabled. I interpreted the degree threshold as > 1, since TP=2 is active.
| block_size=(attention.qk_nope_head_dim + attention.qk_rope_head_dim), | ||
| ) | ||
| ), | ||
| MeshAxisName.TP.value: BlockShard( |
There was a problem hiding this comment.
this is redistributing to compute sharding left-to-right, but storage sharding is right-to-left
I was chatting with astra on this and seems adding shard_order_by_tensor_dim={0: ("tp", "dp_shard")} would be more efficient, i.e. doing compute sharding right-to-left, aligning with storage sharding right-to-left
Yes—for this head layout, matching TP-first storage with TP-first compute is the better default.
TP should retain its heads, and DP should divide the heads within each TP slice.
On a (dp_shard, tp) mesh, that storage order is represented by:
(_StridedShard(0, split_factor=tp_size), Shard(0))
I’d keep both BlockShard declarations and add support for:
shard_order_by_tensor_dim={0: ("tp", "dp_shard")}
The planner should then:
1. Compute head ownership sequentially: split heads over TP, then split each TP-local head range
over DP. Convert those head ranges into row ranges.
2. Compare actual storage and compute ownership: use only DP redistribution when TP ownership
matches; skip redistribution entirely when DP boundaries already align with heads.
I checked the routes for DP=2, TP=2, two rows per head:
Heads Current flattened plan: rows transferred TP-first plan: rows transferred
━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
6 7 2
─────── ────────────────────────────────────────── ─────────────────────────────────
8 8 0
These counts cover one storage-to-compute pass. TP-first requires no transfers across TP
coordinates in either case. For six heads, its per-rank head counts become [2,2,1,1], replacing
[2,2,2,0].
This requires both ordered BlockShard ownership and transport selection based on that ownership.
Merely adding the configuration field would not fix it.
| MeshAxisName.TP.value: BlockShard( | ||
| dim=0, | ||
| block_size=attention.qk_nope_head_dim + attention.v_head_dim, | ||
| ), |
There was a problem hiding this comment.
same to above, compute sharding order should be right-to-left to minimize data movement
| scales_H: torch.Tensor, | ||
| weight: DTensor, | ||
| *, | ||
| num_heads: int, |
There was a problem hiding this comment.
TP shards attention first, then DP shards. it's guranteed TP Shard(0) won't overshard heads (decoder.py:181 requires num_heads % tp_size == 0), only DP overshard
astra suggested following simplification. note 3rd point needs to be consolidated with my comment in config_registry.py
With TP assigning an equal number of complete heads, I’d simplify these parts:
1. Remove extra metadata handling in torchtitan/torchtitan/models/kimi_k2_7/qk_clip.py:50. Drop
the helper’s num_heads argument, rank-dependent Shard.local_shard_size_and_offset(...), and
explicit shape/stride. DTensor.from_local can infer the global shape because scales are
evenly sharded across TP and replicated across DP.
2. Build row scales locally in torchtitan/torchtitan/models/kimi_k2_7/qk_clip.py:134. Use
ordinary tensor operations to expand each local head’s scale into its rows, flatten, then
wrap once as a DTensor. This removes the distributed view/pow/expand/cat/reshape sequence.
Keep one check that the inferred global row count matches the weight.
Flat weight multiplication and _StridedShard support remain necessary because FSDP can still
split heads. The placement validation can also be consolidated.
3. Preserve TP ownership for per-head Muon in torchtitan/torchtitan/distributed/flex_shard/
dist_muon.py:763. Redistribute complete heads only within each TP rank’s DP group. This is a
separate behavior improvement: simply deleting TP’s BlockShard declaration currently fails
validation, so the resolver must support preserving that head-aligned TP partition.
The broader multi-axis redistribution machinery still serves whole-matrix Owned and expert
layouts; the attention-head invariant doesn’t eliminate those changes.
There was a problem hiding this comment.
make sense. since num_heads % tp_size == 0, one always has evenly sharded heads on dim 0. 1) each tp rank has complete head metadata and fsdp ranks have replicated metadata for its tp sharded heads. 2) as suggested, the sequence is now removed now. 3) per-head structure is preserved in tp axis and comms is only needed over dp axis when head is oversharded.
792b82a to
2cc7649
Compare
91305e5 to
c440632
Compare
8467c96 to
68bdf75
Compare
56407ce to
e5755ec
Compare
6b614e4 to
eb4820f
Compare
Generalize optimizer redistribution across multiple DeviceMesh axes so DistMuon can form whole matrices and matrix batches from combined DP and TP storage shards. Enable the Kimi DistMuon recipe with TP and cover whole, per-head, and expert layouts.
|
this pr is incorporated into #5678 as a new pr to support tp and cp, validated for kimi 3 runs, so closing this one. |
oops, i made a mistake here. the condition tp suggestion was already incorporated in this pr, but when i use agents to refactor this pr for max_ctas in the new pr, it was dropped and i did not catch that. |
Part **5/n** of the Kimi K3 / Dist-MoE training stack. Based on `main`. Replaces #4353. ## Summary human notes: add tp support for distmuon. ## Why DistMuon cannot be used with tensor parallelism on `main`. Muon must orthogonalize complete matrices, but with TP+FSDP a matrix is split across two mesh axes, and the FlexShard planner only supports transport along one axis with every other axis replicated. The Kimi recipes therefore reject `tensor_parallel_degree > 1` when DistMuon is configured (`TODO(#3353)`). **Example.** ```text storage mesh: (dp_shard=2, tp=2); one matrix stored as (Shard(0), Shard(1)) rank (dp, tp) holds the [rows of dp] x [cols of tp] fragment compute: {"dp_shard": Owned(), "tp": Owned()} # one rank updates the whole matrix main: NotImplementedError: multi-axis transport is not implemented this PR: the 4 ranks form one "dp_shard_tp" transport group; the owner receives the complete matrix, runs Newton-Schulz once, and every rank gets its original (Shard(0), Shard(1)) fragment back ``` The same applies to MLA head blocks stored as `(_StridedShard(0), Shard(0))` (TP and FSDP sharding the same dim) and to experts stored as `(Shard(0), Shard(1))`. CP already works with DistMuon on `main` (`dp_shard_cp` is one flattened axis); with this PR it also composes with TP (`dp_shard_cp` + `tp`). ## What changed **FlexShard planner** (`flex_shard/dist_muon.py`, `_optimizer_reshard_schedule.py`) -- the core of the PR: - A transition may span several storage mesh axes; `redistribution_storage_mesh_axis` becomes `redistribution_storage_mesh_axes`. - Storage is described as per-dimension index runs, so `_StridedShard`, uneven, and empty shards map to logical regions exactly; each rank's storage must be one contiguous region (true for TP + FSDP layouts), otherwise planning raises. `_StridedShard` storage whose dimension is not divisible by its split factor also raises: FSDP2 lays out that uneven case differently from DTensor's split-then-shard rule (TODO in the code). Non-transport axes keep their storage placement. - `Owned` compute requires every non-owned axis to be replicated; changing an axis outside the transport group raises `ValueError`. **Explicit transport meshes.** FlexShard never creates process groups. `BucketConfig.mesh` is removed: `DistMuon(..., transport_meshes=...)` takes a pool of caller-owned 1D meshes, and each bucket uses the pool mesh whose ranks equal the storage ranks of its transport axes (names are not used). Without a match, a single-axis transport reuses its storage group and a combined transport raises. - `ParallelismContext.build_optimizer_meshes(axes_list, backend=..., pg_options=...)` builds the pool. For each axes tuple it creates one group per slice of those axes over the whole world and returns this rank's 1D meshes, named by the joined axes (`dp_shard_tp`). Axes that cover the same ranks share one group and one mesh: with dp_shard=2, tp=2, ep=2, each rank's `edp_shard` slice equals its `dp_shard` slice, and two pool meshes with the same ranks would make the bucket's mesh ambiguous. Every rank creates every slice, so ranks on different PP stages (including an expert-free stage) create the same groups in the same order without an extra collective. The meshes are not registered on the root mesh, so DTensor never uses them. This replaces `build_alternative_fsdp_mesh`. - The TorchTitan `DistMuon` wrapper (`components/optim/optimizer.py`) requests `(dp_shard[, cp], tp)` when TP > 1. With `max_nccl_ctas_for_comms` it also requests `dp_shard[, cp]` and, with EP, `edp_shard`, all as NCCL communicators with that CTA cap (FSDP groups unchanged). `Optim` passes `parallelism_context` through `OptimizersContainer` to every optimizer build for this. **Compute buffer reuse** (`_optimizer_reshard_runtime.py`, `_optimizer_reshard_schedule.py`): the compute exchange buffer is reused in place for returned fragments, which is only safe when both directions pack each parameter identically. A replicated holder (e.g. a TP-replicated `Owned` matrix) gets its update back on every holder, so returned fragments could overwrite later parameters' unread input. The bucket plan records `compute_to_storage_offset`: `0` when the layouts match, otherwise returned fragments go after the received ones. This duplicates #5695, where the same bug reproduces on `main` with plain `Replicate` storage on a 1D mesh. #5695 lands first; this PR then rebases and keeps only its TP test. | | #5695 | this PR | | --- | --- | --- | | Plan field | `compute_to_storage_input_offset` | `compute_to_storage_offset` | | Offset rule | `0` if the compute -> storage input spans equal the storage -> compute output spans, else the received buffer size | same | | Runtime | buffer sized `offset + input_buffer_numel` (2 sites); returned fragments and the outgoing all-to-all use `buffer[offset:]` | same | | Test | 1D `dp_shard`, `Replicate` storage between `Shard(1)` params; shared bucket vs per-parameter buckets | DP x TP, TP-replicated `Owned` before TP-sharded params; vs unsharded `torch.optim.Muon` | **Kimi** (`models/kimi_k2_7/qk_clip.py`, recipes, README): - QK-Clip derives its per-head scale placements from the MAX all-reduce group (the `loss` mesh) instead of axis names: scales are `Replicate` on mesh axes inside that group and keep the weight's `Shard(0)` on axes that split heads (TP); anything else raises. - Recipe compute layouts declare the `tp` axis only when `tensor_parallel_degree > 1`; the TP guard is removed, so TP=1 layouts are unchanged. TP with DistMuon is verified on K3. - The recipes' `__post_init__` re-derives the dense layouts' `tp` axis (and, as before, the routed-expert layouts) from the final parallelism config, so a config that sets TP after building the recipe, like the b200 cell, still gets TP layouts. **Integration coverage:** the b200 `kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4` cell (FSDP 2, TP 2, EP 2, interleaved PP 2 x 4 stages, 8 GPUs, no golden file) now keeps the recipe's DistMuon with its CTA cap instead of AdamW, so CI runs the TP layouts, QK-Clip on TP-local heads, and transport group creation across stages on real NCCL. **Mechanical / skimmable:** FlexShard and Kimi README updates, integration-test comments, DeepSeek V4 guard message (its layouts do not declare `tp`), deletion of `build_alternative_fsdp_mesh` and its mocked tests, `parallelism_context` plumbing through `Optim`, `OptimizersContainer` and `TorchFTOptimizersContainer` and its test updates. ## Alternatives considered - Run Newton-Schulz on TP fragments independently: changes Muon's math. - Let FlexShard create the groups itself: hides process-group policy (CTA cap, NCCL options) inside the planner; the caller owns process groups instead. - Create groups lazily per bucket, with only their members (`use_local_synchronization=True`), or with `split_group` from the storage group (as `main` did for the CTA cap): every group creation advances a per-rank counter that names later groups, so when PP stages create different groups, later WORLD-wide group creation hangs. - `DeviceMesh._flatten` from a storage mesh: private, needs the storage mesh on every rank (fails for an expert-free stage), and registers the combined mesh on the world root, which changes how DTensor gathers other parameters on those axes. - Create the combined groups in `ParallelismContext.build_mesh` (as first proposed for option (a)): every TP run, AdamW included, would pay for the extra communicators, and `build_mesh` would need the DistMuon-only CTA cap. Instead the DistMuon wrapper calls `build_optimizer_meshes` once at construction, and FlexShard picks each bucket's mesh by ranks, so `BucketConfig.mesh` and the wrapper's bucket matching are no longer needed. - Create only the groups this rank's buckets need (query FlexShard for each bucket's transport axes, all-gather the rank lists across PP stages, create the union): needs a FlexShard query API and an extra collective; creating every slice of a few fixed axis combinations is simpler. - DP-only transport for TP-local head blocks (a dedicated `dp_shard` group, or pinning each head block to its TP shard inside the `(dp_shard, tp)` group): not needed for correctness, and not faster in the microbenchmark below. Head blocks use the same `(dp_shard, tp)` all-to-all as the other dense weights. `all_to_all_single` (bf16, uneven splits) on 4 GB300s, all NVLink, as dp_shard=2 x tp=2. Time per call after warmup, slowest rank. Each rank sends 2x "bytes/peer" in total in every column: - pinned: 4-rank group, the same-TP peer and self get "bytes/peer" each, cross-TP peers get 0 - spread: 4-rank group, the same total split evenly over all 4 ranks (cross-TP allowed) - dp_shard: dedicated 2-rank group, same bytes as pinned | bytes/peer | pinned | spread | dp_shard | | --- | --- | --- | --- | | **default CTAs** | | | | | 64 KiB | 70 us | 90 us | 68 us | | 1 MiB | 74 us | 78 us | 70 us | | 8 MiB | 72 us | 76 us | 67 us | | 32 MiB | 212 us | 124 us | 123 us | | 128 MiB | 758 us | 415 us | 407 us | | **8-CTA cap (`max_nccl_ctas_for_comms`)** | | | | | 64 KiB | 74 us | 80 us | 69 us | | 1 MiB | 70 us | 74 us | 67 us | | 8 MiB | 197 us | 104 us | 113 us | | 32 MiB | 746 us | 394 us | 390 us | | 128 MiB | 1536 us | 1406 us | 1157 us | Pinning is up to ~1.9x slower than spreading at 8 MiB/peer and above. Spreading is within ~10% of a dedicated group except at 128 MiB with the cap (1.2x). Single node only; cross-node behavior is unmeasured. ## User-facing changes | Before | After | | --- | --- | | Kimi recipes with DistMuon reject `tensor_parallel_degree > 1` | DP x TP supported (K3 also CP x TP) | | `max_nccl_ctas_for_comms` caps `split_group` children of `dp_shard`/`edp_shard` | caps the actual optimizer transport groups, incl. combined DP/TP | | `BucketConfig.mesh` overrides a bucket's groups with a storage-axis child mesh | removed; FlexShard `DistMuon(transport_meshes=...)` takes a pool of 1D meshes matched by ranks, including combined ones (`dp_shard_tp`); the TorchTitan wrapper builds it with `ParallelismContext.build_optimizer_meshes` | Mesh setup requires every rank to construct the same sequence of DistMuon optimizers (true for torchtitan PP schedules). Memory: a bucket that contains a replicated holder region (e.g. a TP-replicated `Owned` matrix) places returned fragments after the received ones, so its compute exchange buffer grows by the bucket's receive size, up to about 2x. Buckets whose receive and return layouts match are unchanged. ## Numerics Newton-Schulz arithmetic and the Muon update are unchanged; TP=1 layouts take the same paths as before. With TP, every block/matrix is orthogonalized whole, as without TP. | Check | Workers / backend | Result | | --- | --- | --- | | Whole, TP-replicated `Owned`, strided head-block and expert matrices, 2 real Muon steps, DP-only `(4,1)`, TP-only `(1,4)` and DP x TP `(2,2)` each vs. unsharded `torch.optim.Muon` | 4 / NCCL | whole matrices exact; batched head blocks and experts within 2e-2 of the lr-normalized update per step (batched vs per-matrix BF16 GEMMs) | | Same parameters, shared bucket vs one bucket per parameter | 4 / NCCL | exact | **Kimi K3 debug model, 50 steps**, rebased on `main` at `72e556678`, `scripts/loss_compare.py` from a shared seed checkpoint, dp_shard=2 + ep=2, TP=1 (2 GPUs) vs TP=2 + SP (4 GPUs), GB300. TP changes reduction order, so loss is not bitwise; the AdamW run shows the TP noise floor: | Step | DistMuon TP=2 - TP=1 | AdamW TP=2 - TP=1 | | --- | --- | --- | | 2 | +0.001 | -0.002 | | 5 | +0.008 | +0.000 | | 10 | -0.001 | +0.006 | | 25 | +0.009 | -0.009 | | 50 | -0.007 | +0.002 | | max \|diff\| over 50 steps | 0.017 | 0.021 | | mean \|diff\| over 50 steps | 0.006 | 0.006 | ## Testing ```bash CUDA_VISIBLE_DEVICES='' python -m pytest -q \ tests/unit_tests/cpu/distributed/flex_shard \ tests/unit_tests/cpu/distributed/test_distributed_utils.py \ tests/unit_tests/cpu/distributed/test_parallelism_context.py \ tests/unit_tests/cpu/components/optim \ tests/unit_tests/cpu/recipes \ torchtitan/experiments/torchft/tests python -m pytest -q \ tests/unit_tests/gpu/distributed/flex_shard/test_dist_muon.py \ tests/unit_tests/gpu/models/kimi_k2_7/test_qk_clip.py # 4 GPUs ``` CPU: 230 passed, 13 skipped (198 + 32 TorchFT; the skips are all in `test_fused_mla_override.py`, which needs CUDA). GPU: 19 passed on 4x GB300. Run with the attn-gym and torch_checkpointing commits pinned in `requirements.txt`. `pre-commit` passes except Pyrefly, which reports 8 errors, all in files this PR does not change. New tests and the regressions they catch: - GPU `test_dist_muon.py::TestDistMuonMatchesUnshardedMuon`: DP-only, TP-only and DP x TP storage each match unsharded `torch.optim.Muon` (whole matrices exactly; batched head blocks and experts within the 2e-2 tolerance the other DistMuon tests use), for a bucket where a TP-replicated `Owned` matrix sorts before TP-sharded, head-block and expert parameters. The shared bucket must also match per-parameter buckets exactly; the TP-only case fails that check without the buffer-reuse fix. Also checks that FlexShard never creates groups and that a combined transport without a matching transport mesh raises. - GPU `test_dist_muon.py::TestDistMuonTensorParallelCudaGraph`: TP routing stays exact under CUDA-graph replay. - GPU `test_qk_clip.py::QKClipTensorParallelTest`: QK-Clip scales TP-local heads when FSDP's shard splits a head, and raises when the reduction group does not match the weight's placements. - Group creation across PP stages: `TestBuildOptimizerMeshes` (next bullet) checks that every rank creates every stage's groups in the same order, and the b200 `kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4` cell runs DistMuon with the CTA cap under PP, TP and EP on 8 GPUs. - CPU `test_parallelism_context.py::TestBuildOptimizerMeshes`: with PP 2 on a fake PG, a stage-1 rank also creates stage 0's slices, in the same order as every other rank; `dp_shard` and `edp_shard` slices with equal ranks share one group and return one mesh; the meshes are not registered on the root mesh; an axis combination spanning the dense and sparse meshes raises. ## Known issues / follow-ups - Depends on #5695 landing first; this PR then drops its copy of the buffer-reuse fix. - The b200 `kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4` cell needs 8 GPUs, so only a 4-GPU variant (dp_shard=1, TP 2, EP 2, PP 2 x 4 stages) was run here: DistMuon builds for all 4 model parts, then the first forward fails in the attn-gym KDA kernel (`'tuple' object has no attribute 'atom'`), the same failure as the cell config with AdamW on `main` on this machine. The cell is therefore not verified end-to-end locally. - Kimi K3.1 shares the K3 DistMuon recipe, so it can now run DistMuon with TP. DistMuon construction under FSDP 2, TP 2, EP 2 succeeds (243 Muon parameters, including the indexer layouts), but training was not verified: the first forward fails in the attn-gym KDA kernel (`'tuple' object has no attribute 'atom'`), with AdamW on `main` as well. - Kimi `__post_init__` mutates a shared optimizer config under `dataclasses.replace`; pre-existing on main, separate fix. ## Stack | Position | PR | | --- | --- | | 5/n | [#5678 — Support TP storage-to-compute layouts](#5678) | | 7/n | [#5680 — Keep linear-attention graph metadata replayable](#5680) | | 11/n | [#5684 — Enable Kimi K3 SiTU-GLU training and pipeline lifecycle](#5684) | | 13/n | [#5686 — Add block-scoped activation retention](#5686) | | 14/n | [#5793 — Add full-scale Kimi K3 MXFP8 recipes](#5793) | Merged: 1/n (#5674), 4/n (#5677), 6/n (#5679), 8/n (#5681), 9/n (#5682). Closed: 2/n, 3/n, 10/n, 12/n.
Based on
mainat09c98e528after #5183 merged. This PR contains only the two TP/QK-clipping commits.Summary
Shardand_StridedShardstorage for whole-matrix, variable-sized per-head block, and expert Muon computation.edp_shard/epmesh; TP is declared only for the EP-disabled dense expert layout.Motivation
DistMuon previously assumed that optimizer redistribution operated over one storage mesh axis. Kimi's FSDP+TP parameters instead use multi-axis layouts such as
_StridedShard(0)over the data-parallel axis together withShard(0)over TP. This prevented the recipe from using TP even though model forward/backward TP was already available.This change makes optimizer transport operate over the required storage axes while retaining the storage/compute layout contract. With EP enabled, routed experts live on the sparse
(edp_shard, ep)mesh rather than a mesh containing a namedtpaxis, so their layout preserves EP-firstShard(0)ordering without advertising an ignored TP placement. Shared experts and dense attention/MLP parameters still use the dense TP mesh.QK clipping is updated separately so TP-local attention heads are scaled against the same distributed storage layout.
#5183 supplies isolated DP/EDP child communicators through
build_alternative_fsdp_mesh(). Custom NCCL options for a combined DP/TP group are configured on its flattened explicit mesh; flattening does not inherit options from the individual axis groups. The four-GPU regression covers both the isolated DP-only head bucket and an explicitly capped combined group.The rebase also preserves main's newer compute-chunk balancing, source-locality preference, and per-rank region packing. Strided storage mappings and transport-local block-pattern offsets feed that planner rather than restoring the older redistribution builders. The variable-block regression checks complete matrix views and exactly-once coverage without depending on which DP rank the balancer selects.
Testing
Rebased onto
mainat09c98e528on 2026-10-29. Local tests usett12with pinned Python dependencies installed in an isolated validation directory; the shared environment was not changed.param_dtype_override_fnAPI was excluded from thistt12run.7.85023to5.49017. This training run was not repeated for this rebase.main, with no additional type errors.