Skip to content

[Kimi K3] Attention residual: zero initialisation and a recomputing aggregation - #4780

Closed
QIU023 wants to merge 2 commits into
pytorch:mainfrom
QIU023:k3_attnres_recompute
Closed

QIU023 wants to merge 2 commits into
pytorch:mainfrom
QIU023:k3_attnres_recompute

Conversation

@QIU023

@QIU023 QIU023 commented Sep 18, 2026

Copy link
Copy Markdown
Contributor

Summary

Two independent corrections to Kimi K3's attention residual, both in the aggregation that #4025 introduced and both unrelated to parallelism.

The pseudo-query initialisation does not match the report. Section 5 of the Kimi Linear tech report states that all pseudo-query vectors must be initialised to zero, which is what makes the depth softmax start uniform and the residual reduce to a standard residual at step 0. The three residual projections are built with trunc_normal_ at std 0.02 instead.

The aggregation retains more than it needs. _apply_attention_residual keeps two FP32 [T, N + 1, D] intermediates alive until backward, the upcast values and the normalized keys. With activation checkpointing on, which is the default, they are rebuilt during recompute as well, so they set the backward peak.

  • torchtitan/models/kimi_k3/__init__.py: the three residual projections initialise to zero.
  • torchtitan/models/kimi_k3/model.py: _AttentionResidualAggregation, registered as a local autograd Function for SPMD type checking; _apply_attention_residual keeps its signature and becomes a thin call into it.
  • tests/unit_tests/cpu/test_kimi_k3_attention_residual.py: the aggregation against a plain autograd reference, a bfloat16 precision case, the registration, and the initialisation.

Design

The forward unbinds the block stack into per-source views, computes each source's inverse RMS and its score against the query, and forms the depth softmax from those. It saves the score weight, the norm weight, the softmax weights, the scores, the inverse RMS and references to the two inputs. None of the saved statistics carries a hidden-size factor. The backward recomputes one FP32 upcast per source and applies the softmax Jacobian, the score path and the variance path explicitly, accumulating the query gradient as a GEMV per source so the reduction order is fixed.

Both factors of the score weight are upcast before multiplying. Multiplying them in bfloat16 and upcasting the product moves the output by about half a percent at a realistic logit scale, which is larger than the reordering this change introduces.

The Function is registered with register_local_autograd_function. It runs no collective, leaves the token dimension alone, and reduces over the stack and hidden axes, neither of which is sharded; the two parameters are declared TP unsharded. Without the registration the type checker raises in strict mode, which the multimodal cell runs under.

At zero initialisation the scores are zero, the depth softmax is uniform, and the aggregation returns the mean of its sources. The projection still receives a gradient and moves off zero on the first step; the norm weight reaches the loss only through its product with the projection, so it gains one once the projection is nonzero.

Compilation

Nothing here interacts with torch.compile, and the custom Function does not stand in its way.

parallelize_kimi_k3 calls torch.compile nowhere today, so this path does not exist for Kimi K3 as the tree stands. The change touches model.py, the model's __init__.py and one test file, none of which is compile related. The Kimi K3 model carries no compile_with_inductor annotation either, so the regional inductor backend in distributed/compile.py has no region near the aggregation to lower.

If per-block compilation is turned on later it arrives as transformer_block.compile(backend=backend, fullgraph=True), where a graph break is an error rather than a fallback. Checked with torch._dynamo.explain on the aggregation itself, the Function traces into one graph with no break, and the op count drops from 8 to 2. That is the aggregation in isolation rather than a whole block under fullgraph=True, which cannot be run here while the model does not compile.

Relation to #4656

The two touch the same function from opposite sides and compose. #4656 wraps _apply_attention_residual in a checkpoint or, under RegionAC, declares it as a named region whose output the save policy may keep instead of replaying. This change rewrites the body of that function. All four combinations run.

They are complementary rather than alternative. Keeping the region saved costs whatever the region retains, and this change is what makes that cheap: on one aggregation at 2048 tokens and D 7168, a saved region costs 1036.2 MiB without this change and 28.2 MiB with it.

Results

One aggregation, bfloat16, H100 80GB, one shape per process, 10 warmups and the median of 7. Shapes run from the debug flavor up to the released model's hidden size and block count, dim 7168 with a stack of 8. kept counts the storages autograd holds that are not already live as inputs, and the two peak columns are increments over the allocation already standing when the call begins.

tokens is training.num_tokens_per_microbatch_per_dp_rank, described in the config as the number of input-token slots processed per data-parallel rank in one model forward, before context or tensor parallel sharding. Kimi K3's hidden states are token-major [T, D], so it is the leading dimension of every tensor below. For reference the released flavor sets it to one times max_context_length, which is 262144, so even the widest row here is an eighth of that default.

With activation checkpointing, which is the default

The block checkpoint discards the saved tensors, so neither form retains anything and the difference is entirely in peak. The naive form still builds both FP32 tensors in forward, and builds them a second time during recompute.

tokens dim stack form kept MiB fwd peak MiB bwd peak MiB fwd ms bwd ms
2048 1024 2 main 0.0 100.0 144.1 0.52 1.27
2048 1024 2 this 0.0 40.1 68.2 0.63 1.46
2048 4096 4 main 0.0 560.1 960.0 1.00 2.88
2048 4096 4 this 0.0 160.2 256.3 1.16 2.87
2048 7168 8 main 0.0 1764.1 3024.0 2.51 7.99
2048 7168 8 this 0.0 280.4 644.6 2.99 7.92
8192 7168 8 main 0.0 7056.3 12096.0 9.26 30.39
8192 7168 8 this 0.0 1121.4 2578.1 10.02 27.52
32768 7168 8 main 0.0 28225.2 48384.0 36.50 120.83
32768 7168 8 this 0.0 4485.7 10312.0 37.85 106.06

Forward peak falls 6.3x and backward peak 4.7x once the stack reaches 8, and both ratios hold as the context grows. At the widest shape a single aggregation's backward peak is 47.25 GiB against 10.07 GiB, a difference of 37.2 GiB on one call.

Without activation checkpointing

Here the retained bytes are the visible difference, and they stop growing with the shape.

tokens dim stack form kept MiB fwd peak MiB bwd peak MiB fwd ms bwd ms dev
2048 1024 2 main 48.1 100.1 120.0 0.32 0.71
2048 1024 2 this 0.1 40.1 68.1 0.44 0.76 0.195%
2048 4096 4 main 320.1 560.1 639.9 0.86 2.10
2048 4096 4 this 0.1 160.2 256.2 1.00 1.77 0.195%
2048 7168 8 main 1008.2 1764.2 2015.8 2.37 5.85
2048 7168 8 this 0.2 280.4 644.4 2.83 4.97 0.220%
8192 7168 8 main 4032.6 7056.6 8063.4 9.13 22.39
8192 7168 8 this 0.8 1121.4 2577.2 9.89 17.64 0.206%
32768 7168 8 main 16130.3 28226.3 32253.7 36.34 89.06
32768 7168 8 this 3.4 4485.7 10308.6 37.69 68.25 0.355%

48.1, 320.1, 1008.2, 4032.6 and 16130.3 MiB become 0.1, 0.1, 0.2, 0.8 and 3.4.

Forward is consistently slower, between 3% and 21%, because a few large operations become N + 1 smaller ones. Backward is slower at the smallest shape and faster from dim 4096 upward, reaching 1.14x with checkpointing on at the widest shape.

The result is not bitwise. The reordering takes the dot product first and scales by the inverse RMS where the current form normalizes and then contracts, which lands at about one bfloat16 ulp. In FP32 the two agree exactly, forward and every gradient, which the CPU test asserts at the default tolerance.

The released model, computed rather than measured

93 layers at block size 12 gives 8 blocks and 186 aggregations, and an aggregation inside block b runs over b + 2 values. Each call retains two FP32 [T, b + 2, D] tensors today against three FP32 [b + 2, T] statistics after, so the ratio is the hidden size. Computed from that structure at dim 7168 with pipeline degree 8, with no block level checkpointing, where retained bytes are what the change removes:

tokens aggregations per rank retained today retained after
4096 23 27.6 GiB 0.006 GiB
8192 23 55.2 GiB 0.012 GiB
32768 23 220.7 GiB 0.046 GiB

Under the default checkpointing that residency is already absorbed by the block checkpoint, and what the change removes instead is the peak of a single aggregation, which does not accumulate across layers. The measured peaks in the first table are the relevant figures there.

Where the naive form stops fitting

Same hidden size and stack, one process per point, peak reported as the process total rather than as an increment, so these numbers are larger than the two tables above and are not comparable to them.

tokens main this change
32768 52.06 GiB 14.88 GiB
65536 out of memory 29.77 GiB
131072 out of memory 59.53 GiB
262144 out of memory out of memory

On a 79.18 GiB card the naive form stops at 32768 tokens and this change reaches 131072, four times further. Neither reaches 262144, so this raises the context a single rank can carry through one aggregation and does not make the released default fit on one card; that configuration is sharded by context, tensor and pipeline parallelism, and tokens here is counted before any of that sharding.

Test plan

pytest tests/unit_tests/cpu/test_kimi_k3_attention_residual.py -q
6 passed, 2 subtests passed

The cases are the aggregation against a plain autograd reference in FP32 at stack widths 1 and 3, a bfloat16 case that fails if the score weight is rounded before the upcast, a check that the Function is registered for SPMD type checking, and three for the initialisation: the uniform depth weights, the gradient behaviour of the two parameters, and that all three residual projections carry a zero initialiser.

The whole CPU suite was also run against a worktree at unmodified upstream/main, since a count from any other tree is not a baseline. Failures and errors are identical on both sides, 19 and 7, the same files in both cases and none of them a Kimi K3 test; the seven errors are missing packages in that environment. Passed differs only by the tests this PR adds, and the new file was confirmed present in the collection list rather than inferred from the counts.

tests/unit_tests/gpu/test_kimi_k3.py has no case covering the aggregation, so the GPU suite does not exercise this path today.

The attention residual held two FP32 [T, N + 1, D] intermediates per call, the
upcast values and the normalized keys, for the whole forward. At the real
model's shape that is 1008 MiB for one call. Save the scores, the inverse RMS
and the softmax weights instead, none of which carry a hidden-size factor, and
recompute the rest in backward.

The score weight is the product of the norm weight and the projection weight,
and both factors are upcast before multiplying so a bfloat16 parameter does not
round the product.
The depth weights come from a softmax over per-source scores, and the score
weight is the product of the norm weight and the residual projection. With the
projection drawn from trunc_normal the initial depth weights are arbitrary. The
report requires them to be uniform at initialisation for training stability, so
initialise the three residual projections to zero.

At zero the aggregation returns the mean of its sources exactly. The projection
still receives a gradient; the norm weight does not, since it reaches the loss
only through its product with the projection, and it gains one as soon as the
projection leaves zero. Both are covered by tests.
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 18, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 18, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude It's not clear to me what problem this PR is solving. Could you explain using simple terms?

Also, since the autograd function uses many small ops, I would doubt about the performance. Maybe we should use something like https://github.com/fla-org/flash-linear-attention/blob/main/fla/ops/attnres/fused.py as a fused op, e.g. through the override mechanism in the repo.

@claude

claude Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 38s —— View job


What this PR fixes

Background. Kimi K3 doesn't use a plain residual (x + f(x)). Each layer's input is a weighted average of the outputs of earlier blocks plus the running sum. The weights come from a softmax over depth: every source gets a score, score = learned_query · RMSNorm(source). The learned query is attention_res_proj.weight / ffn_res_proj.weight / output_res_proj.weight.

The PR bundles two unrelated changes:

  1. Initialisation fix (__init__.py, small). The report says the learned query should start at zero. Then every score is 0, the softmax is uniform, and training starts from a plain average. Today it starts from trunc_normal(std=0.02), so the starting weights are arbitrary. This is a fix for mismatched training behaviour and is independent of everything else here. I'd split it into its own PR so it can land quickly.

  2. Memory (model.py, most of the diff). The current 8-line _apply_attention_residual makes two FP32 copies of the whole stack, shape [T, N+1, D]: the upcast values and the normalized keys. Autograd keeps both until backward. With D=7168, a stack of 8 and T=2048, that is about 1 GiB per call. Activation checkpointing is on by default, so these copies don't pile up across layers. They are still built twice, in forward and again in recompute, and that creates a large temporary peak inside a single call: 3.0 GiB before vs 0.64 GiB after, per the PR's table. The new autograd.Function saves only per-token scalars (scores, 1/rms, probs, each [N+1, T]). In backward it rebuilds the FP32 upcasts from the bf16 inputs.

In short, the goal is lower peak memory for this one op. It does not change results beyond about 1 bf16 ulp.

On performance: I agree with your concern

  • It's a hand fusion that still runs op by op. It avoids keeping the big tensors, but it doesn't reduce memory traffic. Each loop step over a source still upcasts to a new FP32 [T, D] temporary. Each source is read about 2× in forward and about 3× in backward. The PR's own numbers show forward 3–21% slower. Backward is faster only at large shapes, and only because it moves fewer bytes than the current, even less efficient version.
  • About 100 lines of hand-derived backward in the model file. That's hard to maintain and goes against "keep model code minimal" (.claude/rules/models.md).
  • No end-to-end numbers. Everything measured is one aggregation in isolation. With AC on, it isn't shown whether this call is actually a layer's peak, compared with MoE or attention. A 10+ step training run showing peak memory and throughput before and after would settle whether it matters.

The op is memory-bound and does a small reduction over depth for each token. The right kernel makes one pass over the N+1 sources per token tile, uses an online softmax, and saves only probs/lse and rms. That's the fla-style fused attnres approach you linked. Caveat: this job couldn't fetch web pages, so I haven't checked fla/ops/attnres/fused.py's exact signature or semantics. Before wiring it in, someone should confirm it matches Kimi's version: the RMSNorm weight is folded into the query, the softmax runs in FP32, and the running sum is the last source.

How to route it through the override mechanism

torchtitan/config/override.py swaps Configurable.Config nodes. _apply_attention_residual is a free function that takes (projection, norm) modules, so today there is nothing it can target. Suggested path:

  1. Wrap the aggregation in a small Configurable module, e.g. AttentionResidual(Module), whose Config holds norm: RMSNorm.Config and proj: Linear.Config. Its default forward is the current simple 8-line eager code. The blocks call self.attention_res(...), self.ffn_res(...) and self.output_res(...). Two things to watch:
    • Parameter names change (layers.{i}.attention_res_norm.weight → layers.{i}.attention_res.norm.weight), so the mappings in kimi_k3/state_dict_adapter.py:40-41 need updating, and existing HF checkpoints must still load.
    • kimi_k3/sharding.py:85-109 sets sharding_config on these configs directly and needs the same update.
  2. Add torchtitan/overrides/fused_attnres.py, modelled on overrides/fused_swiglu.py. It uses @override(target=AttentionResidual.Config) to swap in a subclass backed by a Triton fused forward and backward. Wrap the kernel as a torch custom op, as overrides/README.md recommends, and register it for SPMD type checking.
  3. Dependencies. fla is not a PyTorch library, so under Core Principle 1 it can't be a core default. Either vendor the Triton kernel into torchtitan/overrides/ as fused_swiglu.py does, or have the override import fla, which keeps it opt-in.

A cheaper option to measure first: torch.compile only the original 8-line eager _apply_attention_residual. Inductor would fuse the elementwise work and reductions, and its partitioner would typically save only the small per-token values and recompute the upcasts. That could give both the memory win and the speed without a hand-written backward. It's also worth running alongside #4656.

Recommendation

  • Land the zero-init change on its own.
  • Don't land the hand-written autograd.Function in model.py. Keep the simple eager version as the default. Get the memory and speed through either (a) regional compile of that function or (b) a fused kernel behind an override, after adding the Configurable wrapper above.
  • Ask for training-level peak memory and throughput before and after to justify either one.

No code changes were made.

Comment on lines -161 to -170

values_TND = torch.cat((block_residual_TND, prefix_sum_TD.unsqueeze(1)), dim=1)
values_float = values_TND.float()
variance = values_float.pow(2).mean(dim=-1, keepdim=True)
keys_TND = values_float * torch.rsqrt(variance + norm.eps)
score_weight_D = norm.weight.float() * projection.weight.squeeze(0).float()
scores_TN = (keys_TND * score_weight_D).sum(dim=-1)
probs_T1N = torch.softmax(scores_TN, dim=-1).unsqueeze(1)
output_TD = torch.matmul(probs_T1N, values_float).squeeze(1)
return output_TD.to(values_TND.dtype)

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.

after reading claude's analysis, I would suggest:

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.

Could you tell me "with this reference impl as default" refer to the original eager implementation (I suspect this one) or the new autograd.Function version ?

And we don't need the autograd.Function in current PR but due to performance concern (too many small OPs) in this commit, want to know the torch.compiled version is coming from which place (optimizing the current autograd.Function version impl ?)

If the entire point 3 is handled together, happy to leave it to Jessica @acisseJZhong

I think the recomputation issue seems have been addressed in #4656 , but anyway these 2 PRs need to be considered together, I will address @shuhuayu 's comment in the #4656 and LMK if any combined plan on these 2 together, thanks!

@QIU023

QIU023 commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor Author

closing this PR since the zero init and activation checkpointing of attn res is splitted away to #4881 and #4656

autograd.Function with bunch of small op is concerning in performance, hence not proceed

the compile part saw: felipemello1#109 and will be handled by meta maintainers

@QIU023 QIU023 closed this Oct 2, 2026
tianyu-l pushed a commit that referenced this pull request Oct 3, 2026
Initialize Kimi K3's attention residual projections to zero, as Section
5 of the Attention Residuals technical report requires, so the depth
softmax starts uniform and each residual starts as an equal-weight
average of its sources.

- `torchtitan/models/kimi_k3/__init__.py`: `attention_res_proj`,
`ffn_res_proj` and `output_res_proj` take `nn.init.zeros_` instead of
`trunc_normal_` at std 0.02.
- `tests/unit_tests/cpu/test_kimi_k3_attention_residual_init.py`: the
projections are zero initialized; at zero the aggregation returns the
mean of its sources; the projection still gets a gradient and the norm
weight does not.

Split out of #4780, as suggested there.

## Test plan

- The three projections of the debug model take `nn.init.zeros_`, and at
zero the aggregation returns the mean of its sources (checked locally).
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 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.

3 participants