Repository navigation
[flops] Count the lightning indexer's no-grad scoring as forward only - #6372
Conversation
The indexer in Kimi K3.1 DSA, DeepSeek-V4 CSA and Flash-Next QSA scores every causal key under no_grad (2 FLOPs per multiply-add), then the indexer loss recomputes only the selected top-k scores with grad (6). Count the two passes separately instead of charging forward and backward over every key. Kimi K3.1 Pro FLOPs per token drop by 0.8% at 32k and 21.7% at 1M (one document). Only tflops and mfu change.
|
@claude review |
There was a problem hiding this comment.
Verdict: Request changes -- the split into a no-grad scoring pass and a with-grad pass is right, but the with-grad term counts its forward a second time. torchtitan's MFU convention excludes recomputation, so that term should be 4, not 6.
What this PR does. It changes how the lightning indexer's FLOPs are counted for Kimi K3.1 DSA, DeepSeek-V4 CSA and Qwen3.8 Flash-Next QSA. Main charges 6 * index_dim per causal key. The PR charges 2 * index_dim per causal key for the no-grad scoring, plus 6 * index_dim per selected key when the indexer loss is on. Only tflops and mfu(%) change.
Example. Kimi K3.1, one query at document position p, per index channel (index_dim = num_index_heads * index_head_dim):
p < topk (all keys selected) p >> topk
main 6 * (p + 1) 6 * (p + 1)
this PR 2 * (p + 1) + 6 * (p + 1) = 8 2 * (p + 1) + 6 * topk
model FLOPs (proposed) 2 * (p + 1) + 4 * (p + 1) = 6 2 * (p + 1) + 4 * topk
The selected scores are computed in the forward once, by the scoring pass. The grad-enabled pass recomputes them so autograd can run the backward. Under quadratic_attention_flops' rule (models/common/flops.py:35-36, "recomputation should not be counted in calculating MFU"), only that backward (4 per key) is new model work. With 4, a short document costs exactly what it does on main, so the "+0.02% to +0.08%" rise in the table goes away.
Must fix
torchtitan/models/kimi_k3/dsa.py:316,torchtitan/models/deepseek_v4/attention.py:365,torchtitan/models/qwen3_8_flash_next/attention.py:714: the with-grad term should be4 * index_dim * selected, not6(see the inline comment). Updatetest_kimi_k3_1_dsa.py:159, the two pinned DeepSeek-V4 values, and the results table to match.
Should consider
- Description: for QSA,
_selected_block_scores(qwen3_8_flash_next/attention.py:134-147) doesn't recompute only the top-k. It runs a dense Q x W GEMM over a window of blocks (W = 1280 at 125B/16K) and then gathers, and each chunk is checkpointed. Counting only the selected blocks fits the "useful pairs" convention, but the description should say this pass is a dense windowed GEMM, so the measured cost isn't mistaken for the formula.
Details
- Gate: the problem is real on main.
InnerIndexer.forward(deepseek_v4/compressor.py:310-321) scores every compressed key undertorch.no_grad(), and QSA's_select_blocksruns underno_grad(qwen3_8_flash_next/attention.py:353), yet main charges forward plus backward over all causal keys. The root cause is in each model'sflops(), the right layer. There's no duplicated helper to unify: the three sites differ in key counting (raw,// 4, block budget). - The recompute term is gated on the right conditions. DSv4 and Kimi run
return_scoresonly whentraining and aux_loss is not None(deepseek_v4/attention.py:459-462,kimi_k3/dsa.py:207-214). QSA usestraining and indexer_loss is not None(:617).flops()checks only the config, which is right for a training-FLOPs estimate. - Clamps are correct: Kimi uses
topk, DSv4 uses compressed keys clamped totopk, and QSA usestoken_budget // compress_ratio(=block_topk,:308). - The PR leaves the indexer loss's no-grad teacher recompute of the main-attention logits uncounted. That's consistent with the same recompute rule, and the rule is the reason the 6 here should be 4.
Not verified: the revised pinned values. They need a rerun of the two DeepSeek-V4 FLOPs tests after the change.
| # The indexer loss recomputes the top-k scores with grad. | ||
| if self.inner_attention.aux_loss is not None: | ||
| indexer_flops += 6 * index_dim * int(num_selected_keys.sum()) |
There was a problem hiding this comment.
The forward half of this term counts a recompute. The scoring pass on line 313 already charged 2 FLOPs for every key, selected ones included. Re-running the forward on the top-k with grad enabled is recomputation, and quadratic_attention_flops (models/common/flops.py:35-36) says "recomputation should not be counted in calculating MFU". It's the same reason flash attention's backward recompute and activation remat are left out. The model FLOPs that this pass adds are just the backward through the selected scores: 4 per (query, selected key, index channel).
What goes wrong today: for any document shorter than top-k, this charges 2 + 6 = 8 per key, which is more than main's 6. That's the "+0.02% / +0.05% / +0.08%" rise in the PR table, and it's an artifact of the double count. With 4, a key below top-k costs 2 + 4 = 6 again, and only the unselected keys get cheaper.
| # The indexer loss recomputes the top-k scores with grad. | |
| if self.inner_attention.aux_loss is not None: | |
| indexer_flops += 6 * index_dim * int(num_selected_keys.sum()) | |
| # The indexer loss backpropagates through the top-k scores. Their | |
| # forward is already counted above; the grad-enabled recompute is | |
| # recomputation and is not counted, as in quadratic_attention_flops. | |
| if self.inner_attention.aux_loss is not None: | |
| indexer_flops += 4 * index_dim * int(num_selected_keys.sum()) |
The same 6 -> 4 change applies at deepseek_v4/attention.py:365 and qwen3_8_flash_next/attention.py:714. You'll also need to update the test expectation (test_kimi_k3_1_dsa.py:159), the two pinned DeepSeek-V4 values, and the results table in the description.
Its forward repeats the no-grad scoring pass, and torchtitan's MFU convention excludes recomputation. Below top-k a query now costs the same as on main.
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- the with-grad recompute now counts only its backward (4 per selected key) at all three sites, so the earlier must-fix is resolved and nothing new turned up in ce2e012.
Since the last review
- Resolved: the
6->4change in the recompute term is inkimi_k3/dsa.py:317,deepseek_v4/attention.py:367andqwen3_8_flash_next/attention.py:715. A query whose document is shorter than top-k now costs2 + 4 = 6per key, the same as main. - Resolved:
test_kimi_k3_1_dsa.pyexpects4 * index_dim * (1 + topk)and checks thatindexer_loss_coeff=0.0drops that term. - Resolved: the description now says that QSA's
_selected_block_scoresis a dense, checkpointed windowed GEMM, and the results table shows no increases.
Example. Kimi K3.1, one query at document position p, per index channel:
p < topk p >> topk
main 6 * (p + 1) 6 * (p + 1)
this PR (HEAD) 6 * (p + 1) 2 * (p + 1) + 4 * topk
Details
- Pinned values match the
4factor. DSv4 flash at position 4095 has 1024 compressed keys and top-k 512. The per-layer change per index channel is-6*1024 + 2*1024 + 4*512 = -2048. The test's delta,92_762_352_876 - 92_410_031_340 = 352_321_536, is a whole number of those (2048 * 172_032). With the old factor 6, the change would have been-1024per layer. - The recompute term is gated the same way the forward is:
aux_lossfor DSv4 and Kimi, andinner_attention.indexer_lossfor QSA (qwen3_8_flash_next/attention.py:617). The QSA clamptoken_budget // compress_ratioequalsblock_topk(:308).
Not verified: I could not run the unit tests here (no permission to run commands). The pinned values were checked by hand against the formula.
Co-authored-by: hitwdy<[email protected]> # message auto-generated for no-merge-commit merge: !1381 merge fix/dsv4-document-mfu into master [fix] 修正 DeepSeek-V4 的文档级 MFU 估算 Created-by: hitwdy Commit-by: 1Fire4;hitwdy Merged-by: cann-robot Description: ## 描述 ### 修改原因 - 现行 DeepSeek-V4 的 MFU 按整段压缩序列估算注意力 FLOPs,并把全部 Indexer 候选计入反向,打包长上下文时会高估 ModelFLOPs。 - 仓库已按文档级口径公布 MFU,但代码仍按整段 `seq_len` 计算,官方 4k / 1M 配方(已开启 `per_doc_alignment`)会对不上。 - 文档真实边界只在训练 batch 的 `positions` 里,只改模型侧静态 `get_nparams_and_flops(seq_len)` 既拿不到打包后的实际文档长度,也赶不上上游打日志的时机。 ### 修改方案 - 回移 [TorchTitan #6325](pytorch/torchtitan#6325) 和 [#6372](pytorch/torchtitan#6372) 的文档级估算:按文档段累计因果可见的滑窗、压缩前缀和 CSA 选中项;Indexer 前向按候选,反向只按 top-k。 - 在 `model.py` 增加 `attention_flops_for_documents`,并修正静态 `get_nparams_and_flops`。 - 在扩展 `TrainerEx.step_batches` 中,于 CP 切分前读取文档边界,在日志窗口内累加注意力 FLOPs,并在 `metrics.log` 前改写 `num_flops_per_token`;失败时回滚计数。FLOPs 只在 DP 间汇总。 - 这是针对当前 pinned TorchTitan 0.3.0 的临时适配,上游纳入上述变更后应删除。 - DP 归约先将注意力 FLOPs 转为整数 MFLOPs,归约后再换算回 FLOPs,以避免长序列日志窗口溢出 `int64`。 - TorchFT 复用文档计数与 MFLOPs 缩放,在 optimizer 提交前沿 DP 和当前 TorchFT 副本归约。故障中断的 step 从 FLOPs、吞吐 token 和数据加载统计中排除。 ## 类型 - [x] Bug 修复 - [ ] 新功能 - [ ] 重构(即不是新增功能,也不是修改bug的代码变动) - [ ] 构建过程或辅助工具的变动 - [ ] 文档内容更新 ## Checklist: - [ ] 我的代码遵循这个项目的代码风格 - [ ] 我已经自己测试过我的代码 - [ ] 我已经更新了相应的文档 - [x] 我已经在标题中正确使用了类型标签(例如:`feat`, `fix`, `refactor`, `docs`, `test`) ## 如何测试 运行 DeepSeek-V4 的 FLOPs 单测。 ```bash python -m pytest -q tests/unit_tests/models/deepseek_v4/test_dsv4_config.py \ -k 'test_flash_mtp_4k_model_flops or test_flash_packed_attention_flops_reset_at_document_boundaries' ``` - **Flash + MTP,4K 单文档**。校验参数量为 `290,942,278,866`,将全模型 FLOPs/token 的预期值从 `92,762,352,876` 更新为 `90,923,588,844`。 - **Flash,4K packed**。按 query 独立累加两个 2K 文档的滑窗、HCA 压缩块、CSA 候选和 top-k 选中项,与闭式公式对照。再与同样为 4,096 token 的单文档比较,校验文档边界会降低注意力 FLOPs。 - **执行结果**。提交 `b79d6d06` 的 CI 已通过。本地 CPU UT 在导入阶段因缺少 `libhccl.so` 未能执行。1M MFU 为公式复算,NPU 训练性能与精度未实测。[CI 流水线](https://gitcode.com/cann/torchtitan-npu/actions/runs/19ddc8f2e39f435c9109c494e329af92) - 补充 DP 归约回归用例。独立 CPU 检查模拟 DP=16、单 rank 8 条和 128 条 1M 文档,两种情况下的缩放误差均在 1 FLOP/token 以内。改动文件 Ruff 通过,正式 pytest 仍受 `libhccl.so` 限制。 - TorchFT 新增回归用例,模拟跨副本的不同文档 FLOPs、提交前归约,以及中断 step 后恢复日志计数。独立 CPU 模拟检查通过,实际 TorchFT 多副本训练和故障恢复未运行。 #### UT 新旧公式对比 | UT 输入 | 计数范围 | 旧算法(GFLOPs/token) | 新算法(GFLOPs/token) | 相对变化 | | --- | --- | ---: | ---: | ---: | | Flash + MTP,`[4096]` | 全模型 | 92.762353 | 90.923589 | −1.98% | | Flash,`[2048, 2048]` | 注意力及 Indexer | 7.700742 | 4.532048 | −41.15% | | Flash,`[4096]`(packed UT 对照组) | 注意力及 Indexer | 7.700742 | 5.862758 | −23.87% | Packed UT 直接断言整条样本的注意力 FLOPs。旧公式对两种文档布局均得到 `31,542,239,821,824` FLOPs。新公式对 `[2048, 2048]` 和 `[4096]` 分别得到 `18,563,268,083,712` 和 `24,013,858,406,400` FLOPs。同用新公式,两个 2K 文档比单个 4K 文档少 22.70%。 ### 精度和性能验证结果 本修改不涉及精度变动。 #### 1M BF16 MFU 估算 采用 Flash 无 MTP 配置,1M 为 1,048,576 token。新旧公式均假设吞吐为 1,500 tokens/s/卡,并使用仓库 1M 基准的 Ascend 950 BF16 峰值 432 TFLOPS/卡。例如,新公式下单文档的 MFU 为 `163.665835 × 1,500 ÷ 1,000 ÷ 432 ≈ 56.83%`。 | 1M 输入 | 旧算法(GFLOPs/token) | 新算法(GFLOPs/token) | 旧 MFU | 新 MFU | MFU 变化(百分点) | | --- | ---: | ---: | ---: | ---: | ---: | | 1 个 1M 文档 | 421.020 | 163.666 | 146.19% | 56.83% | −89.36 | | 64 个 16K 文档 | 421.020 | 87.274 | 146.19% | 30.30% | −115.88 | 旧公式按整行长度计数,因此两种布局得到相同的 MFU。新公式按文档内的因果可见前缀计数,并将 Indexer 反向计数限制在 top-k。表中吞吐固定,MFU 差异来自 FLOPs 估算变化。 ## 其他信息 跟踪的 TorchTitan 版本包含上述两个 PR 后,删除临时估算器和训练指标适配。 See merge request: cann/torchtitan-npu!1381
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 lossrecomputes 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
tflopsandmfu(%)drop by 0.9% at 32ktokens and 21.7% at 1M. This is the follow-up the TODO in #6363 describes.
Problem
Each indexer runs in two passes:
InnerIndexer.forward(deepseek_v4/compressor.py:310no_gradscoring,
:329-333recompute).InnerIndexer, over compressed keys.QSAIndexer._select_blocksunder no_grad, then_selected_block_scores.Main charges
6 * index_heads * index_head_dim * (p + 1)per query: forward andbackward over all causal keys. The scoring pass has no backward, and the
recompute (which does) touches at most top-k keys.
Solution
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 costs2 + 4 = 6per key, thesame as main.
DeepSeek-V4 and Flash-Next count compressed keys,
(p + 1) // 4, as before. Therecompute term counts only when the indexer loss exists (
aux_loss, orindexer_lossfor 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,
-1top-k slots), the forward ofthe 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: itruns 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):FlopCounterModeonInnerIndexer(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
tflopsandmfu(%)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=0drops therecompute's backward term.
test_deepseek_v4_flops.py(flash, 4096 queries at position 4095):92_762_352_876->92_410_031_340per token.test_flops_estimators.py(deepseek_v4debugmodel):59_824_686->59_791_918.Test plan
pre-commit on the changed files passes (pyrefly left to CI).