Skip to content

[kimi_k3_1] Add Kimi K3.1 Pro with Gated DSA - #6007

Merged
shuhuayu merged 22 commits into
pytorch:mainfrom
JavaZeroo:kimi-k3.1-pro
Nov 24, 2026
Merged

shuhuayu merged 22 commits into
pytorch:mainfrom
JavaZeroo:kimi-k3.1-pro

Conversation

@JavaZeroo

@JavaZeroo JavaZeroo commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Add Kimi K3.1 Pro. It differs from K3 only in its 24 full-attention layers, which change from Gated MLA to Gated DSA. So this PR reuses the K3 backbone, adds the DSA layers with DSV4's existing top-k selection and indexer loss, and runs the sparse attention with Attention Gym's gather_attn.

I've already checked the model code, model accuracy, test cases, and the model README.md

Why

Kimi K3.1 Pro (RFC #5936) is Kimi K3 with its 24 Gated MLA layers replaced by Gated DeepSeek Sparse Attention (DSA). torchtitan cannot build, train or load it today.

from torchtitan.models.kimi_k3_1 import build_model_config

config = build_model_config("Kimi-K3.1-Pro", parallelism=parallelism)

What changed

  • New torchtitan/models/kimi_k3/dsa.py: the indexer and the sparse attention. Top-k selection and the indexer loss are imported from deepseek_v4/compressor.py; DSV4 is not changed. Attention over the selected tokens runs Attention Gym gather_attn with (latent, rope) pairs, under spmd.no_typecheck() as in DSV4. KimiSparseAttention.Config.impl picks the gather_attn implementation ("fused" by default).
  • New torchtitan/models/kimi_k3_1/, flavors only like qwen3_6:
    • flavors.py: debugmodel and Kimi-K3.1-Pro (text only), plus debugmodel_mm and Kimi-K3.1-Pro_mm with the vision encoder, built with the K3 config builder like the K3 flavors. build_model_config raises unless each TP rank has 16 to 128 query heads, which the pair kernel needs.
  • Kimi K3:
    • The block passes padding_mask and aux_loss_denominator to Kimi MLA attention. K3 ignores them; the K3.1 DSA attention uses them.
    • KimiK3Model registers the aux-loss zero hook, and KimiK3StateDictAdapter maps the five indexer tensors. Both are no-ops for K3.
    • kimi_k3_config takes a full_attention_config_factory.
    • mla_attention_config is split out of mla_config so K3.1 reuses the MLA projections.
    • Mechanical: four private helpers become public; two K3 tests are updated.
  • Recipes: a K3.1 debug recipe. The K3 DistMuon builder gets one optional argument so K3.1 can add the indexer weights.
  • Tests: kimi_k3_1_fsdp2_tp2_ep2_pp2_vpp4 in the B200 integration suite, the same shape as the K3 cell, without a golden for now.
  • README: the supported parallelisms and the parity check.

Numerics

Check Result
Kimi K3 debug model, main vs this branch, 10 steps, 1 GPU loss and grad_norm bitwise equal; configs identical
One K3.1 DSA layer (random weights) vs vLLM's K3.1 DSA forward in plain PyTorch (no HF model code is released) fp32 (CPU): same top-k, relative L2 6.6e-7; bf16 (H100): top-k overlap 99.6%, relative L2 7.2e-3
Kimi K3.1 debug model, 20 steps, 2x H100, same seed checkpoint: FSDP 2 + EP 2, TP 2 + EP 2 (32 heads), PP 2, each vs its 1- or 2-GPU baseline step 1 grad_norm equal; loss differs by up to 4.6e-3 to 8.0e-3, while two runs of the same baseline differ by up to 4.9e-3 to 6.0e-3 (the pair backward is not deterministic)

Testing

pytest tests/unit_tests/cpu/models/kimi_k3/ tests/unit_tests/cpu/models/test_build_model_config.py
NGPU=1 MODULE=torchtitan_recipes.tests.models.kimi_k3_1 CONFIG=kimi_k3_1_debugmodel ./run_train.sh

The H100 Kimi integration tests (kimi_k3_mm_allgather_kv_cp, kimi_k3_mm_ulysses_cp) pass on 2x H100.

Known issues / follow-ups

  • Not verified: parallel combinations larger than 2 GPUs. CP is not supported; the CP transform raises for the K3.1 sparse attention.
  • gather_attn has no deterministic backward for (latent, rope) pairs yet, so K3.1 raises with debug.deterministic = True, and the integration test has no golden: gather_attn: deterministic backward for (latent, rope) pairs meta-pytorch/attention-gym#795.
  • K3.1 is the second user of the DSV4 InnerIndexer and SparseIndexerLoss. Move them to models/common/ after [QSA] sparseindexerloss teacher #5863 lands.
  • KimiDSAAttention subclasses KimiMLAAttention on purpose: the MLA weights are the same, so the K3 HF mapping and Muon grouping apply as is.

Kimi K3.1 Pro is Kimi K3 with its 24 Gated MLA layers replaced by Gated
DeepSeek Sparse Attention. The new kimi_k3_1 model adds the indexer, the
sparse attention (Attention Gym gather_attn over the absorbed MLA latent),
the debugmodel and Kimi-K3.1-Pro flavors built with the Kimi K3 config
builder, a K3.1 block and model, and a state dict adapter that adds the
indexer weights to the Kimi K3 mapping. Top-k selection and the indexer loss
come from DeepSeek V4. Kimi K3 gets small builder hooks so K3.1 can reuse it.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 10, 2026
Attention Gym main now runs the shared-KV schedule with (latent, rope)
pairs on Ampere and newer. The Kimi-K3.1-Pro shape compiles in seconds
this way; a single 576-wide tensor stays on the slow per-head kernel.

The fused pair path needs 16 to 128 heads, so the debug model now has
16 heads.
Indexer.select, gather_attn and the indexer loss read the untyped varlen
offsets, so a type-checked run failed in compressed_cu_seqlens. Run them
under spmd.no_typecheck() and assert the output keeps the query's type,
as DeepSeek V4's sparse attention does.
@pytorch-bot

pytorch-bot Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

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

The Kimi K3.1 block was a copy of the K3 block that only also passed padding_mask and aux_loss_denominator to the attention. The K3 block now passes them to Kimi MLA attention, which K3 ignores and the K3.1 DSA subclass uses, so the K3.1 block and the block class argument of kimi_k3_config are removed. K3 configs are unchanged; K3.1 configs differ only in the block class.
@JavaZeroo
JavaZeroo force-pushed the kimi-k3.1-pro branch 2 times, most recently from 301153a to d29924d Compare November 12, 2026 09:33
@JavaZeroo
JavaZeroo marked this pull request as ready for review November 13, 2026 11:56
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 13, 2026
@JavaZeroo

Copy link
Copy Markdown
Contributor Author

@tianyu-l @shuhuayu this PR is ready for review. The K3.1 integration test has no golden yet, because KimiSparseAttention calls Attention Gym's gather_attn, and that kernel has no deterministic backward yet: meta-pytorch/attention-gym#795.

Follow the Kimi K3 split from pytorch#6084: debugmodel and Kimi-K3.1-Pro build the text KimiK31Model, and the _mm flavors build KimiK31MultimodalModel with the vision encoder. kimi_k3_config takes the multimodal config class next to the text one.
mla_attention_config's config_cls takes a callable, not only a class, so call it config_factory. kimi_k3_config's full_attention becomes full_attention_config_factory, like attention_config_factory in the DeepSeek V3 builder.
…type

KimiDSAAttention.Config skipped the Kimi MLA inner attention check and had none of its own. It now requires a KimiSparseAttention.Config and an indexer loss with the attention's softmax scale and head count, since a mismatch gives a wrong loss without an error.

The fused (latent, rope) pair kernel only runs BF16 on Ampere or newer. Other dtypes and devices now use the reference kernel, as the indexer selection already does, instead of raising inside Attention Gym.
Kimi K3.1 was missing from the build_model_config tests, so none of its flavors were built on CPU.
@pytorch-bot pytorch-bot Bot added the ciflow/b200 Trigger B200 CI label Nov 19, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review -- in particular, is @shuhuayu 's feedback addressed?

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items before merging. The code addresses all five of @shuhuayu's comments. The PR description is stale and still needs updating. Review posted; @shuhuayu still needs to re-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 code at HEAD addresses all five of @shuhuayu's comments. What's left is a PR description that no longer matches the code. @shuhuayu's change request is still open, so a maintainer still needs to re-review.

What this PR does. Kimi K3.1 Pro is now a flavor-only folder (kimi_k3_1/flavors.py), like qwen3_6. It builds KimiK3Model / KimiK3MultimodalModel through kimi_k3_config(..., full_attention_config_factory=_dsa_config). The DSA layer lives in kimi_k3/dsa.py. K3 itself now registers the aux-loss zero hook and maps the five indexer HF keys. A K3 checkpoint has no indexer keys and K3 has no AuxLoss, so both are no-ops for K3.

Example.

# before (first round): separate model, adapter and config classes
kimi_k3_config(..., config_cls=KimiK31Model.Config, multimodal_config_cls=KimiK31MultimodalModel.Config)
# now: same K3 classes, only the full-attention factory differs
kimi_k3_config(..., full_attention_config_factory=partial(mla_config, attn_backend="varlen"))  # K3
kimi_k3_config(..., full_attention_config_factory=partial(_dsa_config, index_topk=2048, ...))  # K3.1

@shuhuayu's feedback at HEAD

Comment Status
Move the test to b200.py, use 32 heads, copy the shape of kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4 Addressed: b200.py:115. The debug model has num_heads=32 (16 per TP rank), and the FSDP2/TP2/EP2/PP2/VPP4 split, schedule and optimizer match the K3 cell
Add the aux-loss hook to the K3 model Addressed: kimi_k3/model.py:210
Fold the state dict adapter into K3 Addressed: kimi_k3/state_dict_adapter.py:111-121. kimi_k3_1/state_dict_adapter.py is deleted
Fold model.py into K3, keep kimi_k3_1 flavor-only Addressed: kimi_k3_1/ now has only __init__.py, flavors.py and README.md. config_cls / multimodal_config_cls are removed from kimi_k3_config
Remove the run-to-run noise paragraph from the README Addressed: the paragraph is removed. A deterministic loss-parity check across parallelisms, which is the bar the comment sets, still has to wait for meta-pytorch/attention-gym#795. That is tracked by the TODO at b200.py:193

Must fix

  1. The PR description no longer matches the code, and reviewers verify against it:
    • "What changed" still lists kimi_k3_1/dsa.py, model.py (KimiK31Model, KimiK31MultimodalModel), state_dict_adapter.py, and the "optional text and multimodal model config classes".
    • "Tests" still says H100 kimi_k3_1_fsdp+ep (FSDP 2 + EP 2, SPMD type checking on). At HEAD it is B200 kimi_k3_1_fsdp2_tp2_ep2_pp2_vpp4 on 8 GPUs with type checking off.
    • The testing commands point to tests/unit_tests/cpu/models/kimi_k3_1/ and h100 ... kimi_k3_1_debugmodel_fsdp2_ep2. Neither exists anymore.
    • Please update these sections, and say whether the new 8-GPU B200 cell was run.

Should consider

  • tests/integration_tests/b200.py:115 -- this function duplicates the K3 VPP4 cell. Factor out the shared body (see the inline comment).
  • Still open from the first review: torchtitan_recipes/tests/models/kimi_k3_1.py:34-38 imports _dist_muon_optimizer, _kimi_k3_multimodal_dataloader and _KimiK3TrainerConfig, which are private to another module. The root README.md model table has no row for K3.1.

Questions

  • Still unanswered from the first review: were the five self_attn.indexer.* HF names checked against the released K3.1 checkpoint index? The README now says the adapter "maps the released Hugging Face checkpoint, including the indexer weights", but no test or check in the PR shows that.
Details
  • Items from the first automated review: the DSV4 promotion TODO is at kimi_k3/dsa.py:393-394 and the golden TODO at b200.py:190-192. Both are resolved. The fp32 silent-fallback finding is handled by the new KimiSparseAttention.Config.impl: Literal["fused", "reference"] = "fused". With that field nothing chooses an implementation from dtype or device, and has_cuda_capability is gone from the model code. Only the CPU oracle test uses "reference".
  • The block branch isinstance(self.attention, KimiMLAAttention) in kimi_k3/model.py:158 sends padding_mask and aux_loss_denominator to MLA and DSA. K3's KimiMLAAttention.forward drops them with del, so the K3 numerics don't change. The description reports a bitwise K3 comparison, which I did not re-run.
  • kimi_k3_1/__init__.py re-exports the K3 model classes, as qwen3_6/__init__.py re-exports Qwen35Model.

Not verified: that gather_attn(impl="fused") raises on fp32 or non-accelerator inputs (Attention Gym is not importable here); where debug.deterministic = True raises for K3.1 (nothing in this diff checks for it, so it must come from Attention Gym); and the GPU runs.

return config


def kimi_k3_1_debugmodel_fsdp2_tp2_ep2_pp2_vpp4() -> Trainer.Config:

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.

(should consider) Apart from the recipe it starts from, this function is a line-for-line copy of kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4 above. The copy also leaves out the comments that explain why type checking is off, why the split uses 4 stages, and why it keeps AdamW (#3353). Factoring the shared body into a module-private helper that takes the base Trainer.Config removes about 25 lines and keeps those comments in one place:

def _fsdp2_tp2_ep2_pp2_vpp4(config: Trainer.Config) -> Trainer.Config:
    # (body of the K3 function, starting at _set_spmd_typechecking)
    ...

def kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4() -> Trainer.Config:
    return _fsdp2_tp2_ep2_pp2_vpp4(kimi_k3_debugmodel(parallelism=ParallelismConfig(expert_parallel_degree=2)))

def kimi_k3_1_debugmodel_fsdp2_tp2_ep2_pp2_vpp4() -> Trainer.Config:
    return _fsdp2_tp2_ep2_pp2_vpp4(kimi_k3_1_debugmodel(parallelism=ParallelismConfig(expert_parallel_degree=2)))

@shuhuayu shuhuayu 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.

some minor issues

Comment thread torchtitan/models/kimi_k3/dsa.py Outdated
remat.recompute_needs_tensor(q_TJ)
q_THK = local_head_split(q_TJ, self.q_head_dim, cp_shard_dim=0)

compressed_kv_TC = self.wkv_a(x_TD)

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 is not C but L + R.

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.

Fixed.

Comment thread torchtitan/models/kimi_k3/dsa.py Outdated

compressed_kv_TC = self.wkv_a(x_TD)
remat.recompute_needs_tensor(compressed_kv_TC)
kv_latent_TC, k_shared_TR = torch.split(

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.

Suggested change
kv_latent_TC, k_shared_TR = torch.split(
kv_latent_TL, k_shared_TR = torch.split(

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.

Fixed.

@tianyu-l

Copy link
Copy Markdown
Contributor

@JavaZeroo could you check CI failures? some are unrelated, but some seem related

pytorch#6181 changed Indexer.select and SparseIndexerLoss to take
DeepSeekV4CompressedSparseAttentionMetadata instead of cu_seqlens.
KimiSparseAttention now builds that metadata once per variant, with the
compressed pool equal to the token pool since K3.1 selects at ratio 1.
@JavaZeroo

JavaZeroo commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor Author

@JavaZeroo could you check CI failures? some are unrelated, but some seem related

@tianyu-l #6181 changed Indexer.select and SparseIndexerLoss to take the DSV4 sparse-attention metadata instead of cu_seqlens, which broke lint and the K3.1 CPU test. K3.1 now builds that metadata once in build_attention_metadata.
and B200 and RL B200 failures are in DeepSeek V3 / dist_moe tests look unrelated.

pytorch#6216 replaced Indexer.select with the InnerIndexer module. KimiSparseAttention
now holds an InnerIndexer (ratio 1, the K3.1 top-k) in place of index_topk.
InnerIndexer has no parameters, so state dict keys and the HF mapping do not
change.
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items before merging (the PR description's "Known issues" section is stale, and the author should say whether the B200 cell was run). Review posted; a maintainer still needs to sign off.

@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 three new commits are a rename and a port to the DSV4 API that #6181 / #5722 changed. I found no new problems in them. Two lines of the PR description are now stale. @shuhuayu has approved; a maintainer still needs to sign off.

What changed since the last automated review (5351ee7..3d311af, +42/-32 in 3 files)

  • 8f277b5: kv_latent_TC -> kv_latent_TL and compressed_kv_TC -> compressed_kv_TG, with a new G = L + R legend entry. This resolves both of @shuhuayu's comments.
  • 51950cd + 3d311af: KimiSparseAttention now selects through a DSV4 InnerIndexer submodule instead of the removed Indexer.select. index_topk: int becomes inner_indexer: InnerIndexer.Config(ratio=1, topk=...), and build_attention_metadata returns a DeepSeekV4CompressedSparseAttentionMetadata.

Example.

# before
Indexer.select(q, k, w, max_seqlen=md.max_k, ratio=1, topk=self.index_topk, cu_seqlens=md.cu_seq_q, ...)
# after
self.inner_indexer(q, k, w, attention_metadata=md, return_scores=...)
# md.cu_seq_compressed = md.cu_seq_q  (ratio 1: every token is its own "compressed" slot)

Earlier items at HEAD

  • Resolved: the TODO at kimi_k3/dsa.py:28 now names only #5863. #5722 is closed and its InnerIndexer API is what the code uses.
  • Resolved: most of the stale description from the last review. "What changed" and "Tests" now describe kimi_k3/dsa.py, the flavor-only kimi_k3_1/ folder, and the B200 cell.

Must fix

  1. PR description, "Known issues": it still says K3.1 is "the second user of the DSV4 Indexer.select" and that the move to models/common/ waits for "#5722 and #5863". The code now uses InnerIndexer, and #5722 is closed. Please also say whether the 8-GPU B200 cell kimi_k3_1_fsdp2_tp2_ep2_pp2_vpp4 was run, and whether the 2-GPU numerics rows were run again after the switch to InnerIndexer (they came before 3d311af).

Should consider (still open from earlier reviews, no new inline comments)

  • torchtitan_recipes/tests/models/kimi_k3_1.py:33-37 imports three _private names from the K3 recipe module.
  • tests/integration_tests/b200.py:122 copies the body of the K3 VPP4 cell.
  • The root README.md model table has no K3.1 row.

Questions

  • Still unanswered: were the five self_attn.indexer.* HF names checked against the released K3.1 checkpoint index?
Details
  • Metadata at ratio 1: cu_seq_compressed = cu_seq_q, so compressed_gather_indices (deepseek_v4/compressor.py:55) adds each document's token offset. That is the same packed indexing gather_attn uses with cu_seqlens_k=cu_seqlens. group_start / group_first are empty, and only Compressor reads them (compressor.py:169). K3.1 has no Compressor.
  • InnerIndexer.forward carries @spmd.no_typecheck() itself, so removing the explicit with spmd.no_typecheck() around selection changes nothing. Because inner_indexer is now a submodule, any hook or FQN walk sees one extra parameterless module. It has no state dict entries, so HF loading is unaffected.
  • Decoder caches metadata by inner-attention class (common/decoder.py:544), so the DSV4 metadata type built for KimiSparseAttention doesn't collide with the KDA layers' metadata.
  • flops_per_token now reads inner_indexer.topk. The value is the same as before.
  • InnerIndexer picks the reference lightning_indexer on anything below SM90 or on fp32 (compressor.py:304-308), while gather_attn follows impl. That is pre-existing DSV4 behavior, not part of this PR.

Not verified: GPU runs, and whether InnerIndexer selects the same tokens bitwise as the removed Indexer.select.

@JavaZeroo

Copy link
Copy Markdown
Contributor Author

Still unanswered: were the five self_attn.indexer.* HF names checked against the released K3.1 checkpoint index?

yes

Please also say whether the 8-GPU B200 cell kimi_k3_1_fsdp2_tp2_ep2_pp2_vpp4 was run, and whether the 2-GPU numerics rows were run again after the switch to InnerIndexer (they came before 3d311af).

8-GPU B200 was run by ci, and switch to InnerIndexer is bit-wise equal

@shuhuayu

Copy link
Copy Markdown
Contributor

looks good to me, will merge once ci tests pass, thx.

@shuhuayu

Copy link
Copy Markdown
Contributor

the failed test is unrelated, so good to merge.

@shuhuayu
shuhuayu merged commit 74a2c8e into pytorch:main Nov 24, 2026
27 of 28 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in TorchTitan Development Nov 24, 2026
shuhuayu pushed a commit that referenced this pull request Nov 25, 2026
…6363)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Agent details

**TLDR:** Since main 74a2c8e, `lint` fails on every PR into main that
changes a Python file. pyrefly reports `Could not import
quadratic_attention_flops_per_token from torchtitan.models.common.flops`
at `torchtitan/models/kimi_k3/dsa.py:297`. It broke when #6007 (Kimi
K3.1) merged after #6325 replaced the attention FLOPs API: each passed
CI on its own. @JavaZeroo @acisseJZhong, could you please take a look?
This PR ports `KimiDSAAttention.Config.flops_per_token(seq_len)` to
`flops(positions)`, the method the FLOPs estimator calls now. That also
restores the top-k cap and the indexer in Kimi K3.1's FLOPs count.
Today, main counts its sparse attention (DSA) layers as dense attention,
so Kimi K3.1 Pro's `tflops` and `mfu(%)` read 8.4% high at 32k tokens
and 3.1x at 1M.

![This PR makes the FLOPs estimator use Kimi K3.1's own sparse-attention
formula: in the unit test main counts 130 attention keys (7,987,200
FLOPs) and this PR 129 attention keys plus 130 indexer keys (8,125,440
FLOPs), and for one Kimi K3.1 Pro document main's FLOPs per token read
8.4% high at 32k tokens and 3.1x at
1M.](https://raw.githubusercontent.com/felipemello1/pr_images/dcf6509833af9dea31341e0b8a8028a141198d27/torchtitan/6363/cells.png)
<!-- pr-image drawn at a81832f -->

```python
# before: never called, and imports a removed function
def flops_per_token(self, seq_len: int) -> int: ...

# after
def flops(self, positions: torch.Tensor) -> int:
    num_keys = positions + 1
    attention_flops = quadratic_attention_flops(..., num_keys=num_keys.clamp(max=topk))
    indexer_flops = 6 * num_index_heads * index_head_dim * int(num_keys.sum())
    return attention_flops + indexer_flops
```

**Problem**
1. Commit bd64f5c ("Count causal and document-masked attention FLOPs
per query position") replaced each attention config's
`flops_per_token(seq_len)` with `flops(positions)`. It removed
`quadratic_attention_flops_per_token`.
2. Commit 74a2c8e ("Add Kimi K3.1 Pro with Gated DSA") added
`KimiDSAAttention.Config.flops_per_token` on the old API. Its lint
passed on 11-23 at 23:38 UTC, before bd64f5c merged (11-24 01:55 UTC).
3. pyrefly checks the whole project whenever a PR changes a Python file.
So `lint` now fails on those PRs, from their next push on.
4. The estimator calls `attention.flops(positions)` (`decoder.py:214`).
DSA layers inherit it from `KimiMLAAttention`: all p + 1 keys, no top-k
cap, no indexer.

**Solution**
1. Port the method to `flops(positions)`, as DeepSeek-V4's sparse
attention does (`deepseek_v4/attention.py:337`).
2. Attention reads at most top-k keys per query. The indexer scores all
p + 1 keys.
3. At full length (every query at position seq_len - 1), it gives the
same number as the old method.
4. Only Kimi K3.1's `tflops` and `mfu(%)` metrics change. Loss and
gradients don't.

**Results**
```
Kimi K3.1 Pro, FLOPs/token, one document (positions 0..seq_len-1)
  seq_len     main       this PR    main reads
  4096        6.37e11    6.36e11    +0.2%
  32768       7.01e11    6.47e11    +8.4%
  131072      9.18e11    6.76e11    +35.8%
  1048576     2.95e12    9.46e11    3.1x
debugmodel, FLOPs/token, seq_len 128, every query at position 127 (top-k = 128, so only the indexer differs)
  main 834,345,216    this PR 835,328,256 = the old flops_per_token formula
```

You may ask: Why count the indexer over p + 1 keys instead of seq_len?
Since bd64f5c, the estimator charges each query its causal keys. At
full length both give the same count.

NOTE: The indexer term keeps the old method's factor of 6, a forward and
backward over all p + 1 keys, as DeepSeek-V4's does. The indexer scores
all keys without grad, and recomputes only the top-k with grad for the
indexer loss (`deepseek_v4/compressor.py:310-333`). Counting that would
cut Kimi K3.1 Pro's estimate by 0.8% at 32k and 21.7% at 1M. A TODO at
the line records it. The fix belongs in both models, so it's left for a
follow-up.

**Test plan**
```
pytest tests/unit_tests/cpu/models/kimi_k3/test_kimi_k3_1_dsa.py -k flops
  main:    1 failed (7987200 != 8125440: the inherited dense formula)
  this PR: 1 passed
pytest tests/unit_tests/cpu/models/kimi_k3/ tests/unit_tests/cpu/models/common/test_flops_estimators.py \
  tests/unit_tests/cpu/models/deepseek_v4/test_deepseek_v4_flops.py: 48 passed
```
pyrefly check, whole project, on a copy of this PR: the `dsa.py` error
is gone. One error remains locally, in `activation_offload.py:449`. It
comes from our older torch nightly, which lacks
`FSDPModule.get_all_gather_copy_in_stream`, and CI's lint doesn't report
it.
pre-commit run --files <changed files>, with SKIP=pyrefly-check because
pyrefly ran above: all hooks pass.

Co-authored-by: Felipe Mello <[email protected]>
tianyu-l added a commit that referenced this pull request Nov 26, 2026
…er override; agent self-review; rl/transport (#6407)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why

Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it
approved,
30 then got a formal "request changes" from a maintainer, and about 20
more got
substantive inline asks. In nearly all of them the bot either saw the
problem
and approved anyway, or never asked the questions maintainers ask most
("does
the repo already do this?", "who should own this?"). The opposite
failure, the
bot blocking something a maintainer was fine with, is rare: in the PRs
we
sampled, 2 of its 81 must-fix items were wrong and about a third were
minor
(the empty human-written summary was the biggest source).

**Example** (#6112, controller sizes the rollout worker pool):

```
before: bot approved 10 times; tianyu-l then blocked: "the controller reads
        rollouter.rollouts_per_worker to compute a count it hands back to the
        Rollouter -- violates encapsulation"
after:  same commit, new skill -> Request changes, must-fix #1:
        "controller.py:589 -- wrong owner for the worker count ..."
```

There was also no way for a code owner to overrule the bot except
dismissing
its review in the GitHub UI, and a later `@claude review again` would
block
again.

## What changed

**Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`):
- Verdict rules: Approve only when every remaining item is an edit the
bot
could write itself. Anything the author still owes (a design change, an
unexplained golden change, evidence the PR rests on) is Request changes;
anything only a maintainer can decide is Needs discussion. A hedge like
"a
  maintainer should decide" can't come with Approve.
- Always must-fix: a violated written rule, a silent wrong result, a
second
  definition of an existing concept, a gate finding.
- Design gate: new questions for the existing counterpart, in-repo
ownership,
and the design behind a bug; "ban only what doesn't work on main"; read
the
numbers behind a claim. The overlapping-PR search is mandatory and
reported.
- Re-review covers every commit since the last full review, including
code
taken from the bot's own suggestions. A scoped question gets a
`COMMENT`, not
  a whole-PR verdict.
- The bot fact-checks its own proposed fixes, and cites a source for
claims
  about external tools or marks them unverified (never must-fix).
- An empty "Summary (human-written)" is a one-line "Before merge" note
that
  never affects the verdict.
- Checklist: config ownership direction, general shared wrappers, dead
code the
PR creates, model variants as flavors, a mechanical pass over every new
or
  changed function.

**Code owner override** (`SKILL.md`, `claude-code.yml`,
`CONTRIBUTING.md`): a
code owner comments `@claude override` (optionally `@claude override
2,3:
<reason>`); the bot approves if nothing else is open and doesn't
re-raise the
overridden items. A code owner's GitHub approval or "LGTM" is not an
override,
so a teammate can approve without the bot dropping its findings.
Dismissing the
bot's review still unblocks the PR, but isn't an override: the bot can't
tell
who dismissed it.

**Agent self-review** (`CLAUDE.md`, `pr-description`): an agent
preparing a PR
runs `pr-review` in branch mode first and records unaddressed items in
an
optional "Self-review" section. PRs written without an agent are
unaffected; a
missing section is never a finding.

Where each new rule comes from (maintainer asks the bot missed):

| Change | PRs |
| --- | --- |
| No Approve with open design/evidence items or a "maintainer should
decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 |
| Author waiver can't clear a must-fix | #6201, #6202, #6203 |
| Existing counterpart; one source of truth | #5228, #6169, #5881,
#5823, #5824, #6059, #5812 |
| Responsibility owner; config ownership direction | #6112, #6332,
#5802, #5803, #6325 |
| Fix the design behind the bug; a TODO doesn't justify a workaround |
#5572, #5689, #5657 |
| Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819,
#5543 |
| Re-review covers all new commits; scoped asks don't approve | #5824,
#5842 |
| Mandatory overlap search | #5885, #6248 |
| Ban only what doesn't work on main | #5543 |
| Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868
|

**Rules**: `design.md` gets the one-general-wrapper rule (moved from
`models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the
consumer owning its values; `config.md` gets ownership direction and "a
Config
doesn't read runtime state"; `direction.md` calls all-to-all the MoE
reference
implementation, so a new vendor-specific dispatch path (e.g. #6242)
needs a
reason the existing backends can't serve.

**Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/`
-> d4l3k.

**Mechanical, skim**: `torchtitan/rl/transport/` holds data movement
between RL
actors.
- `rl/model_state_dict_transport.py` ->
`rl/transport/model_state_dict.py`
- `rl/MODEL_STATE_DICT_TRANSPORT.md` ->
`rl/transport/MODEL_STATE_DICT_TRANSPORT.md`
- `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py`
- tests:
`tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py`
->
`tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py`
- imports, READMEs and `scripts/install_rl_env.sh` updated; no code
changes.

## User-facing changes

| Before | After |
| --- | --- |
| Overrule the bot: dismiss its review in the UI, and it blocks again on
the next run | `@claude override [items]: <reason>`; the bot approves
and doesn't re-raise them |
| Empty human-written summary: bot must-fix | One "Before merge" line,
no effect on the verdict |
| `from torchtitan.rl.model_state_dict_transport import ...` | `from
torchtitan.rl.transport.model_state_dict import ...` |
| `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from
torchtitan.rl.transport.rdma_microbatch import ...` |

## Testing

Backtest: the new skill run locally (nothing posted) on each PR at the
commit
and thread state the bot originally saw.

| PR | Bot then | New skill | What the maintainer asked |
| --- | --- | --- | --- |
| #6112 | Approve | Request changes | worker-count ownership (caught) |
| #5837 | Approve | Request changes | apply to `dp_shard` too (caught) |
| #5572 | Approve | Request changes | delete the injection design
(caught) |
| #6201 | Approve after author waived pins | Request changes, waiver
ignored | pins broke GPU tests after merge (caught) |
| #6007 | Approve | Request changes | fold K3.1 into K3 (caught) |
| #5543 | Request changes: "ban it" | Request changes: keep main's path
| don't break gpt-oss + DeepEP (fixed) |
| #6144, #5905 (controls) | Approve | Approve | -- |
| #6137 (control) | Approve | Needs discussion | -- (merge gate on an
upstream API) |

Code owner override, simulated on #6201: override by a code owner lifts
the
named item; `@claude override` from the author changes nothing; a code
owner's
"LGTM" approval followed by "review again" keeps Request changes.

Transport move: 83 RL CPU unit tests pass locally
(`transport/test_model_state_dict.py`, `test_trainer.py`,
`test_engine_loop.py`). `transport/test_rdma_microbatch.py`,
`test_generator.py` and
`test_batcher_actor.py` fail to collect in my env on `origin/main` too
(stale
attention-gym / Monarch), so CI is the check for those.

## Known issues / follow-ups
- Open PRs that edit the moved files rebase cleanly (git follows the
renames),
but new imports of the old module paths will break: #6309 (adds a delta
transport that should live in `rl/transport/`), #6237, #6176, #6177,
#5862,
  and drafts #6127, #6393, #6163, #5764.
- The Actions bot can't read dependency source (e.g. SGLang); follow-up
for the
  workflow.

## Self-review
pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch
mode diffs
against `origin/main` and skips description findings before a
description
exists; the "Config doesn't read runtime state" rule no longer
contradicts
hardware validation; dismissal dropped as an override form (the bot
can't tell
who dismissed); `test_rdma_microbatch.py` added to the transport area.
Not
addressed:
- One concern per PR -- the five changes ship together at the
maintainer's
  request.
- Open PRs touching the moved files -- listed above; the maintainer will
  coordinate.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI 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

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants