Compare commits

..
Author SHA1 Message Date
NeoandGitHub 0164aab72c perf(metrics): count attention FLOPs with the real head dim and report SFT MFU per step (#3755)
For discussion: this is the MFU accounting used in the Qwen3-235B
prime-rl vs torchtitan benchmarks (#3753, #3754), so that both stacks
report comparable numbers. Opening it as its own PR so we can decide
whether to adopt it as the trainer's metric.

## What changes

1. **Attention FLOPs use the real head dim.** `PerfCounter` counted
attention as `12 * layers * heads * (hidden_size / heads) * seq`. For
models whose `head_dim` is not `hidden_size / num_attention_heads` that
undercounts: Qwen3-235B-A22B has head_dim 128 but hidden/heads = 64. The
new term is torchtitan's `quadratic_attention_flops_per_token`: `6 *
layers * heads * (qk_head_dim + v_head_dim) * seq`, with the MLA qk/v
head dims when the config has them. Identical to the old value when
head_dim == hidden/heads.
2. **SFT throughput and MFU are per step over the full step wall time**,
including the optimizer step, as torchtitan reports with `log_freq=1`.
Before, they came from a 10-step sliding window over forward/backward
time only. The RL trainer is unchanged and still reports over
forward/backward time.

## Effect

- Qwen3-235B-A22B at seq 8192: 167.3 -> 205.1 GFLOP/token; at 16384:
280.8 GFLOP/token. Logged MFU on such models goes up accordingly, so
dashboards and the benchmark tables in
`benchmarks/results/BENCHMARKS.md` are not directly comparable across
this change.
- Two expected values in `tests/unit/train/test_perf.py` updated
(Qwen3-0.6B: head_dim 128 vs hidden/heads 64; the debug MoE likewise).

## Caveat worth discussing

Both formulas charge dense causal attention. On packed short documents
with varlen attention the executed attention FLOPs are far lower, so
absolute MFU is overstated for both stacks (roughly 2x at seq 16k on the
235B bench). Counting executed FLOPs from the packed sequence lengths
would be a separate change.
2026-10-03 13:26:42 -07:00
3 changed files with 18 additions and 8 deletions
+12 -4
View File
@@ -179,19 +179,27 @@ class PerfCounter:
if hasattr(model_config, "text_config"):
model_config = model_config.text_config
l, h, q, t = ( # noqa: E741
l, h, t = ( # noqa: E741
model_config.num_hidden_layers,
model_config.num_attention_heads,
model_config.hidden_size // model_config.num_attention_heads,
seq_len,
)
# Reasoning behind the factor of 12 for the self-attention part of the formula:
# Head dims as torchtitan's quadratic_attention_flops_per_token: the real head_dim (e.g. 128 for
# Qwen3-235B, whose hidden_size / num_attention_heads is 64), or the MLA qk / v head dims.
if hasattr(model_config, "qk_head_dim") and hasattr(model_config, "v_head_dim"):
qk_head_dim, v_head_dim = model_config.qk_head_dim, model_config.v_head_dim
else:
qk_head_dim = v_head_dim = (
getattr(model_config, "head_dim", None) or model_config.hidden_size // model_config.num_attention_heads
)
# Reasoning behind the factor of 6 for the self-attention part of the formula:
# 1. each self-attention has 2 matmul in the forward and 4 in the backward (6)
# (q @ K^T over qk_head_dim, then scores @ V over v_head_dim, per head and attended token)
# 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
attention_flops = 12 * l * h * q * t
attention_flops = 6 * l * h * (qk_head_dim + v_head_dim) * t
if has_lora_layers(self.model):
# LoRA case:
+5 -3
View File
@@ -556,15 +556,17 @@ def train(config: SFTConfig):
progress.total_tokens += num_tokens
dataset_progress = get_dataset_progress(dataloader)
progress.total_samples = dataset_progress["step"]
# Throughput / MFU per step over the full step wall time, as torchtitan reports them with
# log_freq=1 (tokens since last log / elapsed time), instead of a smoothed sliding window.
step_time = time.perf_counter() - step_start_time
perf_counter = get_perf_counter(model, config.data.seq_len)
perf_counter.count_tokens(num_tokens)
throughput = perf_counter.get_tokens_per_second() or 0
mfu = perf_counter.get_mfu() or 0
throughput = perf_counter.get_step_tokens_per_second(num_tokens, step_time)
mfu = perf_counter.get_step_mfu(num_tokens, step_time)
peak_memory = torch.cuda.max_memory_reserved() / 1024**3 # GiB
max_peak_memory = max(max_peak_memory, peak_memory)
# Log step metrics
step_time = time.perf_counter() - step_start_time
step_message = f"Step {progress.step} | {format_time(step_time):>7} | Loss {batch_loss:.4f}"
if grad_norm is not None:
step_message += f" | Grad. Norm {grad_norm:.4f}"
+1 -1
View File
@@ -7,7 +7,7 @@ from prime_rl.trainer.perf import PerfCounter
@pytest.mark.parametrize(
"model_name, active_params, flops_per_token",
[("Qwen/Qwen3-0.6B", 595_984_384, 3_928_227_840), ("Jackmin108/debug-moe-0.5B", 256_442_368, 1_689_649_152)],
[("Qwen/Qwen3-0.6B", 595_984_384, 4_280_549_376), ("Jackmin108/debug-moe-0.5B", 256_442_368, 1_840_644_096)],
)
def test_perf_counter(model_name: str, active_params: int, flops_per_token: int):
# This speeds up the model loading as its a fake device