Skip to content

[metrics] Count causal and document-masked attention FLOPs per query position - #6325

Merged
acisseJZhong merged 10 commits into
mainfrom
mfu-causal-document-flops
Nov 24, 2026
Merged

acisseJZhong merged 10 commits into
mainfrom
mfu-causal-document-flops

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

update mfu calculation to account for causal&document mask, and paddings, otherwise in some case linear attention model mfu > 100%. Intentionally keep tps unchanged(left as future work, @felipemello1 seems already have #5455).

Why

The FLOPs estimator charges every token for attention over max_context_length keys. A causal query at position p sees only p + 1 keys, and with packed documents only keys in its own document, so long-context MFU goes above 100%.

Example. Qwen3.5 9B, 1M-token rows with 2-3 packed documents, CP 8 on 8 H100s:

main:  steps 3-12  mfu 89% - 129% (mean 112.8%)

What changed

  • Attention.Config.flops_per_token(seq_len) is replaced by Attention.Config.flops(positions): each attention config computes its cost from the document positions of the non-padding queries (positions restart at 0 at each document start). Full attention charges p + 1 keys per query at position p, sliding window min(p + 1, W), DeepSeek V4 / Flash-Next compressed attention their own per-position counts, and linear attention (GDN, KDA) a fixed cost per query.
  • Padding tokens (padding_mask) are not counted, including DeepSeek V3 / V4 MTP head FLOPs.
  • HF backend (transformers_modeling_backend): same per-position counting for full and sliding-window attention. With attn_mask_type="causal" (attends across documents) keys are counted from the row start.

Megatron-LM (attention.py, training.py) and Megatron-Bridge (flop_utils.py) count the same way: causal, per packed document, no padding.

User-facing changes

tflops / mfu drop for every model with full attention (Llama 3 8B, 8K, one document per row: 0.889x), and also for sliding-window and compressed attention layers (gpt-oss, Muse, DeepSeek V4, Flash-Next). Loss and grad_norm are unchanged.

Config main mfu this PR mfu
Qwen3.5 9B, 1M, 1 node (2,425 tok/s/GPU) 112.8% 40.3%
Qwen3.5 9B, 1M, 16 nodes (1,910 tok/s/GPU) 88.9% 31.7%

Offline recount: measured tok/s, FLOPs/token from this estimator over 111 rows packed from the same data.

Overhead

CPU only, no device sync. Identical attention configs (equal apart from param_init) are counted once, so each microbatch calls flops(positions) once per distinct config (Qwen3.5 9B and gpt-oss 120B: 2, Llama 3 8B: 1).

Per microbatch, single CPU thread, median of 20 runs on a shared host (noisy):

Config main this PR
Qwen3.5 9B, 256K 0.44 ms 2.49 ms
gpt-oss 120B, 128K 0.21 ms 1.36 ms
Llama 3 8B, 8K 0.02 ms 0.09 ms

Testing

  • pytest tests/unit_tests/cpu/models/common/test_flops_estimators.py tests/unit_tests/cpu/models/deepseek_v4/test_deepseek_v4_flops.py: pass, except the Flash-Next multimodal case, which fails the same way on main in my env.
  • Existing tests pass full-length positions and no padding, so recorded main values are unchanged.
  • HF backend: checked offline that causal minus block_causal equals the cross-document keys times the per-key FLOPs, and that a trailing padding token adds nothing (no test added: no CI job runs transformers_modeling_backend unit tests).
  • New test_attention_counts_each_query_at_its_document_position: Qwen3.5 debugmodel (full attention + GatedDeltaNet), documents of lengths 3 and 2 plus one padding token; expects 1 + 2 + 3 + 1 + 2 = 9 keys for full attention and 5 queries for GatedDeltaNet.

Known issues / follow-ups

  • tps still counts padding tokens, as on main and in Megatron-LM / Megatron-Bridge; this PR does not change it.

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

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 3m 49s —— View job


Approve -- please address the items in the review before merging (the human-written summary is empty and models/README.md still describes the old FLOPs convention): 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 problem is real: MFU goes above 100% on main at long context. The fix sits in the shared Decoder.Config.build_flops_estimator, so pretraining, graph_trainer and RL all use it. The math is right, and the leftover items are doc edits. models/common/decoder.py is core code, so a maintainer still needs to review.

What this PR does. For each Attention.Config in the decoder, the estimator evaluates flops_per_token at 1, 2 and seq_len keys. If the formula is affine in the number of keys, the layer is charged at f(position + 1) per real token. That needs only sum(positions + 1) over non-padding tokens. Other layers (sliding window shorter than the context, compressed attention) keep f(seq_len). Padding tokens are dropped from the parameter FLOPs and from the DeepSeek V3/V4 MTP head term.

Example. One row with seq_len=8: documents of length 3 and 2, then 3 padding tokens (positions=[0,1,2,0,1,0,1,2]). Let P be the parameter FLOPs per token and A the attention FLOPs per key, both summed over layers.

main: 8 tokens * (P + 8A)              = 8P + 64A
PR:   5 real tokens * P + (1+2+3 + 1+2) A = 5P +  9A

All language-model backends use block-causal masking (config_utils.get_attention_config). Positions restart at each document and at each max_context_length chunk (packing.py:400), so positions + 1 matches the keys the kernel actually attends to.

Must fix

  1. The PR description's "Summary (human-written)" section is empty. Please fill it in.
  2. torchtitan/models/README.md:109-110 (not in the diff) still says "Decoder attention uses configured sequence length rather than packed document lengths. Causal sparsity ... are omitted." After this PR that is wrong. Please update the "FLOPs estimation" section to say three things: attention is charged per query position within its document, padding is excluded, and sliding-window and compressed attention keep the full-length estimate.

Should consider

  • torchtitan/models/common/flops.py:37 -- the docstring claims causal and document masking apply to every layer, which isn't true (see the inline comment).
  • torchtitan/experiments/transformers_modeling_backend/model.py:713 still charges input.numel() tokens at max_context_length keys. MFU from the HF backend and from the native model for the same architecture now differ by about 1.1x at 8K and far more at long context. A follow-up is fine; please mention it under Known issues.

Questions

  • #5455 (open, felipemello1) fixes the same thing only for RL mfu_percent, using a non-causal L * f(L) per document. RL goes through TrainingEngine.flops_estimator and gets this fix for free, so #5455's FLOPs part looks superseded. Its other part, counting only real tokens in RL tokens_per_second, is still open here ("tps still counts padding tokens"). Should the two authors agree which PR owns tps, and close the FLOPs half of #5455?
Details
  • Decomposition check: for an affine layer, f(k) = f(1) + (k-1)d with d = f(2) - f(1). The code adds f(1) - d per real token plus d * sum(p + 1), which is exactly sum f(p + 1). The equality probe uses Python ints, so there is no float-rounding misclassification.
  • A sliding window with W >= max_context_length passes the probe and is counted causally. That is correct, because min(p + 1, W) = p + 1 for every position.
  • GDN/KDA return a constant, so d = 0 and they are charged once per real token. This matches main apart from padding.
  • Encoder attention: vision/audio encoders don't subclass Attention, so Decoder.Config.traverse(Attention.Config) doesn't pick them up. Encoder estimators are unchanged.
  • Cost: the estimator runs on the CPU microbatch before to_input_dict (training_engine.py:732, graph_trainer/trainer.py:268). The added .sum() is a CPU reduction with no device sync.
  • CP/PP: the estimate covers the unsharded per-DP-rank microbatch and is replicated across CP ranks, as before. PP calls it per microbatch. Neither is affected.
  • TokenizedTrainingMicrobatch.as_input_dict always provides positions and padding_mask, and so does the RL TrainingMicrobatch, which builds on it. Every Decoder caller therefore has the new keys.

Not verified: the description's MFU numbers (offline recount on GPU data). I couldn't run the unit tests in this environment.

Comment thread torchtitan/models/common/flops.py Outdated
Comment on lines +37 to +39
``seq_len`` is the number of keys one query attends to.
``Decoder.Config.build_flops_estimator`` applies causal and document
masking by summing over each query's position in its document.

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 says the decoder estimator applies causal and document masking, but it only does that for layers whose formula is affine in the number of keys. A sliding window shorter than max_context_length (gpt_oss, Muse sliding layers, DeepSeek V4) and compressed attention (DeepSeek V4, Flash-Next) still get the full-length estimate in the else branch of decoder.py. The docstring should say which case applies:

Suggested change
``seq_len`` is the number of keys one query attends to.
``Decoder.Config.build_flops_estimator`` applies causal and document
masking by summing over each query's position in its document.
``seq_len`` is the number of keys one query attends to.
``Decoder.Config.build_flops_estimator`` sums this over each query's
position in its document when it is affine in ``seq_len``; sliding-window
and compressed attention keep the full-length estimate.

@acisseJZhong
acisseJZhong force-pushed the mfu-causal-document-flops branch from 265cf07 to cb76e5b Compare November 23, 2026 03:47
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review latest changes

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 1m 38s —— View job


Approve -- the earlier must-fix items are resolved; there are two small should-consider items: 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 earlier must-fix items are resolved, and the new HF-backend counting is correct. models/common/decoder.py is core code, so a maintainer still needs to review.

What changed since the last review (48fd5a0, 7b33b99, 4b54ac6). The HF backend now splits its estimate in two. Full-attention layers are charged per attended key. Sliding-window and chunked layers keep the full-length estimate. With block_causal, the HF backend uses positions, the same as Decoder. With causal, it counts keys from the start of the 1-D microbatch, which matches the flex causal BlockMask built over all num_tokens. The README and the flops.py docstring now describe the new convention.

Example (HF Llama, 2 layers, from the new test). Documents of length 3 and 2, then 1 padding token, so positions=[0,1,2,0,1,2]:

main:          6 tokens * (6N + 128 keys * K)
block_causal:  5 * 6N + (1+2+3 + 1+2) * K =  9K keys
causal:        5 * 6N + (1+2+3+4+5)   * K = 15K keys

Earlier items

  • Human-written summary is empty: resolved.
  • models/README.md described the old convention: resolved.
  • flops.py docstring overclaimed: resolved (the suggested wording was applied).
  • HF backend still used the full-length estimate: resolved in this PR rather than as a follow-up.
  • Overlap with #5455: the description now says tps is left to #5455.

Should consider

  • torchtitan/experiments/transformers_modeling_backend/model.py:735 -- positions is always 1-D, so drop shape[-1] and expand_as (see the inline comment).
  • torchtitan/experiments/transformers_modeling_backend/tests/test_flops_estimator.py -- no CI job runs this file. unit_test_cpu.yaml ignores torchtitan/experiments/**. The HF workflow runs only integration_tests. run_tests.sh runs only test_moe_parallelism.py. Sibling tests such as test_flex_attention.py have the same gap. At minimum, add the new file to the pytest line in run_tests.sh. Otherwise the causal vs block_causal check is never exercised.
Details
  • HF flops_per_key evaluates quadratic_attention_flops_per_token(seq_len=1). That formula is linear in seq_len with no constant term, so K * sum(p + 1) is exact for full-attention layers. The test's 2 * 6 * 4 * (16 + 16) matches this.
  • The getattr(self, "attn_mask_type", "causal") default matches how get_attention_metadata and _build_dense_attention_mask read the same field. The estimator therefore agrees with the mask the model actually builds.
  • Unrecognized HF layer types were already approximated as full attention. They are now charged causally as well, which is consistent.
  • DSA models (glm_moe_dsa) attend to top-k keys, so the causal count still overestimates past k. That was already an approximation on main (main used full length), and it is not made worse here.
  • Sliding window with W >= max_context_length: Decoder counts it causally, while the HF backend keeps it at full length. This only matters for unusual configs; no change needed.
  • The _text test helper (positions = seq_len - 1, no padding) reproduces main's values, so the recorded constants in test_text_estimates_preserve_main and the DSv4 test still check that nothing regressed.

Not verified: I couldn't run the unit tests in this environment.

is_real = ~input_dict["padding_mask"]
positions = input_dict["positions"]
if not document_masked:
positions = torch.arange(positions.shape[-1]).expand_as(positions)

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.

positions is always 1-D here. get_attention_metadata and _build_dense_attention_mask read positions.shape[0], and forward calls unsqueeze(0) on it. So shape[-1] plus expand_as reads as if a 2-D [B, L] input were supported, which it isn't. The "causal" mask spans the whole 1-D microbatch, so an arange over all of it is the correct count. Suggest matching the sibling code:

Suggested change
positions = torch.arange(positions.shape[-1]).expand_as(positions)
positions = torch.arange(positions.shape[0])

@acisseJZhong
acisseJZhong marked this pull request as ready for review November 23, 2026 04:38
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 23, 2026
"""Return total and architecturally active native decoder parameters."""
return get_parameter_counts(model)

def build_flops_estimator(

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 math looks confusing -- could you explain to me like to a 5-year-old?

I believe there must be a way to refactor the code to make it readable.

Comment thread torchtitan/models/common/decoder.py Outdated
Comment on lines +199 to +200
# TODO: sliding-window and compressed attention are not affine
# in the number of keys; they keep the full-length estimate.

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.

How about linear attention?

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude address my inline comments

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 26s —— View job


I made the change for both inline comments, but the push was rejected: the branch rule requires the "Meta CLA Check" status for my commit. @acisseJZhong, please apply the patch below yourself. Tests and lint have not been run on it: this environment doesn't allow me to run pytest or pre-commit.

decoder.py:174 -- "explain like to a 5-year-old"

The old code looked at each layer's cost at 1, 2 and seq_len keys and checked whether it was a straight line (affine). That was general, but hard to follow. The new version asks one question per layer: does this layer cost the same for every key a query looks at?

  • Yes (full attention): cost(k keys) = k × cost(1 key). The layer is charged cost(1 key) for each key a query actually sees.
  • No (everything else): the layer is charged cost(seq_len keys) once per real token, the same as main.

A query at document position p sees p + 1 keys. Documents of lengths 3 and 2 have positions = [0, 1, 2, 0, 1], so they see 1 + 2 + 3 + 1 + 2 = 9 keys in total. That example is now in the code comment.

decoder.py:200 -- "How about linear attention?"

Linear attention (GDN, KDA) keeps a fixed-size state, so its cost per token doesn't depend on how many keys come before it: delta_rule_flops_per_token ignores seq_len. It lands in the "No" branch, where cost(seq_len) equals cost(1). So it is charged exactly once per real token, the same as main except that padding is now dropped. The code comment now says this. The existing test_attention_counts_each_query_at_its_document_position covers it, because the Qwen3.5 debugmodel mixes GatedDeltaNet with full attention.

Same numbers as before

I checked every flops_per_token override by hand. Each one either grows exactly with the number of keys (GQA, DSv3, Kimi K3, Qwen3.5, gpt-oss without a window) or doesn't depend on it at all (GDN, KDA). None has both a fixed part and a per-key part, which is the only case the old affine check handled differently. Sliding-window layers shorter than seq_len, DSv4 compressed attention and Flash-Next still take the full-length branch. So all recorded test values should stay the same.

Patch (commit 5af7e07, apply with git apply)
diff --git a/torchtitan/models/common/decoder.py b/torchtitan/models/common/decoder.py
--- a/torchtitan/models/common/decoder.py
+++ b/torchtitan/models/common/decoder.py
@@ -181,32 +181,32 @@ class Decoder(BaseModel):
             flops_per_token = active_parameter_flops_per_token(
                 model, excluded_submodules=excluded_submodules
             )
-            # A causal query at document position p attends to p + 1 keys. When
-            # attention FLOPs are affine in the number of keys, the batch total
-            # needs only sum(positions + 1).
+            # A causal query at document position p attends to p + 1 keys. Full
+            # attention costs the same for each key, so it is charged per key a
+            # query attends to. Every other layer is charged per token at
+            # seq_len keys: exact for linear attention (GDN, KDA), whose cost
+            # does not depend on the number of keys.
             flops_per_key = 0
             for _, attention, _, _ in self.traverse(Attention.Config):
                 one_key_flops = attention.flops_per_token(1)
-                layer_flops_per_key = attention.flops_per_token(2) - one_key_flops
                 full_length_flops = attention.flops_per_token(seq_len)
-                if (
-                    full_length_flops
-                    == one_key_flops + (seq_len - 1) * layer_flops_per_key
-                ):
-                    flops_per_token += one_key_flops - layer_flops_per_key
-                    flops_per_key += layer_flops_per_key
+                if full_length_flops == seq_len * one_key_flops:
+                    flops_per_key += one_key_flops
                 else:
-                    # TODO: sliding-window and compressed attention are not affine
-                    # in the number of keys; they keep the full-length estimate.
+                    # TODO: sliding-window and compressed attention keep the
+                    # full-length estimate.
                     flops_per_token += full_length_flops
 
             def estimate(input_dict: Mapping[str, Any]) -> int:
-                # positions restart at 0 at each document start. Padding does
-                # no useful work, so it is not counted.
+                # positions restart at 0 at each document, e.g. documents of
+                # lengths 3 and 2 have positions [0, 1, 2, 0, 1], so their
+                # queries attend to 1 + 2 + 3 + 1 + 2 = 9 keys in total.
+                # Padding does no useful work, so it is not counted.
                 is_real = ~input_dict["padding_mask"]
+                num_real_tokens = int(is_real.sum())
                 num_attended_keys = int(((input_dict["positions"] + 1) * is_real).sum())
                 return (
-                    flops_per_token * int(is_real.sum())
+                    flops_per_token * num_real_tokens
                     + flops_per_key * num_attended_keys
                 )
 
diff --git a/torchtitan/models/common/flops.py b/torchtitan/models/common/flops.py
--- a/torchtitan/models/common/flops.py
+++ b/torchtitan/models/common/flops.py
@@ -36,8 +36,8 @@ def quadratic_attention_flops_per_token(
 
     ``seq_len`` is the number of keys one query attends to.
     ``Decoder.Config.build_flops_estimator`` sums this over each query's
-    position in its document when it is affine in ``seq_len``; sliding-window
-    and compressed attention keep the full-length estimate.
+    position in its document when it is proportional to ``seq_len``;
+    sliding-window and compressed attention keep the full-length estimate.
     ``qk_head_dim`` and ``v_head_dim`` describe the two attention
     contractions. The factor of 6 accounts for multiply-adds in forward and
     backward. Backward recomputation is not counted.

After applying it, please run pytest tests/unit_tests/cpu/models/common/test_flops_estimators.py tests/unit_tests/cpu/models/deepseek_v4/test_deepseek_v4_flops.py and pre-commit run --all-files.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude Why do we infer from implicit behavior and treat other components as blackbox? We are the repo owner, we can change anything to make improvement.

E.g. can we just refactor the usage of attention.flops_per_token so that each attention backend can take positions and decide the cost?
https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/decoder.py#L184

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 7m 50s —— View job


Agreed. I replaced Attention.Config.flops_per_token(seq_len) with Attention.Config.flops(positions), so each attention config computes its own cost from the document positions. The push was rejected again by the "Meta CLA Check" branch rule, so @acisseJZhong, please apply the patch below. It replaces the patch from my previous comment.

Not run: I couldn't run pytest or pre-commit in this environment, so neither has run on this patch.

What changes

The Decoder no longer guesses how a layer's cost grows by probing f(1), f(2) and f(seq_len). It removes padding and hands the positions to every attention config:

positions = input_dict["positions"][~input_dict["padding_mask"]]
return parameter_flops_per_token * positions.numel() + sum(
    attention.flops(positions) for attention in attentions
)

Each config states its own rule. Documents of lengths 3 and 2 give positions = [0, 1, 2, 0, 1]:

Config Keys per query at position p Example total
Full attention (GQA, DSv3, Kimi K3, Qwen3.5) p + 1 1+2+3+1+2 = 9
Sliding window W (GQA, gpt-oss, Muse) min(p + 1, W)
DSv4 min(p + 1, W) plus (p + 1) // ratio compressed keys, top-k capped. The indexer scores all compressed keys
Flash-Next QSA min(p + 1, budget + ratio - 1), and the indexer scores (p + 1) // ratio keys
GDN / KDA (linear) Fixed cost per query: positions.numel() * delta_rule_flops_per_token 5 queries

Fewer exceptions. Sliding-window, DSv4 compressed and Flash-Next attention no longer fall back to the full-length estimate, so the TODO is gone. DSv4's (p + 1) // ratio is the same limit that HeavilyCompressedAttention builds its causal mask from.

Recorded test values stay the same. The _text helper gives every query 128 keys. So for every layer the new rule reduces to the old min(seq_len, ...) and seq_len // ratio. The DSv4 test works the same way with 4096 keys.

Details
  • flops.py: adds quadratic_attention_flops(*, num_heads, qk_head_dim, v_head_dim, num_keys), which sums the per-query cost. quadratic_attention_flops_per_token stays for Flux, whose attention is bidirectional. I dropped its sliding_window_size argument because nothing uses it anymore.
  • HF backend: it uses the same helper, grouping layers by (qk_head_dim, v_head_dim, sliding_window_size), so HF sliding-window layers are also counted per position. Chunked attention is still treated as a window of attention_chunk_size, as before.
  • seq_len is now unused in Decoder and the HF estimator (del seq_len). I kept it in the shared build_flops_estimator signature because Flux still uses it.
  • Tests: the Qwen3.5 document test now writes out its expected value (9 keys for full attention, 5 queries for GDN) instead of calling the method it tests. The MTP test passes positions to flops.
  • Overhead: each quadratic layer now does a few elementwise ops plus one sum over the microbatch's positions on CPU, once per layer. For Qwen3.5 9B at 1M that touches only the 8 full-attention layers. DSv4 at long context does a few ops per layer across all layers. I couldn't measure this, so please re-measure the per-microbatch cost in the "Overhead" section of the PR description. If it's too high, the fix is to group identical configs, as the HF backend does.
Patch (commit 8d6c57f on top of 9ad9d9b, apply with git apply)
diff --git a/tests/unit_tests/cpu/models/common/test_flops_estimators.py b/tests/unit_tests/cpu/models/common/test_flops_estimators.py
--- a/tests/unit_tests/cpu/models/common/test_flops_estimators.py
+++ b/tests/unit_tests/cpu/models/common/test_flops_estimators.py
@@ -16,8 +16,10 @@ from torchtitan.config.parallelism import ParallelismConfig
 from torchtitan.models.common.attention import Attention
 from torchtitan.models.common.flops import (
     active_parameter_flops_per_token,
+    delta_rule_flops_per_token,
     get_parameter_counts,
 )
+from torchtitan.models.qwen3_5.model import Qwen35Attention
 from torchtitan.training_engine import TrainingEngine
 
 
@@ -68,20 +70,23 @@ def test_attention_counts_each_query_at_its_document_position():
     # sees, with GatedDeltaNet, whose cost per token is fixed.
     config, model = _build("qwen3_5")
     estimate = config.build_flops_estimator(model, seq_len=128)
-    # Two packed documents of lengths 3 and 2, then one padding token.
-    positions = torch.tensor([0, 1, 2, 0, 1, 2])
-    padding_mask = torch.tensor([False] * 5 + [True])
-    attentions = [attention for _, attention, _, _ in config.traverse(Attention.Config)]
-    expected = 5 * active_parameter_flops_per_token(model) + sum(
-        attention.flops_per_token(position + 1)
-        for position in positions[:5].tolist()
-        for attention in attentions
-    )
+    # Two packed documents of lengths 3 and 2, then one padding token. The five
+    # real queries attend to 1 + 2 + 3 + 1 + 2 = 9 keys in total.
     inputs = {
         "input": torch.empty(6),
-        "positions": positions,
-        "padding_mask": padding_mask,
+        "positions": torch.tensor([0, 1, 2, 0, 1, 2]),
+        "padding_mask": torch.tensor([False] * 5 + [True]),
     }
+    expected = 5 * active_parameter_flops_per_token(model)
+    for _, attention, _, _ in config.traverse(Attention.Config):
+        if isinstance(attention, Qwen35Attention.Config):
+            expected += 9 * 6 * attention.n_heads * 2 * attention.head_dim
+        else:
+            expected += 5 * delta_rule_flops_per_token(
+                num_heads=attention.n_heads,
+                key_head_dim=attention.key_head_dim,
+                v_head_dim=attention.value_head_dim,
+            )
     assert estimate(inputs) == expected
 
 
@@ -112,10 +117,11 @@ def test_mtp_counts_attention_and_repeated_output_projection(family):
     mtp_parameter_flops = active_parameter_flops_per_token(model.mtp_layers)
     repeated_head_flops = 2 * active_parameter_flops_per_token(model.lm_head)
     mtp_attention_flops = sum(
-        layer.attention.flops_per_token(128) for layer in config.mtp_layers
+        layer.attention.flops(inputs["positions"]) for layer in config.mtp_layers
     )
-    assert flops - base_flops == 128 * (
-        mtp_parameter_flops + repeated_head_flops + mtp_attention_flops
+    assert (
+        flops - base_flops
+        == 128 * (mtp_parameter_flops + repeated_head_flops) + mtp_attention_flops
     )
     if family == "kimi_k2_7":
         image_inputs = {
diff --git a/torchtitan/experiments/transformers_modeling_backend/model.py b/torchtitan/experiments/transformers_modeling_backend/model.py
--- a/torchtitan/experiments/transformers_modeling_backend/model.py
+++ b/torchtitan/experiments/transformers_modeling_backend/model.py
@@ -9,6 +9,7 @@ import importlib
 import logging
 import math
 import os
+from collections import Counter
 from collections.abc import Mapping
 from dataclasses import dataclass, field, fields, MISSING
 from fractions import Fraction
@@ -36,7 +37,7 @@ from torchtitan.models.common.attention import (
     get_causal_mask_mod,
     get_document_mask_mod,
 )
-from torchtitan.models.common.flops import quadratic_attention_flops_per_token
+from torchtitan.models.common.flops import quadratic_attention_flops
 
 from .parallelize import parallelize_hf_transformers
 from .pipeline import pipeline_hf_transformers
@@ -635,6 +636,8 @@ class HFTransformerModel(BaseModel):
         def build_flops_estimator(
             self, model: nn.Module, *, seq_len: int
         ) -> FlopsEstimator:
+            # Attention cost comes from each microbatch's positions.
+            del seq_len
             _, active_nparams = self._parameter_counts(model, include_embeddings=False)
 
             if all(
@@ -669,10 +672,9 @@ class HFTransformerModel(BaseModel):
                         ["full_attention"] * (len(model.layers) - len(layer_types))
                     )
 
-            # Full attention is charged per key a query attends to; other layer
-            # types keep the full-length estimate.
-            flops_per_token = 6 * active_nparams
-            flops_per_key = 0
+            # Number of layers for each (qk_head_dim, v_head_dim,
+            # sliding_window_size) attention shape.
+            attention_shapes: Counter[tuple[int, int, int | None]] = Counter()
             unsupported_layer_types = set()
             for layer_type in layer_types:
                 if layer_type in ("attention", "full_attention"):
@@ -698,21 +700,9 @@ class HFTransformerModel(BaseModel):
                         layer_qk_head_dim = global_head_dim
                         layer_v_head_dim = global_head_dim
 
-                if sliding_window_size is None:
-                    flops_per_key += quadratic_attention_flops_per_token(
-                        num_heads=self.n_heads,
-                        qk_head_dim=layer_qk_head_dim,
-                        v_head_dim=layer_v_head_dim,
-                        seq_len=1,
-                    )
-                else:
-                    flops_per_token += quadratic_attention_flops_per_token(
-                        num_heads=self.n_heads,
-                        qk_head_dim=layer_qk_head_dim,
-                        v_head_dim=layer_v_head_dim,
-                        seq_len=seq_len,
-                        sliding_window_size=sliding_window_size,
-                    )
+                attention_shapes[
+                    (layer_qk_head_dim, layer_v_head_dim, sliding_window_size)
+                ] += 1
 
             if unsupported_layer_types:
                 logger.warning(
@@ -729,15 +719,24 @@ class HFTransformerModel(BaseModel):
                 # A causal query at position p attends to p + 1 keys. positions
                 # restart at each document, which only "block_causal" masks
                 # follow. Padding does no useful work, so it is not counted.
-                is_real = ~input_dict["padding_mask"]
                 positions = input_dict["positions"]
                 if not document_masked:
                     positions = torch.arange(positions.shape[0])
-                num_attended_keys = int(((positions + 1) * is_real).sum())
-                return (
-                    flops_per_token * int(is_real.sum())
-                    + flops_per_key * num_attended_keys
-                )
+                num_keys = positions[~input_dict["padding_mask"]] + 1
+                flops = 6 * active_nparams * num_keys.numel()
+                for shape, num_layers in attention_shapes.items():
+                    layer_qk_head_dim, layer_v_head_dim, sliding_window_size = shape
+                    flops += num_layers * quadratic_attention_flops(
+                        num_heads=self.n_heads,
+                        qk_head_dim=layer_qk_head_dim,
+                        v_head_dim=layer_v_head_dim,
+                        num_keys=(
+                            num_keys
+                            if sliding_window_size is None
+                            else num_keys.clamp(max=sliding_window_size)
+                        ),
+                    )
+                return flops
 
             return estimate
 
diff --git a/torchtitan/models/README.md b/torchtitan/models/README.md
--- a/torchtitan/models/README.md
+++ b/torchtitan/models/README.md
@@ -96,7 +96,7 @@ The folder should be organized as follows
 CPU microbatch dictionary to model-wide logical training FLOPs before sharding.
 Build it from the full model; runtime estimation should use CPU metadata and tensor
 shapes without device-to-host synchronization or retaining model modules.
-Native decoders use `Attention.Config.flops_per_token(seq_len)`. Multimodal models
+Native decoders use `Attention.Config.flops(positions)`. Multimodal models
 share encoder composition through `multimodal_encoder_fqns`. Muse overrides the
 estimator to add output-module work using encoder-owned output-token counts.
 `ForwardBackwardResult.num_flops` reports unreduced work for this DP rank's raw
@@ -106,7 +106,8 @@ Trainers average it over the DP mesh; CP ranks hold the same value.
 `Config.get_parameter_counts(model)` reports unique total and architecturally
 active parameters, including embeddings and encoders and weighting routed experts
 by their active ratio. FLOPs exclude lookup-only embeddings separately.
-Decoder attention is charged per query position within its document: a query at
-position p attends to p + 1 keys. Padding tokens are excluded. Sliding-window and
-compressed attention keep the full-length estimate. Recomputation and elementwise
-operations are omitted.
+Each decoder attention config computes its cost from the positions of the
+non-padding queries within their documents: a causal query at position p attends
+to p + 1 keys, at most the window size for sliding-window attention, while linear
+attention costs the same for every query. Padding tokens are excluded.
+Recomputation and elementwise operations are omitted.
diff --git a/torchtitan/models/common/attention/attention.py b/torchtitan/models/common/attention/attention.py
--- a/torchtitan/models/common/attention/attention.py
+++ b/torchtitan/models/common/attention/attention.py
@@ -116,8 +116,12 @@ class Attention(Module):
         def __post_init__(self):
             assert self.n_heads > 0, "n_heads must be > 0"
 
-        def flops_per_token(self, seq_len: int) -> int:
-            """Training attention contractions, excluding parameter-based work."""
+        def flops(self, positions: torch.Tensor) -> int:
+            """Training attention contractions, excluding parameter-based work.
+
+            ``positions`` holds each non-padding query's position in its
+            document, e.g. ``[0, 1, 2, 0, 1]`` for documents of lengths 3 and 2.
+            """
             raise NotImplementedError(type(self).__qualname__)
 
 
@@ -228,28 +232,25 @@ class GQAttention(Attention):
                     f"n_kv_heads ({n_kv_heads})"
                 )
 
-        def flops_per_token(self, seq_len: int) -> int:
-            from torchtitan.models.common.flops import (
-                quadratic_attention_flops_per_token,
-            )
+        def flops(self, positions: torch.Tensor) -> int:
+            from torchtitan.models.common.flops import quadratic_attention_flops
 
             head_dim = self.head_dim or self.dim // self.n_heads
-            return quadratic_attention_flops_per_token(
+            # A causal query at document position p attends to p + 1 keys.
+            num_keys = positions + 1
+            if isinstance(
+                self.inner_attention,
+                (
+                    SlidingWindowFlexInnerAttention.Config,
+                    SlidingWindowVarlenInnerAttention.Config,
+                ),
+            ):
+                num_keys = num_keys.clamp(max=self.inner_attention.sliding_window_size)
+            return quadratic_attention_flops(
                 num_heads=self.n_heads,
                 qk_head_dim=head_dim,
                 v_head_dim=head_dim,
-                seq_len=seq_len,
-                sliding_window_size=(
-                    self.inner_attention.sliding_window_size
-                    if isinstance(
-                        self.inner_attention,
-                        (
-                            SlidingWindowFlexInnerAttention.Config,
-                            SlidingWindowVarlenInnerAttention.Config,
-                        ),
-                    )
-                    else None
-                ),
+                num_keys=num_keys,
             )
 
     def __init__(self, config: Config):
diff --git a/torchtitan/models/common/attention/gdn.py b/torchtitan/models/common/attention/gdn.py
--- a/torchtitan/models/common/attention/gdn.py
+++ b/torchtitan/models/common/attention/gdn.py
@@ -620,10 +620,11 @@ class GDN(LinearAttention):
                     f"n_key_heads * sum(in_proj_split_sizes) ({in_proj_rows})"
                 )
 
-        def flops_per_token(self, seq_len: int) -> int:
+        def flops(self, positions: torch.Tensor) -> int:
             from torchtitan.models.common.flops import delta_rule_flops_per_token
 
-            return delta_rule_flops_per_token(
+            # The recurrent state has a fixed size, so every query costs the same.
+            return positions.numel() * delta_rule_flops_per_token(
                 num_heads=self.n_heads,
                 key_head_dim=self.key_head_dim,
                 v_head_dim=self.value_head_dim,
diff --git a/torchtitan/models/common/attention/kda.py b/torchtitan/models/common/attention/kda.py
--- a/torchtitan/models/common/attention/kda.py
+++ b/torchtitan/models/common/attention/kda.py
@@ -343,10 +343,11 @@ class KDA(LinearAttention):
                     f"conv_kernel_size must be positive, got {self.conv_kernel_size}"
                 )
 
-        def flops_per_token(self, seq_len: int) -> int:
+        def flops(self, positions: torch.Tensor) -> int:
             from torchtitan.models.common.flops import delta_rule_flops_per_token
 
-            return delta_rule_flops_per_token(
+            # The recurrent state has a fixed size, so every query costs the same.
+            return positions.numel() * delta_rule_flops_per_token(
                 num_heads=self.n_heads,
                 key_head_dim=self.head_dim,
                 v_head_dim=self.head_dim,
diff --git a/torchtitan/models/common/decoder.py b/torchtitan/models/common/decoder.py
--- a/torchtitan/models/common/decoder.py
+++ b/torchtitan/models/common/decoder.py
@@ -178,36 +178,20 @@ class Decoder(BaseModel):
             seq_len: int,
             excluded_submodules: tuple[Module | None, ...] = (),
         ) -> FlopsEstimator:
-            flops_per_token = active_parameter_flops_per_token(
+            # Attention cost comes from each microbatch's document positions.
+            del seq_len
+            parameter_flops_per_token = active_parameter_flops_per_token(
                 model, excluded_submodules=excluded_submodules
             )
-            # A causal query at document position p attends to p + 1 keys. When
-            # attention FLOPs are affine in the number of keys, the batch total
-            # needs only sum(positions + 1).
-            flops_per_key = 0
-            for _, attention, _, _ in self.traverse(Attention.Config):
-                one_key_flops = attention.flops_per_token(1)
-                layer_flops_per_key = attention.flops_per_token(2) - one_key_flops
-                full_length_flops = attention.flops_per_token(seq_len)
-                if (
-                    full_length_flops
-                    == one_key_flops + (seq_len - 1) * layer_flops_per_key
-                ):
-                    flops_per_token += one_key_flops - layer_flops_per_key
-                    flops_per_key += layer_flops_per_key
-                else:
-                    # TODO: sliding-window and compressed attention are not affine
-                    # in the number of keys; they keep the full-length estimate.
-                    flops_per_token += full_length_flops
+            attentions = [
+                attention for _, attention, _, _ in self.traverse(Attention.Config)
+            ]
 
             def estimate(input_dict: Mapping[str, Any]) -> int:
-                # positions restart at 0 at each document start. Padding does
-                # no useful work, so it is not counted.
-                is_real = ~input_dict["padding_mask"]
-                num_attended_keys = int(((input_dict["positions"] + 1) * is_real).sum())
-                return (
-                    flops_per_token * int(is_real.sum())
-                    + flops_per_key * num_attended_keys
+                # Padding does no useful work, so it is not counted.
+                positions = input_dict["positions"][~input_dict["padding_mask"]]
+                return parameter_flops_per_token * positions.numel() + sum(
+                    attention.flops(positions) for attention in attentions
                 )
 
             return estimate
diff --git a/torchtitan/models/common/flops.py b/torchtitan/models/common/flops.py
--- a/torchtitan/models/common/flops.py
+++ b/torchtitan/models/common/flops.py
@@ -7,6 +7,7 @@
 from collections.abc import Iterable
 from fractions import Fraction
 
+import torch
 from torch import nn
 
 from torchtitan.models.common.moe import MoE
@@ -18,9 +19,8 @@ def quadratic_attention_flops_per_token(
     qk_head_dim: int,
     v_head_dim: int,
     seq_len: int,
-    sliding_window_size: int | None = None,
 ) -> int:
-    """Training FLOPs per token for quadratic or windowed attention.
+    """Training FLOPs per token for quadratic attention.
 
     Reasoning behind the factor of 6 for the self-attention part of the formula:
     1. each self-attention has 2 matmul in the forward and 4 (counted as 2)
@@ -35,17 +35,27 @@ def quadratic_attention_flops_per_token(
     3. each matmul performs 1 multiplication and 1 addition                 (*2)
 
     ``seq_len`` is the number of keys one query attends to.
-    ``Decoder.Config.build_flops_estimator`` sums this over each query's
-    position in its document when it is affine in ``seq_len``; sliding-window
-    and compressed attention keep the full-length estimate.
     ``qk_head_dim`` and ``v_head_dim`` describe the two attention
     contractions. The factor of 6 accounts for multiply-adds in forward and
     backward. Backward recomputation is not counted.
     """
-    attended_tokens = (
-        seq_len if sliding_window_size is None else min(seq_len, sliding_window_size)
-    )
-    return 6 * num_heads * (qk_head_dim + v_head_dim) * attended_tokens
+    return 6 * num_heads * (qk_head_dim + v_head_dim) * seq_len
+
+
+def quadratic_attention_flops(
+    *,
+    num_heads: int,
+    qk_head_dim: int,
+    v_head_dim: int,
+    num_keys: torch.Tensor,
+) -> int:
+    """Training FLOPs of softmax attention over a microbatch of queries.
+
+    ``num_keys`` holds the number of keys each query attends to, e.g. a causal
+    query at document position p attends to p + 1 keys. Each query costs
+    ``quadratic_attention_flops_per_token`` at its number of keys.
+    """
+    return 6 * num_heads * (qk_head_dim + v_head_dim) * int(num_keys.sum())
 
 
 def delta_rule_flops_per_token(
diff --git a/torchtitan/models/deepseek_v3/attention.py b/torchtitan/models/deepseek_v3/attention.py
--- a/torchtitan/models/deepseek_v3/attention.py
+++ b/torchtitan/models/deepseek_v3/attention.py
@@ -63,16 +63,15 @@ class DeepSeekMLAAttention(Attention):
                     f"but got {type(self.inner_attention).__qualname__}."
                 )
 
-        def flops_per_token(self, seq_len: int) -> int:
-            from torchtitan.models.common.flops import (
-                quadratic_attention_flops_per_token,
-            )
+        def flops(self, positions: torch.Tensor) -> int:
+            from torchtitan.models.common.flops import quadratic_attention_flops
 
-            return quadratic_attention_flops_per_token(
+            # A causal query at document position p attends to p + 1 keys.
+            return quadratic_attention_flops(
                 num_heads=self.n_heads,
                 qk_head_dim=self.qk_nope_head_dim + self.qk_rope_head_dim,
                 v_head_dim=self.v_head_dim,
-                seq_len=seq_len,
+                num_keys=positions + 1,
             )
 
     def __init__(self, config: Config):
diff --git a/torchtitan/models/deepseek_v4/attention.py b/torchtitan/models/deepseek_v4/attention.py
--- a/torchtitan/models/deepseek_v4/attention.py
+++ b/torchtitan/models/deepseek_v4/attention.py
@@ -348,37 +348,39 @@ class DeepSeekV4Attention(Attention):
         compressor_128: Compressor.Config | None = None
         indexer: Indexer.Config | None = None
 
-        def flops_per_token(self, seq_len: int) -> int:
-            from torchtitan.models.common.flops import (
-                quadratic_attention_flops_per_token,
-            )
+        def flops(self, positions: torch.Tensor) -> int:
+            from torchtitan.models.common.flops import quadratic_attention_flops
 
             inner_attention = self.inner_attention
-            attention_op_flops = quadratic_attention_flops_per_token(
+            # A causal query at document position p attends to p + 1 keys,
+            # at most window_size of them uncompressed.
+            num_keys = positions + 1
+            attention_op_flops = quadratic_attention_flops(
                 num_heads=self.n_heads,
                 qk_head_dim=self.head_dim,
                 v_head_dim=self.head_dim,
-                seq_len=seq_len,
-                sliding_window_size=inner_attention.window_size,
+                num_keys=num_keys.clamp(max=inner_attention.window_size),
             )
 
             if self.compress_ratio > 1:
-                compressed_seq_len = seq_len // self.compress_ratio
+                num_compressed_keys = num_keys // self.compress_ratio
                 if self.compress_ratio == 4:
+                    # The indexer scores every compressed key; attention reads
+                    # only the top-k.
                     attention_op_flops += (
                         6
                         * self.index_n_heads
                         * self.index_head_dim
-                        * compressed_seq_len
+                        * int(num_compressed_keys.sum())
                     )
-                    compressed_seq_len = min(
-                        compressed_seq_len, inner_attention.index_topk
+                    num_compressed_keys = num_compressed_keys.clamp(
+                        max=inner_attention.index_topk
                     )
-                attention_op_flops += quadratic_attention_flops_per_token(
+                attention_op_flops += quadratic_attention_flops(
                     num_heads=self.n_heads,
                     qk_head_dim=self.head_dim,
                     v_head_dim=self.head_dim,
-                    seq_len=compressed_seq_len,
+                    num_keys=num_compressed_keys,
                 )
             return attention_op_flops
 
diff --git a/torchtitan/models/gpt_oss/model.py b/torchtitan/models/gpt_oss/model.py
--- a/torchtitan/models/gpt_oss/model.py
+++ b/torchtitan/models/gpt_oss/model.py
@@ -73,17 +73,18 @@ class GptOssAttention(Attention):
             scale *= mscale * mscale
             return scale
 
-        def flops_per_token(self, seq_len: int) -> int:
-            from torchtitan.models.common.flops import (
-                quadratic_attention_flops_per_token,
-            )
-
-            return quadratic_attention_flops_per_token(
+        def flops(self, positions: torch.Tensor) -> int:
+            from torchtitan.models.common.flops import quadratic_attention_flops
+
+            # A causal query at document position p attends to p + 1 keys.
+            num_keys = positions + 1
+            if self.sliding_window_size is not None:
+                num_keys = num_keys.clamp(max=self.sliding_window_size)
+            return quadratic_attention_flops(
                 num_heads=self.n_heads,
                 qk_head_dim=self.head_dim,
                 v_head_dim=self.head_dim,
-                seq_len=seq_len,
-                sliding_window_size=self.sliding_window_size,
+                num_keys=num_keys,
             )
 
     def __init__(self, config: Config):
diff --git a/torchtitan/models/kimi_k3/attention.py b/torchtitan/models/kimi_k3/attention.py
--- a/torchtitan/models/kimi_k3/attention.py
+++ b/torchtitan/models/kimi_k3/attention.py
@@ -76,16 +76,15 @@ class KimiMLAAttention(Attention):
             """Attention softmax scale."""
             return (self.qk_nope_head_dim + self.qk_rope_head_dim) ** -0.5
 
-        def flops_per_token(self, seq_len: int) -> int:
-            from torchtitan.models.common.flops import (
-                quadratic_attention_flops_per_token,
-            )
+        def flops(self, positions: torch.Tensor) -> int:
+            from torchtitan.models.common.flops import quadratic_attention_flops
 
-            return quadratic_attention_flops_per_token(
+            # A causal query at document position p attends to p + 1 keys.
+            return quadratic_attention_flops(
                 num_heads=self.n_heads,
                 qk_head_dim=self.qk_nope_head_dim + self.qk_rope_head_dim,
                 v_head_dim=self.v_head_dim,
-                seq_len=seq_len,
+                num_keys=positions + 1,
             )
 
     def __init__(self, config: Config):
diff --git a/torchtitan/models/qwen3_5/model.py b/torchtitan/models/qwen3_5/model.py
--- a/torchtitan/models/qwen3_5/model.py
+++ b/torchtitan/models/qwen3_5/model.py
@@ -117,18 +117,15 @@ class Qwen35Attention(Attention):
         q_norm: OffsetRMSNorm.Config
         k_norm: OffsetRMSNorm.Config
 
-        def flops_per_token(self, seq_len: int) -> int:
-            from torchtitan.models.common.flops import (
-                quadratic_attention_flops_per_token,
-            )
+        def flops(self, positions: torch.Tensor) -> int:
+            from torchtitan.models.common.flops import quadratic_attention_flops
 
-            head_dim = self.head_dim
-            return quadratic_attention_flops_per_token(
+            # A causal query at document position p attends to p + 1 keys.
+            return quadratic_attention_flops(
                 num_heads=self.n_heads,
-                qk_head_dim=head_dim,
-                v_head_dim=head_dim,
-                seq_len=seq_len,
-                sliding_window_size=None,
+                qk_head_dim=self.head_dim,
+                v_head_dim=self.head_dim,
+                num_keys=positions + 1,
             )
 
     def __init__(self, config: Config):
diff --git a/torchtitan/models/qwen3_8_flash_next/attention.py b/torchtitan/models/qwen3_8_flash_next/attention.py
--- a/torchtitan/models/qwen3_8_flash_next/attention.py
+++ b/torchtitan/models/qwen3_8_flash_next/attention.py
@@ -688,21 +688,21 @@ class QSAAttention(Qwen35Attention):
             ):
                 raise ValueError("Flash-Next QSA requires compress_ratio=4")
 
-        def flops_per_token(self, seq_len: int) -> int:
-            from torchtitan.models.common.flops import (
-                quadratic_attention_flops_per_token,
-            )
+        def flops(self, positions: torch.Tensor) -> int:
+            from torchtitan.models.common.flops import quadratic_attention_flops
 
-            attended_tokens = min(
-                seq_len, self.indexer.token_budget + self.indexer.compress_ratio - 1
-            )
-            return quadratic_attention_flops_per_token(
+            # A causal query at document position p can see p + 1 keys.
+            num_keys = positions + 1
+            num_compressed_keys = num_keys // self.indexer.compress_ratio
+            return quadratic_attention_flops(
                 num_heads=self.n_heads,
                 qk_head_dim=self.head_dim,
                 v_head_dim=self.head_dim,
-                seq_len=attended_tokens,
-            ) + 6 * self.indexer.num_heads * self.indexer.head_dim * (
-                seq_len // self.indexer.compress_ratio
+                num_keys=num_keys.clamp(
+                    max=self.indexer.token_budget + self.indexer.compress_ratio - 1
+                ),
+            ) + 6 * self.indexer.num_heads * self.indexer.head_dim * int(
+                num_compressed_keys.sum()
             )
 
     def __init__(self, config: Config):

After applying it, please run pytest tests/unit_tests/cpu/models/common/test_flops_estimators.py tests/unit_tests/cpu/models/deepseek_v4/test_deepseek_v4_flops.py and pre-commit run --all-files. The PR description also needs updating: its "Sliding-window and compressed attention keep the full-length estimate" lines are no longer true.

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review latest changes

@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 2m 35s —— View job


Approve -- the flops(positions) refactor resolves @tianyu-l's comments; please update the stale parts of the PR description before merging: 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 flops(positions) refactor (8aa5bac) answers both of @tianyu-l's comments. The counts are right for every attention config, and recorded test values are unchanged. What's left is updating the description. models/common/ is core code, so a maintainer still needs to review.

What changed since the last review. The Decoder no longer probes flops_per_token at 1, 2 and seq_len keys to infer each layer's cost. Instead it drops padding and passes the document positions to each Attention.Config.flops(positions). Each config applies its own rule:

  • Full attention (GQA, DSv3/Kimi MLA, Qwen3.5): p + 1 keys.
  • Sliding window (GQA, gpt-oss): min(p + 1, W) keys.
  • DSv4: window keys plus (p + 1) // ratio compressed keys, capped at top-k. This is the same limit as attention.py:229.
  • Flash-Next: min(p + 1, budget + ratio - 1) keys.
  • GDN/KDA: numel times a fixed per-query cost.

The sliding-window, DSv4 and Flash-Next layers no longer fall back to the full-length estimate.

Example. Documents of lengths 3 and 2 plus one padding token give positions=[0,1,2,0,1] after the mask:

full attention:  (1+2+3+1+2) = 9 keys * 6*H*(Dqk+Dv)
GDN:             5 queries * delta_rule_flops_per_token
sliding W=2:     (1+2+2+1+2) = 8 keys   (main: 6 tokens * 2 keys = 12)

Earlier items

  • tianyu-l decoder.py:174 (math is hard to follow): resolved. The probing is gone and each config states its own rule.
  • tianyu-l decoder.py (linear attention?): resolved. GDN/KDA now charge positions.numel() explicitly.
  • Earlier shape[-1] / expand_as suggestion: resolved.

Must fix

  1. The PR description no longer matches the code:
    • "Known issues: Sliding-window and compressed attention still use the full-length estimate" is now false. Remove it.
    • "Testing" says the new test "matches the per-token sum of flops_per_token(position + 1)". That method no longer exists. The test now writes out 9 keys and 5 GDN queries.
    • "Overhead" was measured before this commit. Each attention layer now does its own tensor ops (see the inline comment), so please re-measure.
    • "User-facing changes" should say that MFU now also drops for sliding-window and compressed layers (gpt-oss, Muse, DSv4, Flash-Next), not only for full attention.

Should consider

  • torchtitan/models/common/decoder.py:186 -- the per-layer CPU work per microbatch scales with depth at long context. Group identical attention configs, as the HF backend does (inline).
  • torchtitan/models/common/flops.py:44 -- quadratic_attention_flops restates the 6 * num_heads * (qk_head_dim + v_head_dim) formula from quadratic_attention_flops_per_token, which Flux still uses. Return quadratic_attention_flops_per_token(..., seq_len=int(num_keys.sum())) so the factor lives in one place.
  • torchtitan/experiments/transformers_modeling_backend/model.py:686 (not in the diff) -- chunked attention is still treated as a sliding window. With per-position counting, the exact rule is a one-liner: positions % attention_chunk_size + 1. clamp(max=chunk) overcounts every query past the first chunk. This is no worse than main.
Details
  • Callsites: grep finds no remaining flops_per_token( on any Attention.Config in models, experiments, RL or graph_trainer. The only remaining user of quadratic_attention_flops_per_token is Flux (bidirectional). Its dropped sliding_window_size argument had no other callers.
  • _text gives every query positions = seq_len - 1, i.e. 128 keys. So clamp(max=W), 128 // ratio and the top-k cap all reduce to main's min(seq_len, ...) values, and test_text_estimates_preserve_main still checks against main. The same holds for the DSv4 4096-token test: window 128, 1024 compressed keys capped at top-k.
  • MTP test: inputs has no padding, so flops(inputs["positions"]) equals 128 tokens at 128 keys, and the updated assertion is consistent.
  • Gate: unchanged since the first review. The problem is real (MFU above 100% at 1M) and the fix sits in the shared estimator. RL and graph_trainer pick it up through build_flops_estimator. No overlapping PR owns FLOPs now; #5455 keeps tps.
  • No device sync: the boolean-mask indexing and int(sum) run on the CPU microbatch, as before.

Not verified: I couldn't run the unit tests or time the estimator in this environment.

Comment thread torchtitan/models/common/decoder.py Outdated
Comment on lines +186 to +195
attentions = [
attention for _, attention, _, _ in self.traverse(Attention.Config)
]

def estimate(input_dict: Mapping[str, Any]) -> int:
# Padding does no useful work, so it is not counted.
positions = input_dict["positions"][~input_dict["padding_mask"]]
return parameter_flops_per_token * positions.numel() + sum(
attention.flops(positions) for attention in attentions
)

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.

Every microbatch now calls flops(positions) once per attention layer, and each call does its own full-length tensor ops on CPU (positions + 1, clamp, //, sum). At 1M tokens that is several passes over a 1M-element tensor per layer. A DeepSeek V4 decoder does about 6 passes in each of its ~40 layers, so the cost grows with depth. The old code did a single reduction. The "Overhead" numbers in the description were measured before this commit.

Layers are almost always copies of a few configs: Qwen3.5 has 2 distinct configs and DSv4 has 3 (one per compress_ratio). Grouping equal configs at build time brings the per-microbatch cost back to a handful of passes. It also matches what the HF backend already does with attention_shapes:

# Layers repeat a few attention configs; count each distinct config once.
attention_counts: list[tuple[Attention.Config, int]] = []
for _, attention, _, _ in self.traverse(Attention.Config):
    for i, (seen, count) in enumerate(attention_counts):
        if seen == attention:
            attention_counts[i] = (seen, count + 1)
            break
    else:
        attention_counts.append((attention, 1))
...
return parameter_flops_per_token * positions.numel() + sum(
    count * attention.flops(positions) for attention, count in attention_counts
)

If you re-measure and it's negligible at 1M for DSv4, just update the Overhead section and skip this. (unverified: I couldn't time it here)

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 56s —— View job


Approve: a107d81 resolves every item from the last review, and the one remaining item (HF chunked attention) can be a follow-up: 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 -- a107d81 and the updated description resolve every item from the last review, and the new commit introduces no new problems. models/common/ is core code, so a maintainer still needs to review.

What changed since the last review (a107d81). At build time the Decoder now groups attention configs that are equal apart from param_init, then calls count * attention.flops(positions) once per group. param_init is a dict of functools.partial objects (llama3/flavors.py:64). Partials compare by identity, so a plain == would never match two layers. _equal_ignoring_param_init recurses through nested dataclasses and skips that one field. quadratic_attention_flops now calls quadratic_attention_flops_per_token, so the 6 * H * (Dqk + Dv) factor is defined in one place.

Example. Llama 3 8B has 32 identical GQAttention.Configs, differing only in depth-scaled wo init:

before: 32 x flops(positions)       -> 32 passes over positions
after:  32 * flops(positions)       ->  1 pass

Qwen3.5 9B and gpt-oss collapse to 2 groups each, matching the re-measured Overhead table.

Earlier items

  • PR description out of date (Known issues, Testing, Overhead, User-facing changes): resolved.
  • decoder.py: per-layer CPU work grew with depth: resolved by the grouping.
  • flops.py: duplicated attention formula: resolved.
  • HF backend model.py:684-685: chunked attention is still counted as a sliding window. positions % attention_chunk_size + 1 would be exact. It is no worse than main and it lives in experiments, so it is fine as a follow-up (still open).
Details
  • Grouping can't change the count. flops() never reads param_init, so any two configs grouped together return the same value. If some other field holds a per-layer callable, those layers just form separate groups, which costs speed but gives the same FLOPs.
  • Lists and dicts of nested configs fall back to == rather than recursing. That is conservative in the same way.
  • Recorded test values: quadratic_attention_flops now returns 6*H*(Dqk+Dv)*sum(num_keys) through the shared function, which is the same integer as before. test_attention_counts_each_query_at_its_document_position uses the Qwen3.5 debugmodel, which has repeated layers, so it exercises groups with count > 1.

Not verified: I couldn't run the unit tests in this environment.

@tianyu-l tianyu-l 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.

please fix remaining comments

Comment thread torchtitan/models/common/flops.py Outdated

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.

do we still need to keep this function standalone?

Comment thread torchtitan/models/common/decoder.py Outdated
ffn_norm: Module.Config


def _equal_ignoring_param_init(a: object, b: object) -> bool:

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.

if only used one, put this nested into where it's used

…position

A causal, document-masked query at position p attends to p + 1 keys. The
decoder FLOPs estimator now sums attention FLOPs over each query's position
in its document instead of charging every token for max_context_length keys.
Attention whose FLOPs are not affine in the number of keys (sliding window,
compressed attention) keeps the full-length estimate.
Replace Attention.Config.flops_per_token(seq_len) with
Attention.Config.flops(positions): each config computes its cost from the
document positions of the non-padding queries, so the decoder no longer
infers per-key cost by probing flops_per_token. Sliding-window, DeepSeek V4
compressed and Flash-Next attention are now also counted per position.
…ion FLOPs formula

Layers repeat a few attention configs that differ only in depth-scaled
param_init, so the estimator groups equal configs at build time and calls
flops(positions) once per group. quadratic_attention_flops now calls
quadratic_attention_flops_per_token so the factor lives in one place.
…g comparison

Keep a single quadratic_attention_flops(num_keys) helper; Flux passes
seq_len keys per token. The param_init-insensitive config comparison has one
caller, so it now lives inside Decoder.Config.build_flops_estimator.
@acisseJZhong
acisseJZhong force-pushed the mfu-causal-document-flops branch from de86756 to 5e57c98 Compare November 24, 2026 01:22
@acisseJZhong
acisseJZhong merged commit bd64f5c into main Nov 24, 2026
28 of 30 checks passed
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Nov 30, 2026
Conflicts, per-commit effect on ezpz, the three replays (pytorch#6164, pytorch#6325, pytorch#5881),
the attn_gym venv upgrade for pytorch#6172, and the 21-arm smoke matrix on 15efc8b
across Sunspot, Aurora and Sirius. Aurora 2B losses differ from earlier syncs;
an attn_gym-hidden control on the same nodes reproduces the old values exactly.
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 ciflow/rl 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