Skip to content

Fix mfu calculation for muse glimmer and gpt_oss - #4300

Merged
jinsooihm merged 6 commits into
pytorch:mainfrom
jinsooihm:fix-mfu-calculation
Aug 26, 2026
Merged

jinsooihm merged 6 commits into
pytorch:mainfrom
jinsooihm:fix-mfu-calculation

Conversation

@jinsooihm

@jinsooihm jinsooihm commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

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 HFTransformerModel as 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_moe now matches torchtitan Qwen3 30B A3B
  • transformers_modeling_backend:full now matches torchtitan Qwen3 4B
  • transformers_modeling_backend:sft_full now mathces torchtitan Qwen3 0.6B

Changes in num_flops_per_token compared to commit 30eb5e5:

Model Reference FLOPs/token Current FLOPs/token Delta
deepseek_v3:debugmodel_mtp 948,461,568 1,077,436,416 +128,974,848 (+13.5983%)
gpt_oss:120b 38,044,854,144 34,534,221,696 -3,510,632,448 (-9.2276%)
gpt_oss:20b 26,481,681,792 24,141,260,160 -2,340,421,632 (-8.8379%)
gpt_oss:debugmodel 1,078,183,104 688,112,832 -390,070,272 (-36.1785%)
kimi_k3:Kimi-K3 643,256,488,512 645,209,985,600 +1,953,497,088 (+0.3037%)
kimi_k3:debugmodel 2,996,775,360 3,018,009,024 +21,233,664 (+0.7086%)
muse_glimmer:30B 169,528,679,424 165,602,810,880 -3,925,868,544 (-2.3158%)
muse_glimmer:30B_mm 181,059,753,984 165,602,810,880 -15,456,943,104 (-8.5369%)
muse_glimmer:debugmodel 144,754,176 71,616,000 -73,138,176 (-50.5258%)
muse_glimmer:debugmodel_mm 146,302,848 71,616,000 -74,686,848 (-51.0495%)
qwen3_5:0.8B 5,118,337,920 5,203,272,576 +84,934,656 (+1.6594%)
qwen3_5:2B 11,894,930,304 11,979,864,960 +84,934,656 (+0.7140%)
qwen3_5:4B 26,845,120,512 27,071,612,928 +226,492,416 (+0.8437%)
qwen3_5:9B 49,230,720,000 49,457,212,416 +226,492,416 (+0.4601%)
qwen3_5:27B 158,579,438,592 159,258,915,840 +679,477,248 (+0.4285%)
qwen3_5:35B-A3B 19,691,843,328 19,974,958,848 +283,115,520 (+1.4377%)
qwen3_5:122B-A10B 58,882,535,424 59,562,012,672 +679,477,248 (+1.1540%)
qwen3_5:397B-A17B 104,031,330,816 104,880,677,376 +849,346,560 (+0.8164%)
qwen3_5:debugmodel 438,220,320 439,989,792 +1,769,472 (+0.4038%)
qwen3_5:debugmodel_moe 414,594,576 415,479,312 +884,736 (+0.2134%)
transformers_modeling_backend:debugmodel 215,493,120 549,530,112 +334,036,992 (+155.0105%)
transformers_modeling_backend:debugmodel_moe 2,521,810,944 2,609,891,328 +88,080,384 (+3.4927%)
transformers_modeling_backend:full 25,424,950,272 31,382,565,888 +5,957,615,616 (+23.4322%)
transformers_modeling_backend:full_moe 186,157,584,384 27,914,883,072 -158,242,701,312 (-85.0047%)
transformers_modeling_backend:sft_debugmodel 215,493,120 549,530,112 +334,036,992 (+155.0105%)
transformers_modeling_backend:sft_full 4,052,090,880 6,394,871,808 +2,342,780,928 (+57.8166%)

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

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

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.

Comment thread torchtitan/models/utils.py Outdated
return total


def get_dense_model_nparams_and_flops(

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.

I think we can deprecate this one and consolidate with the moe one, and maintain only one get_model_nparams_and_flops.

@jinsooihm jinsooihm Aug 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

get_moe_model_nparams_and_flops would work for calling on dense TorchTitan models, but it would not work on HFTransformerModel. HFTransformerModel currently does

def get_nparams_and_flops(
self, model: nn.Module, seq_len: int
) -> tuple[int, int]:
return get_dense_model_nparams_and_flops(
model,
n_layers=self.n_layers,
n_heads=self.n_heads,
head_dims=self.head_dim,
seq_len=seq_len,
)

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

## Known issues to address later
- When using HF modeling, the test `FSDP=2 vs FSDP=2 + PP=2`, the `loss` and `grad_norm` not bitwise matching (but converging) while it is the case with Torchtitan modeling. This will be addressed in another PR but the culprit is probably `register_buffer` when loading `seed_checkpoint`
- the HF modeling has lower MFU than Torchtitan MFU

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.

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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread torchtitan/models/utils.py Outdated
return stacked_tensor


def attention_flops_per_token(

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.

could you also fix linear attention models, e.g. qwen3.5, kimi k3

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added them, although it barely changes the number. See the above table

@jinsooihm
jinsooihm marked this pull request as draft August 25, 2026 19:56
@jinsooihm
jinsooihm force-pushed the fix-mfu-calculation branch from 90134a0 to 721264c Compare August 25, 2026 21:18
@jinsooihm
jinsooihm force-pushed the fix-mfu-calculation branch from 721264c to 8d02a7a Compare August 25, 2026 21:24
@jinsooihm
jinsooihm marked this pull request as ready for review August 25, 2026 21:35
seq_len=seq_len,
)
assert isinstance(model, HFTransformerModel)
return _get_hf_model_nparams_and_flops(self, model, seq_len)

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.

don't need to create this as a separate function?

Comment thread torchtitan/models/llama3/model.py Outdated
Comment on lines +93 to +98
if not isinstance(attention, GQAttention.Config):
logger.warning(
"Skipping FLOP accounting for unsupported Llama 3 "
f"attention config {type(attention).__name__}."
)
continue

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 is a partial guard that we probably don't need to maintain

Comment thread torchtitan/models/qwen3/model.py Outdated
Comment on lines +118 to +123
if not isinstance(attention, GQAttention.Config):
logger.warning(
"Skipping FLOP accounting for unsupported Qwen 3 "
f"attention config {type(attention).__name__}."
)
continue

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.

similar

Comment thread torchtitan/models/kimi_k3/model.py Outdated
seq_len,
excluded_modules=(kimi_model.vision_encoder,),
)
sequence_mixing_flops = 0

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.

is this common name?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment thread torchtitan/models/kimi_k2_7/model.py Resolved
Comment thread torchtitan/models/gpt_oss/model.py Outdated
Comment on lines +224 to +229
if not isinstance(attention, Attention.Config):
logger.warning(
"Skipping FLOP accounting for unsupported GPT-OSS "
f"attention config {type(attention).__name__}."
)
continue

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.

similar

Comment thread torchtitan/models/qwen3_5/model.py Outdated
logger.warning(
"Skipping FLOP accounting for unsupported Qwen 3.5 "
f"sequence mixer {type(configured_mixer).__name__}."
)

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.

just raise

Comment thread torchtitan/models/utils.py Outdated
*,
num_heads: int,
qk_head_dim: int,
value_head_dim: int,

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.

Suggested change
value_head_dim: int,
v_head_dim: int,

Comment thread torchtitan/models/utils.py Outdated
head_dims: int,
seq_len: int,
*,
excluded_modules: Iterable[nn.Module | None] = (),

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.

misleading

Comment on lines -443 to -453
# 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.

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 keep this

Comment thread torchtitan/models/kimi_k3/model.py Outdated
seq_len,
modules_excluded_from_active_params=(kimi_model.vision_encoder,),
)
additional_flops = 0

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.

I think we can do attention_op_flops

@jinsooihm
jinsooihm merged commit e7fa776 into pytorch:main Aug 26, 2026
20 checks passed
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 28, 2026
…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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 29, 2026
…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.
tianyu-l pushed a commit that referenced this pull request Aug 30, 2026
## 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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