Skip to content

[rl] Trainer MFU over real documents: no padding, attention at each document's length - #5455

Draft
felipemello1 wants to merge 3 commits into
mainfrom
felipemello1/rl-mfu-real-documents
Draft

felipemello1 wants to merge 3 commits into
mainfrom
felipemello1/rl-mfu-real-documents

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

TLDR: RL trainer/mfu_percent counted padding as work, and counted every token as attending to max_context_length tokens. 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

  1. The RL batcher packs documents into microbatches padded to num_tokens_per_microbatch_per_dp_rank.
  2. The trainer counts that padded total as trained tokens. Padding was 5-22% in our long-context runs.
  3. FLOPs per token come from get_nparams_and_flops(model, max_context_length), so every token attends to max_context_length tokens.
  4. Packed documents are much shorter: 39-72k of 131k tokens on average in those runs.
  5. So trainer/mfu_percent and trainer/tflops read ~1.8x too high there (estimate, under torchtitan's non-causal convention).

Solution

  1. Under the non-causal convention, a token that attends to L tokens costs f(L) = intercept + slope * L FLOPs, so a document of length L costs L * f(L).
  2. TrainingEngine also stores num_flops_per_token_at_one_token = f(1). With f(max_context_length), it gives the intercept and the slope.
  3. The batcher records num_real_tokens = sum(L) and sum_squared_document_lengths = sum(L**2) on each TrainingMicrobatch at pack time. They are plain ints, so they travel by value in RDMA microbatches too.
  4. The trainer sums both over its column and averages them over DP ranks. MFU = (intercept * sum(L) + slope * sum(L**2)) / time / peak.
  5. trainer/tokens_per_second now counts real tokens, not padded ones.
  6. Unchanged: the non-causal convention, the pretraining trainer's metrics, the peak-FLOPS table.

Results

Qwen3-0.6B alphabet sort, 2 H100s (trainer TP=1, generator TP=1), max_context_length 2048, 3 steps.
Two separate runs, so the batches differ. The last column applies main's formula to this PR's batches.

step   padding (main / PR)   MFU main run   MFU this PR   main's formula on this PR's batches
1      0.36 / 0.36           1.76%          0.83%         1.78%    (step 1 includes compilation)
2      0.28 / 0.29           5.32%          2.52%         4.82%
3      0.04 / 0.04           6.32%          4.39%         6.03%

The documents are short here: their length-weighted mean is 80-265 tokens, against a 2048 context.

You may ask:

  • Why average over DP ranks? The controller logs only DP rank 0's optim_step metrics. 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.
  • Why not reuse global_routing_token_counts? It gives sum(L), but not sum(L**2).
  • Why plain ints on the microbatch, not tensors? With rdma_min_tensor_bytes set, 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: TrainingEngine now calls get_nparams_and_flops twice, 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 .fields on the RDMA path, and are averaged over 2 DP ranks when rank 0 got only padding.
  • Each new or changed assertion fails on main. These broken variants each fail at least one test: main's per-token FLOPs, no DP mean, the slope off by one, the RDMA path reading attributes, intercept = f(1), and counting padded sample lengths.
  • 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).
  • pyrefly 0.45.1: 31 errors on main and on this branch, none in training_engine.py.
  • GPU: the 3-step runs above, with python -m torchtitan.rl.train and a local recipe that sets TP=1 on rl_grpo_qwen3_0_6b_varlen.

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

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

1 participant