Skip to content

[flops] Count the lightning indexer's no-grad scoring as forward only - #6372

Merged
shuhuayu merged 2 commits into
pytorch:mainfrom
shuhuayu:indexer-flops
Nov 25, 2026
Merged

shuhuayu merged 2 commits into
pytorch:mainfrom
shuhuayu:indexer-flops

Conversation

@shuhuayu

@shuhuayu shuhuayu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

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

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

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.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 25, 2026
@shuhuayu

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @shuhuayu's task in 1m 49s —— View job


Request changes -- the indexer's with-grad pass should add 4 FLOPs per selected key, not 6, because its forward is a recompute: 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: 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

  1. 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 be 4 * index_dim * selected, not 6 (see the inline comment). Update test_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 under torch.no_grad(), and QSA's _select_blocks runs under no_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's flops(), 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_scores only when training and aux_loss is not None (deepseek_v4/attention.py:459-462, kimi_k3/dsa.py:207-214). QSA uses training 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 to topk, and QSA uses token_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.

Comment thread torchtitan/models/kimi_k3/dsa.py Outdated
Comment on lines +314 to +316
# 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())

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.

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.

Suggested 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())
# 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.
@shuhuayu

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @shuhuayu's task in 44s —— View job


Approve -- the indexer's with-grad recompute now counts only its backward (4 per selected key) at all three sites: 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 -- 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 -> 4 change in the recompute term is in kimi_k3/dsa.py:317, deepseek_v4/attention.py:367 and qwen3_8_flash_next/attention.py:715. A query whose document is shorter than top-k now costs 2 + 4 = 6 per key, the same as main.
  • Resolved: test_kimi_k3_1_dsa.py expects 4 * index_dim * (1 + topk) and checks that indexer_loss_coeff=0.0 drops that term.
  • Resolved: the description now says that QSA's _selected_block_scores is 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 4 factor. 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 -1024 per layer.
  • The recompute term is gated the same way the forward is: aux_loss for DSv4 and Kimi, and inner_attention.indexer_loss for QSA (qwen3_8_flash_next/attention.py:617). The QSA clamp token_budget // compress_ratio equals block_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.

@shuhuayu
shuhuayu marked this pull request as ready for review November 25, 2026 01:04
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 25, 2026
@shuhuayu
shuhuayu merged commit 32c026e into pytorch:main Nov 25, 2026
16 checks passed
Mystri pushed a commit to cann-framework/torchtitan-npu that referenced this pull request Dec 1, 2026
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
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