Repository navigation
Add opt-in TFLOPs and MFU logging with LoRA aware FLOP counts - #13885
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…ime, per GPU average for split models, skip encoder-decoder [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if self._handle is None: | ||
| self._handle = model.register_forward_pre_hook(self._count_batch, with_kwargs = True) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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]
…rm only for softmax attention layers, Unsloth logits keep spellings, exclude pauses from GPU completion [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 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".
| flags = [m.is_causal for m in model.modules() if isinstance(getattr(m, "is_causal", None), bool)] | ||
| return bool(flags) and not any(flags) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| tokens = int(self._tokens) | ||
| head_tokens = int(self._head_tokens) | ||
| pairs = int(self._pairs) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…GPU model, UNSLOTH_LOG_MFU for SentenceTransformerTrainer [skip ci]
…, Dense) out of the per-token count [skip ci]
…arallel [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…-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.
This adds an opt-in callback that logs achieved TFLOPs per GPU and model FLOPs utilization during training. Set
UNSLOTH_LOG_MFU=1before creating the trainer, or callunsloth.utils.mfu.add_mfu_callback(trainer). Training logs then gaintrain_tflops_per_gpuand, 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.pychecks 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.