Repository navigation
[metrics] Count causal and document-masked attention FLOPs per query position - #6325
Conversation
|
@claude review |
|
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 |
There was a problem hiding this comment.
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
- The PR description's "Summary (human-written)" section is empty. Please fill it in.
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:713still chargesinput.numel()tokens atmax_context_lengthkeys. 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-causalL * f(L)per document. RL goes throughTrainingEngine.flops_estimatorand gets this fix for free, so #5455's FLOPs part looks superseded. Its other part, counting only real tokens in RLtokens_per_second, is still open here ("tpsstill counts padding tokens"). Should the two authors agree which PR ownstps, and close the FLOPs half of #5455?
Details
- Decomposition check: for an affine layer,
f(k) = f(1) + (k-1)dwithd = f(2) - f(1). The code addsf(1) - dper real token plusd * sum(p + 1), which is exactlysum f(p + 1). The equality probe uses Python ints, so there is no float-rounding misclassification. - A sliding window with
W >= max_context_lengthpasses the probe and is counted causally. That is correct, becausemin(p + 1, W) = p + 1for every position. - GDN/KDA return a constant, so
d = 0and they are charged once per real token. This matches main apart from padding. - Encoder attention: vision/audio encoders don't subclass
Attention, soDecoder.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_dictalways providespositionsandpadding_mask, and so does the RLTrainingMicrobatch, 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.
| ``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. |
There was a problem hiding this comment.
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:
| ``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. |
265cf07 to
cb76e5b
Compare
|
@claude review latest changes |
|
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 |
There was a problem hiding this comment.
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.mddescribed the old convention: resolved.flops.pydocstring 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
tpsis left to #5455.
Should consider
torchtitan/experiments/transformers_modeling_backend/model.py:735--positionsis always 1-D, so dropshape[-1]andexpand_as(see the inline comment).torchtitan/experiments/transformers_modeling_backend/tests/test_flops_estimator.py-- no CI job runs this file.unit_test_cpu.yamlignorestorchtitan/experiments/**. The HF workflow runs onlyintegration_tests.run_tests.shruns onlytest_moe_parallelism.py. Sibling tests such astest_flex_attention.pyhave the same gap. At minimum, add the new file to the pytest line inrun_tests.sh. Otherwise thecausalvsblock_causalcheck is never exercised.
Details
- HF
flops_per_keyevaluatesquadratic_attention_flops_per_token(seq_len=1). That formula is linear inseq_lenwith no constant term, soK * sum(p + 1)is exact for full-attention layers. The test's2 * 6 * 4 * (16 + 16)matches this. - The
getattr(self, "attn_mask_type", "causal")default matches howget_attention_metadataand_build_dense_attention_maskread 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:Decodercounts it causally, while the HF backend keeps it at full length. This only matters for unusual configs; no change needed. - The
_texttest helper (positions = seq_len - 1, no padding) reproduces main's values, so the recorded constants intest_text_estimates_preserve_mainand 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) |
There was a problem hiding this comment.
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:
| positions = torch.arange(positions.shape[-1]).expand_as(positions) | |
| positions = torch.arange(positions.shape[0]) |
| """Return total and architecturally active native decoder parameters.""" | ||
| return get_parameter_counts(model) | ||
|
|
||
| def build_flops_estimator( |
There was a problem hiding this comment.
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.
| # TODO: sliding-window and compressed attention are not affine | ||
| # in the number of keys; they keep the full-length estimate. |
There was a problem hiding this comment.
How about linear attention?
|
@claude address my inline comments |
|
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 decoder.py:174 -- "explain like to a 5-year-old"The old code looked at each layer's cost at 1, 2 and
A query at document position p sees p + 1 keys. Documents of lengths 3 and 2 have 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: Same numbers as beforeI checked every Patch (commit
|
|
@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 |
|
Claude finished @tianyu-l's task in 7m 50s —— View job Agreed. I replaced Not run: I couldn't run What changesThe Decoder no longer guesses how a layer's cost grows by probing 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
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 Recorded test values stay the same. The Details
Patch (commit
|
|
@claude review latest changes |
|
Claude finished @acisseJZhong's task in 2m 35s —— View job Approve -- the |
There was a problem hiding this comment.
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 + 1keys. - Sliding window (GQA, gpt-oss):
min(p + 1, W)keys. - DSv4: window keys plus
(p + 1) // ratiocompressed keys, capped at top-k. This is the samelimitasattention.py:229. - Flash-Next:
min(p + 1, budget + ratio - 1)keys. - GDN/KDA:
numeltimes 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 chargepositions.numel()explicitly. - Earlier
shape[-1]/expand_assuggestion: resolved.
Must fix
- 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_flopsrestates the6 * num_heads * (qk_head_dim + v_head_dim)formula fromquadratic_attention_flops_per_token, which Flux still uses. Returnquadratic_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:
grepfinds no remainingflops_per_token(on anyAttention.Configin models, experiments, RL or graph_trainer. The only remaining user ofquadratic_attention_flops_per_tokenis Flux (bidirectional). Its droppedsliding_window_sizeargument had no other callers. _textgives every querypositions = seq_len - 1, i.e. 128 keys. Soclamp(max=W),128 // ratioand the top-k cap all reduce to main'smin(seq_len, ...)values, andtest_text_estimates_preserve_mainstill checks against main. The same holds for the DSv4 4096-token test: window 128, 1024 compressed keys capped at top-k.- MTP test:
inputshas no padding, soflops(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 keepstps. - 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.
| 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 | ||
| ) |
There was a problem hiding this comment.
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)
|
@claude review again |
|
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 |
There was a problem hiding this comment.
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 + 1would 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 readsparam_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_flopsnow returns6*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_positionuses the Qwen3.5 debugmodel, which has repeated layers, so it exercises groups withcount > 1.
Not verified: I couldn't run the unit tests in this environment.
tianyu-l
left a comment
There was a problem hiding this comment.
please fix remaining comments
There was a problem hiding this comment.
do we still need to keep this function standalone?
| ffn_norm: Module.Config | ||
|
|
||
|
|
||
| def _equal_ignoring_param_init(a: object, b: object) -> bool: |
There was a problem hiding this comment.
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.
…fy the flops docstring
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.
de86756 to
5e57c98
Compare
…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.  <!-- 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]>
…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.
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.
Co-authored-by: hitwdy<[email protected]> # message auto-generated for no-merge-commit merge: !1381 merge fix/dsv4-document-mfu into master [fix] 修正 DeepSeek-V4 的文档级 MFU 估算 Created-by: hitwdy Commit-by: 1Fire4;hitwdy Merged-by: cann-robot Description: ## 描述 ### 修改原因 - 现行 DeepSeek-V4 的 MFU 按整段压缩序列估算注意力 FLOPs,并把全部 Indexer 候选计入反向,打包长上下文时会高估 ModelFLOPs。 - 仓库已按文档级口径公布 MFU,但代码仍按整段 `seq_len` 计算,官方 4k / 1M 配方(已开启 `per_doc_alignment`)会对不上。 - 文档真实边界只在训练 batch 的 `positions` 里,只改模型侧静态 `get_nparams_and_flops(seq_len)` 既拿不到打包后的实际文档长度,也赶不上上游打日志的时机。 ### 修改方案 - 回移 [TorchTitan #6325](pytorch/torchtitan#6325) 和 [#6372](pytorch/torchtitan#6372) 的文档级估算:按文档段累计因果可见的滑窗、压缩前缀和 CSA 选中项;Indexer 前向按候选,反向只按 top-k。 - 在 `model.py` 增加 `attention_flops_for_documents`,并修正静态 `get_nparams_and_flops`。 - 在扩展 `TrainerEx.step_batches` 中,于 CP 切分前读取文档边界,在日志窗口内累加注意力 FLOPs,并在 `metrics.log` 前改写 `num_flops_per_token`;失败时回滚计数。FLOPs 只在 DP 间汇总。 - 这是针对当前 pinned TorchTitan 0.3.0 的临时适配,上游纳入上述变更后应删除。 - DP 归约先将注意力 FLOPs 转为整数 MFLOPs,归约后再换算回 FLOPs,以避免长序列日志窗口溢出 `int64`。 - TorchFT 复用文档计数与 MFLOPs 缩放,在 optimizer 提交前沿 DP 和当前 TorchFT 副本归约。故障中断的 step 从 FLOPs、吞吐 token 和数据加载统计中排除。 ## 类型 - [x] Bug 修复 - [ ] 新功能 - [ ] 重构(即不是新增功能,也不是修改bug的代码变动) - [ ] 构建过程或辅助工具的变动 - [ ] 文档内容更新 ## Checklist: - [ ] 我的代码遵循这个项目的代码风格 - [ ] 我已经自己测试过我的代码 - [ ] 我已经更新了相应的文档 - [x] 我已经在标题中正确使用了类型标签(例如:`feat`, `fix`, `refactor`, `docs`, `test`) ## 如何测试 运行 DeepSeek-V4 的 FLOPs 单测。 ```bash python -m pytest -q tests/unit_tests/models/deepseek_v4/test_dsv4_config.py \ -k 'test_flash_mtp_4k_model_flops or test_flash_packed_attention_flops_reset_at_document_boundaries' ``` - **Flash + MTP,4K 单文档**。校验参数量为 `290,942,278,866`,将全模型 FLOPs/token 的预期值从 `92,762,352,876` 更新为 `90,923,588,844`。 - **Flash,4K packed**。按 query 独立累加两个 2K 文档的滑窗、HCA 压缩块、CSA 候选和 top-k 选中项,与闭式公式对照。再与同样为 4,096 token 的单文档比较,校验文档边界会降低注意力 FLOPs。 - **执行结果**。提交 `b79d6d06` 的 CI 已通过。本地 CPU UT 在导入阶段因缺少 `libhccl.so` 未能执行。1M MFU 为公式复算,NPU 训练性能与精度未实测。[CI 流水线](https://gitcode.com/cann/torchtitan-npu/actions/runs/19ddc8f2e39f435c9109c494e329af92) - 补充 DP 归约回归用例。独立 CPU 检查模拟 DP=16、单 rank 8 条和 128 条 1M 文档,两种情况下的缩放误差均在 1 FLOP/token 以内。改动文件 Ruff 通过,正式 pytest 仍受 `libhccl.so` 限制。 - TorchFT 新增回归用例,模拟跨副本的不同文档 FLOPs、提交前归约,以及中断 step 后恢复日志计数。独立 CPU 模拟检查通过,实际 TorchFT 多副本训练和故障恢复未运行。 #### UT 新旧公式对比 | UT 输入 | 计数范围 | 旧算法(GFLOPs/token) | 新算法(GFLOPs/token) | 相对变化 | | --- | --- | ---: | ---: | ---: | | Flash + MTP,`[4096]` | 全模型 | 92.762353 | 90.923589 | −1.98% | | Flash,`[2048, 2048]` | 注意力及 Indexer | 7.700742 | 4.532048 | −41.15% | | Flash,`[4096]`(packed UT 对照组) | 注意力及 Indexer | 7.700742 | 5.862758 | −23.87% | Packed UT 直接断言整条样本的注意力 FLOPs。旧公式对两种文档布局均得到 `31,542,239,821,824` FLOPs。新公式对 `[2048, 2048]` 和 `[4096]` 分别得到 `18,563,268,083,712` 和 `24,013,858,406,400` FLOPs。同用新公式,两个 2K 文档比单个 4K 文档少 22.70%。 ### 精度和性能验证结果 本修改不涉及精度变动。 #### 1M BF16 MFU 估算 采用 Flash 无 MTP 配置,1M 为 1,048,576 token。新旧公式均假设吞吐为 1,500 tokens/s/卡,并使用仓库 1M 基准的 Ascend 950 BF16 峰值 432 TFLOPS/卡。例如,新公式下单文档的 MFU 为 `163.665835 × 1,500 ÷ 1,000 ÷ 432 ≈ 56.83%`。 | 1M 输入 | 旧算法(GFLOPs/token) | 新算法(GFLOPs/token) | 旧 MFU | 新 MFU | MFU 变化(百分点) | | --- | ---: | ---: | ---: | ---: | ---: | | 1 个 1M 文档 | 421.020 | 163.666 | 146.19% | 56.83% | −89.36 | | 64 个 16K 文档 | 421.020 | 87.274 | 146.19% | 30.30% | −115.88 | 旧公式按整行长度计数,因此两种布局得到相同的 MFU。新公式按文档内的因果可见前缀计数,并将 Indexer 反向计数限制在 top-k。表中吞吐固定,MFU 差异来自 FLOPs 估算变化。 ## 其他信息 跟踪的 TorchTitan 版本包含上述两个 PR 后,删除临时估算器和训练指标适配。 See merge request: cann/torchtitan-npu!1381
Summary (human-written)
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_lengthkeys. 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:
What changed
Attention.Config.flops_per_token(seq_len)is replaced byAttention.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 chargesp + 1keys per query at position p, sliding windowmin(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_mask) are not counted, including DeepSeek V3 / V4 MTP head FLOPs.transformers_modeling_backend): same per-position counting for full and sliding-window attention. Withattn_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/mfudrop 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.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 callsflops(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):
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.causalminusblock_causalequals the cross-document keys times the per-key FLOPs, and that a trailing padding token adds nothing (no test added: no CI job runstransformers_modeling_backendunit tests).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
tpsstill counts padding tokens, as on main and in Megatron-LM / Megatron-Bridge; this PR does not change it.