Skip to content

[Kimi K3] Zero-initialize the attention residual projections - #4881

Merged
tianyu-l merged 1 commit into
pytorch:mainfrom
QIU023:k3_attnres_zero_init
Oct 3, 2026
Merged

tianyu-l merged 1 commit into
pytorch:mainfrom
QIU023:k3_attnres_zero_init

Conversation

@QIU023

@QIU023 QIU023 commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

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).

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

pytorch-bot Bot commented Sep 25, 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 review this PR

@claude

claude Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 57s —— View job


Review: Zero-initialize the Kimi K3 attention residual projections

  • Gather diff and context
  • Review init change against model code
  • Check test coverage claimed in PR body
  • Post review

Overall: The code change is correct and small. LGTM on the code. There is one thing to fix in the PR itself: the test file listed in the description is not in the PR.

Correctness ✅

  • In _apply_attention_residual (torchtitan/models/kimi_k3/model.py:175-192), the scores are keys_TND · (norm.weight * projection.weight). With projection.weight == 0, every score is 0, so the softmax over the N sources is uniform. output_TD is then the plain mean of the block residuals and the prefix sum, which is what Section 5 of the report asks for.
  • Gradients at init behave as expected. d scores / d projection.weight = norm.weight * keys, which is non-zero, so the projection learns from step 1. d scores / d norm.weight = projection.weight * keys = 0, so attention_res_norm, ffn_res_norm and output_res_norm get no gradient until the projection has moved off zero. This is the usual "zero one factor" behaviour, the same as LoRA's B=0, and it is expected. It may be worth one line in the comment so nobody later reads it as a bug.
  • The change covers all three sites: attention_res_proj (layers >= 1; layer 0 stays None), ffn_res_proj, and output_res_proj. The projections are bias=False, so a weight-only _RES_PROJ_INIT dict is enough.
  • HF checkpoint loading is not affected. This only changes init_states(), and loaded weights overwrite it. test_state_dict_round_trips_through_hf_adapter still holds with zero tensors.
  • The sharding path (sharding.py:82,101-103, TP-unsharded weight config) does not depend on the init values.

Issues

  1. The PR description lists a test file that is missing. The description names tests/unit_tests/cpu/test_kimi_k3_attention_residual_init.py, but the PR changes only 1 file (torchtitan/models/kimi_k3/__init__.py, +9/-3), and that test file is not on the branch. It looks like it was left out when this was split from [Kimi K3] Attention residual: zero initialisation and a recomputing aggregation #4780. Per the repo guidelines, a CPU unit test is expected. The tests the description lists (projections are zero, the zero-init aggregation equals the mean, the projection gets a gradient, and the norm weight gets zero gradient at init) are exactly the right ones. Please add them, or update the description.
    Fix this →

  2. Nit on the comment. # Zero init gives the uniform initial depth weights the report requires. says "the report" without saying which one. Naming it (e.g. "Attention Residuals tech report, Sec. 5") would help later readers. Optionally, also note that the paired RMSNorm weight gets no gradient until the projection moves off zero.

Numerics

This changes the computation at init, so it will not match earlier runs bit for bit. Per CLAUDE.md, a short loss-convergence comparison against the old init on the debug model would be good to include, though for a spec-mandated init fix it is not blocking.

Section 5 of the Attention Residuals technical report requires every
pseudo-query vector to be initialised to zero, so the depth softmax starts
uniform and each residual starts as an equal-weight average of its sources;
the three residual projections were drawn from trunc_normal at std 0.02.
@QIU023
QIU023 force-pushed the k3_attnres_zero_init branch from ae3a788 to 42dac61 Compare October 3, 2026 07:08
@tianyu-l
tianyu-l merged commit cc32f71 into pytorch:main Oct 3, 2026
shuhuayu added a commit to shuhuayu/torchtitan that referenced this pull request Oct 8, 2026
Refresh the 10-step loss and gradient-norm golden after the Kimi K3 attention residual projections were changed to zero initialization in pytorch#4881.\n\nThe values were extracted from B200 run 37738225414, whose source tree exactly matches upstream/main at 08f7c39.
shuhuayu added a commit to shuhuayu/torchtitan that referenced this pull request Oct 8, 2026
Refresh the 10-step loss and gradient-norm golden after the Kimi K3 attention residual projections were changed to zero initialization in pytorch#4881.

The values were extracted from B200 run 37738225414, whose source tree exactly matches upstream/main at 08f7c39.
shuhuayu added a commit that referenced this pull request Oct 9, 2026
## Summary

- Disable Attention Gym KDA autotuning when PyTorch deterministic
algorithms are enabled; ordinary training still autotunes.
- Refresh the Kimi K3 10-step B200 loss and gradient-norm golden after
the attention-residual initialization change in #4881.
- Keep the existing `kimi_k3_debugmodel_mm_muon` recipe and FSDP2/EP2
topology unchanged.

## Why

The old golden predates #4881, which intentionally changed Kimi K3
attention-residual projections from truncated-normal to zero
initialization.

While re-exporting it, two otherwise identical deterministic B200 runs
diverged after step 1. A back-to-back diagnostic on the same runner
reproduced both traces: Attention Gym's KDA autotuner can select
numerically different valid schedules based on benchmark/cache state.
Deterministic mode now skips that benchmark-dependent choice and uses
the default schedule, matching TorchTitan's existing handling for other
autotuned attention kernels.

## Numerical source

- Back-to-back B200 export:
https://github.com/pytorch/torchtitan/actions/runs/37752597252
- Config: `kimi_k3_debugmodel_mm_muon`
- Topology: FSDP2/EP2 on two B200 GPUs
- Steps: 10
- Metrics: full-precision TensorBoard `loss` and `grad_norm`
- Golden SHA-256:
`a261836fb1c17635d71f2a04b81b882e9b60ba08f6229091393861dc33160ae5`

Both sequential exports were byte-for-byte identical.

## Validation

- Final B200 CI numerics path:
https://github.com/pytorch/torchtitan/actions/runs/37757612886
  - `kimi_k3_mm_muon` completed with `rc=0`.
- `loss_compare.py --assert-equal` matched all 10 losses and all 10
gradient norms exactly.
- The overall B200 workflow was red in unrelated lanes; the K3 numerics
lane passed.
- Formatting, flake8, pydoclint, codespell, and link checks passed. The
repository-wide Pyrefly hook reports four unrelated errors already
present on `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 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