Repository navigation
Conversation
This was referenced Oct 29, 2026
This was referenced Oct 29, 2026
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-09
branch
from
October 30, 2026 06:13
3500d19 to
e34a8d2
Compare
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-10
branch
from
October 30, 2026 06:13
18e317b to
57b3419
Compare
shuhuayu
added a commit
that referenced
this pull request
Oct 30, 2026
#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.
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-09
branch
from
November 3, 2026 23:39
e34a8d2 to
7f4806d
Compare
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-10
branch
from
November 4, 2026 00:13
57b3419 to
116aa5c
Compare
shuhuayu
added a commit
that referenced
this pull request
Nov 4, 2026
…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 |
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-09
branch
from
November 5, 2026 01:50
7f4806d to
a26e109
Compare
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-10
branch
2 times, most recently
from
November 5, 2026 07:13
0b192b7 to
e781420
Compare
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-09
branch
from
November 5, 2026 07:13
a26e109 to
99280bc
Compare
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-10
branch
from
November 5, 2026 08:50
e781420 to
f49f4c6
Compare
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-09
branch
from
November 5, 2026 08:50
99280bc to
6125066
Compare
shuhuayu
added a commit
that referenced
this pull request
Nov 5, 2026
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.
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-10
branch
from
November 5, 2026 19:40
f49f4c6 to
943bbf0
Compare
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-09
branch
from
November 5, 2026 19:40
6125066 to
03fc764
Compare
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-10
branch
from
November 6, 2026 01:27
943bbf0 to
cf13208
Compare
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-09
branch
from
November 6, 2026 01:27
03fc764 to
c2eda21
Compare
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-10
branch
from
November 6, 2026 01:34
cf13208 to
e379f5d
Compare
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-09
branch
5 times, most recently
from
November 10, 2026 08:54
c675212 to
5bd8799
Compare
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-10
branch
from
November 10, 2026 09:00
e379f5d to
a04a52c
Compare
…first backward Kimi K3's full-scale PP runs need driver-visible free memory for buffers allocated outside PyTorch's caching allocator. AttnResPipelineStage now calls torch.accelerator.empty_cache() once per local stage, before its first training backward, returning blocks cached by startup and the first forwards. Eval does not consume the release, and later backwards and accelerator graph replay pay nothing. Numerics are unchanged.
shuhuayu
force-pushed
the
shuhuayu/k3-dm-stack-10
branch
from
November 10, 2026 09:21
a04a52c to
36b539c
Compare
Contributor
Author
|
Closing. On reflection this change does not save memory, and there is no evidence it is needed:
If a non-PyTorch allocation failure in the first backward shows up, this can come back as a small K3-only change with that failure as evidence. |
shuhuayu
added a commit
that referenced
this pull request
Nov 10, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
this approach, and what you checked yourself. -->
Part **9/n** of the Kimi K3 training stack. Based directly on `main`; it
does
not depend on 5/n-7/n and can land independently.
## Why
`materialize_mla_kv` builds per-head K/V from the packed `wkv_b` output
and the
shared rotary key. In eager it runs as strided `torch.cat` copies
(forward K and
backward packed-KV gradient), which take the slow non-vectorized
`CatArrayBatchedCopy` path. At Kimi K3 recipe shapes this costs **767 us
per MLA
layer (fwd+bwd)**; compiling the same function brings it to **234 us**,
bitwise
identical to eager.
**Example.**
```text
T=4096 tokens/rank, 96 heads, nope=128, rope=64, v=128 (Kimi K3)
eager: split(kv) -> expand(k_shared) -> cat # strided cat, fwd + bwd
767 us fwd+bwd per MLA layer
mla_kv: one fused Triton kernel fwd, one fused kernel bwd (+ k_shared sum)
234 us fwd+bwd per MLA layer, outputs and grads bitwise == eager
```
## What changed
- `mla.py`: register `materialize_mla_kv` as the `mla_kv` local-compile
region
(`batch_invariant=True`). The function body is unchanged; only the
decorator is added.
- `kimi_k3/model.py`: enable `mla_kv` in Kimi K3's default local-compile
regions.
- `test_mla_attention.py`: new `TestMLAKVLocalCompile` class, 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-gather
stays async and keeps overlapping the `wkv_b` projection.
## Alternatives considered
- Return V as a contiguous copy (as #5564 does) so attention's saved V
does not
keep the K-nope half of `kv_THP` alive. Measured per MLA layer at
T=4096: it
saves 96 MiB without CP (803 -> 707 MiB held) but costs 96 MiB under
Ulysses
CP2 (577.5 -> 673.5 MiB), because attention's saved `q` view keeps the
shared
all-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.
- Enable `mla_kv` for DeepSeek V3 / Kimi K2.7 as well: the region is
model-agnostic and bitwise, but only K3 shapes were measured here. Left
as a
one-line follow-up.
## User-facing changes
| Before | After |
| --- | --- |
| MLA K/V assembly always eager | `mla_kv` region; on by default for
Kimi K3 |
## Numerics
Component-level, bitwise (`rtol=0, atol=0`):
| Check | Hardware | Result |
| --- | --- | --- |
| Compiled `mla_kv` vs eager: K, V, packed-KV grad, `k_shared` grad | 1x
GB300 | identical |
| Ulysses CP2 (async `k_shared` all-gather, as on main) with compiled
`mla_kv`: output, loss, all input/param grads vs eager | 2x GB300, NCCL
| identical (one-off check, not added as a test) |
No 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):
| | eager | `mla_kv` |
| --- | --- | --- |
| per MLA layer | 767 us | 235 us |
| saved per MLA layer | | **532 us (3.3x)** |
| saved per microbatch, all 24 MLA layers | | **~12.8 ms** |
| saved per microbatch per rank (PP4: ~6 MLA layers) | | **~3.2 ms** |
Kernel 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_shared`
grad 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
```bash
CUDA_VISIBLE_DEVICES='' python -m pytest -q \
tests/unit_tests/cpu/models/common/test_cp_attention.py \
tests/unit_tests/cpu/models/kimi_k3/test_kimi_k3_config.py # 57 passed
CUDA_VISIBLE_DEVICES=0,1,2,3 python -m pytest -q \
tests/unit_tests/gpu/models/common/test_mla_attention.py # 3 passed on 4 GPUs
```
`test_compiled_matches_eager_bitwise` catches any numerics change from
compiling the region. The async-collective gradient path is covered by
#5886's tests. Pre-commit passes on the changed files.
## Known issues / follow-ups
- Overlaps the open draft
[#5564](#5564)
on the `mla_kv` decorator and the K3 region list (#5564 also copies V;
see
Alternatives considered).
- 10/n (#5683) is still stacked on this branch and needs restacking onto
`main`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary (human-written)
Why
Full-scale Kimi K3 pipeline training needs free memory that the driver can see, for buffers allocated outside PyTorch's caching allocator (communication and expert-dispatch buffers). Startup and the first forwards leave blocks in PyTorch's cache that those allocators cannot use.
Example. Kimi K3, PP=2, Interleaved1F1B (two local stages per rank), 4 microbatches:
What changed
AttnResPipelineStage.backward_one_chunk(torchtitan/models/kimi_k3/pipeline_parallel/stage.py) callstorch.accelerator.empty_cache()once per local stage, before that stage's first training backward. Forward-only eval does not consume it. The first backward always runs in an eager step (accelerator graphs capture afterNUM_ACCELERATOR_GRAPH_WARMUP_STEPS = 2warmup steps), so the release never runs under capture.This is K3-only and always on for K3 PP runs. No config field, core stage class, or core change.
Alternatives considered
ParallelismConfigflag with a corePipelineStagesubclass (an earlier version of this PR): K3 is the only consumer and already owns its stage class, so core and the experiment backends would carry a knob for one model.Numerics
empty_cache()only returns unused cached blocks to the driver; it does not change computation. Kimi K3 debugmodel, PP=2 Interleaved1F1B, 4 microbatches, AdamW, seed 42,deterministic=True, 10 steps on 2 GPUs, with the release on vs. replaced by a no-op:On the debug model the release frees 20-60 MiB per stage; the benefit is at full scale.
Testing
tests/unit_tests/cpu/models/kimi_k3/: 21 passed.test_cache_is_released_once_before_the_first_training_backwardcatches the release silently running on every backward (a hot-path regression).pre-commitclean on the changed files.