Skip to content

[kimi_k3_1] Port DSA FLOPs to flops(positions), fixing main's lint - #6363

Merged
shuhuayu merged 1 commit into
pytorch:mainfrom
felipemello1:felipemello1/ci/kimi-dsa-flops
Nov 25, 2026
Merged

shuhuayu merged 1 commit into
pytorch:mainfrom
felipemello1:felipemello1/ci/kimi-dsa-flops

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

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.

# 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 , with SKIP=pyrefly-check because pyrefly ran above: all hooks pass.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 24, 2026
@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve: please fill in the empty "Summary (human-written)" section before merging. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the item below before merging -- the port fixes main's broken lint and restores the top-k cap and the indexer in Kimi K3.1's FLOPs count, using the same formula as DeepSeek-V4's sparse attention.

What this PR does. bd64f5c changed the estimator to call attention.flops(positions) and removed quadratic_attention_flops_per_token. 74a2c8e then landed KimiDSAAttention.Config.flops_per_token(seq_len) on the old API. So pyrefly fails on the import. Nothing calls that method, so DSA layers inherit KimiMLAAttention.Config.flops (kimi_k3/attention.py:79): dense attention over all p + 1 keys, with no top-k cap and no indexer. This PR renames the override to flops(positions). Attention now reads min(p + 1, topk) keys per query, and the indexer scores all p + 1 keys.

Example. debugmodel (index_topk=128), two queries at positions [0, 128]:

num_keys          = [1, 129]
main  (inherited) : 6*H*(Dqk+Dv)*130                       (dense, no indexer)
PR    attention   : 6*H*(Dqk+Dv)*(1 + 128)                 (clamped to top-k)
      indexer     : 6*Hidx*Didx*(1 + 129)

When every query sits at position seq_len - 1, the result equals the old flops_per_token(seq_len), so the formula itself is unchanged. Only the tflops and mfu(%) metrics move, and loss and gradients don't.

Must fix

  1. PR description -- the "Summary (human-written)" section is empty. The author needs to fill it in before merge.
Details
  • Gate: the problem is real on main. No other flops_per_token or quadratic_attention_flops_per_token reference remains in the repo, and no overlapping open PR exists. The fix sits in the model folder, which is the right layer. It mirrors deepseek_v4/attention.py:337-370 term for term (clamped attention plus a factor-6 indexer over all keys).
  • KimiDSAAttention.Config is what first_full_attention returns for kimi_k3_1 (kimi_k3_1/flavors.py:263), so the new test exercises the override and not the inherited method. Positions [0, topk] hit both sides of the clamp, so the test catches the exact silent regression this PR fixes: an override that stops being called.
  • The TODO about the indexer's no-grad scoring pass applies to both models. Leaving it for a follow-up is reasonable.

Not verified: the new unit test wasn't run here; the PR's test plan reports it passing.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @JavaZeroo @acisseJZhong, #6007 merged after #6325 replaced the attention FLOPs API, so KimiDSAAttention.Config.flops_per_token imports a removed function and lint fails on main. This PR ports it to flops(positions). Could you please take a look?

@felipemello1
felipemello1 marked this pull request as ready for review November 24, 2026 20:38
@felipemello1
felipemello1 force-pushed the felipemello1/ci/kimi-dsa-flops branch from 108b6b8 to a81832f Compare November 24, 2026 20:38
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 24, 2026
@shuhuayu

Copy link
Copy Markdown
Contributor

@felipemello1 can you rebase to fix the cpu tests?

bd64f5c replaced the attention configs' flops_per_token(seq_len) with
flops(positions) and removed quadratic_attention_flops_per_token.
74a2c8e added KimiDSAAttention.Config.flops_per_token, which still
imports the removed function. On main this breaks two things:

1. pyrefly reports the missing import, so lint fails on every PR into
   main that changes a Python file.
2. Nothing calls flops_per_token anymore, so the FLOPs estimator uses the
   dense formula inherited from KimiMLAAttention for the DSA layers: all
   p + 1 keys and no indexer. For one Kimi K3.1 Pro document, the tflops
   and mfu(%) metrics read 8.4% high at 32k tokens and 3.1x at 1M.

Port the method to flops(positions): attention reads at most top-k keys
per query, and the indexer scores all p + 1 of them. A TODO records that
the indexer term, like DeepSeek-V4's, still counts a backward over all
keys.
@felipemello1
felipemello1 force-pushed the felipemello1/ci/kimi-dsa-flops branch from a81832f to bdbf900 Compare November 24, 2026 22:57
num_keys=num_keys.clamp(max=self.inner_attention.inner_indexer.topk),
)

# TODO: the indexer scores all keys without grad, then recomputes only the

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 you fix in this PR?

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.

i just checked this, i will do a followup pr to change the formula for both kimi k3.1 and dsv4. let's unblock the ci first.

@shuhuayu
shuhuayu merged commit c561820 into pytorch:main Nov 25, 2026
15 checks passed
shuhuayu added a commit that referenced this pull request Nov 25, 2026
…#6372)

## Summary (human-written)

correct flops count from the indexer attention compute, matters in long
context setups as shown in the table.

## Agent details

**TLDR:** The lightning indexer in Kimi K3.1's DSA, DeepSeek-V4's CSA
and Qwen3.8
Flash-Next's QSA is charged 6 FLOPs per (query, key, index channel), as
if it ran
forward and backward over every causal key. It doesn't: scoring every
key runs
under `torch.no_grad()` (forward only, 2 FLOPs), and only the indexer
loss
recomputes the selected top-k scores with grad. That recompute's forward
repeats
the scoring, so only its backward (4 FLOPs) is new work. This PR counts
the two
passes separately. Kimi K3.1 Pro's `tflops` and `mfu(%)` drop by 0.9% at
32k
tokens and 21.7% at 1M. This is the follow-up the TODO in #6363
describes.

**Problem**

Each indexer runs in two passes:

```
scoring    every causal key, under torch.no_grad()        -> top-k indices
recompute  the top-k selected keys, with grad              -> indexer loss (KL)
```

- Kimi K3.1: `InnerIndexer.forward` (`deepseek_v4/compressor.py:310`
no_grad
  scoring, `:329-333` recompute).
- DeepSeek-V4: the same `InnerIndexer`, over compressed keys.
- Flash-Next: `QSAIndexer._select_blocks` under no_grad, then
  `_selected_block_scores`.

Main charges `6 * index_heads * index_head_dim * (p + 1)` per query:
forward and
backward over all causal keys. The scoring pass has no backward, and the
recompute (which does) touches at most top-k keys.

**Solution**

```python
# before
indexer_flops = 6 * index_dim * sum(p + 1)

# after
indexer_flops = 2 * index_dim * sum(p + 1)                  # scoring, no grad
if indexer loss is on:
    indexer_flops += 4 * index_dim * sum(min(p + 1, topk))  # backward of the recompute
```

The with-grad pass recomputes scores the scoring pass already produced,
so its
forward is not counted, following `quadratic_attention_flops`' rule that
"recomputation should not be counted in calculating MFU"
(`models/common/flops.py`). Below top-k, a query costs `2 + 4 = 6` per
key, the
same as main.

DeepSeek-V4 and Flash-Next count compressed keys, `(p + 1) // 4`, as
before. The
recompute term counts only when the indexer loss exists (`aux_loss`, or
`indexer_loss` for Flash-Next), matching when the models run it.

The counts follow the convention of the other attention terms: useful
causal,
in-document pairs, no recomputation. Executed work that stays uncounted,
as
before: masked pairs (cross-document tiles, `-1` top-k slots), the
forward of
the with-grad recompute, and the indexer loss's no-grad teacher
recompute of the
main attention logits on the top-k.

For QSA, the with-grad pass (`_selected_block_scores`) is not a top-k
gather: it
runs a dense Q x W GEMM over a window of blocks (W = 1280 at 125B, 16K
tokens),
checkpointed per chunk, then gathers the selected blocks. The formula
counts
only the selected blocks, so the measured cost of that pass is higher.

**Results**

FLOPs per token, one document (`positions = 0..seq_len-1`):

| Model | seq_len | main | this PR | change |
| --- | --- | --- | --- | --- |
| Kimi-K3.1-Pro | 4096 | 6.362e11 | 6.360e11 | -0.03% |
| Kimi-K3.1-Pro | 32768 | 6.466e11 | 6.409e11 | -0.88% |
| Kimi-K3.1-Pro | 131072 | 6.758e11 | 6.508e11 | -3.69% |
| Kimi-K3.1-Pro | 1048576 | 9.465e11 | 7.411e11 | -21.70% |
| deepseek_v4_flash | 4096 | 8.557e10 | 8.548e10 | -0.10% |
| deepseek_v4_pro | 4096 | 3.124e11 | 3.124e11 | +0.00% |
| Flash-Next 125B-A6B-text (no indexer loss) | 4096 | 4.192e10 |
4.190e10 | -0.03% |
| Flash-Next 125B-A6B-text (no indexer loss) | 32768 | 4.245e10 |
4.235e10 | -0.24% |
| Flash-Next 125B-A6B-text (no indexer loss) | 262144 | 4.355e10 |
4.275e10 | -1.85% |

`FlopCounterMode` on `InnerIndexer` (reference impl, CPU, I=4, E=64,
topk=128,
packed documents of 300 and 100 tokens) confirms the factors: the
scoring pass
costs exactly 2 FLOPs per multiply-add with no backward, and the
with-grad
recompute executes exactly 6 per (query, slot): 2 forward (not counted,
a
recompute) and 4 backward. The measured pair counts are larger than the
formula's (the reference scores the whole packed T x T, and the
recompute
computes all top-k slots including `-1`), which is the masked work
above.

Only `tflops` and `mfu(%)` change. Loss and gradients don't.

**Tests**

-
`test_kimi_k3_1_dsa.py::test_dsa_flops_index_every_key_and_attend_to_topk`:
expects the two terms, and checks that `indexer_loss_coeff=0` drops the
  recompute's backward term.
- Pinned DeepSeek-V4 values updated; each change matches the formula
exactly:
  - `test_deepseek_v4_flops.py` (flash, 4096 queries at position 4095):
    `92_762_352_876` -> `92_410_031_340` per token.
- `test_flops_estimators.py` (`deepseek_v4` debugmodel): `59_824_686` ->
    `59_791_918`.

**Test plan**
```
pytest tests/unit_tests/cpu/models/kimi_k3 tests/unit_tests/cpu/models/deepseek_v4 \
  tests/unit_tests/cpu/models/common/test_flops_estimators.py \
  tests/unit_tests/cpu/test_deepseek_v4_indexer_loss.py \
  tests/unit_tests/cpu/models/qwen3_8_flash_next
```
pre-commit on the changed files passes (pyrefly left to CI).
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.

4 participants