Repository navigation
[rl] Trainer MFU over real documents: no padding, attention at each document's length - #5455
Draft
felipemello1 wants to merge 3 commits into
Draft
felipemello1 wants to merge 3 commits into
felipemello1 wants to merge 3 commits into
Conversation
…ocument's length The batcher records each microbatch's real-token count and sum of squared document lengths at pack time, as plain ints, so they also travel by value in RDMA microbatches. The trainer averages both over DP ranks, since the controller logs DP rank 0's metrics. Step FLOPs are intercept x real tokens + attention slope x the sum of squared document lengths. The slope comes from a new TrainingEngine.num_flops_per_token_at_one_token, the per-token FLOPs at one attended token. trainer/mfu_percent and trainer/tflops count only real tokens, each attending to its own document; trainer/tokens_per_second counts real tokens.
acisseJZhong
added a commit
that referenced
this pull request
Nov 24, 2026
…position (#6325) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> 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](https://github.com/NVIDIA/Megatron-LM/blob/e54d3896a1c5ce14b08d0a493a078c77c01a182c/megatron/core/transformer/attention.py#L1872-L1892), [training.py](https://github.com/NVIDIA/Megatron-LM/blob/e54d3896a1c5ce14b08d0a493a078c77c01a182c/megatron/training/training.py#L252-L264)) and Megatron-Bridge ([flop_utils.py](https://github.com/NVIDIA-NeMo/Megatron-Bridge/blob/60f7921aa13bff30d801c6b37c063a29786e3626/src/megatron/bridge/training/utils/flop_utils.py#L1513)) 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.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
TLDR: RL
trainer/mfu_percentcounted padding as work, and counted every token as attending tomax_context_lengthtokens. It now counts only real tokens, each attending to its own document's length. On a 0.6B smoke run, logged MFU drops 1.4-2.1x on the same batches. For a 4B run at a 131k context, we estimate 67% -> ~37%.Problem
num_tokens_per_microbatch_per_dp_rank.get_nparams_and_flops(model, max_context_length), so every token attends tomax_context_lengthtokens.trainer/mfu_percentandtrainer/tflopsread ~1.8x too high there (estimate, under torchtitan's non-causal convention).Solution
TrainingEnginealso storesnum_flops_per_token_at_one_token= f(1). With f(max_context_length), it gives the intercept and the slope.num_real_tokens= sum(L) andsum_squared_document_lengths= sum(L**2) on eachTrainingMicrobatchat pack time. They are plain ints, so they travel by value in RDMA microbatches too.trainer/tokens_per_secondnow counts real tokens, not padded ones.Results
The documents are short here: their length-weighted mean is 80-265 tokens, against a 2048 context.
You may ask:
optim_stepmetrics. Rank 0 also gets the all-padding bins first, because they have the highest padding-aware workload. With per-rank counts, the logged MFU would be 0 whenever rank 0 got only padding.global_routing_token_counts? It gives sum(L), but not sum(L**2).rdma_min_tensor_bytesset, a tensor that size or larger stays in the batcher until the trainer reads it. Ints always travel in the message, so the trainer reads them without an RDMA read.NOTE: f(L) is not linear in L for sliding-window layers or DeepSeek-V4's compressed attention, so their MFU stays approximate (TODO in the code). A per-batch FLOPs estimator is in progress in another PR; this moves onto it once it lands.
NOTE:
TrainingEnginenow callsget_nparams_and_flopstwice, so every trainer, pretraining included, logs "Total parameter count" twice at startup.NOTE: the 4B estimate is arithmetic from logged run metrics, not a run of this PR.
Test plan
tests/rl/unit_tests/cpu/test_batcher.py::test_microbatch_counts_real_tokens_and_squared_document_lengths: lengths 3 and 2, each padded to 4, give 5 and 13; an all-padding bin gives 0 and 0.tests/rl/unit_tests/cpu/test_trainer.py::test_optim_step_counts_each_real_document_at_its_own_length: MFU equals 3 * f(3) + 2 * f(2) for the Qwen3.5 debug model (full attention plus delta rule), to rel 1e-12.test_forward_backward_accumulates_microbatch_metrics(both paths): the counts come from.fieldson the RDMA path, and are averaged over 2 DP ranks when rank 0 got only padding.pytest tests/rl/unit_tests/cpu: 481 passed, 9 skipped.pytest tests/unit_tests/cpu: same failures as main (3 SPMD redistribute tests, plus a torchao import in a venv without torchao).training_engine.py.python -m torchtitan.rl.trainand a local recipe that sets TP=1 onrl_grpo_qwen3_0_6b_varlen.