Repository navigation
Fix mfu calculation for muse glimmer and gpt_oss - #4300
Conversation
tianyu-l
left a comment
There was a problem hiding this comment.
Per-batch vision encoder FLOP counting is not yet implemented. Perhaps it can be done in a separate multimodal trainer.
There has been an attempt which doesn't look super clean #4057. And I think what you propose could be potentially better.
| return total | ||
|
|
||
|
|
||
| def get_dense_model_nparams_and_flops( |
There was a problem hiding this comment.
I think we can deprecate this one and consolidate with the moe one, and maintain only one get_model_nparams_and_flops.
There was a problem hiding this comment.
get_moe_model_nparams_and_flops would work for calling on dense TorchTitan models, but it would not work on HFTransformerModel. HFTransformerModel currently does
torchtitan/torchtitan/experiments/transformers_modeling_backend/model.py
Lines 517 to 526 in 30eb5e5
which does not take into account of MoE and also does not do multiplication by 2 on on the head_dim unlike TorchTitan models.
So, the
num_flops_per_token count is different in both dense and MoE models (computed at seq len 8192).
| MoE qwen3 30B A3B | num_flops_per_token |
|---|---|
| TorchTitan | 37,578,559,488 |
| HF (called hf/full_moe) | 192,856,412,160 |
| Dense qwen3 0.6B | num_flops_per_token |
|---|---|
| TorchTitan | 9,213,444,096 |
| HF (called hf/sft_full) | 6,394,871,808 |
There is a comment
There was a problem hiding this comment.
which does not take into account of MoE
it was probably missed, but we should add MoE for HF modeling, so it aligns with my suggestion?
also does not do multiplication by 2 on on the head_dim unlike TorchTitan models. So, the num_flops_per_token count is different in both dense and MoE models
what is this multiply-by-2 about? Are you saying that the computation of flops is problematic / different than core models? Then we should fix it (can be in a separate PR).
There was a problem hiding this comment.
The multiply by 2 is to account for sum of qk and v head dimensions, as the functions get_dense_model_nparams_and_flops and get_moe_model_nparams_and_flops require in the argument for head_dims. Except for DeepSeekV3, TorchTitan models have qk and v head dimensions equal so they pass 2 * head_dim, while DeepSeekV3 passes self.layers[0].attention.qk_nope_head_dim + self.layers[0].attention.qk_rope_head_dim + self.layers[0].attention.v_head_dim.
Since HFTransformerModel just passes head_dim, the flops for the attention part gets undercounted. The sft_full config in the config registry is Qwen 3 0.6B and you can see that the flops computed are way lower than the torchtitan Qwen 3 0.6B.
| return stacked_tensor | ||
|
|
||
|
|
||
| def attention_flops_per_token( |
There was a problem hiding this comment.
could you also fix linear attention models, e.g. qwen3.5, kimi k3
There was a problem hiding this comment.
I added them, although it barely changes the number. See the above table
90134a0 to
721264c
Compare
721264c to
8d02a7a
Compare
| seq_len=seq_len, | ||
| ) | ||
| assert isinstance(model, HFTransformerModel) | ||
| return _get_hf_model_nparams_and_flops(self, model, seq_len) |
There was a problem hiding this comment.
don't need to create this as a separate function?
| if not isinstance(attention, GQAttention.Config): | ||
| logger.warning( | ||
| "Skipping FLOP accounting for unsupported Llama 3 " | ||
| f"attention config {type(attention).__name__}." | ||
| ) | ||
| continue |
There was a problem hiding this comment.
this is a partial guard that we probably don't need to maintain
| if not isinstance(attention, GQAttention.Config): | ||
| logger.warning( | ||
| "Skipping FLOP accounting for unsupported Qwen 3 " | ||
| f"attention config {type(attention).__name__}." | ||
| ) | ||
| continue |
| seq_len, | ||
| excluded_modules=(kimi_model.vision_encoder,), | ||
| ) | ||
| sequence_mixing_flops = 0 |
There was a problem hiding this comment.
It seems to be used at least once https://arxiv.org/html/2403.17844v1, but does not seem to be a common name. Maybe just some generic name like additional_flops might be better?
| if not isinstance(attention, Attention.Config): | ||
| logger.warning( | ||
| "Skipping FLOP accounting for unsupported GPT-OSS " | ||
| f"attention config {type(attention).__name__}." | ||
| ) | ||
| continue |
| logger.warning( | ||
| "Skipping FLOP accounting for unsupported Qwen 3.5 " | ||
| f"sequence mixer {type(configured_mixer).__name__}." | ||
| ) |
| *, | ||
| num_heads: int, | ||
| qk_head_dim: int, | ||
| value_head_dim: int, |
There was a problem hiding this comment.
| value_head_dim: int, | |
| v_head_dim: int, |
| head_dims: int, | ||
| seq_len: int, | ||
| *, | ||
| excluded_modules: Iterable[nn.Module | None] = (), |
| # Reasoning behind the factor of 6 for the self-attention part of the formula: | ||
| # 1. each self-attention has 2 matmul (attention scores and value aggregation, | ||
| # combined in head_dims, counted as 1) in the forward and 4 (counted as 2) | ||
| # in the backward (3) | ||
| # 2. the flash attention does 1 more matmul recomputation in the backward | ||
| # but recomputation should not be counted in calculating MFU (+0) | ||
| # 3. each matmul performs 1 multiplication and 1 addition (*2) | ||
| # 4. we follow the convention and do not account for sparsity in causal attention | ||
| # With tied embeddings, PyTorch's parameter iterator already counts the | ||
| # shared input/output parameter once. That parameter still participates in | ||
| # the lm_head matmul, so do not subtract it for either size or FLOPs. |
| seq_len, | ||
| modules_excluded_from_active_params=(kimi_model.vision_encoder,), | ||
| ) | ||
| additional_flops = 0 |
There was a problem hiding this comment.
I think we can do attention_op_flops
…helper 21 commits behind upstream/main. Merged into a scratch clone (../tt-sync82) rather than the production one, because three optcmp arms are mid-chain with 7 links queued on afterany: each released link re-reads the working tree at launch, so landing this now would have later links training on different code than earlier ones and silently break comparability of the +10B measurement in progress. The merge is clean -- zero conflicts across 127 files -- and agpt is fine: all three optcmp configs build, and SpmdLayout (removed by pytorch#4265) turns out to appear in ezpz only in comments and as a local variable name. ezpz/moe does not build. pytorch#4300 rewrote models/utils.py and removed get_moe_model_nparams_and_flops, which moe/model.py imports at :30 and calls at :344. It is a port rather than a rename: the replacement get_nparams_and_active_nparams takes (model, *, modules_excluded...) and returns (nparams, active_nparams), dropping flops, which are now composed separately via quadratic_attention_flops_per_token. deepseek_v3's get_deepseek_v3_nparams_and_flops is the reference pattern. Landing plan is unchanged: finish the +10B run, then merge, then 2N smoke, with pytorch#4116 (post-dataloading refactor) checked against BlendCorpus specifically since that is where the token-unit fold bugs have lived.
…lpers Upstream pytorch#4300 rewrote models/utils.py and removed get_moe_model_nparams_and_flops, which moe/model.py imported. Without this the whole moe package fails to import under sync 82. It is a port rather than a rename. The replacement returns (nparams, ACTIVE nparams) and no longer computes flops at all, so the attention term is summed here from quadratic_attention_flops_per_token and the 6*N matmul term applied explicitly. Mirrors deepseek_v3's get_deepseek_v3_nparams_and_flops, minus its MTP lm_head term since this decoder has no mtp_layers. Sums attention flops PER LAYER rather than taking layers[0] and multiplying by depth, which is what the old helper did -- it accepted a single n_heads and head_dims for the entire model, so a stack with non-uniform attention would have been silently mismeasured. Per-layer costs nothing here. Verified on the merged tree: 25 of 26 moe configs build (moe_671b fails on a Float8 SM89 hardware gate on a login node with no XPUs, unrelated), and the function executes end to end on a built moe_10b_2b, returning nparams=10,036,915,712 -- the expected 10B. Committed on the sync-82 scratch clone, not production: three optcmp arms are mid-chain there and each released link re-reads the working tree at launch.
## Purpose #4300 moved every model onto the shared `quadratic_attention_flops_per_token`, which carries the two attention contractions in `(qk_head_dim + v_head_dim)`: ```python return 6 * num_heads * (qk_head_dim + v_head_dim) * attended_tokens ``` flux was the one model left on an inline formula: ```python # Add non-parameterized self-attention FLOPs (QK^T and attn*V). # Per PaLM convention: 6 * hidden_size * seq_len per token per # layer (covers 2 matmuls × fwd+bwd × multiply-add). num_flops_per_token += ( 6 * sb_h * seq_len * self.depth_single_blocks + 6 * db_h * seq_len * self.depth ) ``` `6 * hidden_size` is `6 * num_heads * head_dim` — one head_dim, so one of the two matmuls. The comment says it covers "2 matmuls"; the expression covers one. The factor of 6 already accounts for fwd+bwd and multiply-add, which is why the shared helper needs the *sum* of the two head dims on top of it. So flux's attention term is exactly half of what every other model reports for the same computation. That value reaches `trainer.py:381` and then `metrics.py:493`: ```python mfu = 100 * self.num_flops_per_token * tps / self.gpu_peak_flops ``` so the `mfu:` line in a flux training log reads low. | flavor | attention FLOPs/token (inline vs shared) | reported MFU understated by | | --- | --- | --- | | `flux-dev` (hidden 3072, 24 heads, 19 double + 38 single) | 4,303,355,904 vs 8,606,711,808 — **2.00×** | **9.9%** | | `flux-debug` (hidden 1536, 12 heads, 2 double + 2 single) | 150,994,944 vs 301,989,888 — **2.00×** | **16.6%** | (at `seq_len` 4096) ## Test Plan ``` pytest tests/unit_tests/cpu/test_flux_flops.py ``` The new test rebuilds `flops_per_token` from the terms the docstring names — `6 * nparams`, minus one side of each symmetric double-stream block, minus the per-sample modulation amortization, plus attention from the shared helper — and compares it to what `get_nparams_and_flops` returns. ## Test Result On `main` the test fails, which is the defect: ``` E AssertionError: 776752512 != 795626880 tests/unit_tests/cpu/test_flux_flops.py:69: AssertionError ``` With the fix: ``` tests/unit_tests/cpu/test_flux_flops.py . [100%] 1 passed ``` `get_nparams_and_flops` before → after, at `seq_len` 4096: ``` flux-debug 908,098,944 -> 1,059,093,888 flux-dev 43,266,767,232 -> 47,570,123,136 ``` Regression over the neighbouring CPU tests (`test_flux_flops`, `test_dataset_flux`, `test_weight_tying`, `test_module`, `test_train_spec`): ``` 46 passed, 3 subtests passed ``` `ufmt check` clean on both files with the pinned `ufmt==2.3.0 / black==22.12.0 / usort==1.0.5`. This does not touch the sequence length used for the double-stream blocks, which attend over the concatenated image and text streams — that is a separate question from the factor of two, and I left it alone.
FLOPS were overcounted for models using sliding window attention, giving MFU higher than 100% for Muse Glimmer.
Fixed to take into account of sliding window.
Also fixed Muse Glimmer FLOP to not include vision, similar to
get_moe_model_nparams_and_flops.Per-batch vision encoder FLOP counting is not yet implemented. Perhaps it can be done in a separate multimodal trainer.
Update Aug 25
Refactored so that each model should separately calculate the non-matmul/non-MoE term.
Added linear terms for Qwen 35 and Kimi 3.
Separated the calculation for
HFTransformerModelas a separate function since it does not follow torchtitan convention. Also fixed the calculation to match the corresponding torchtitan models.Notably
transformers_modeling_backend:full_moenow matches torchtitan Qwen3 30B A3Btransformers_modeling_backend:fullnow matches torchtitan Qwen3 4Btransformers_modeling_backend:sft_fullnow mathces torchtitan Qwen3 0.6BChanges in
num_flops_per_tokencompared to commit 30eb5e5: