Skip to content

Add opt-in TFLOPs and MFU logging with LoRA aware FLOP counts - #13885

Merged
danielhanchen merged 13 commits into
mainfrom
dh/mfu-logging
Oct 16, 2026
Merged

danielhanchen merged 13 commits into
mainfrom
dh/mfu-logging

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

This adds an opt-in callback that logs achieved TFLOPs per GPU and model FLOPs utilization during training. Set UNSLOTH_LOG_MFU=1 before creating the trainer, or call unsloth.utils.mfu.add_mfu_callback(trainer). Training logs then gain train_tflops_per_gpu and, when the GPU is known, train_mfu. With the variable unset nothing changes.

The usual 6N per token estimate is wrong for LoRA. The FLOP count here walks the linear layers: every layer pays 2n for the forward and 2n for the input gradient, only trainable weights pay 2n for the weight gradient, and gradient checkpointing adds one more forward for the decoder layers (not the output head). Full finetuning comes out at 6N, LoRA at about 4N plus the adapters. Attention adds 4 x layers x heads x head_dim FLOPs per causal query key pair, three times for forward plus backward and four times with checkpointing. Tokens and per sequence lengths come from the batch (attention mask, packed sequence lengths or padding free position ids), so padding is not counted.

The peak comes from a small table of dense 16 bit numbers (T4, L4, A100, H100 variants, H200, B200, MI300X/A, MI325X) and can be overridden with UNSLOTH_PEAK_TFLOPS, for example with a measured maximum achievable matmul number. Unknown GPUs and fp32 training log TFLOPs only.

The callback is inserted first in the callback list so WandB, TensorBoard and the progress bar see the new fields. Token counting stays on device and syncs once per logging window.

Tests: tests/test_mfu_logging.py checks the counts against hand counts on a tiny Llama for full finetuning, frozen weights, LoRA, and gradient checkpointing, the attention term, sequence length extraction, the peak table, and an end to end CPU Trainer run. On an L4 with Qwen2.5-0.5B LoRA r=16 in fp16 the logged MFU settles around 12 to 15 percent.

Known limits: sliding window attention, MoE experts stored as 3D tensors, vision towers and embedding lookups are not modeled, so those models report an approximation.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-16T06:57:16.983723Z abacbcf New commits
🔒 Security Review ⚠️ Failed 2026-10-15T16:14:12.184577Z b2510f3 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ime, per GPU average for split models, skip encoder-decoder

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0d204c8618

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/utils/mfu.py
Comment on lines +290 to +291
if self._handle is None:
self._handle = model.register_forward_pre_hook(self._count_batch, with_kwargs = True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Hook the backbone used by chunked SFT loss

When SFT uses TRL's loss_type="chunked_nll", the repository's _chunked_loss_bypasses_forward path documents that the trainer calls the backbone directly rather than the top-level model. This pre-hook therefore never runs, _tokens remains zero, and the opt-in callback silently emits no TFLOPs or MFU fields; attach the counter to the module that chunked loss actually invokes or explicitly handle this loss mode.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

TRL's chunked_nll path (_patch_chunked_ce_lm_head in trl/trainer/sft_trainer.py) replaces forward on the inner causal LM, but the trainer still calls the top-level model through nn.Module.__call__, which runs forward pre-hooks no matter which forward is installed, so _count_batch still sees every training batch. _chunked_loss_bypasses_forward is about wrappers that replace forward, not module hooks; in TRL 1.15 chunked_nll is a deprecated alias of nll.

…decoder, charge the head for logits_to_keep, square pairs for bidirectional encoders, sync every GPU, move an existing callback first

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…rm only for softmax attention layers, Unsloth logits keep spellings, exclude pauses from GPU completion

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 143063c848

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/utils/mfu.py Outdated
Comment on lines +209 to +210
flags = [m.is_causal for m in model.modules() if isinstance(getattr(m, "is_causal", None), bool)]
return bool(flags) and not any(flags)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Treat flagless encoder attention as bidirectional

For a supported bidirectional encoder such as MPNet (unsloth/models/sentence_transformer.py:2150-2159), the attention modules expose no boolean is_causal, so flags is empty and this function classifies the model as causal. _count_batch then charges L * (L + 1) / 2 pairs instead of L * L, underreporting the attention component by nearly half. Fresh evidence beyond the earlier BERT fix is MPNet's flagless attention implementation; infer this case from the model configuration/type or suppress the metric when causality cannot be determined.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The module docstring defines this as a lower-bound estimate. Without an is_causal flag there is no reliable model-agnostic signal for bidirectionality (config.is_decoder is False for most causal LMs too), so a flagless encoder is counted with causal pairs, which can only under-report, consistent with that contract.

Comment thread unsloth/utils/mfu.py
Comment on lines +453 to +455
tokens = int(self._tokens)
head_tokens = int(self._head_tokens)
pairs = int(self._pairs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Aggregate FLOP counters across data-parallel ranks

In one-process-per-GPU DDP or FSDP training, these are only the current rank's counters, and _num_devices likewise counts only devices visible in that process. Since the externally consumed logs come from world rank zero, variable-length or packed batches report rank zero's local FLOPs divided by the globally synchronized step time rather than aggregate FLOPs divided by the data-parallel world size; differing sequence lengths across ranks can therefore make TFLOPs/MFU materially unrepresentative. All-reduce the three counters across data-parallel ranks and normalize by world size, separately from the existing intra-process device-map normalization.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The callback reports the logging rank's own throughput, as the docstring states; adding an all-reduce on every log step to every distributed run for an opt-in diagnostic would put a collective on the logging path, and with balanced data-parallel batches the per-rank figure equals the average.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…GPU model, UNSLOTH_LOG_MFU for SentenceTransformerTrainer

[skip ci]
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…, Dense) out of the per-token count

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: e86decb8c2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 8c3a14d4fe

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit a1d4daa into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the dh/mfu-logging branch October 16, 2026 12:32
oobabooga pushed a commit to oobabooga/unsloth that referenced this pull request Oct 19, 2026
…-budget metrics across ranks (unslothai#14207)

## Summary

Three follow-ups on opt-in features. Default runs are unchanged.

1. **MFU logging (unslothai#13885).** For packed batches that carry only
`position_ids`, the token count branched on data, which broke `fullgraph
= True` compilation and added a host sync per micro-batch. It is now
computed without a data-dependent branch. Also adds an H200 NVL entry at
835.5 dense TFLOPS (half of NVIDIA's 1,671 with-sparsity figure); it was
being measured against the H200 SXM peak.
2. **NCCL INFO logs under `UNSLOTH_DEBUG_DISTRIBUTED` (unslothai#13884).**
Importing unsloth_zoo sets `NCCL_DEBUG=WARN` whenever a logging or
compile-debug switch is on, so the debug flag lost the NCCL INFO logs it
asks for. With `UNSLOTH_DEBUG_DISTRIBUTED` set, unsloth now saves
`NCCL_DEBUG` before that import and restores it after.
3. **Token-budget split metrics across ranks (unslothai#13878).** Logged accuracy
and entropy from split chunks were averaged per rank. Each chunk is now
weighted by its token count summed across ranks. The decision to merge
is folded into the existing chunk-count collective, so every rank merges
or none do: no extra collective and no chance of one rank waiting on
another.

## Tests

| File | main | this PR |
|---|---|---|
| `tests/test_mfu_logging.py` | 2 failed | pass |
| `tests/test_debug_distributed_env.py` | 2 failed (real zoo import) |
pass |
| `tests/test_token_budget_metrics_distributed.py` (2 gloo ranks) | 3
failed | pass |

53 passed in total.

## Not covered here

- No real multi-rank NCCL run; the distributed tests use gloo.
- The H200 NVL device-name string is assumed to contain "H200 NVL".
- A `NCCL_DEBUG` you export yourself is still overwritten when the debug
flag is off; that needs a change in unsloth_zoo.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant