Repository navigation
[recipes] 14/n Add full-scale Kimi K3 MXFP8 recipes - #5793
Conversation
…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 |
c985b7a to
8bbdbd4
Compare
bded89c to
28b4b25
Compare
7dd2e9d to
c114c27
Compare
28b4b25 to
82afd34
Compare
Part **4/n** of the Kimi K3 / Dist-MoE training stack. Based directly on `main`: the review diff contains only the optimizer-memory changes below. human notes: 1. release distmuon's gpu redistribution and compute scratch after each eager optimizer update by default. 1) in full eager training, later fwd/bwd can reuse the released memory. 2) if one rank has two eager optimizers (fwd/bwd can use cudagraph), like when vpp=2, their scratch allocations can reuse memory instead of remaining simultaneously resident. keep tensor metadata and cpu scratch, and release unused ns intermediates earlier without changing the math. 2. the flow is: reserve shapes/dtypes/device, and use allocate for setting real storage, and use resize_(0) to free the storage. 3. remove some ns step intermediate tensors without changing math. ## Why DistMuon retains exchange and compute scratch between updates, even when eager forward/backward or a second eager optimizer could reuse that memory. Dropping scratch allocated on the transfer stream does not let the caller stream reuse its cached blocks. Prepare the buffer capacities once, then regrow and release accelerator backing storage on the caller stream. Keep CPU backing storage allocated between updates to avoid repeated host allocations. Tensor objects, shapes, bucket plans, communication streams/events, parameters, and optimizer state remain alive. This is the default behavior; no new config knob is added. **Example.** ```python # Forward/backward may be eager or CUDA-graphed; optimizer updates are eager. chunk0_optimizer.step() # Regrow cached scratch, update, resize storage to zero. chunk1_optimizer.step() # Can reuse released caller-stream allocator blocks. # With one optimizer, later eager forward/backward can reuse those blocks too. # A separate forward/backward CUDA-graph pool cannot reuse normal-pool scratch. ``` ## What changed - Keep the four scratch tensor types and their metadata; prepare capacities at construction or checkpoint replanning, not before every update. - Regrow released backing storage with `untyped_storage().resize_(size)` on the current caller stream. Preserve the existing transfer/caller event ordering, then release accelerator storage with `resize_(0)` after a successful eager update. CPU storage stays allocated; `allocate()` already skips correctly sized storage. - Make storage release the default rather than introduce a persistence knob. Because every storage lifetime begins and ends on its caller stream, the old persistent-buffer caller-tracking set is unnecessary. - Release obsolete Newton-Schulz intermediate references after their last use. Arithmetic, compute dtype, and update ordering do not change. The net diff touches the runtime, DistMuon implementation, and one CPU runtime regression. Existing optimizer/checkpoint tests exercise the new default without new distributed CI variants. There are no trainer/container changes, synthetic all-to-all warmups, new dependencies, or communicator/CTA changes. ## User-facing behavior | Before | After | | --- | --- | | Accelerator scratch tensor objects and backing storage remain resident between updates | Tensor objects persist; accelerator backing storage is released after each eager update | | CPU scratch remains allocated between updates | Unchanged; the release loop skips CPU tensors | | Several eager optimizers each retain their scratch arena | Sequential eager updates can reuse caller-stream scratch allocations | | Forward/backward graph pools are separate from optimizer scratch | Unchanged; this PR does not implement graph-pool sharing | ## Numerics Compared with the `main` parent `22047b18a`: - GPU 0: FP32 and BF16 parameters each produced bitwise-identical loss, gradients, and updated weights for ten updates, with both eager and CUDA-graphed forward/backward. Each run reloaded an optimizer checkpoint after update five. - Real two-rank CPU/Gloo redistribution: owned, uneven mixed-block, and expert matrices produced bitwise-identical updated weights for ten updates and a checkpoint reload. The owned matrix also matched `torch.optim.Muon` exactly. Scratch tensor identities survived updates/reloading; CPU backing storage now stays allocated between updates, matching the host-buffer behavior on `main`. - A standalone one-rank optimizer-capture smoke test completed ten exact-parity replays. This is not multi-rank optimizer-graph validation; the Titan optimizer container still does not enable DistMuon capture. Fresh follow-up checks against the previous PR head `a4fada369` also produced exact FP32/BF16 eager and graphed loss/gradient/weight parity, and exact two-rank Gloo updates. An actual single-GPU FSDP2 `CPUOffloadPolicy` run with `ns_device=None` completed ten updates and a checkpoint reload: a 16-to-16-to-8 linear model (384 weights, eight input rows) kept its 1,024-byte host scratch allocated and reused its pointer between replans, with bitwise-identical loss, gradients, and weights. This is correctness/lifecycle evidence, not an offload throughput or host-allocation-cost measurement. Fresh multi-rank NCCL validation has not been rerun because only GPU 0 was available. ## Memory evidence The following accelerator-only measurements predate the CPU-retention correction; the correction does not change the accelerator release branch. This is a synthetic single-GPU GB300 allocator benchmark, not a Kimi K3 training run. BF16 forward/backward uses a bias-free 1024-to-8192 linear layer (8.39M weights) with 4096 input rows. Each eager DistMuon instance updates a separate 29.36M-parameter workload (14.68M local parameters on shape-only fake DP=2), with FP32 parameters/gradients/momentum, BF16 compute, and one Newton-Schulz iteration. The table covers ten updates after two eager warmups; graph cases additionally capture/replay forward/backward before measurement. Values are PyTorch allocator counters, not total device HBM. FakePG is used for shapes here, not distributed numerical evidence. | Forward/backward | Eager optimizers | Peak allocated: parent -> PR | Steady reserved: parent -> PR | | --- | ---: | ---: | ---: | | Eager | 1 | 672 -> 528 MiB | 722 -> 594 MiB | | Eager | 2 | 984 -> 696 MiB | 1058 -> 774 MiB | | CUDA graph | 1 | 424 -> 420 MiB | 788 -> 800 MiB | | CUDA graph | 2 | 736 -> 588 MiB | 1124 -> 980 MiB | Each optimizer retains 144 MiB of scratch capacity metadata but zero backing storage after an update, versus 144 MiB resident on the parent. All cases had zero allocator retries. The single-optimizer graph case does not show meaningful scratch-related peak savings; the two-optimizer case demonstrates normal-pool scratch reuse, not graph-pool sharing. A separate setup-call census over ten updates/two optimizers recorded zero `reserve_buffers` and `_reserve_tensor` calls in the new steady loop, versus 20 and 180 calls in the previous transient implementation. Storage allocation/free operations still occur. No full-scale HBM or throughput gain is claimed. ## Testing - **123 CPU tests passed** for redistribution, optimizer state/configuration, trainer, and accelerator graphs. The one added CPU regression checks all four scratch buffer roles for ten release/allocate cycles, verifying retained host capacity, pointers, and contents; it fails cleanly against the previous PR head. - The supplementary GPU-0, FSDP2 CPU-offload, and real Gloo probes above passed; no new multi-GPU CI variants were added. - All non-type-checking pre-commit hooks passed across the repository. Both changed production files and the CPU regression pass focused Pyrefly. - Full-project Pyrefly reports the same single optional-value error at `components/data/multimodal/utils/video.py:114` on both this patch and the independently checked `main` parent. No unrelated fix or suppression is included. ```bash CUDA_VISIBLE_DEVICES='' python -m pytest -q \ tests/unit_tests/cpu/distributed/flex_shard \ tests/unit_tests/cpu/components/optim/test_optimizer_param_groups.py \ tests/unit_tests/cpu/components/optim/test_optim.py \ tests/unit_tests/cpu/test_trainer.py \ tests/unit_tests/cpu/distributed/test_accelerator_graph.py SKIP=pyrefly-check pre-commit run --all-files pyrefly check torchtitan/distributed/flex_shard/_optimizer_reshard_runtime.py \ torchtitan/distributed/flex_shard/dist_muon.py \ tests/unit_tests/cpu/distributed/flex_shard/test_optimizer_reshard_runtime.py ``` ## Stack Based directly on `main`. Next: [#5678](#5678). <details> <summary>Draft stack — review and land in this order</summary> 1/n (#5674) and 8/n (#5681) are merged. 2/n (#5675) and 3/n (#5676) are closed because the chosen full-scale recipes use neither the prefetch-disable policy nor selected-layer CPU offload. They are no longer in the stack. | Position | Draft PR | | --- | --- | | 4/n | [#5677 — [distmuon] 4/n Release scratch storage between optimizer updates](#5677) | | 5/n | [#5678 — [dist_muon] 5/n Support CP and TP storage-to-compute layouts](#5678) | | 6/n | [#5679 — [profiler] 6/n Preserve active failures during shutdown](#5679) | | 7/n | [#5680 — [attention] 7/n Keep linear-attention graph metadata replayable](#5680) | | 8/n, merged | [#5681 — [cp] 8/n Apply the Ulysses NCCL safeguard to compact and linear attention](#5681) | | 9/n | [#5682 — [compile] 9/n Compile MLA assembly and router postprocessing](#5682) | | 10/n | [#5683 — [pp] 10/n Add once-only startup cache release](#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) | | 14/n | [#5793 — [recipes] 14/n Add full-scale Kimi K3 MXFP8 recipes](#5793) | </details> After this 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.
c114c27 to
4889958
Compare
3cb136a to
14fae59
Compare
2c37acf to
49d8aa4
Compare
09b72fb to
f9d0d38
Compare
f9d0d38 to
7430d8a
Compare
49d8aa4 to
7241cd6
Compare
9dfa0cb to
d0ee436
Compare
5b2594d to
048a55b
Compare
|
@claude review |
|
Claude finished @shuhuayu's task in 2m 40s —— View job Request changes: the Kimi K3 README's throughput numbers weren't measured with this recipe as committed. See the review for details. |
There was a problem hiding this comment.
Verdict: Request changes -- the README publishes throughput numbers for kimi_k3_dist_moe_mxfp8_gb200_512, but neither number was measured with that recipe. The recipe also may not need forced routing at all.
What this PR does. Adds torchtitan_recipes/models/kimi_k3.py with one 512-GB200 recipe for the full 93-layer K3 model. It uses PP8 with one chunk per rank, EP64/FSDP64, MXFP8 Dist-MoE experts, CUDA graphs, DistMuon, and round-robin routing. It also moves the K3 DistMuon optimizer builder out of the debug recipe into the new module, and rewrites it as one table per layer type. The debug recipes and the GPU test now import it from there.
Example (the optimizer refactor, one MoE layer). The FQNs are listed in bucket order and are the same before and after:
layers.N.feed_forward.routed_experts.w13.weight -> per_expert (bucket "layers.N-M.routed-experts")
layers.N.feed_forward.routed_experts.w2.weight -> per_expert
layers.N.feed_forward.router.gate.weight -> owned (bucket "layers.N-M")
layers.N.feed_forward.shared_experts.w13.weight -> Shard(0)
layers.N.feed_forward.shared_experts.w2.weight -> owned
layers.N.feed_forward.routed_down/up.weight -> owned
I checked the new builder against the old one: same FQN order, same is per_expert split, same bucket names and contents, same Muon regex, same AdamW kwargs. That supports the "identical optimizer configs" claim.
Must fix
torchtitan/models/kimi_k3/README.md:66-73-- the forced row came from a run with the fused KDA kernel pinned and EP-phased round-robin routing. The learned row needs a router and a scratch capacity the recipe doesn't set. Re-measure with the recipe as committed, or drop the table.
Should consider
torchtitan_recipes/models/kimi_k3.py:301-- learned routing costs about 4%. Dropping the round-robin override and settingscratch_capacity_factor=2.0would make this a real pretraining recipe, which is whattorchtitan_recipes/README.md:26already calls it. Otherwise, put "round robin" in the recipe name.torchtitan_recipes/models/kimi_k3.py:71-- this is the third copy of_per_expert_compute_layout. The K3 debug recipe's_align_dist_muon_expert_compute_layouts(fromkimi_k2_7) compares this copy against the K2.7 copy with!=, so the two copies have to stay in sync. Make this one public and have K2.7 import it.torchtitan_recipes/models/kimi_k3.py:358-365-- the profiler config readsRANK, so the config differs by rank. It also assumes PP is the outermost mesh axis, and the build-time dp_shard stride goes stale under--override. Droptracefrom the recipe.
Questions
- Using plain
Trainer.Configinstead of_KimiK3TrainerConfigskips the K3 check that DistMuon has TP == 1, and skips the expert-layout realignment when parallelism is overridden. Is that intended for a fixed-hardware recipe?
Details
- Test:
test_full_recipe_selects_dist_moe_before_graph_validationguards a real ordering invariant.validate_model_training_compatrejects the stock dispatcher under graphs, so the transform has to run beforeTrainer.Configis built. The monkeypatch works becausevalidation.py:159importsaccelerator_graphs_supportedinside the function. Running it from the B200 job matches howtests/unit_tests/cpu/models/common/test_dist_moe.pyis already run. - PP split:
range(0, 93, 12)gives 8 parts (7x12 + 9), one per PP rank. That matches the comment. - 64 x 64 / 64 x 8 = 512 ranks.
num_tokens_per_microbatch_per_dp_rank=4096x 64 microbatches x 64 dp_shard = 16,777,216 tokens per update, which matches the table.
Not verified: throughput and memory at 512 GPUs; whether DistMuon raises a clear error when the expert layouts are stale after an EP override.
| | Recipe | GPUs | PP / VPP / EP / FSDP | Routing | Tokens / update | Tokens/s/GPU | Model TFLOP/s/GPU | | ||
| | --- | --- | --- | --- | ---: | ---: | ---: | | ||
| | `kimi_k3_dist_moe_mxfp8_gb200_512` | 512 GB200 | 8 / 1 / 64 / 64 | Forced round-robin | 16.8M | 1,010 | 651 | | ||
| | `kimi_k3_dist_moe_mxfp8_gb200_512` | 512 GB200 | 8 / 1 / 64 / 64 | Learned | 16.8M | 971 | 627 | | ||
|
|
||
| Throughput is the median of steady-state updates in a 12-update run. The | ||
| learned-routing row keeps Kimi K3's default quantile-balanced router and raises | ||
| the Dist-MoE scratch capacity factor from 1.0 to 2.0. |
There was a problem hiding this comment.
Must fix. Both rows credit their numbers to kimi_k3_dist_moe_mxfp8_gb200_512, but the PR description says neither number came from this recipe:
- The forced row came from a source workload that pinned the fused KDA kernel and phased round-robin routing by EP source. This recipe uses core's default KDA kernel selection and plain
RoundRobinTokenChoiceTopKRouter. - The learned row needs the quantile-balanced router and
scratch_capacity_factor=2.0. The recipe hardcodes round-robin attorchtitan_recipes/models/kimi_k3.py:301and uses the defaultDistMoeRuntime.Config()(capacity 1.0) at line 354, so no in-repo config produces this row.
If someone runs the recipe and gets a different number, they can't tell whether something regressed or the table was never accurate. The docs should describe the code as it is. Either re-measure 12 updates with the recipe as committed and report only that, or drop the table until it has been run. If the learned row stays, it needs a recipe that reproduces it (see the routing comment at line 301).
| parallelism, pipeline_parallel_module_fqns_per_model_part=parts | ||
| ) | ||
| for _, moe, _, _ in model.traverse(MoE.Config): | ||
| moe.router = derive(moe.router, RoundRobinTokenChoiceTopKRouter.Config) |
There was a problem hiding this comment.
Should consider. By the README's own numbers, learned routing costs about 4% (971 vs 1,010 tokens/s/GPU). The only extra setting it needs is scratch_capacity_factor=2.0. Tokens above that capacity spill into host-backed pages rather than failing (dist_moe/runtime.py:196-201). So two edits would make this a recipe that actually trains K3: delete these two lines, and use dist_moe_runtime_config(scratch_capacity_factor=2.0) at line 354. The "throughput recipe, not learned-router training" caveat would go away, and torchtitan_recipes/README.md's "K3 pretraining" label would be accurate. Today that label is wrong, because forced routing can't pretrain anything.
If forced routing is the point (for example, isolating Dist-MoE throughput from routing imbalance), the recipe name should say so, for example ..._round_robin_routing, so nobody launches it as a training run.
| ) | ||
|
|
||
|
|
||
| def _per_expert_compute_layout(parallelism: ParallelismConfig) -> ComputeLayout: |
There was a problem hiding this comment.
Should consider. This is the third copy of _per_expert_compute_layout; the other two are in torchtitan_recipes/tests/models/kimi_k2_7.py:264 and qwen3_8_flash_next.py:60. Two of the copies now have to stay identical. kimi_k3_debugmodel builds its layouts with this copy (through dist_muon_optimizer). Its __post_init__ then calls _align_dist_muon_expert_compute_layouts from kimi_k2_7, which compares every routed-expert layout with != against the K2.7 copy and rewrites any that differ. If one copy is edited without the other, the debug recipe quietly replaces the K3 layouts with the K2.7 ones.
Smallest fix: make this function public here (per_expert_compute_layout) and have tests/models/kimi_k2_7.py import it instead of keeping its own copy. Production recipes shouldn't import from tests/, but tests/ importing from models/ is the direction this PR already uses for dist_muon_optimizer. That's about -28 lines.
Separately, the ep_size <= 0 check is copied from K2.7. If ParallelismConfig already rejects non-positive degrees, delete the check.
| # Trace one rank per PP stage: PP is the outermost mesh axis, so each | ||
| # stage starts at a multiple of the dp_shard degree. | ||
| profiler=Profiler.Config( | ||
| trace=( | ||
| KinetoTraceProfiler.Config(freq=6, warmup=2, active=1, repeat=1) | ||
| if rank >= 0 and rank % parallelism.data_parallel_shard_degree == 0 | ||
| else None | ||
| ), |
There was a problem hiding this comment.
Should consider. Reading RANK at line 320 makes the config tree depend on the rank. No other recipe does this; the other os.environ reads are for paths. It also bakes in two assumptions:
- PP is the outermost mesh axis, which
.claude/rules/distributed.mdsays not to assume. data_parallel_shard_degreeis read from the build-timeparallelism, so--override parallelism.data_parallel_shard_degree=...leaves the old stride in place and silently traces the wrong ranks.
The configs built in-process (the CPU test, config dumps) also differ from what runs under torchrun. Since Profiler has no rank filter, the simplest fix is to drop trace from the recipe and leave profiling to --override. If one trace per PP stage is a common need, a rank selector on Profiler.Config that is resolved against the real mesh would be the right layer, as its own PR.
048a55b to
d0f8a37
Compare
|
@claude review again |
|
Claude finished @shuhuayu's task in 1m 16s —— View job Approve -- please address the items below before merging: the forced-routing row is now credited to this recipe, but the learned-routing README row still names a recipe that can't produce it. See the review for details. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. Only the README changed since the last review. The forced-routing row is now credited to this recipe. The learned-routing row still names a recipe that cannot produce it.
What changed since the last review. torchtitan/models/kimi_k3/README.md gained the sentence "The first row was measured with this recipe", and the PR description now says the same. torchtitan_recipes/models/kimi_k3.py, the tests, and the CI change are byte-identical to the version I reviewed before.
Example (the remaining README problem).
python -m torchtitan.train --module torchtitan_recipes.models.kimi_k3 \
--config kimi_k3_dist_moe_mxfp8_gb200_512
# README row 1: Forced round-robin -> 1,010 tok/s/GPU (what this run measures)
# README row 2: Learned -> 971 tok/s/GPU (no config in the repo runs this)
To get row 2, you have to edit the recipe source: delete the router override at kimi_k3.py:301 and set scratch capacity 2.0 at :354. --override can't do the router swap.
Earlier must-fix
- README forced row not measured with this recipe: resolved, based on the updated description (unverified; it needs a 512-GPU run).
- README learned row has no in-repo recipe: still open. See must-fix 1 below.
Must fix
-
torchtitan/models/kimi_k3/README.md:69-- the "Learned" row is labeledkimi_k3_dist_moe_mxfp8_gb200_512, but that recipe hardcodes round-robin routing and capacity 1.0. Pick one of these:- delete the row and the last sentence of lines 71-74, or
- make the recipe use learned routing (drop lines 300-301 and use
dist_moe_runtime_config(scratch_capacity_factor=2.0)), then re-measure and keep a single row.
The second option also removes the "throughput recipe, not learned-router training" caveat.
-
torchtitan_recipes/README.md:26-- the purpose column says "K3 pretraining", but the only recipe in the module uses forced routing and the K3 README says it "measures throughput, not learned-router training". Change it to "K3 full-scale throughput", or leave it as is if you take the second option above.
Still open from last review (should consider)
torchtitan_recipes/models/kimi_k3.py:71-- this is the third copy of_per_expert_compute_layout._align_dist_muon_expert_compute_layoutsintests/models/kimi_k2_7.pycompares this copy against the K2.7 copy with!=, so the two must stay in sync. Make this one public and import it from K2.7.torchtitan_recipes/models/kimi_k3.py:358-365-- thetraceconfig readsRANKat build time, so the config is different on each rank. It also assumes PP is the outermost mesh axis, which.claude/rules/distributed.mdsays not to do. And--override parallelism.data_parallel_shard_degreeleaves the stride from build time in place. Droptraceand leave profiling to--override.
Questions (unanswered)
- The recipe uses plain
Trainer.Configrather than_KimiK3TrainerConfig. That skips the DistMuon TP == 1 check and the expert-layout realignment after a parallelism override. For example,--override parallelism.expert_parallel_degree=32keeps the EP64 layouts. Is that intended?
Details
- I re-checked
torchtitan_recipes/models/kimi_k3.pyagainst the earlier diff context: same 367 lines, router override at 300-301, defaultDistMoeRuntime.Config()at 354,RANKread at 320. My earlier check of the optimizer refactor (same FQN order, buckets, Muon regex, AdamW kwargs) still applies. - This PR doesn't touch core training code. It only changes recipes, docs, tests, and one line in the B200 CI job.
Not verified: the 1,010 / 651 forced-routing numbers at 512 GB200.
Add a text-only 512-GB200 recipe for the full 93-layer Kimi K3 model at 4K: PP8 Interleaved1F1B with one 12-layer chunk per rank, EP64/FSDP64, MXFP8 Dist-MoE routed experts, FP32 parameters/gradients/optimizer state with BF16 compute, DistMuon, CUDA-graph forward/backward, and forced round-robin expert routing. Move the K3 DistMuon optimizer builder from the debug recipe into torchtitan_recipes.models.kimi_k3 and simplify it; the optimizer configs it builds for the full-scale, K3 and K3.1 debug recipes are unchanged. The K3 and K3.1 debug recipes and the GPU test import it from there.
d0f8a37 to
1d242a9
Compare
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 14/n of the Kimi K3 training stack. Independent PR on
main: thepieces it composes are all on
mainnow (SiTU-GLU Dist-MoE #5684, Kimi K3Dist-MoE pipeline stages #6049, per-block remat #6104).
Why
TorchTitan has Kimi K3 debug recipes only. There is no recipe that runs the
full 93-layer model with Dist-MoE, DistMuon and pipeline parallelism together,
so the configuration used for full-scale throughput runs lives outside the
repo.
What changed
torchtitan_recipes/models/kimi_k3.pyadds one text-only 4K MXFP8 recipe:kimi_k3_dist_moe_mxfp8_gb200_512routed-expert GEMMs use MXFP8 (Dist-MoE). Interleaved1F1B with one explicit
chunk per rank (seven 12-layer chunks and a final 9-layer chunk),
CUDA-graph forward/backward, DistMuon, FSDP
parameters kept unsharded across forward/backward.
RoundRobinTokenChoiceTopKRouter, so this is athroughput recipe, not learned-router training; gate scores and their
gradients stay learned. KDA uses core's default kernel selection.
torchtitan/models/kimi_k3/README.md: a short "Full-Scale Recipe" sectionwith measured throughput for forced and learned routing.
torchtitan_recipes.models.kimi_k3.dist_muon_optimizerand is simplified(one layout helper, one table per layer type, one pass over layers); the K3
and K3.1 debug recipes and the GPU test import it from there. The full-scale
recipe keeps its own private copy of the expert compute layout helper
instead of importing it from the K2.7 debug recipe.
(
test_full_recipe_selects_dist_moe_before_graph_validation); it skipswherever Dist-MoE is not installed.
Numerics
No change to existing recipes. The simplified optimizer builder produces
identical optimizer configs (Muon pattern, learning rates, ordered buckets and
ordered per-FQN compute layouts) for the K3 debug, K3 debug MXFP8, K3.1 debug
and full-scale recipes, and for the debug model at EP=1 and EP=2.
Testing
tests/unit_tests/cpu/recipes/test_kimi_dist_moe.py(Dist-MoE selection before graph validation)tests/unit_tests/cpu/models/kimi_k3/tests/unit_tests/gpu/models/kimi_k3/test_kimi_k3.py -k dist_muon(1 GPU)The README's forced-routing row (1,009.5 tokens/s/GPU, 651.44 model TFLOP/s/GPU,
158.41 GiB maximum reserved, twelve updates on 512 GB200) was measured with
this recipe. The learned-routing row (971 tokens/s/GPU, 626.52 model
TFLOP/s/GPU) used Kimi K3's default router with Dist-MoE scratch capacity 2.0.