Repository navigation
[compile] 9/n Compile MLA key/value assembly - #5682
Conversation
|
Reply from claude: Hi @shuhuayu, heads-up: this PR overlaps two of Felipe's drafts.
One bug to know about either way: with How would you like to split this? One option: #5564 and #5343 land these two regions, and this PR rebases on top for whatever Kimi-specific part is left. |
507ccd6 to
4f6690e
Compare
3500d19 to
e34a8d2
Compare
#5674) Part **1/n** of the Kimi K3 / Dist-MoE training stack. Based on `main`: the review diff contains only this feature. human notes: previously: `distributed/utils.py::init_distributed()` passes `CommConfig.init_timeout_seconds` to `torch.distributed.init_process_group()` so the world group has, say, 30 minutes timeout. now, that remains unchanged. Additionally, `TrainingEngine._initialize_distributed_runtime()` calls `set_pg_timeouts()` after `ParallelismContext.from_config()`, so the tracked mesh subgroups get the configured timeout before model/FSDP/optimizer initialization. this also covers the RL trainer. without this pr, independently created NCCL subgroups can still use the default 10-minute timeout even though we configured 30 minutes. the existing switch to `train_timeout_seconds` after the first step is unchanged. ## Why The world process group receives `comm.init_timeout_seconds`, but mesh subgroups created later do not inherit it. They can retain the backend-default startup timeout through model initialization and the first update. Example: with `CommConfig(init_timeout_seconds=1800)`, the world group uses 1,800 seconds but a later NCCL subgroup can use its 600-second default. This change applies the configured startup budget to the groups tracked by `ParallelismContext` before model/FSDP/optimizer initialization. ## What changed - Call the existing `set_pg_timeouts()` helper immediately after `ParallelismContext.from_config()` in the shared training engine. - Apply the same call in the TorchFT runtime override. - Preserve the unconditional post-first-step switch to `train_timeout_seconds`, including fake backends. - Add no helper, configuration field, or test. The deleted forwarding-only mock test is not coverage for the current code. ## User-facing changes | Configuration | Before | After | | --- | --- | --- | | `init_timeout_seconds=1800` | World: 1,800 s; tracked NCCL mesh groups may use 600 s during startup. | World and tracked mesh groups: 1,800 s during startup. | | Default `init_timeout_seconds=300` | World: 300 s; tracked NCCL mesh groups may use 600 s. | World and tracked mesh groups: 300 s during startup. | | After the first update | Existing switch to `train_timeout_seconds`. | Unchanged. | Groups created separately outside the context's tracked mesh map, including optimizer-specific communicators, are not covered by this call. ## Numerics No model math, parameter layout, gradient policy, or checkpoint mapping changes. The existing helper adds one startup barrier/device synchronization; there is no new per-update synchronization. ## Testing Rebased onto upstream `ad7a9937b5e57ccadebbb98b3eb14ff139ceb2b3`. The feature diff is unchanged: ten added lines in the shared engine and TorchFT override. ```bash CUDA_VISIBLE_DEVICES='' python -m pytest -q -p no:cacheprovider --tb=short \ tests/unit_tests/cpu/test_trainer.py \ tests/unit_tests/cpu/distributed/test_distributed_utils.py ``` Result: **76 passed**. These existing CPU tests do not directly verify real NCCL subgroup timeout values. ## Known issues / landing gates All non-type pre-commit checks passed in the preceding review. The three Pyrefly failures were independently reproduced on unchanged upstream: missing `torch_checkpointing.checkpoint_writer.CallbackArgs`, its callback signature mismatch, and optional `video.stream.time_base` multiplication. No unrelated source or dependency workaround is included. ## Stack Bottom of stack; based on `main`. Next: [#5675](#5675). <details> <summary>Full draft stack — review and land in this order</summary> | Position | Draft PR | | --- | --- | | 1/n | [#5674 — [distributed] 1/n Apply initialization timeouts to mesh process groups](#5674) | | 2/n | [#5675 — [fsdp] 2/n Expose explicit backward-prefetch policy](#5675) | | 3/n | [#5676 — [fsdp] 3/n Support layer-scoped CPU offload](#5676) | | 4/n | [#5677 — [optim] 4/n Bound optimizer memory ownership and allocation lifetimes](#5677) | | 5/n | [#5678 — [dist_muon] 5/n Support CP and TP storage-to-compute layouts](#5678) | | 6/n | [#5679 — [profiler] 6/n Preserve failure context and merge CUDA-graph streams](#5679) | | 7/n | [#5680 — [kda] 7/n Preserve graph metadata and expose chunk-kernel options](#5680) | | 8/n | [#5681 — [cp] 8/n Add configurable graph-friendly Ulysses transport](#5681) | | 9/n | [#5682 — [compile] 9/n Compile MLA assembly and router postprocessing](#5682) | | 10/n | [#5683 — [pp] 10/n Make cache release and FSDP chunk lifetimes explicit](#5683) | | 11/n | [#5684 — [dist_moe] 11/n Enable Kimi K3 SiTU-GLU training and pipeline lifecycle](#5684) | | 12/n | [#5685 — [moe] 12/n Add opt-in shared-expert CUDA stream overlap](#5685) | | 13/n | [#5686 — [ac] 13/n Add block-scoped activation retention](#5686) | </details> After the preceding PR lands, rebase the remaining suffix onto updated main and retarget its next bottom PR to main. Keep the rest stacked; no automatic landing is requested.
4f6690e to
c28f63b
Compare
e34a8d2 to
7f4806d
Compare
62a2148 to
f7c6638
Compare
…tion (#5681) Part **8/n** of the Kimi K3 / Dist-MoE training stack. Based directly on `main`; this PR can land independently of the remaining stack. human notes: fix the nccl ulysses safeguard that uses `Ulysses.Config` instead of `UlyssesInnerAttention.Config`. ## Why The existing NCCL Ulysses safeguard detects `UlyssesInnerAttention.Config`. Compact MLA, Ulysses KDA, and Ulysses GDN instead inherit directly from `Ulysses.Config`, so these models miss the existing protection on affected NCCL versions. Example: `UlyssesMLAAttention.Config` does not inherit from `UlyssesInnerAttention.Config`. On NCCL 2.32.2 the old traversal leaves graph registration enabled; traversing the common base selects the existing safeguard. The NCCL fix and version boundary are unchanged: [NVIDIA/nccl#2362](NVIDIA/nccl#2362). ## What changed - Match the common `Ulysses.Config` base in the existing safeguard. - Add one isolated GDN regression for a subclass outside the old hierarchy. Full attention uses K/V all-gather in this test, so it cannot accidentally trigger the old safeguard. - Keep the existing version-boundary and unsupported-runtime tests rather than repeating them for each backend. There are only two production-line replacements. Native attention and communication paths are unchanged; no new option or dependency is introduced. ## User-facing changes | Before | After | | --- | --- | | The safeguard detects only full-attention Ulysses wrappers. | It also detects compact MLA and linear-attention Ulysses wrappers. | | NCCL >= 2.32.3, non-CUDA, and fake runtimes skip the safeguard. | Unchanged. | ## Numerics No tensor computation, collective implementation, parameter, or checkpoint layout changes. This extends an existing pre-initialization runtime policy. The CPU checks below do not claim fresh end-to-end training or throughput acceptance. ## Testing Fresh validation against upstream `73c4ebdac57de0d89bb20d5dfabed340449c8b0d`: - **91 CPU tests and 84 subtests passed**, with no deselection. - **Fresh negative control:** the retained GDN regression fails on untouched main because `NCCL_GRAPH_REGISTER` remains unset; it passes with this change. - All non-type-checking pre-commit hooks passed over all files. ```bash CUDA_VISIBLE_DEVICES='' python -m pytest -q -o addopts='' -p no:cacheprovider --tb=short \ tests/unit_tests/cpu/distributed/test_ulysses_nccl.py \ tests/unit_tests/cpu/models/common/test_cp_attention.py \ tests/unit_tests/cpu/config/test_context_parallel_validation.py ``` The type error at unchanged `torchtitan/components/data/multimodal/utils/video.py:114` independently reproduces on untouched upstream `73c4ebdac`. This PR does not change that file. Not verified: a fresh real multi-rank CP/CUDA-graph training run. ## Stack This PR is directly based on `main` and does not require 4/n-7/n. The other source branches are unchanged by this update. 1/n (#5674) is merged; 2/n (#5675) and 3/n (#5676) are closed. | Position | PR | | --- | --- | | 4/n | [#5677](#5677) | | 5/n | [#5678](#5678) | | 6/n | [#5679](#5679) | | 7/n | [#5680](#5680) | | 8/n | [#5681](#5681), independent on main | | 9/n | [#5682](#5682) | | 10/n | [#5683](#5683) | | 11/n | [#5684](#5684) | | 12/n | [#5685](#5685) | | 13/n | [#5686](#5686) | | 14/n | [#5793](#5793), full-scale MXFP8 recipes |
7f4806d to
a26e109
Compare
a26e109 to
99280bc
Compare
e1974a9 to
27e2122
Compare
c2eda21 to
2694d6a
Compare
…regions (#5886) Stacked PRs: * #5904 * #5895 * #5894 * #5893 * #5892 * #5891 * #5890 * #5889 * #5888 * #5887 * #5885 * __->__#5886 --- --- --- ### [distributed] Keep grads of async collective inputs to local_compile regions ## Summary (human-written) See the issue: pytorch/pytorch#201700 This is a bug when compiling: AOTAutograd doesn't trace through AsyncCollectiveTensors and loses the requires_grad. This PR works around the problem in general. But the real solution should be fixing pytorch/pytorch#201700. ## Why On main, Muse Spark with TP > 1 and local compile on never trains tok_embeddings: its grad is None, for text-only and multimodal runs, with SP on and off. Module-boundary redistributions return un-awaited AsyncCollectiveTensors (async_op=True). AOTAutograd unwraps such an input with trigger_wait(), which returns the inner tensor without requires_grad (torch/_functorch/_aot_autograd/frontend_utils.py, added by pytorch/pytorch#179849), so the compiled region's output has no grad path back to the input. In Spark, the embedding output redistribution feeds the compiled embedding norm. Tracking issue: pytorch/pytorch#201700 (pytorch/pytorch#191113 is a closed, unmerged PR for the same bug). **Example.** ``` emb = tok_embeddings(tokens) # redistributed at the Module boundary -> AsyncCollectiveTensor h = compiled_norm(emb) # local_compile region loss(h).backward() before: tok_embeddings.weight.grad is None after: tok_embeddings.weight.grad is set ``` ## What changed - Every local_compile region and always-compiled helper is wrapped so an AsyncCollectiveTensor argument is awaited by a small autograd Function before the compiled call. The Function keeps the autograd edge. - Only top-level arguments are awaited. No in-tree region or always-compiled helper takes tensors inside a container (checked every signature; the only container argument is gdn's split_sizes: list[int]). - TODO(pytorch/pytorch#201700) in code: remove once AOTAutograd keeps the requires_grad of an unwrapped AsyncCollectiveTensor input. - The same bug hits the async k_shared all-gather into the mla_kv region in open PRs #5564 and #5682, which work around it with async_op=False. k_shared is a top-level argument of that region, so this fix covers it and they can keep async_op=True. In-tree CP MLA is not affected: in UlyssesMLAAttention only the k_shared all-gather stays async, and it feeds the eager materialize_mla_kv. The Q/KV all-to-all is synchronous in spmd_types 0.3.1, so the compiled flex call gets plain tensors. ## Alternatives considered - Wait inside Module redistribution (async_op=False): gives up the comm overlap for every Module boundary, not only compiled regions. - Fix in each model: the bug is in the local_compile layer and affects any model with a compiled region after a redistribution. ## Numerics Only Muse Spark with TP > 1 and local compile on changes: tok_embeddings gets grads and trains. Configs below were checked; others are unchecked. Setup: 2x H100, BASE = parent commit, TEST = this commit. debug.seed = 42, debug.deterministic = True, 10 steps, c4_test. Loss and grad_norm are read from TensorBoard. **Muse Spark debugmodel, TP2 + EP2 + SP, flex, default local_compile regions.** Changes, as expected. Step 1 loss is equal (same forward); step 1 grad_norm differs by the added tok_embeddings grad. | step | BASE loss | BASE grad_norm | TEST loss | TEST grad_norm | |---|---|---|---|---| | 1 | 7.82727003 | 4.97379541 | 7.82727003 | 4.97423124 | | 2 | 7.03273010 | 3.67558002 | 7.03092051 | 3.66602159 | | 3 | 6.13859034 | 2.72887707 | 6.14003372 | 2.73221183 | | 4 | 5.76145124 | 2.13588810 | 5.76339674 | 2.15090728 | | 5 | 5.83007097 | 2.06997371 | 5.82927275 | 2.06360984 | | 6 | 5.56987143 | 1.85165656 | 5.56976700 | 1.84894443 | | 7 | 5.37956715 | 1.88629401 | 5.37123251 | 1.88281417 | | 8 | 6.01605892 | 1.97213578 | 6.01554680 | 1.95823133 | | 9 | 5.18035460 | 1.96500850 | 5.18841839 | 1.98249125 | | 10 | 5.20351505 | 1.78124106 | 5.20615530 | 1.78476560 | - Step 1 per-parameter grads (local grad norm, both ranks): tok_embeddings.embedding.weight is None in BASE and nonzero in TEST (rank 0: 0.06576, rank 1: 0.00345). The other 225 parameters have bitwise equal grad norms. - Determinism: two TEST runs give bitwise equal loss and grad_norm at all 10 steps and equal step 1 per-parameter grads. So the BASE/TEST difference comes from this change. **DeepSeek V3 debugmodel, CP2, flex, default local_compile regions.** Unchanged: loss, grad_norm, and step 1 per-parameter grads are bitwise equal for both CP MLA backends. - UlyssesMLAAttention (no load balancer): step 10 loss 4.13782024, grad_norm 2.26978993 in BASE and TEST. - AllGatherKVMLAFlexAttention (no load balancer; the CP attention of the deepseek_v3_cp_pp golden): step 10 loss 4.13834953, grad_norm 2.27362609 in BASE and TEST. Not checked: DeepSeek V3 varlen with CP, because FlashAttention 3 supports head dim at most 128 and the debug MLA head dim is 192. ## Testing - CPU test: a compiled region (aot_eager) on an AsyncCollectiveTensor input passes the grad back. It fails without the fix. - CPU tests at this commit: tests/unit_tests/cpu/config/test_compile_config.py, 9 passed.
2694d6a to
3df0161
Compare
3df0161 to
8486937
Compare
0447e40 to
57e538a
Compare
Thanks for the heads-up! I've narrowed this PR to just the mla_kv region (router compilation dropped, so no overlap with #5343). It includes the synchronous k_shared all-gather fix with a two-rank CP gradient test, and it's needed for my K3 recipes, so I'd like to land it as is. #5564 can rebase on top and drop its mla_kv part. |
c675212 to
5bd8799
Compare
|
@claude review |
There was a problem hiding this comment.
Verdict: Request changes -- the V copy is meant to save memory, but under Ulysses CP it may cost memory instead, and two statements in the description and thread don't match the code.
What this PR does. It registers materialize_mla_kv (split packed KV -> broadcast shared rope key -> cat) as the mla_kv local-compile region and turns it on by default for Kimi K3. When the function is traced with grad enabled, V is returned as a contiguous copy instead of a view of kv_THP, so the K-nope half of kv_THP can be freed before backward.
Example.
kv_THP (T,H,N+V) --split--> k_nope_THN, v_THV (view)
k_shared_TR --expand--> (T,H,R); k_THK = cat(k_nope, k_shared) # copy
main, eager: strided CatArrayBatchedCopy, 767 us fwd+bwd per layer;
attention saves v_THV -> all of kv_THP stays alive
PR, K3 compiled: fused Triton fwd/bwd, 234 us; v_THV copied ->
kv_THP freed (non-CP: 803 -> 707 MiB per layer)
Must fix
- The description and thread don't match the code. (a) The description says "Core DeepSeek V3/V4 recipes and golden tests enable only the
lossregion". They don't: DSV3 enablesloss, fused_binary_activation, fp32_to_bf16_split, moe_aux_loss, rope, mla_qk(deepseek_v3/model.py:85-92), and DSV4 enables four regions. The conclusion still holds, because neither enablesmla_kv, but please correct the sentence. (b) Your reply to Felipe says this PR "includes the synchronous k_shared all-gather fix with a two-rank CP gradient test". The diff contains neither.cp_mla.py:115is stillasync_op=True, and the gradient fix comes from #5886's_wait_async_collective_inputs(local_compile.py:36-62, already on main), as the description says. Please correct the reply so #5564's author doesn't drop a fix that isn't here. torchtitan/models/common/attention/mla.py:62-66-- under Ulysses CP,q_THKandkv_THPare views of the same all-to-all buffer, so the V copy may add a V-sized buffer per layer instead of freeing K-nope (unverified, see inline).
Should consider
torchtitan/models/kimi_k3/model.py:230-- enablemla_kvfor DeepSeek V3 as well (this also covers Kimi K2.7), or say why not (see inline).tests/unit_tests/gpu/models/common/test_mla_attention.py:202-209-- hardcode the dims instead of building a K3 config in a common test (see inline).
Questions
- "~32 us writing V ... happens with or without the V copy": without the copy, V is a view of an input. Which kernel writes V in that case? If it is the backward grad-of-V write into the packed-KV gradient, then the copy's forward cost was never measured, and the claim that "it adds no measured time" needs a forward-only number.
Details
- Necessity gate: passes. The problem is concrete and measured (component 3.3x faster, bitwise equal), the fix is at the right layer, it reuses the existing
local_compilemachinery, and it adds no new knob. Net +92 LoC, mostly the test. - Async collectives: in the CP path,
q_THK,kv_THPandk_shared_TRreach the region asAsyncCollectiveTensors or views of one._wait_async_collective_inputswaits on each top-level argument through_WaitAsyncCollective, which keeps the autograd edge, so Felipe's zero-k_shared-grad concern is addressed on main.q_THKis only read for its shape, but waiting on it costs nothing extra becausekv_THPcomes from the same collective. torchtitan_recipes/overrides/fused_mla.py:1092replacesmaterialize_kv, so it is unaffected. The vLLM generator runs without grad, so it never takes the copy.batch_invariant=Trueis plausible: the only reduction is the backward sum over heads, which doesn't depend on the number of tokens.
Not verified: GPU numerics and perf claims; whether varlen_attn / flex save the strided q view under CP (see must-fix 2). A maintainer still needs to review (this PR touches models/common).
| # Attention saves V for backward. As a view, V would keep all of kv_THP | ||
| # alive, including its K-nope half, which K's concat has already copied. | ||
| # Copying V lets that half be freed; compiled, it adds no measured time. | ||
| if torch.compiler.is_compiling() and torch.is_grad_enabled(): | ||
| v_THV = v_THV.contiguous() |
There was a problem hiding this comment.
The memory win measured here (707 vs 803 MiB) is for the non-CP path, where kv_THP has its own buffer. Under Ulysses CP (cp_mla.py:121-133), q_THK and kv_THP are both torch.split views of the single all-to-all output packed_q_kv_THF. The inner attention saves q_THK for backward. As far as I can tell varlen_attn / flex save the strided view and don't make their own contiguous copy, so the whole packed Q|K-nope|V buffer stays alive anyway. In that case the copy frees nothing, and each MLA layer holds an extra V-sized buffer between forward and backward. That would be a memory regression on the K3 CP recipes, which this PR turns on by default. (Unverified: I couldn't run it. It depends on whether the inner kernel saves the view.)
Please measure saved-activation memory for one layer under Ulysses CP2 with and without the copy. If the copy costs memory there, the smallest fix is to make the copy conditional on kv_THP owning its storage. Alternatively, keep the copy out of materialize_mla_kv and do it in MLAAttention.forward only, since that is the path where it pays off.
| "fused_binary_activation", | ||
| "fp32_to_bf16_split", | ||
| "attention_residual", | ||
| "mla_kv", |
There was a problem hiding this comment.
The region is model-agnostic: it lives in models/common/attention/mla.py and is bitwise equal to eager. DeepSeek V3 uses the same MLAAttention.forward -> materialize_mla_kv path, and so does Kimi K2.7, which inherits DeepSeekV3Model.Config.local_compile. DeepSeek V3 already enables the neighbouring mla_qk region by default (deepseek_v3/model.py:85-92). Why not add "mla_kv" there too? It is one line, and both models get the 3.3x component speedup. If there is a reason (for example, the DSV3 fake-PG goldens), please state it in the description. Otherwise one MLA model gets a free speedup that its siblings don't.
| layers = build_model_config( | ||
| "debugmodel", attn_backend="flex", parallelism=ParallelismConfig() | ||
| ).layers | ||
| attention_config = next( | ||
| layer.attention | ||
| for layer in layers | ||
| if isinstance(layer.attention, KimiMLAAttention.Config) | ||
| ) |
There was a problem hiding this comment.
This is a models/common test, but it builds a full Kimi K3 model config and imports KimiMLAAttention only to read four head dims. materialize_mla_kv only needs shapes. Hardcode small dims (e.g. n_heads=4, nope=16, rope=8, v=16) and drop the two kimi_k3 imports. That keeps the common test independent of one model, and it stops breaking whenever the K3 debug flavor changes.
Register materialize_mla_kv as the mla_kv local-compile region and enable it for Kimi K3. Eager runs the K/V assembly as strided cat copies; the compiled region is 3.3x faster at K3 shapes and bitwise identical to eager. Ulysses CP needs no change: #5886 already keeps gradients of async collective inputs to local-compile regions.
5bd8799 to
ed1756d
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. The V copy is gone, so the Ulysses CP memory concern no longer applies. The diff is now just the decorator, one region-list entry, and a model-agnostic bitwise test.
What changed since the last review. materialize_mla_kv again returns V as a view of kv_THP. The only change to the function is @local_compile("mla_kv", batch_invariant=True). The test now uses hardcoded small dims and has no kimi_k3 imports. The description was rewritten to match the code.
Example.
kv_THP (T,H,N+V) --split--> k_nope_THN, v_THV (view, unchanged)
k_shared_TR --expand--> (T,H,R); k_THK = cat(k_nope, k_shared)
main: strided CatArrayBatchedCopy fwd+bwd, 767 us/layer (K3, T=4096)
PR: K3 enables "mla_kv" -> fused Inductor fwd/bwd, 234 us/layer, bitwise == eager
Earlier findings
- Must-fix 1a (description misstated the DSV3/V4 regions): resolved, the sentence was removed.
- Must-fix 1b (thread reply to Felipe): still open, see below.
- Must-fix 2 (V copy under Ulysses CP): resolved, the copy was dropped. "Alternatives considered" now includes the CP2 measurement (577.5 -> 673.5 MiB with the copy), which confirms the concern.
- Should-consider, DSV3 / K2.7 enablement: answered in the description (only K3 shapes were measured; one-line follow-up).
- Should-consider, K3 config in the common test: resolved.
- Question about the 32 us V write: moot now that the copy is gone.
Must fix
- Your 2026-11-10 reply to Felipe still says this PR "includes the synchronous k_shared all-gather fix with a two-rank CP gradient test". It doesn't:
cp_mla.py:115still usesasync_op=True, and the gradient fix comes from #5886's_wait_async_collective_inputs(local_compile.py:36-62, already on main). The description now says this correctly. Please edit the comment or add a correction too, so #5564 doesn't drop work based on it.
Details
- Dispatch: the
materialize_kv=materialize_mla_kvdefaults inmla.py:114andcp_mla.py:92capture thewrappeddispatcher, which reads the boundfnat call time. Enabling the region throughLocalCompileConfig.apply()therefore reaches both the plain and the Ulysses paths. - CP:
q_THKandkv_THPare split views of the async all-to-all output, andk_shared_TRis an async all-gather. All three are top-level arguments, so_WaitAsyncCollectivewaits on them and keeps their autograd edges. torchtitan_recipes/overrides/fused_mla.py(used by the DSV3 recipes) replacesmaterialize_kv, so it is unaffected. The K3 recipes don't use it, so they do take the new region.batch_invariant=True: the only reduction is the backward sum over heads for each token, and it doesn't depend on the number of tokens.- The region is bitwise equal to eager, so the K3 golden losses should not change.
Not verified: the GPU numerics and perf numbers (no GPU here). A maintainer still needs to review, since this touches models/common.
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.
Summary (human-written)
Part 9/n of the Kimi K3 training stack. Based directly on
main; it doesnot depend on 5/n-7/n and can land independently.
Why
materialize_mla_kvbuilds per-head K/V from the packedwkv_boutput and theshared rotary key. In eager it runs as strided
torch.catcopies (forward K andbackward packed-KV gradient), which take the slow non-vectorized
CatArrayBatchedCopypath. At Kimi K3 recipe shapes this costs 767 us per MLAlayer (fwd+bwd); compiling the same function brings it to 234 us, bitwise
identical to eager.
Example.
What changed
mla.py: registermaterialize_mla_kvas themla_kvlocal-compile region(
batch_invariant=True). The function body is unchanged; only thedecorator is added.
kimi_k3/model.py: enablemla_kvin Kimi K3's default local-compile regions.test_mla_attention.py: newTestMLAKVLocalCompileclass, compiled vs eager, bitwise.Ulysses CP needs no change: #5886 already waits on async collective inputs to
local-compile regions while keeping their gradient, so
k_shared's all-gatherstays async and keeps overlapping the
wkv_bprojection.Alternatives considered
keep the K-nope half of
kv_THPalive. Measured per MLA layer at T=4096: itsaves 96 MiB without CP (803 -> 707 MiB held) but costs 96 MiB under Ulysses
CP2 (577.5 -> 673.5 MiB), because attention's saved
qview keeps the sharedall-to-all buffer alive anyway. It also adds a 32 us forward kernel that runs
again under recompute. K3 recipes use CP, so V stays a view.
mla_kvfor DeepSeek V3 / Kimi K2.7 as well: the region ismodel-agnostic and bitwise, but only K3 shapes were measured here. Left as a
one-line follow-up.
User-facing changes
mla_kvregion; on by default for Kimi K3Numerics
Component-level, bitwise (
rtol=0, atol=0):mla_kvvs eager: K, V, packed-KV grad,k_sharedgradk_sharedall-gather, as on main) with compiledmla_kv: output, loss, all input/param grads vs eagerNo end-to-end loss comparison has been run for this PR.
Performance and memory
Microbenchmark, 1x GB300, T=4096, K3 MLA shapes, fwd+bwd under CUDA graph
replay (the K3 recipes run with CUDA graphs, so launch overhead is excluded):
mla_kvKernel breakdown of the compiled region: 42 us fwd K build; bwd 61 us
packed-KV grad, 32 us writing V's grad into it, and 12 us
k_sharedgrad sum(all near HBM bandwidth). Eager's time is dominated by the strided
CatArrayBatchedCopy(664 us for the fwd and bwd cats).Memory is unchanged from eager: V is still returned as a view of
kv_THP.No end-to-end TPS number yet.
Testing
test_compiled_matches_eager_bitwisecatches any numerics change fromcompiling the region. The async-collective gradient path is covered by
#5886's tests. Pre-commit passes on the changed files.
Known issues / follow-ups
on the
mla_kvdecorator and the K3 region list ([mla][perf] Compile MLA's key/value build as the mla_kv region #5564 also copies V; seeAlternatives considered).
main.