Repository navigation
[kimi_k3_1] Port DSA FLOPs to flops(positions), fixing main's lint - #6363
Conversation
|
Reply from claude: @claude review |
|
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. |
There was a problem hiding this comment.
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
- 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_tokenorquadratic_attention_flops_per_tokenreference remains in the repo, and no overlapping open PR exists. The fix sits in the model folder, which is the right layer. It mirrorsdeepseek_v4/attention.py:337-370term for term (clamped attention plus a factor-6 indexer over all keys). KimiDSAAttention.Configis whatfirst_full_attentionreturns 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.
|
Reply from claude: @JavaZeroo @acisseJZhong, #6007 merged after #6325 replaced the attention FLOPs API, so |
108b6b8 to
a81832f
Compare
|
@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.
a81832f to
bdbf900
Compare
| num_keys=num_keys.clamp(max=self.inner_attention.inner_indexer.topk), | ||
| ) | ||
|
|
||
| # TODO: the indexer scores all keys without grad, then recomputes only the |
There was a problem hiding this comment.
can you fix in this PR?
There was a problem hiding this comment.
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.
…#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).
Summary (human-written)
Agent details
TLDR: Since main 74a2c8e,
lintfails on every PR into main that changes a Python file. pyrefly reportsCould not import quadratic_attention_flops_per_token from torchtitan.models.common.flopsattorchtitan/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 portsKimiDSAAttention.Config.flops_per_token(seq_len)toflops(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'stflopsandmfu(%)read 8.4% high at 32k tokens and 3.1x at 1M.Problem
flops_per_token(seq_len)withflops(positions). It removedquadratic_attention_flops_per_token.KimiDSAAttention.Config.flops_per_tokenon the old API. Its lint passed on 11-23 at 23:38 UTC, before bd64f5c merged (11-24 01:55 UTC).lintnow fails on those PRs, from their next push on.attention.flops(positions)(decoder.py:214). DSA layers inherit it fromKimiMLAAttention: all p + 1 keys, no top-k cap, no indexer.Solution
flops(positions), as DeepSeek-V4's sparse attention does (deepseek_v4/attention.py:337).tflopsandmfu(%)metrics change. Loss and gradients don't.Results
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
pyrefly check, whole project, on a copy of this PR: the
dsa.pyerror is gone. One error remains locally, inactivation_offload.py:449. It comes from our older torch nightly, which lacksFSDPModule.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.