Skip to content

[distributed] Keep grads of async collective inputs to local_compile regions - #5886

Merged
fegin merged 1 commit into
mainfrom
fegin/stack/15
Nov 9, 2026
Merged

fegin merged 1 commit into
mainfrom
fegin/stack/15

Conversation

@fegin

@fegin fegin commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Stacked PRs:


[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

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.

@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 6, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 6, 2026
@fegin

fegin commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

@claude review this pr

@claude

claude Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @fegin's task in 3m 58s —— View job


Approve -- please address the docstring wording and the numerics evidence before merging: 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 items below before merging. The bug is real, local_compile is the right layer to work around it, the fix is small, and the TODO links upstream. The open items are the docstring's account of the bug and the numerics evidence.

What this PR does. Every compiled callable that local_compile hands out (named regions and the always-compiled helpers such as _compiled_flex_attn and create_block_mask) is now wrapped. If a top-level argument is an un-awaited AsyncCollectiveTensor, the wrapper awaits it with a pass-through autograd.Function before the compiled call. The wait now produces a tensor that has a grad_fn back to the ACT. Before, the compiled graph saw a grad-less inner tensor.

Example.

x = spmd_redistribute_per_axis(emb, ..., async_op=True)   # ACT, requires_grad=True
y = compiled_region(x)       # AOTAutograd unwraps x via trigger_wait() -> requires_grad=False
y.sum().backward()
before: emb's producer (tok_embeddings.weight) gets grad None
after:  x -> _WaitAsyncCollective -> plain tensor with grad_fn; the grad reaches tok_embeddings

Eager regions, and inputs that aren't ACTs, take the same path as before.

Must fix

  1. torchtitan/distributed/local_compile.py:39-48 -- the docstring and TODO blame Dynamo, but the drop happens in AOTAutograd's trigger_wait() unwrap. They also give the wrong reason for the top-level-only check. Suggested wording is inline.
  2. PR description, Numerics -- the description says Muse Spark's loss changes but shows no comparison. Add a short before/after of loss and grad_norm for Muse Spark at TP2 with local compile on, plus a check that tok_embeddings now has a nonzero grad. Also, "Other parameters get the same grads" may be too broad. In cp_mla.py:120-143, q_THK is a torch.split view of an async all-to-all, which is still an ACT. It reaches the always-compiled _compiled_flex_attn at top level, so CP MLA with the Flex backend probably changes numerics too (q-projection grads come back). Either confirm that path, or limit the claim to the configs you checked. The DeepSeek V3 CP golden uses attn_backend="varlen", so it shouldn't move.
Details
  • Necessity: the problem is real. Module._redistribute_inputs/_redistribute_outputs (models/base/module.py:580,626) use async_op=True, and the compiled regions take those tensors directly. The cause is upstream (pytorch/pytorch#179849's unwrap, with a fix in flight in #191113). Doing the wait in local_compile, not in Module, keeps comm overlap at eager boundaries. Waiting at region entry costs no overlap compared with before, because AOTAutograd already waits on top-level ACTs at entry.
  • Top-level only: Dynamo turns every tensor graph input into a top-level AOT input, so an ACT nested in a list or tuple argument would hit the same bug. I checked current region signatures (kimi_k3 attention_residual, fp32_to_bf16_split, rope, norm, loss, flex), and all of them take tensors at top level. Current code doesn't need a tree_map_only.
  • Test: it guards a silent grad drop with no other test coverage, it's cheap, and it extends an existing file. No change needed.
  • This touches core torchtitan/distributed/, so a maintainer still needs to review.

Not verified: that torch.split and transpose views keep the ACT wrapper on the CP MLA Flex path in the pinned PyTorch, and that AOTAutograd is the layer doing the unwrap in that version. I couldn't run torch or GPUs here.

Comment on lines +39 to +48
"""Pass compiled regions plain tensors instead of un-awaited collectives.

Module-boundary redistributions return ``AsyncCollectiveTensor``s. Dynamo
traces such an input with the inner tensor's ``requires_grad=False``, so the
compiled region's output has no grad path back to the collective input.
Only top-level arguments are checked because Module redistributes only
top-level tensors.
TODO(pytorch/pytorch#191113): Remove once Dynamo traces an
``AsyncCollectiveTensor`` input with the wrapper's autograd state.
"""

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.

The docstring gets two things wrong, and whoever removes this workaround will rely on it:

  1. Which layer drops the grad. Preserve requires_grad when unwrapping ACT inputs in process_inputs pytorch#191113 puts the drop in AOTAutograd, not Dynamo: process_inputs unwraps top-level ACT inputs with trigger_wait() (added in Unwrap AsyncCollectiveTensor inputs before AOT autograd tracing and at runtime pytorch#179849), and that returns the inner .elem without requires_grad. The TODO's removal condition ("Dynamo traces ... with the wrapper's autograd state") names the wrong component. Also, #191113 is a PR, not an issue (the PR description says "issue" too).
  2. Where ACTs come from. They don't only come from Module boundaries. cp_mla.py:105-135 also calls spmd.redistribute(..., async_op=True) directly, and torch.split keeps its views wrapped as ACTs. So q_THK reaches _compiled_flex_attn as an ACT. The top-level-only check still covers that case, but "because Module redistributes only top-level tensors" isn't the real reason. The real reason is that no current region receives an ACT inside a container.

Suggested wording:

Suggested change
"""Pass compiled regions plain tensors instead of un-awaited collectives.
Module-boundary redistributions return ``AsyncCollectiveTensor``s. Dynamo
traces such an input with the inner tensor's ``requires_grad=False``, so the
compiled region's output has no grad path back to the collective input.
Only top-level arguments are checked because Module redistributes only
top-level tensors.
TODO(pytorch/pytorch#191113): Remove once Dynamo traces an
``AsyncCollectiveTensor`` input with the wrapper's autograd state.
"""
"""Pass compiled regions plain tensors instead of un-awaited collectives.
Async redistributions (Module boundaries, CP MLA) return
``AsyncCollectiveTensor``s. AOTAutograd unwraps such an input with
``trigger_wait()``, which returns the inner tensor without
``requires_grad``, so the compiled region's output has no grad path back to
the collective input. Only top-level arguments are awaited; no region
currently receives an async collective inside a container.
TODO(pytorch/pytorch#191113): Remove once AOTAutograd keeps the
``requires_grad`` of an unwrapped ``AsyncCollectiveTensor`` input.
"""

@fegin
fegin marked this pull request as draft November 6, 2026 18:23
@fegin
fegin changed the base branch from fegin/stack/14 to main November 6, 2026 18:23
@pytorch-bot pytorch-bot Bot added ciflow/rl and removed ciflow/fake-pg Run 1-GPU Fake PG integration tests labels Nov 6, 2026
@fegin
fegin changed the base branch from main to fegin/stack/14 November 6, 2026 18:24
@fegin
fegin marked this pull request as ready for review November 6, 2026 22:27
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 6, 2026
@tianyu-l
tianyu-l requested a review from anijain2305 November 8, 2026 05:41

@tianyu-l tianyu-l 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.

please address comments

)

def bind_compile(config: LocalCompileConfig) -> None:
nonlocal fn

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.

maybe it was missed in previous code reivew

  • is this used at all?

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.

Not in our code base, but this exists to provide an extension for 3rd party users who want to use a different compiler backend.

**compile_kwargs: Any,
) -> Callable[..., Any]:
"""Create an always-compiled helper controlled by ``LocalCompileConfig``."""
fn = LocalCompileConfig()._compile(reference, **compile_kwargs)

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.

we don't need this line anyway?

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.

We need this only if we need bind_compile.

raise ValueError("local_compile requires fullgraph=True.")

def decorate(reference: Callable[..., Any]) -> Callable[..., Any]:
fn = reference

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.

do we need this line?

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.

Yes, we need this. wrapped either calls reference or compiled reference. But compiled reference doesn't exist when decorate is called -- it is later applied when parallelize() is called. So we need a fn, a placeholder to keep the actual callable. In the beginning, it refers to reference, and if it is configured to be compiled, fn will refer to compiled reference. fn is used by wrapped.

fn = reference

def bind_local_compile(config: LocalCompileConfig) -> None:
nonlocal fn

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.

can we directly use reference here?

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.

No, see the reply for line 123.

@tianyu-l

tianyu-l commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

@claude review my review

@claude

claude Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 0s —— View job


Approve -- 1 of 4 review comments is partly right (a pre-existing design question for a separate PR), the other 3 point at lines the code needs, and 2 earlier must-fix items are still open: 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 items below before merging. Of @tianyu-l's four comments, one is partly right and is a pre-existing design question that belongs in its own PR. The other three point at lines that the code needs. The two items from the earlier bot review are still open at HEAD.

What this PR does. Every compiled callable that local_compile hands out is wrapped, so a top-level AsyncCollectiveTensor argument is awaited through an autograd Function before the compiled call. Without the wrapper, the compiled region drops the grad edge back to the input.

Example. This is how the fn indirection that several comments ask about works:

_compiled_flex_attn = compile(flex_attention)   # import time: returns `wrapped`, fn = compiled (line 156)
...
model.parallelize(local_compile=cfg)            # base/model.py:167 -> cfg.apply() -> bind_compile(cfg) rebinds fn (line 162)
_compiled_flex_attn(q, k, v)                    # wrapped -> current fn

Callers keep the wrapped object they imported, so turning a region on or off has to go through the rebindable fn.

On tianyu-l's comments

  1. local_compile.py:161 "is this used at all?" -- Partly correct. In the repo, no production code subclasses LocalCompileConfig. So bind_compile only rebuilds the same torch.compile it already had. It does have a consumer: the documented out-of-tree _compile hook (local_compile.py:79-82). test_custom_config_controls_all_torchtitan_compile_boundaries (test_compile_config.py:209-235) checks that flex attention and both create_block_mask helpers get rebound with the custom backend, and the new test relies on the same path. The code predates this PR, so dropping it is its own change. That change would remove the out-of-tree backend hook and delete bind_compile, _ALWAYS_COMPILE_CALLBACKS, apply() lines 99-100, and that test. Keep it here.
  2. Old line 109 (now 156-158) "we don't need this line anyway?" -- Mistaken. compile() runs at import time (attention.py:641,982, vision_encoder.py:40), and apply() only runs from parallelize. Deleting the line is a SyntaxError: nonlocal fn at 161 needs a binding in the enclosing scope. Changing it to fn = reference would run flex attention and create_block_mask eagerly (unfused, much more memory) on any path that never calls apply(). That is a silent slow fallback. The line keeps the "always compiled" contract.
  3. Line 123 fn = reference "do we need this line?" -- Mistaken. It's required for the same two reasons. Without it, nonlocal fn at 126 has nothing to bind to. It also gives the documented default: before apply(), or when the region isn't in regions, the function runs eagerly.
  4. Line 126 "can we directly use reference here?" -- Mistaken if it means having wrapped call reference directly. Callers hold wrapped from decoration time, so the compiled version could never be installed. The disabled branch (line 139) already sets fn = reference, which is the only place reference fits.

Still open from the earlier review

  • local_compile.py:39-48 -- the docstring and the TODO still say Dynamo drops the grad, and they still explain the top-level-only check with Module boundaries. See the suggested wording in the earlier inline comment.
  • PR description, Numerics -- there is still no loss/grad_norm before/after for Muse Spark at TP2 with local compile. The "other parameters get the same grads" claim still needs to be checked or narrowed, because CP MLA + Flex q_THK is likely an ACT.
Details
  • The fix touches three sites (lines 135, 156, 162), all of the form _wait_async_collective_inputs(<config>._compile(...)). Putting the wrap inside _compile would be wrong, because out-of-tree overrides would skip it. The current placement is correct.
  • This touches core torchtitan/distributed/. A maintainer approval is already on the PR.

Not verified: I couldn't fetch inline-comment anchors, so I read lines 123/126 as new-file lines (fn = reference, nonlocal fn). If they were meant for other lines, items 3-4 may not apply.

@fegin
fegin marked this pull request as draft November 9, 2026 08:40
@fegin
fegin changed the base branch from fegin/stack/14 to main November 9, 2026 08:40
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 9, 2026
@fegin
fegin changed the base branch from main to fegin/stack/13 November 9, 2026 08:41
@fegin
fegin marked this pull request as ready for review November 9, 2026 08:41
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 9, 2026
fegin added a commit that referenced this pull request Nov 9, 2026
Stacked PRs:
 * #5904
 * #5895
 * #5894
 * #5893
 * #5892
 * #5891
 * #5890
 * #5889
 * #5888
 * #5887
 * #5885
 * #5886
 * __->__#5884


--- --- ---

### [lora] Derive adapter sharding from the base weight


## Summary (human-written)
The current LoRA adapter assumes the sharding of the base weights to be
`{DP: R, CP: R, TP: S(0)}` or ` {DP: R, CP: R, TP: S(1)}`. This is not
always true. For example, if we apply LoRA to the vision encoder, the
sharding is not the same.

This PR fixes the issue by deriving adapter sharding from the base
weight

## Why
On main, LoRA adapter sharding accepts only a base weight equal to
dense_param_placement(tp=S(0)) or dense_param_placement(tp=S(1)). Any
other base placement fails at model build. This blocks LoRA on vision
linears (CP-invariant, cp=I), TP-invariant vision adapters and
projections (tp=I), and TP-replicated router gates (tp=R).

**Example.**
```
LoRATransform(target_modules=["vision_encoder.block.mlp.fc1"])  # Muse Spark, base weight {dp: R, cp: I, tp: S(0)}
before: AssertionError at build (placement is not dense_param_placement(tp=S(0)))
after:  lora_a {dp: R, cp: I, tp: R}, lora_b {dp: R, cp: I, tp: S(0)}
```

## What changed
- Adapters copy the base weight placement and change only the TP axis.
Other axes, such as cp=I on vision weights, are kept.
  - Column-wise base: A is TP-replicated, B is sharded like the base.
  - Row-wise base: A is sharded like the base, B is TP-replicated.
- TP-replicated or TP-invariant base (R, I), or no TP axis: both
adapters copy the base.
  - Any other TP type (another Shard, P, V) raises ValueError.
- Stacked projections ([num_linears, O, I]) use the same rule, with the
output dim at 1. The separate stacked code path is removed.

## Numerics
Unchanged for the bases main supports: the adapter placements for dense
column-wise and row-wise bases, and for stacked column-wise bases, are
the same as on main. No loss comparison was run.

## Testing
- 2-rank CPU test with SPMD type checking: LoRA output and adapter grads
of a Spark-style vision MLP and vision adapter at TP2 match TP1 (fp32,
atol=rtol=1e-4). It catches wrong adapter placements on non-dense bases.
- CPU tests at this commit:
tests/unit_tests/cpu/models/common/test_lora.py, 32 passed.
…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.

stack-info: PR: #5886, branch: fegin/stack/15
@fegin
fegin marked this pull request as draft November 9, 2026 17:23
@fegin
fegin changed the base branch from fegin/stack/13 to main November 9, 2026 17:23
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 9, 2026
@fegin
fegin marked this pull request as ready for review November 9, 2026 17:25
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 9, 2026
@fegin

fegin commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Updated: the docstring now says AOTAutograd drops the grad (trigger_wait() in process_inputs) and the TODO points to the open issue pytorch/pytorch#201700 (#191113 was closed unmerged). Numerics are measured: Muse Spark debug TP2 with local compile, tok_embeddings grad goes from None to nonzero and the other 225 grads are bitwise equal; DeepSeek V3 CP2 + Flex (both MLA backends) is bitwise unchanged, since no async collective reaches a compiled region there (the Q/KV all-to-all is synchronous). The description lists exactly the configs checked.

@fegin
fegin merged commit 8a33dbf into main Nov 9, 2026
@claude claude Bot mentioned this pull request Nov 9, 2026
6 tasks
shuhuayu added a commit that referenced this pull request Nov 10, 2026
Register materialize_mla_kv as the mla_kv local-compile region and enable it
for Kimi K3. Eager runs the K/V assembly as strided cat copies; the compiled
region is 3.3x faster at K3 shapes and bitwise identical to eager. When
compiling with grad, return V as a copy so attention's saved V does not keep
the K-nope half of the packed KV alive. Ulysses CP needs no change: #5886
already keeps gradients of async collective inputs to local-compile regions.
shuhuayu added a commit that referenced this pull request Nov 10, 2026
Register materialize_mla_kv as the mla_kv local-compile region and enable it
for Kimi K3. Eager runs the K/V assembly as strided cat copies; the compiled
region is 3.3x faster at K3 shapes and bitwise identical to eager. When
compiling with grad, return V as a copy so attention's saved V does not keep
the K-nope half of the packed KV alive. Ulysses CP needs no change: #5886
already keeps gradients of async collective inputs to local-compile regions.
shuhuayu added a commit that referenced this pull request Nov 10, 2026
Register materialize_mla_kv as the mla_kv local-compile region and enable it
for Kimi K3. Eager runs the K/V assembly as strided cat copies; the compiled
region is 3.3x faster at K3 shapes and bitwise identical to eager. Ulysses CP
needs no change: #5886 already keeps gradients of async collective inputs to
local-compile regions.
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`.
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.

2 participants