Skip to content

[refactor] estimate model FLOPs per input batch - #4819

Merged
tianyu-l merged 9 commits into
pytorch:mainfrom
jinsooihm:model-owned-mfu-computation
Nov 5, 2026
Merged

tianyu-l merged 9 commits into
pytorch:mainfrom
jinsooihm:model-owned-mfu-computation

Conversation

@jinsooihm

@jinsooihm jinsooihm commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #4009

Previously, each models returned a function get_nparams_and_flops which returned num_flops_per_token, which the trainer used to compute the FLOPs by multiplying the number of text tokens seen to it.

This does not take into account of FLOPs of multimodal models. The computation becomes more complicated, because vision inputs may have images of different sizes.

Change

  • Each Model defines build_flops_estimator that takes in input batch and outputs flops for that batch.
  • Each Attention module defines flops_per_token, since now all attentions (except vision attention) actually inherit from Attention
  • There is a shared function for Decoder.build_flops_estimator that sums the flops_per_token of its owned attention modules and active params, removing duplicated logic.
  • Each encoders also define their own estimator functions.
  • There is a default for multimodal models, but the Muse series has additional modules that consumes encoder output before putting into the decoder, so they override.
  • Multimodal models override build_flops_estimator it by adding the contributions from the encoders.
  • Text input flops is still not sensitive to the individual document lengths
Model / input Tokens¹ Main FLOPs Branch FLOPs Change
Llama 3 text 16 546,103,296 546,103,296 0%
Qwen 3 MoE text 16 4,945,698,816 4,945,698,816 0%
GPT-OSS text 16 4,416,359,424 4,416,359,424 0%
DeepSeek V3 + MTP 8 1,586,823,168 1,586,823,168 0%
DeepSeek V4 Flash + MTP 4,096 379,954,597,380,096 379,954,597,380,096 0%
HF dense text 16 3,355,041,792 3,355,041,792 0%
HF MoE text 16 30,685,298,688 30,685,298,688 0%
Qwen 3.5 image + video² 16 6,875,902,464 7,700,494,848 +11.9925%
Kimi K2.7 image 16 2,694,340,608 2,945,955,840 +9.3387%
Kimi K2.7 video 16 2,694,340,608 3,172,325,376 +17.7403%
Kimi K3 image² 16 1,997,167,104 2,197,344,768 +10.0231%
Muse Glimmer image 16 711,745,536 731,043,840 +2.7114%
Muse Glimmer two images 16 711,745,536 791,298,048 +11.1771%
Flux, batch 2 1,024 814,721,925,120 814,721,925,120 0%
Muse Spark image + audio 16 462,176,256 483,217,920 +4.5527%

Limitations

This PR makes the FLOPs calculation take into account of each images in the batch, but it does not make the calculation aware of the different document lengths present in an input text sequence.

I don't have GPUs so I will rely on CI for testing.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 21, 2026
@jinsooihm jinsooihm changed the title [refactor] estimate model FLOPs per input batch Do not review yet [refactor] estimate model FLOPs per input batch Sep 21, 2026
@jinsooihm
jinsooihm force-pushed the model-owned-mfu-computation branch 2 times, most recently from 2b43c71 to 15e8646 Compare September 21, 2026 20:49
@jinsooihm jinsooihm changed the title Do not review yet [refactor] estimate model FLOPs per input batch [refactor] estimate model FLOPs per input batch Sep 21, 2026
@jinsooihm
jinsooihm force-pushed the model-owned-mfu-computation branch from 15e8646 to be0345e Compare September 21, 2026 21:17
@jinsooihm
jinsooihm marked this pull request as ready for review September 21, 2026 21:17
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 21, 2026

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

graph trainer change looks fine to me

Comment thread torchtitan/models/utils.py Outdated
)
return nparams, active_nparams

def build_token_flops_estimator(

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.

already having build_flops_estimator, so prefer to not have this thin wrapper with similar name

Comment thread torchtitan/models/utils.py Outdated
assert usage_weighted_nparams.denominator == 1
return 6 * usage_weighted_nparams.numerator

logger.info(

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 gone from CLI?

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.

Should the vision encoder parameters also be included in the logged num_active_parameters? Previously, it was not included.

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 feel we should, but please check with popular multimodal models -- when they publish a model, claim the size, do they count the vision encoder?

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.

takeaways

  • vision encoder is usually very small, so it is hard to say whether it was included in the param count or active param count after rounding ( I guess more often not )
  • published Qwen 3.5 numbers seems to be after weight tying, so calling literal sum of param.numel() gives wrong number
  • Torchtitan excludes embedding from active param
    • qwen 3.5 includes embedding in active param
    • kimi seems to exclude it
Family Flavor Published total Published active TorchTitan total Vision encoder TT decoder-active TT active + encoder
Kimi Kimi-VL-A3B ~16B ~3B 16.408B 447.546M 2.579B 3.027B
Kimi Kimi-K2.5 / K2.6 / K2.7-Code ~1T ~32B 1,026.879B 471.144M 31.687B 32.158B
Kimi Kimi-K3 2.8T 104B 2,779.932B 447.359M 104.190B 104.637B
Muse Glimmer 30B_mm 30B Not separately stated 29.777B 1,852.640M 26.510B 28.363B
Qwen3.5 0.8B 0.8B Not separately stated (dense) 1.107B 100.593M 0.752B 0.853B
Qwen3.5 2B 2B Not separately stated (dense) 2.722B 331.417M 1.882B 2.213B
Qwen3.5 4B 4B Not separately stated (dense) 5.175B 333.514M 4.206B 4.539B
Qwen3.5 9B 9B Not separately stated (dense) 9.410B 456.010M 7.937B 8.393B
Qwen3.5 / 3.6 / 3.8 27B 27B Not separately stated (dense) 27.357B 460.730M 25.625B 26.085B
Qwen3.5 / 3.6 35B-A3B 35B 3B 35.107B 446.571M 2.946B 3.393B
Qwen3.5 122B-A10B 122B 10B 122.563B 451.291M 9.008B 9.460B
Qwen3.5 397B-A17B 397B 17B 396.802B 456.010M 16.332B 16.788B

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.

There seems to be no one nice way to exactly match the official published param/active param count.

I think for our numbers we should make a choice:

  • total_parameters: every unique parameter in the actual torchtitan model, no double counting weight tied params.
  • active_parameters: MoE consideration + embedding params + multimodal encoders

And params used for matmul flops would exclude the embedding params, so it will not directly use active_parameters.

Comment thread torchtitan/training_engine.py Outdated
self.num_flops_per_token,
) = self.model_config.get_nparams_and_flops(
model, self.config.training.max_context_length
self.model_param_count = sum(param.numel() for param in model.parameters())

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.

but I'm losing active param count

Comment thread torchtitan/models/utils.py Outdated
return lambda batch: flops_per_token * batch["input"].numel()


def sum_packed_grid_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.

should this go to multimodal.py?

Comment thread torchtitan/models/flux/model/model.py Outdated
*,
seq_len: int,
) -> FlopsEstimator:
cached_flops_per_token = self._estimate_flops_per_token(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.

what is "cached" referring to here?

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.

Cacheing for capturing by the closure below. I will just change it to flops_per_token.

Comment thread torchtitan/models/utils.py Outdated
flops_per_token: int,
) -> Callable[[Mapping[str, Any]], int]:
"""Build an estimator for work that scales with input token count."""
return lambda batch: flops_per_token * batch["input"].numel()

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.

"batch" is not great name, because sometimes you call this function on a microbatch

Comment thread torchtitan/distributed/utils.py Outdated
)


def materialize_scalar_tensors(

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.

maybe is it not worth the complexity? if only concatenating two tensors in log steps only

Comment thread torchtitan/distributed/utils.py Outdated
)


def mean_flops_tensor(

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.

prefer not having this thin wrappers

Comment thread torchtitan/rl/trainer.py Outdated
performance = compute_training_performance_metrics(
num_tokens=self._step_num_tokens_per_dp_rank,
elapsed_time=elapsed_time,
non_data_parallel_size=engine.parallel_dims.non_data_parallel_size,

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.

when computing flogs, this flag should be used with caution, because we have CP replicate input -> CP shard -> loss mesh reduction

Comment thread torchtitan/models/kimi_k2_7/model.py Outdated
modules_excluded_from_active_params=(kimi_model.vision_encoder,),
return (kimi_model.vision_encoder,)

def build_flops_estimator(

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.

maybe only multimodal defines it once and each encoder is responsible for their own specialization; maybe same for attention variants (maybe not differentiate recurrent vs. chunk for linear attention)

@jinsooihm
jinsooihm marked this pull request as draft September 22, 2026 21:05
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 22, 2026
@jinsooihm
jinsooihm force-pushed the model-owned-mfu-computation branch from be0345e to f869641 Compare September 23, 2026 21:37
@jinsooihm
jinsooihm marked this pull request as ready for review September 24, 2026 19:44
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 24, 2026
@jinsooihm
jinsooihm force-pushed the model-owned-mfu-computation branch from b5cf364 to d98ab2a Compare September 24, 2026 19:45
@felipemello1

Copy link
Copy Markdown
Contributor

message from claude: Hi @jinsooihm, thanks for this. We're opening a small RL-only fix for MFU: RL microbatches are padded to a fixed token count (5-22% padding in our runs), and attention FLOPs assume max_context_length for every token, so in our 131k-context runs RL's mfu_percent reads ~1.8x too high under the non-causal convention.

Our fix uses the fact that under that convention, a document of length L costs L**2 attended tokens. The RL batcher records the sum of squared document lengths at pack time. With positions that restart per document, that sum is also the sum over non-padding tokens of (2 * position + 1).

Happy to move this onto your per-batch estimator once it lands, or to add it there if you'd like.

@jinsooihm

jinsooihm commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Thank you @felipemello1 .
After @acisseJZhong refactored the attention and transformer blocks, this should be a lot more straightforward to implement, by making each Attention class to own a constant or a function that can be used to compute flops per sequence length.
Then, probably we just need a few functions for Decoder, MultimodalModel, and the vision encoders and can get rid of most of the model specific code.

Feel free to take over, since I do not have GPUs (and agents) anymore...

@jinsooihm
jinsooihm marked this pull request as draft October 31, 2026 19:25
@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 4s —— View job


Approve: review. Both of tianyu-l's latest comments are fixed (the frozen-parameter TODO and the DP-mesh reduction), and I found no new problems in 54924e1.

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

Verdict: Approve -- HEAD (54924e1) fixes both of tianyu-l's 03:40 comments and my should-consider from the last review. I found no new problems in the new commit.

What changed since the last review. FLOPs are now counted in _preprocess_microbatch_group (training_engine.py:719), in the same loop that already counts ntokens_seen. The two separate estimator loops are gone: the eager sum in forward_backward and the lazy sum in _forward_backward_body. forward_backward now builds ForwardBackwardResult(..., num_flops=...) itself. The graphable runners return a plain (loss, loss_metrics) tuple (LossAndMetrics), which explains the mechanical churn in graph_trainer and the tests.

Example (dp_shard=2, cp=2, tp=2).

before: dist_sum(F, loss_mesh)   / loss_mesh.size()  -> mean over 4 ranks (dp*cp)
after:  dist_sum(F, dp_mesh)     / dp_mesh.size()    -> mean over 2 ranks (dp)
        same value, since CP ranks hold the same pre-shard F; the collective is smaller
cp-only run: no FLOPs collective at all (gated on dp_enabled)

Resolved since the last review

  • flops.py:160 frozen-parameter TODO (tianyu-l): added. It says 2P for forward-only and 4P for input-grad-only, which is correct.
  • DP-mesh reduction instead of loss mesh (tianyu-l): done in trainer.py, rl/trainer/trainer.py, and torchft/trainer.py. The torchft version stays inside the dp_cp_enabled branch and adds ft_pg plus / ft_pg.size(), so FLOPs and loss reduce over the same replica group. The engine docstring and the README now say "DP mesh; CP is not reduced".
  • ForwardBackwardResult.num_flops no longer defaults to 0. A missed path now fails when the result is constructed, instead of silently reporting MFU 0.
  • Double counting: lazy preprocessing is still rejected with SDC replay and with accelerator graphs (training_engine.py:198-210). Eager preprocessing runs once, before _run_forward_backward. So the comment at :717 holds, and test_engine_replay_checks_whole_accumulation now also checks that the counter resets between calls. The graph_trainer non-PP override (graph_trainer/trainer.py:261) counts in the same place. Its PP path delegates to the base class.

Should consider

  • The PR description doesn't mention two changes reviewers will see in logs. First, the startup log line now reports "architecturally active" parameters, which include embeddings and encoders. Second, MFU is now the DP mean of per-rank work. A one-line note on each, plus a Testing section, would help the maintainer who merges this.

A maintainer still needs to review, since this touches trainer.py, training_engine.py, and models/base.

Not verified: MFU values on GPUs under PP, CP, and torchft. CI does not check MFU, so one short multi-GPU run comparing mfu_percent against main on llama3 (which should be unchanged) would confirm it.

grid_sample_mode: str = "bilinear"
pos_emb_grid_order: str = "raster"

def build_output_flops_estimator(

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.

What makes muse spark special that it owns both build_output_flops_estimator and build_flops_estimator.

I don't feel they are very readable, and other vision encoders don't seem to define the output one.

I see the output one used by model.py, but do we still need the build_flops_estimator.

# Graphable computation returns only loss and its metrics. FLOPs are estimated
# during preprocessing, outside capture/replay, and added to ForwardBackwardResult
# by the outer engine method after computation completes.
LossAndMetrics: TypeAlias = tuple[torch.Tensor, list[list[dict[str, torch.Tensor]]]]

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 curious: why do we need to make them a tuple instead of a dataclass?

@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

@claude review my review

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 16s —— View job


Approve -- please address the item before merging: review. The Muse vision-output comment is right: replace build_output_flops_estimator with NaViTEncoder.Config.get_num_output_tokens, mirroring audio. The tuple in LossAndMetrics is fine; a NamedTuple would be optional.

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

Verdict: Approve -- please address the item below before merging -- tianyu-l's first comment holds up: NaViTEncoder.Config should not own an estimator for modules it doesn't contain. That is a small local edit. The second comment is a question, and the tuple is fine.

Example (what Muse does differently).

Qwen3.5:  vision_encoder = [patch_embed, layers, merger]                   -> encoder estimator covers everything
Muse:     vision_encoder = [conv1_linear, ln_pre, layers, ln_post]
          model.vision_adapter, model.vision_projection, model.perception_emb_norm
                                                                           -> top-level modules, run once per output token

tianyu-l's comments, one by one

  1. muse_spark/vision_encoder.py:158 "why both, do we still need build_flops_estimator": partly correct.

    • Both estimates are needed. MultimodalModel.Config calls NaViTEncoder.Config.build_flops_estimator for the encoder's own layers and attention, through multimodal_encoder_fqns (multimodal.py:56).
    • What sets Muse apart: its adapter, projection, and perception norm belong to the model, not the encoder (muse_glimmer/model.py:283-288, muse_spark/model.py:407-413). Qwen3.5 keeps its merger inside the encoder (qwen3_5/vision_encoder.py:343-351), so one estimator covers everything there.
    • The readability problem is real. build_output_flops_estimator(output_modules) is an encoder-config method that charges modules passed in from its parent. Only the token count is the encoder's job.
    • Fix: replace it with get_num_output_tokens(input_dict) on NaViTEncoder.Config, mirroring MuseSparkAudioEncoder.Config.get_num_output_tokens (audio_encoder.py:132). Then let Glimmer and Spark multiply that count by their own modules' FLOPs per token. Vision and audio become symmetric in Spark:
      vision_output_flops = sum(active_parameter_flops_per_token(m) for m in vision_outputs if m is not None)
      def estimate(input_dict):
          flops = base_estimate(input_dict)
          if vision_config is not None:
              flops += vision_config.get_num_output_tokens(input_dict) * vision_output_flops
          if audio_config is not None:
              flops += audio_config.get_num_output_tokens(input_dict) * audio_output_flops
          return flops
      Unlike the earlier one-caller version that tianyu-l asked about, this helper has two callers (Glimmer and Spark), the same as the audio counterpart. This edit removes about 10 lines in total, and the FLOPs numbers stay the same.
  2. training_engine.py:81 tuple vs dataclass: a question; the current choice is fine.

    • The split is needed. num_flops is a host int built up during preprocessing. It must not be part of a captured graph's output, because replay returns the object saved at capture time unchanged (accelerator_graph.py:574), so an int field would stay fixed at its capture value.
    • The inner runners therefore return only loss and metrics, and forward_backward adds the FLOPs (training_engine.py:688).
    • Nothing requires a tuple in particular. Outputs are not pytree-flattened, and SDC replay only reads get_loss. A dataclass would work too, but it would break the loss, loss_metrics = ... unpacking at about six call sites.
    • main already used a NamedTuple here (ForwardBackwardResult). If named fields are wanted, class LossAndMetrics(NamedTuple) costs nothing and keeps the unpacking. Optional.

Missed by the review

Nothing new I'd block on.

A maintainer still needs to review, since this PR touches trainer.py, training_engine.py, and models/base.

@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

@jinsooihm please rebase

and see if you would like to address

muse_spark/vision_encoder.py:158 "why both, do we still need build_flops_estimator": partly correct.

I'm fine with whatever you decide to do.

@jinsooihm
jinsooihm force-pushed the model-owned-mfu-computation branch from 54924e1 to ef8e408 Compare November 4, 2026 16:46
@jinsooihm

jinsooihm commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

@tianyu-l I agree with the fix.

@tianyu-l
tianyu-l merged commit 0a1fbf5 into pytorch:main Nov 5, 2026
felipemello1 pushed a commit that referenced this pull request Nov 5, 2026
Conflicts resolved so main's new behavior and this PR's sum-then-scale design both hold:
- #4819 (FLOPs per input batch): the graphable forward/backward returns (loss, metrics) and
  forward_backward builds ForwardBackwardResult with num_flops; kept, with this PR's single-argument
  _run_forward_backward. The core, GraphTrainer and TorchFT trainers keep main's FLOPs reduction and
  this PR's loss logging (sums divided by the step's loss tokens). TorchFT averages FLOPs over the
  replicas when ft_pg is set, also without DP or CP.
- #5779 (max_context_length from the model config): preprocess_inputs drops max_context_length and
  keeps aux_loss_denominators.
- #5563 (ChunkedLossWrapper keeps caller FSDP policies): main's chunked loop, without the count
  argument. test_chunked_loss_fsdp.py: losses are sums; the test divides gradients once by the loss
  tokens before comparing, as optim_step does.
- #5757/#5796 (SFT data change): sft.txt goldens taken from main; regenerated from CI next.
felipemello1 pushed a commit that referenced this pull request Nov 5, 2026
…ches/3-sdc-replay

Conflicts: main's #4819 made the graphable forward/backward return (loss, metrics)
(LossAndMetrics). Kept this PR's _ForwardBackwardFn protocol with its
preprocess_microbatch_groups_lazily keyword, now returning LossAndMetrics; the per-group graph
runner, GraphTrainer bodies and their tests follow. forward_backward resets the call's FLOPs count
before choosing lazy or up-front preprocessing; a checked call still preprocesses once, so its
FLOPs count once.
felipemello1 pushed a commit that referenced this pull request Nov 5, 2026
…/4-segment-graphs

Conflicts:
- training_engine.py: this PR's segment graphs replace the per-group graph runner (main's #4819
  had made it return (loss, metrics)). _run_forward_backward_segments now returns
  LossAndMetrics like the eager body; preprocessing stays outside the graphs, so FLOPs count once.
- rl/trainer/trainer.py: a trainer call can make two engine calls (the step's first group alone
  with graphs); each engine call's FLOPs add to the step's total.
- muse_spark recipe: main's precision.reduce_dtype, without the per-group graph opt-in.
- Tests: tuple results; the split-call RL test also checks the FLOPs of both engine calls.
- test_accelerator_graph_segments.py (GPU): main moved max_context_length to the model config
  and added TrainingEngine(precision=...).
fegin added a commit that referenced this pull request Nov 8, 2026
Stacked PRs:
 * #5882
 * #5881
 * #5880
 * __->__#5879


--- --- ---

## Summary (human-written)

With fake_pg, the tflops becomes `tflops // dp_mesh_size`. The reason is
that `allreduce` is an no-op but `dp_mesh_size` is a constant value not
affected by whether it is fake pg or real pg. This PR submit another row
that contains all 1 so that when doing real or fake `allreduce`, the
`tflops` is always accurate (fake pg tflops is pure computation).

## Why
Since #4819, the trainer logs the DP average of FLOPs as
`dist_sum(flops) / dp_mesh.size()`. On a fake process group the
all-reduce is a no-op, so the "sum" is only the local value, but it is
still divided by the DP size. Logged TFLOPS and MFU come out 1/DP of the
right value. Real process groups are not affected.

**Example.** DP8, each rank does 100 TFLOPS:

| | all-reduce sum | divided by | logged |
|---|---|---|---|
| real PG | 800 | 8 (mesh size) | 100 |
| fake PG, main | 100 | 8 (mesh size) | 12.5 (8x too low) |
| fake PG, this PR | 100 | 1 (summed count) | 100 |

## What changed
- New `dist_utils.dist_mean(x, mesh)`: all-reduces `[x, 1]` and returns
`sum / count`. On a real process group this equals `dist_sum(x) /
mesh.size()`. On a fake process group it returns the local value.
- `Trainer.train_step` and the RL trainer use it for the DP average of
FLOPs.

## Alternatives considered
- Log local FLOPs only: drops the DP average that #4819 added for
batches whose FLOPs differ across ranks.
- Check for the fake backend in the trainer: extra code for a case the
count already handles.

## Numerics / performance
- Loss and grad norm are unchanged. Logged FLOPs are unchanged on real
process groups.
- llama3 debug model, fake PG, NGPU=8 (DP8): FLOPs per token is 8.946e6
on main and 7.158e7 with this PR, matching the value before #4819.

## Testing
-
`test_trainer_accumulates_reused_accelerator_graph_losses[fake_dp=True]`
runs `train_step` on an 8-way fake DP mesh. On main it logs 75.0 instead
of 600.0.
- CPU tests for the trainer, distributed utils, FLOPs estimators, and
observability pass.

## Known issues / follow-ups
- The TorchFT trainer divides its FLOPs and loss sums by the mesh size
in the same way. Not changed here.
fegin added a commit that referenced this pull request Nov 10, 2026
…lash backward (#5889)

## Summary (human-written)
In the vision encoder region, some weights are invariant along the TP and CP axes. The backward must be deterministic; otherwise the gradients can vary across ranks and eventually cause weight drift.

This PR replaces Muse Spark and Muse Glimmer's vision encoder attention with a deterministic varlen attention class.

## Why
Muse Spark and Muse Glimmer vision weights are invariant over TP and CP. Every rank runs the same vision encoder backward and updates its own copy with no gradient reduction, so the copies stay equal only if that backward is bitwise repeatable. On main it is not: the NaViT attention uses flex, which picks autotuned templates and Inductor reduction configs per rank. Under CP the q/k grads differ across ranks and the replicated vision weights drift apart. Switching to Flash varlen alone does not fix it, because the Flash varlen backward is repeatable only under global deterministic mode.

**Example.**
```
Spark debug_mm, 2 x H100, global deterministic mode off, compare the two ranks' copies of each replicated param after every step
before (flex), CP2:             vision params differ across ranks
after (this PR), CP2 and TP2:   0 params differ and grad_norm is identical on both ranks at all 60 steps
```

## What changed
- Add torchtitan::deterministic_varlen_attn (torchtitan/ops/varlen_attn.py), a Flash varlen custom op. Its backward turns on deterministic mode only for itself, turns off the NaN fill of new tensors (fill_uninitialized_memory, which races with DeepEP comm streams) for that time, and restores both. It calls torch's varlen forward and backward ops directly, so the backward does not recompute the forward. It passes num_splits=1 in batch-invariant mode, except on ROCm, as VarlenInnerAttention does.
- The op calls the private torch_attn::_varlen_attn and _varlen_attn_backward ops, with every argument after max_k passed by keyword so a schema change fails loudly. A TODO in code says to switch to a public option once torch varlen_attn has one; no upstream issue is filed.
- Add DeterministicVarlenInnerAttention (common/attention/attention.py), a sibling of VarlenInnerAttention selected by config type. It runs the op on q/k/v and a VarlenAttentionMetadata that the caller builds, as VisionAttention callers do. It always uses Flash, so it has no sdpa_backends. It takes no enable_gqa or out_transform and has no metadata builder, so decoder attention cannot use it as is. The NaViT encoder (Muse Spark and Muse Glimmer) is the current user. NaViT builds cu_seqlens per image (full layers) and per window (sparse layers). Max lengths come from host-side grid sizes, so there is no device sync. NaViTEncoder.Config raises ValueError at config time for any other inner attention.
- The attention output takes the query's SPMD type. The vision layout from vision_inner_attention_sharding_config ({DP: V, CP: I, TP: S(1)}) holds under SPMD type checking.
- Common VisionAttention accepts flex or varlen metadata. Mechanical: its attribute flex_attention is renamed inner_attention; callers updated in the remat GPU test and the Kimi and Qwen3.5 checkpoint-conversion scripts.
- Mechanical: the varlen dtype choice moves out of VarlenInnerAttention into a module-private helper in attention.py, shared with DeterministicVarlenInnerAttention. Both classes activate FA3/FA4 with activate_cuda_flash_attention_impl().

## Alternatives considered
- Global deterministic mode: makes the whole model pay for determinism, and it raises on ops without a deterministic CUDA kernel, such as the grid_sample backward.
- Hooks on the grad_fn of the public varlen_attn that toggle the flag: work in eager, but Dynamo cannot trace grad_fn, and a compiled backward raises when the flag differs from the forward.

## Numerics
Vision attention changes from flex to Flash varlen, so Spark and Glimmer multimodal losses change. No golden loss file covers them. Vision attention outputs and grads are bitwise equal to torch Flash varlen in deterministic mode, whether or not global deterministic mode is on. Text-only models are unchanged.

| Config | Hardware | Result |
| --- | --- | --- |
| Spark debug_mm CP2, full FT and LoRA vision + decoder, deterministic off, 60 steps | 2 x H100 | replicated params bitwise equal, grad_norm identical per rank, every step |
| Spark debug_mm TP2, full FT and LoRA vision + decoder, deterministic off, 60 steps | 2 x H100 | same |
| Spark debug_mm CP2 and TP2, SPMD type checking on, 5 steps | 2 x H100 | passes (CP2 raised SpmdTypeError "has V, expected I" before the type fix) |
| muse_spark_debugmodel_mm_fsdp2_tp2_cp2_ep4 (dp_shard 2, TP2, CP2, EP4), type checking on, 10 steps (job 2344774) | 8 x GB300 | passes, identical on all 8 ranks |
| Spark 816B mm CP16 EP16, LoRA vision + decoder, deterministic on, 20 steps (job 2344772 vs 2342345) | GB300 | no deterministic error; loss and grad_norm identical to the run before rebasing at all 20 steps |

## Performance
Spark 816B mm, CP16 EP16, 32K packed, LoRA vision + decoder, median step time over steps 6-20 on GB300:

| Run | Attention | Deterministic mode | Step time | MFU |
| --- | --- | --- | --- | --- |
| 2340824 | flex | off | 5555 ms | 4.84% |
| 2342345 | this op | on | 4731 ms | 5.68% |
| 2344772 | this op (rebased tree) | on | 5003 ms | 5.37% |

MFU uses the text-token FLOPs formula from before #4819; compare the step times.

The runs are noisy (outliers up to 7.3 s) and change both the attention backend and deterministic mode, so read this as not slower than flex, not as a speedup. In isolation on H100, the op's forward + backward costs 0-13% more than the non-deterministic Flash varlen.

## Testing
- GPU test (gpu/ops/test_varlen_attn.py): with deterministic mode off, the out and q/k/v grads of DeterministicVarlenInnerAttention (which runs the op) are bitwise equal over 10 eager runs and one compiled run, and equal to torch Flash varlen with deterministic mode on. It also checks that the op restores fill_uninitialized_memory. It catches a backward that does not turn on deterministic mode, a schema change in the private ops, or a flag that is not restored.
- The Glimmer CPU tests replace the NaViT kernel with a per-segment SDPA stand-in, since varlen has no CPU kernel.
- The vision save-region remat GPU test passes with the renamed attribute.
- CPU tests at this commit: models/common/test_vision_attention.py, models/muse_spark and models/muse_glimmer, 167 passed, 1 skipped, 3 xfailed.

## Known issues / follow-ups
- Kimi K2.7, Kimi K3 and the Qwen3.5 family (qwen3_5, qwen3_6, qwen3_8) vision weights are also trainable and invariant over CP (and over TP for the unsharded ones), and their vision attention is still flex, so they can drift the same way under CP. This PR does not change them; this is from reading the code, not from a run.
- The batch-invariant num_splits=1 path has no test.
tianyu-l added a commit that referenced this pull request Nov 26, 2026
…er override; agent self-review; rl/transport (#6407)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why

Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it
approved,
30 then got a formal "request changes" from a maintainer, and about 20
more got
substantive inline asks. In nearly all of them the bot either saw the
problem
and approved anyway, or never asked the questions maintainers ask most
("does
the repo already do this?", "who should own this?"). The opposite
failure, the
bot blocking something a maintainer was fine with, is rare: in the PRs
we
sampled, 2 of its 81 must-fix items were wrong and about a third were
minor
(the empty human-written summary was the biggest source).

**Example** (#6112, controller sizes the rollout worker pool):

```
before: bot approved 10 times; tianyu-l then blocked: "the controller reads
        rollouter.rollouts_per_worker to compute a count it hands back to the
        Rollouter -- violates encapsulation"
after:  same commit, new skill -> Request changes, must-fix #1:
        "controller.py:589 -- wrong owner for the worker count ..."
```

There was also no way for a code owner to overrule the bot except
dismissing
its review in the GitHub UI, and a later `@claude review again` would
block
again.

## What changed

**Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`):
- Verdict rules: Approve only when every remaining item is an edit the
bot
could write itself. Anything the author still owes (a design change, an
unexplained golden change, evidence the PR rests on) is Request changes;
anything only a maintainer can decide is Needs discussion. A hedge like
"a
  maintainer should decide" can't come with Approve.
- Always must-fix: a violated written rule, a silent wrong result, a
second
  definition of an existing concept, a gate finding.
- Design gate: new questions for the existing counterpart, in-repo
ownership,
and the design behind a bug; "ban only what doesn't work on main"; read
the
numbers behind a claim. The overlapping-PR search is mandatory and
reported.
- Re-review covers every commit since the last full review, including
code
taken from the bot's own suggestions. A scoped question gets a
`COMMENT`, not
  a whole-PR verdict.
- The bot fact-checks its own proposed fixes, and cites a source for
claims
  about external tools or marks them unverified (never must-fix).
- An empty "Summary (human-written)" is a one-line "Before merge" note
that
  never affects the verdict.
- Checklist: config ownership direction, general shared wrappers, dead
code the
PR creates, model variants as flavors, a mechanical pass over every new
or
  changed function.

**Code owner override** (`SKILL.md`, `claude-code.yml`,
`CONTRIBUTING.md`): a
code owner comments `@claude override` (optionally `@claude override
2,3:
<reason>`); the bot approves if nothing else is open and doesn't
re-raise the
overridden items. A code owner's GitHub approval or "LGTM" is not an
override,
so a teammate can approve without the bot dropping its findings.
Dismissing the
bot's review still unblocks the PR, but isn't an override: the bot can't
tell
who dismissed it.

**Agent self-review** (`CLAUDE.md`, `pr-description`): an agent
preparing a PR
runs `pr-review` in branch mode first and records unaddressed items in
an
optional "Self-review" section. PRs written without an agent are
unaffected; a
missing section is never a finding.

Where each new rule comes from (maintainer asks the bot missed):

| Change | PRs |
| --- | --- |
| No Approve with open design/evidence items or a "maintainer should
decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 |
| Author waiver can't clear a must-fix | #6201, #6202, #6203 |
| Existing counterpart; one source of truth | #5228, #6169, #5881,
#5823, #5824, #6059, #5812 |
| Responsibility owner; config ownership direction | #6112, #6332,
#5802, #5803, #6325 |
| Fix the design behind the bug; a TODO doesn't justify a workaround |
#5572, #5689, #5657 |
| Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819,
#5543 |
| Re-review covers all new commits; scoped asks don't approve | #5824,
#5842 |
| Mandatory overlap search | #5885, #6248 |
| Ban only what doesn't work on main | #5543 |
| Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868
|

**Rules**: `design.md` gets the one-general-wrapper rule (moved from
`models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the
consumer owning its values; `config.md` gets ownership direction and "a
Config
doesn't read runtime state"; `direction.md` calls all-to-all the MoE
reference
implementation, so a new vendor-specific dispatch path (e.g. #6242)
needs a
reason the existing backends can't serve.

**Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/`
-> d4l3k.

**Mechanical, skim**: `torchtitan/rl/transport/` holds data movement
between RL
actors.
- `rl/model_state_dict_transport.py` ->
`rl/transport/model_state_dict.py`
- `rl/MODEL_STATE_DICT_TRANSPORT.md` ->
`rl/transport/MODEL_STATE_DICT_TRANSPORT.md`
- `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py`
- tests:
`tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py`
->
`tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py`
- imports, READMEs and `scripts/install_rl_env.sh` updated; no code
changes.

## User-facing changes

| Before | After |
| --- | --- |
| Overrule the bot: dismiss its review in the UI, and it blocks again on
the next run | `@claude override [items]: <reason>`; the bot approves
and doesn't re-raise them |
| Empty human-written summary: bot must-fix | One "Before merge" line,
no effect on the verdict |
| `from torchtitan.rl.model_state_dict_transport import ...` | `from
torchtitan.rl.transport.model_state_dict import ...` |
| `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from
torchtitan.rl.transport.rdma_microbatch import ...` |

## Testing

Backtest: the new skill run locally (nothing posted) on each PR at the
commit
and thread state the bot originally saw.

| PR | Bot then | New skill | What the maintainer asked |
| --- | --- | --- | --- |
| #6112 | Approve | Request changes | worker-count ownership (caught) |
| #5837 | Approve | Request changes | apply to `dp_shard` too (caught) |
| #5572 | Approve | Request changes | delete the injection design
(caught) |
| #6201 | Approve after author waived pins | Request changes, waiver
ignored | pins broke GPU tests after merge (caught) |
| #6007 | Approve | Request changes | fold K3.1 into K3 (caught) |
| #5543 | Request changes: "ban it" | Request changes: keep main's path
| don't break gpt-oss + DeepEP (fixed) |
| #6144, #5905 (controls) | Approve | Approve | -- |
| #6137 (control) | Approve | Needs discussion | -- (merge gate on an
upstream API) |

Code owner override, simulated on #6201: override by a code owner lifts
the
named item; `@claude override` from the author changes nothing; a code
owner's
"LGTM" approval followed by "review again" keeps Request changes.

Transport move: 83 RL CPU unit tests pass locally
(`transport/test_model_state_dict.py`, `test_trainer.py`,
`test_engine_loop.py`). `transport/test_rdma_microbatch.py`,
`test_generator.py` and
`test_batcher_actor.py` fail to collect in my env on `origin/main` too
(stale
attention-gym / Monarch), so CI is the check for those.

## Known issues / follow-ups
- Open PRs that edit the moved files rebase cleanly (git follows the
renames),
but new imports of the old module paths will break: #6309 (adds a delta
transport that should live in `rl/transport/`), #6237, #6176, #6177,
#5862,
  and drafts #6127, #6393, #6163, #5764.
- The Actions bot can't read dependency source (e.g. SGLang); follow-up
for the
  workflow.

## Self-review
pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch
mode diffs
against `origin/main` and skips description findings before a
description
exists; the "Config doesn't read runtime state" rule no longer
contradicts
hardware validation; dismissal dropped as an override form (the bot
can't tell
who dismissed); `test_rdma_microbatch.py` added to the transport area.
Not
addressed:
- One concern per PR -- the five changes ship together at the
maintainer's
  request.
- Open PRs touching the moved files -- listed above; the maintainer will
  coordinate.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests 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.

VLM MFU is miscomputed: vision-encoder FLOPs billed per decoder token, not per image patch

4 participants