Skip to content

[mla][perf] Compile MLA's key/value build as the mla_kv region - #5564

Draft
felipemello1 wants to merge 1 commit into
mainfrom
felipemello1/muse-followups/2-mla-kv-region
Draft

felipemello1 wants to merge 1 commit into
mainfrom
felipemello1/muse-followups/2-mla-kv-region

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

Written with Claude Code: the analysis, measurements and test plan below.

TLDR: materialize_mla_kv, the k/v build shared by DeepSeek-V3 and Kimi K3 MLA, becomes the mla_kv local-compile region, which fuses the eager concat kernels. Two DeepSeek-V3 layers at 16k: -2.6% wall, -2.7% under CUDA graphs, -1.07 GB peak (2 layers, no activation remat). Outputs are bitwise; grads are bitwise except k_shared's, a sum over heads in Inductor's order (1 bf16 ulp on 1 of 1,048,576 elements under some configs). UlyssesMLAAttention now all-gathers k_shared synchronously, so the region keeps k_shared's grad.

main:     kv -> split -> k_nope, v (a view of kv);  k = cat(k_nope, k_shared on every head)   eager cat; bwd: eager cat
this PR:  region(kv, k_shared) -> k, v (dense when grad is on)                                Triton copies; bwd: one copy + head sum

Based on main; no dependency on other open PRs.

Problem

  1. Shared k/v build. MLAAttention builds per-head k and v in materialize_mla_kv, from packed kv [T, H, 256] and the shared key [T, 64].
  2. Eager copies. It splits kv into k_nope and v, broadcasts the shared key to all heads, and concatenates k = [k_nope, k_shared] [T, H, 192].
  3. Slow kernels. Both concats run ATen's generic cat kernel: k's 1552 us vs 189 us at full memory bandwidth (8x), the backward's 1940 vs 302 us (6.4x).
  4. Cost. 3.55 ms per DeepSeek-V3 layer at 16k, fwd+bwd kernel time (ideal 0.53 ms).

Solution

  1. Region. materialize_mla_kv is now the mla_kv region. Inductor fuses split, broadcast and concat into one copy kernel, and the backward concat into another.
  2. Dense v when grad is on. Attention saves v, and a v that views kv keeps all of kv alive. A dense v lets kv go after the forward: -0.54 GB per MLA layer at 16k without activation remat. Under compile the copy is free: it replaces the backward's copy of v's grad.
  3. Ulysses CP. UlyssesMLAAttention all-gathered k_shared with async_op=True. A compiled region detaches an unwaited async input, so k_shared's grad came out all zeros under mla_kv. The all-gather is now synchronous. The gathered k_shared is [T, 64] (2 MB at 16k in bf16); the overlap it loses was not measured.
  4. Enabled in DeepSeekV3Model.Config (Kimi K2.x inherits it) and KimiK3Model.Config.
  5. Unchanged: the function's signature and how both callers call it (MLAAttention.forward, also used after the CP all-gather, and UlyssesMLAAttention.forward). no_grad keeps the view.

Results

Numerics: bitwise except one grad. Outputs, k, v and kv's grad are copies: bitwise vs main under every autotune config.
          k_shared's grad sums over heads in Inductor's order, not ATen's: 1 of 1,048,576 elements is 1 bf16 ulp
          off under some reduction configs (op level, DeepSeek-V3 dims).
          rel L2 vs fp64, k_shared grad:  main 1.656e-3 | this PR 1.656e-3
          DeepSeek-V3, 2 layers:  output and all grads bitwise vs main in every run below
          Kimi K3, 2 layers:      output bitwise; grads 5.6e-3 rel L2 vs main, same as main vs main (its backward is nondeterministic)
          Batch invariant in deterministic mode: full batch vs uneven chunks, k, v and both grads bitwise.

Measured on main of 10-20 + this change. That tree's gate also checked is_compiling(); the compiled path is the same, so these rows hold.
DeepSeek-V3 671B layers 2-3 (dense FFN + MoE at one EP8 rank's shapes, 32 experts), native dims, flex attention,
no activation checkpointing except the remat rows, 1x GB300, ms per 2-layer step;
median of 5 fresh processes (16k train), else 1 process
mode                     T     main      this PR  delta
train fwd+bwd            16k   177.48    172.89   -2.6%
train CUDA graphs        16k   176.96    172.22   -2.7%
train fwd+bwd            4k     41.05     39.60   -3.5%
train CUDA graphs        4k     39.36     38.32   -2.6%
train, activation remat  16k   194.82    188.01   -3.5%   (DefaultActivationRematConfig, the 671B recipe's)
prefill no_grad          16k    51.02     48.85   -4.3%
peak memory              16k    34.20     33.13 GB
peak memory, remat       16k    30.38     29.84 GB         (kv is kept for the replay, so the saving is transient)
train 32k: not run (the region's copies are per token, so the 16k delta should scale)

Kimi K3 layers 50 (KDA + MoE) + 51 (MLA + MoE), one EP8 rank's experts, varlen, no AC, 16k, median of 3 processes
train fwd+bwd            16k   215.35    213.25   -0.7%   (median of per-process deltas)
train CUDA graphs        16k   214.47    211.98   -1.2%   (2 processes)
peak memory              16k    73.89     73.48 GB

k/v build alone, kernel time per MLA layer, 16k, us
DeepSeek-V3 fwd+bwd   3550 -> 737   (ideal 530; 680 with the dense-v copy)
DeepSeek-V3 no_grad   1552 -> 218
Kimi K3 fwd+bwd       2682 -> 617

graphs: mla_kv 3 over T = 2k/4k/8k/16k + no_grad (static T, dynamic T, no_grad), limit 8; cold compile ~+1 s (first call, caches off)

Results, varlen at the 671B recipe's microbatch (GB300)

DeepSeek-V3 671B layer 3 (MLA + MoE; one EP2 rank's 128 experts, router at full width), varlen attention on FA4
(cuDNN SDPA off: cuDNN varlen overflows int32 at 64k with MLA's head dims), DefaultActivationRematConfig (the 671B
recipe's), T = 65536 (4 x 16384, the recipe's microbatch), 1x GB300, main and this PR back to back on one GPU,
one run each, fwd+bwd, CUDA-graph replay
mode               T     main        this PR     delta
train fwd+bwd      64k   312.6 ms    300.3 ms    -3.9%
peak memory        64k   79.1 GiB    77.1 GiB    -2.0 GiB   (dense v frees kv)

k/v build kernels, one profiled step per arm, us
eager k build, CatArrayBatchedCopy: forward + remat replay          16176 (2 calls) -> 0
fused k build (split + broadcast + cat)                             0 -> 1905 (2 calls)
dense v copy (grad on)                                              0 -> 1258 (2 calls)
backward: one cat 1289 + head sum 166; removed: strided copies 1235, bf16 head-sum reduce 234
net, k/v build only: -13.0 ms (4.2% of main's step)

The two profiled processes differ by +6 ms in kernels this PR doesn't touch (MoE indexing_backward +2.6 ms, grouped GEMMs +0.8 ms), so their replay times show -2.3% (306.6 -> 299.6 ms). The k/v-build kernel delta above doesn't depend on that noise.
Rebased on main 9f70e55 (clean): test_mla_compile.py, test_mla_remat.py, test_cp_attention.py, deepseek_v3/, kimi_k3/, muse_spark/ CPU tests: 125 passed, 3 xfailed.

Decode: not reached in the RL generator, which runs vLLM's native MLA. The exception is batch-invariant mode, whose only MLA configs (the Kimi K3 RL tests) set regions [].

You may ask: why a dense v in eager too? Same memory reason, one code path instead of an eager/compiled fork. Measured 10-19 on the same split + copy, before it moved into materialize_mla_kv (2 DeepSeek-V3 layers at 4k): eager +0.2-0.3%, GraphTrainer +0.3-0.8% kernel time.
You may ask: why not a dense v under no_grad? Nothing is saved for backward, so it's only a copy: +0.44 ms wall on the 16k prefill (2 layers; two 155 us clones).
You may ask: why not always the view? Same time without activation checkpointing, but +0.54 GB per MLA layer at 16k without activation remat. Under activation remat the forward copy replays: +0.16 ms per layer (0.2%).
NOTE: the region is on in the recipes that keep the model's default regions: deepseek_v3_671b, deepseek_v3_671b_dist_moe_bf16, deepseek_v3_671b_dist_moe_mxfp8, the Kimi K2.x / K3 model configs (debugmodel test recipes), and rl_grpo_deepseek_v3_debug (the H100 RL integration test, 4 GPUs: its trainer runs the region, its generator runs vLLM's native MLA). That RL test is the PR's only GPU end-to-end coverage.
NOTE: the region is off in deepseek_v3_671b_nvfp4_ffn_mxfp8_attn (regions ["loss"]), GraphTrainer and SPMD-typechecking configs (regions []), the Kimi K3 RL test configs ([]) and the fused_mla override (it skips materialize_mla_kv). With grad on, these still return a dense v (cost in "You may ask").
NOTE: Ulysses CP: q keeps the packed q/kv buffer alive, so there a dense v adds [T, H/cp, 128] per MLA layer instead of saving memory. No recipe uses Ulysses MLA.
NOTE: goldens: the fake-PG A10G DeepSeek-V3 golden is unchanged (bitwise; the region is on there). The real-PG CP+PP goldens (A10G, mi350x) get refreshed if they move. The Kimi K3 B200 golden runs with typechecking, so regions are off there.
NOTE: not tested: multi-GPU TP and CP, loss curve. Varlen DeepSeek-V3 (the 671B recipe's default backend): see "Results, varlen at the 671B recipe's microbatch" above.

Test plan

  • pytest tests/unit_tests/cpu/models/common/test_mla_compile.py: 3 passed.
    • region vs eager for the projected and Ulysses input layouts, v dense with grad on. Fails before: eager v is a view, and mla_kv is not a region.
    • UlyssesMLAAttention.forward on a 1-rank gloo CP group (an SDPA stand-in for FlexInnerAttention, whose compiled flex doesn't build on every CPU): every input and weight grad under mla_kv matches eager. Fails without the cp_mla.py change: k_shared's grad is all zeros.
  • pytest tests/unit_tests/cpu/models/common/test_mla_compile.py tests/unit_tests/cpu/models/common/test_mla_remat.py tests/unit_tests/cpu/models/common/test_cp_attention.py tests/unit_tests/cpu/models/deepseek_v3/ tests/unit_tests/cpu/models/kimi_k3/: 96 passed.
  • Core CPU (tests/unit_tests/cpu/models/common, muse_spark, kimi_k3, deepseek_v3, recipes): 497 passed, 3 failed (main's 3). RL CPU: 504 passed, 1 failed (main's alphabet_sort).

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 20, 2026
@felipemello1
felipemello1 added this pull request to stack #5499 October 20, 2026 09:15
@felipemello1 felipemello1 added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 20, 2026
@felipemello1
felipemello1 force-pushed the felipemello1/muse-followups/2-mla-kv-region branch 2 times, most recently from b8324c7 to d5eda0f Compare October 20, 2026 15:56
@felipemello1
felipemello1 force-pushed the felipemello1/muse-followups/1-qkv-split-in-region branch from 3e5f59a to 262ae6d Compare October 29, 2026 20:50
@felipemello1
felipemello1 force-pushed the felipemello1/muse-followups/2-mla-kv-region branch from d5eda0f to 97695c4 Compare October 29, 2026 20:50
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 1s —— View job


Approve -- see the review (one optional test suggestion; a maintainer still needs to review).

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- a small change that follows the existing local_compile pattern (mla_qk), with measured end-to-end wins and bitwise outputs. A maintainer still needs to review because it touches models/common/.

What this PR does. It decorates materialize_mla_kv (shared by DeepSeek-V3, the Kimi K2.x models that inherit its config, and Kimi K3, including both CP variants) as the mla_kv local-compile region, and enables that region in both model configs. It also makes v dense when grad is on, so attention no longer saves a view that keeps the whole [T, H, N+V] kv alive.

Example. One DeepSeek-V3 MLA layer at T=16k, grad on:

before: k_nope, v = split(kv)            # v is a view of kv
        k = cat(k_nope, expand(k_shared)) # eager CatArrayBatchedCopy
        attention saves v -> kv [T,H,256] stays alive until backward
after:  one Inductor copy builds k and a dense v
        attention saves the dense v -> kv freed after forward (-0.54 GB/layer)
        no_grad: v is still a view (nothing is saved, so no copy)

Should consider

  • tests/unit_tests/cpu/models/common/test_mla_compile.py:50 -- the no_grad view assertion pins a perf choice and costs a third CPU compile; consider keeping only the grad-on contiguity assert (inline).
Details
  • Call sites: MLAAttention.forward binds materialize_kv=materialize_mla_kv at def time. That binding is the local_compile wrapper, so the region applies to MLAAttention, to the all-gather CP variant (which calls MLAAttention.forward), and to UlyssesMLAAttention. The fused_mla override passes its own materialize_kv, so it isn't affected, as the description says.
  • torch.is_grad_enabled() inside the region is guarded by Dynamo. That matches the description's 3 graphs (static T, dynamic T, no_grad), which fits under the recompile limit.
  • Remat: recompute_needs_tensor(kv_THP, k_shared_TR) already keeps kv for replay, so with remat on, the dense v changes time (the description measures +0.16 ms per layer) but not peak memory.
  • The test is in the right place (models/common, next to the shared function). The Ulysses parametrization adds real coverage: a non-contiguous kv taken from a packed q/kv tensor.
  • Eager configs (GraphTrainer, RL with regions []) pay the copy of v (+0.2-0.8% kernel time) to get the same memory win. I agree with keeping one code path here.

Not verified: the GPU perf and memory numbers, and the golden-loss impact on A10G/mi350x (integration runs are still queued). The CPU Unit Test workflow was skipped on this stacked PR, so test_mla_compile.py has not run in CI yet.

Comment on lines +50 to +51
with torch.no_grad(): # nothing is saved, so v stays a view
assert not materialize_mla_kv(q, kv, leaves[-1])[1].is_contiguous()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: the grad-on v.is_contiguous() check guards a real memory invariant (a view would keep all of kv alive). The no_grad check only pins a perf choice (skip a copy nobody saves), and under ["mla_kv"] it adds a third Inductor compile per parametrization on the CPU runner. Consider dropping these two lines and keeping only the grad-on assert.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reply from claude: keeping it. The no_grad assert is the one that catches an always-dense v: that costs +0.44 ms on the 16k prefill (2 DeepSeek-V3 layers, two 155 us clones) and saves nothing, since nothing is saved for backward. With an always-dense v, the grad-on assert and the eager comparison both still pass; only this assert fails. The file still runs in about 5 s on CPU.

@felipemello1
felipemello1 force-pushed the felipemello1/muse-followups/1-qkv-split-in-region branch from 262ae6d to 45d7c3e Compare October 30, 2026 03:02
@felipemello1
felipemello1 force-pushed the felipemello1/muse-followups/2-mla-kv-region branch from 97695c4 to 45152e0 Compare October 30, 2026 03:02
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: pushed 45152e0. UlyssesMLAAttention all-gathered k_shared with async_op=True, and the mla_kv region detached that unwaited input, so k_shared's grad was all zeros under Ulysses CP. The all-gather is now synchronous, and test_ulysses_mla_grads_match_eager runs the real forward on a 1-rank gloo group (it fails without the fix). Body updated: memory under remat and Ulysses, goldens, provenance. @claude please review

@claude

claude Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 22s —— View job


Approve -- please add a TODO with an upstream issue link for the synchronous all-gather workaround, and check whether kv_THP also reaches mla_kv unwaited at CP > 1 -- see the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- please address the item below before merging -- the new commit fixes a real silent zero-grad under Ulysses CP with the smallest change and adds a test that fails without it. The workaround still needs a TODO that links an upstream issue. A maintainer still needs to review, since this touches models/common/.

What changed since the last review. UlyssesMLAAttention now all-gathers k_shared synchronously (cp_mla.py:107-117). test_cp_attention.py now pins [False, True, True] for the async flags. test_ulysses_mla_grads_match_eager runs the real forward on a 1-rank gloo group and compares every grad under mla_kv against eager. The earlier optional note about the no_grad view assert is settled by the author's reply: only that assert catches an always-dense v.

Example. Ulysses CP with mla_kv on, before this commit:

k_shared = redistribute(k_shared, S(0) -> R, async_op=True)  # AsyncCollectiveTensor, not waited
k, v = materialize_mla_kv(q, kv, k_shared)                   # compiled region gets the unwaited input
                                                             # -> detached, k_shared.grad == 0, no error
after:  sync all-gather -> plain tensor -> grad flows; matches eager

Must fix

  • torchtitan/models/common/attention/cp_mla.py:105 -- the comment describes a PyTorch bug: compile silently detaches an unwaited AsyncCollectiveTensor input. Add a TODO with an upstream issue link so async_op=True can come back once it's fixed (see the inline comment).

Questions

  • Under real multi-rank Ulysses, kv_THP comes from torch.split of the async_op=True all-to-all output (cp_mla.py:121-136). An AsyncCollectiveTensor passes view ops through without waiting, so kv_THP may also reach mla_kv unwaited. The 1-rank test shows kv_c.grad matching eager. Can you confirm that the 1-rank all-to-all really returns an async tensor (and not a short-circuit), so the test covers this path too? If it doesn't, kv's grad may have the same silent zero at CP > 1. Unverified: I couldn't read the installed spmd_types here.
Details
  • Root cause and layer: the fix belongs at the call site because local_compile has no place to wait on inputs generically. Waiting in its wrapped would also be possible, but ACT.wait() returns the inner elem, which would drop autograd too, so that isn't a drop-in. The real fix is upstream, hence the TODO.
  • Overlap loss: the gathered k_shared is [T, 64] (about 2 MB at 16k). The all-gather used to overlap with project_mla_kv and the packed cat. No recipe uses Ulysses MLA, so the unmeasured cost is acceptable.
  • Test placement and cost: tests/unit_tests/cpu/models/common/ mirrors the source tree. The gloo HashStore single-rank group is cheap and guards a silent-grad regression that no other test covers.

Not verified: GPU perf and memory numbers, and the real-PG CP+PP golden impact.

Comment on lines +105 to +106
# Not async: the mla_kv region would detach an unwaited input and drop
# k_shared's grad.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This works around a PyTorch gap: torch.compile takes an unwaited AsyncCollectiveTensor input and silently detaches it, so the grad comes out as zeros with no error. The repo rule for upstream workarounds is a TODO with an issue link. Without one, nobody will know to restore async_op=True once it's fixed. The same silent zero-grad can hit any local_compile region that gets an async collective output as a direct input, so filing it upstream is worth more than this one call site.

Suggested change
# Not async: the mla_kv region would detach an unwaited input and drop
# k_shared's grad.
# TODO(<issue link>): not async -- torch.compile detaches an unwaited
# AsyncCollectiveTensor input, so the mla_kv region would drop k_shared's grad.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reply from claude: applied in a5f3fb7. There's no open PyTorch issue for this; the closest upstream record is pytorch/pytorch#191113 ("Preserve requires_grad when unwrapping ACT inputs in process_inputs"), which describes this exact bug and was closed unmerged. The TODO links that.

@felipemello1
felipemello1 force-pushed the felipemello1/muse-followups/2-mla-kv-region branch from 45152e0 to a5f3fb7 Compare October 30, 2026 03:07
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: on the all-to-all question: spmd_types' shard all-to-all (_AllToAllShard.forward) is a blocking dist.all_to_all followed by torch.cat, at every world size. It accepts async_op but never returns an AsyncCollectiveTensor, and there is no world-size-1 short-circuit for it (the only one is in all_reduce). On the 1-rank gloo group: the all-to-all with async_op=True returns a plain Tensor, and the k_shared all-gather returns an AsyncCollectiveTensor. So the test covers both paths as they run at CP > 1, and q / kv reach mla_kv as plain tensors.

The TODO is in a5f3fb7 (comment-only change). @claude please review

@claude

claude Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 48s —— View job


Approve: the TODO is in, and the all-to-all question is answered. No new problems. See the review. A maintainer still needs to review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- both items from the last review are settled, and the new commit only changes a comment. This touches models/common/, so a maintainer still needs to review.

What changed since the last review. a5f3fb7 adds TODO(pytorch/pytorch#191113) to the synchronous k_shared all-gather (cp_mla.py:105-106). No code changed.

Example. The Ulysses CP path at HEAD:

k_shared = redistribute(S(0) -> R)                  # synchronous: plain tensor, grad flows
packed   = redistribute(S(0) -> S(1), async_op=True) # spmd_types all-to-all blocks anyway -> plain tensor
q, kv    = split(packed)
k, v     = materialize_mla_kv(q, kv, k_shared)      # mla_kv region: all three inputs keep autograd

Earlier items

  • Must fix (TODO with upstream link): resolved. #191113 is a closed, unmerged PR, not an open issue, but it describes this exact bug and gives a future reader the trail to restoring async_op=True.
  • Question (does kv_THP reach mla_kv unwaited at CP > 1?): answered. The author says spmd_types' shard all-to-all is a blocking dist.all_to_all plus torch.cat at every world size and never returns an AsyncCollectiveTensor, so q/kv reach the region as plain tensors. test_ulysses_mla_grads_match_eager compares kv_c.grad against eager. If spmd_types ever makes the all-to-all truly async, that test fails instead of kv's grad going silently to zero.

No new problems found.

Not verified: the spmd_types internals behind the all-to-all answer (the package isn't readable in this checkout), the GPU perf and memory numbers, and the real-PG CP+PP golden impact.

materialize_mla_kv (split packed kv into k_nope and v, broadcast the shared
key to all heads, concat into k) ran eagerly, as CatArrayBatchedCopy kernels
in the forward and in the split's backward. It is now the mla_kv
local_compile region, so Inductor fuses split, broadcast and concat.
With grad on, v is returned dense, so kv is freed after the forward instead
of being kept alive by attention's saved v. Enabled for DeepSeek-V3 (and
Kimi K2.x, whose config inherits it) and Kimi K3.
@felipemello1
felipemello1 removed this pull request from stack #5499 November 7, 2026 06:12
@felipemello1
felipemello1 force-pushed the felipemello1/muse-followups/1-qkv-split-in-region branch from f57974e to b6d0cfb Compare November 7, 2026 06:13
@felipemello1
felipemello1 force-pushed the felipemello1/muse-followups/2-mla-kv-region branch from da24e02 to bbe73d4 Compare November 7, 2026 06:13
@felipemello1
felipemello1 changed the base branch from felipemello1/muse-followups/1-qkv-split-in-region to main November 7, 2026 06:13
fegin added a commit that referenced this pull request Nov 9, 2026
…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.
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 branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant