Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Add opt-in TFLOPs and MFU logging with LoRA aware FLOP counts (#13885)
Daniel Hana1d4daa47541
diff --git a/tests/test_mfu_logging.py b/tests/test_mfu_logging.pynew file mode 100644index 00000000000..6a16a0f2928--- /dev/null+++ b/tests/test_mfu_logging.py@@ -0,0 +1,573 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""FLOP accounting of unsloth/utils/mfu.py against hand counts on a tiny Llama."""++import importlib.util+import pathlib++import pytest+import torch++pytest.importorskip("transformers")++MFU = pathlib.Path(__file__).resolve().parents[1] / "unsloth" / "utils" / "mfu.py"+++def _load():+ spec = importlib.util.spec_from_file_location("_unsloth_mfu", MFU)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++mfu = _load()++# hidden 16, 4 heads of 4, 2 kv heads, intermediate 32, vocab 64, 2 layers, untied head.+PER_LAYER = 16 * 16 + 16 * 8 + 16 * 8 + 16 * 16 + 3 * 16 * 32 # 2304+LAYERS = 2 * PER_LAYER+HEAD = 16 * 64+N = LAYERS + HEAD+# LoRA r=2 on q_proj (16->16) and v_proj (16->8): A 16*2 + B 2*16 and A 16*2 + B 2*8 per layer.+LORA = 2 * (32 + 32 + 32 + 16)+++def _model():+ from transformers import LlamaConfig, LlamaForCausalLM++ config = LlamaConfig(+ hidden_size = 16,+ intermediate_size = 32,+ num_hidden_layers = 2,+ num_attention_heads = 4,+ num_key_value_heads = 2,+ vocab_size = 64,+ tie_word_embeddings = False,+ max_position_embeddings = 64,+ )+ torch.manual_seed(0)+ return LlamaForCausalLM(config)+++def test_full_finetune_is_6n():+ total, parts = mfu.count_linear_flops_per_token(_model())+ assert parts == {"forward": 2 * N, "input_grad": 2 * N, "weight_grad": 2 * N, "recompute": 0}+ assert total == 6 * N+++def test_full_finetune_checkpointing_recomputes_layers_not_head():+ total, parts = mfu.count_linear_flops_per_token(_model(), gradient_checkpointing = True)+ assert parts["recompute"] == 2 * LAYERS+ assert total == 6 * N + 2 * LAYERS+++def test_frozen_is_4n():+ model = _model().requires_grad_(False)+ total, parts = mfu.count_linear_flops_per_token(model)+ assert parts["weight_grad"] == 0+ assert total == 4 * N+++def test_lora_counts_weight_grads_only_for_adapters():+ peft = pytest.importorskip("peft")+ model = peft.get_peft_model(+ _model(),+ peft.LoraConfig(r = 2, target_modules = ["q_proj", "v_proj"], lora_dropout = 0.0),+ )+ total, parts = mfu.count_linear_flops_per_token(model)+ assert parts == {+ "forward": 2 * (N + LORA),+ "input_grad": 2 * (N + LORA),+ "weight_grad": 2 * LORA,+ "recompute": 0,+ }+ total_gc, parts_gc = mfu.count_linear_flops_per_token(model, gradient_checkpointing = True)+ assert parts_gc["recompute"] == 2 * (LAYERS + LORA)+ assert total_gc == total + 2 * (LAYERS + LORA)+++def test_attention_flops_per_pair():+ config = _model().config+ # QK^T and AV: 2 FLOPs per multiply add, head_dim 4, 4 heads, 2 layers.+ forward = 2 * 2 * 4 * 4 * 2+ assert mfu.count_attention_flops_per_pair(config) == 3 * forward+ assert mfu.count_attention_flops_per_pair(config, gradient_checkpointing = True) == 4 * forward+++def test_sequence_lengths_exclude_padding_and_split_packing():+ mask = torch.tensor([[1, 1, 1, 0], [1, 1, 0, 0]])+ assert mfu._sequence_lengths({"attention_mask": mask}, ()).tolist() == [3, 2]+ packed = torch.tensor([[0, 1, 2, 0, 1, 0, 1, 2, 3]])+ lengths = mfu._sequence_lengths({"input_ids": packed, "position_ids": packed}, ())+ assert lengths.tolist() == [3, 2, 4]+ ids = torch.zeros(2, 5, dtype = torch.long)+ assert mfu._sequence_lengths({"input_ids": ids}, ()).tolist() == [5, 5]+++def test_peak_tflops_override_and_table(monkeypatch):+ monkeypatch.setenv("UNSLOTH_PEAK_TFLOPS", "123.5")+ assert mfu.get_peak_tflops() == 123.5+ monkeypatch.delenv("UNSLOTH_PEAK_TFLOPS")+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda device = None: "Tesla T4")+ assert mfu.get_peak_tflops(dtype = torch.float16) == 65.0+ assert mfu.get_peak_tflops(dtype = torch.bfloat16) is None+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda device = None: "NVIDIA H100 PCIe")+ assert mfu.get_peak_tflops(dtype = torch.bfloat16) == 756.0+ assert mfu.get_peak_tflops(dtype = torch.float32) is None+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda device = None: "Mystery GPU")+ assert mfu.get_peak_tflops() is None+++def test_callback_logs_tflops_and_mfu(tmp_path, monkeypatch):+ from transformers import Trainer, TrainingArguments++ monkeypatch.setenv("UNSLOTH_PEAK_TFLOPS", "1")+ model = _model()+ rows = [+ {"input_ids": [1, 2, 3, 4], "attention_mask": [1, 1, 1, 0], "labels": [1, 2, 3, -100]},+ {"input_ids": [5, 6, 7, 8], "attention_mask": [1, 1, 0, 0], "labels": [5, 6, -100, -100]},+ ]+ dataset = [{k: torch.tensor(v) for k, v in row.items()} for row in rows]+ trainer = Trainer(+ model = model,+ args = TrainingArguments(+ output_dir = str(tmp_path),+ per_device_train_batch_size = 2,+ max_steps = 2,+ logging_steps = 1,+ report_to = [],+ use_cpu = True,+ save_strategy = "no",+ ),+ train_dataset = dataset,+ )+ callback = mfu.add_mfu_callback(trainer)+ assert mfu.add_mfu_callback(trainer) is callback+ assert trainer.callback_handler.callbacks[0] is callback++ seen = []+ original = callback._count_batch++ def spy(module, args, kwargs):+ before = int(callback._tokens)+ original(module, args, kwargs)+ seen.append(int(callback._tokens) - before)++ callback._count_batch = spy+ trainer.train()+ assert seen == [5, 5]+ logs = [entry for entry in trainer.state.log_history if "loss" in entry]+ assert len(logs) == 2+ for entry in logs:+ assert entry["train_tflops_per_gpu"] > 0+ assert entry["train_mfu"] == pytest.approx(entry["train_tflops_per_gpu"])+ assert callback._handle is None+++def test_gpt2_conv1d_projections_are_counted():+ from transformers import GPT2Config, GPT2LMHeadModel++ config = GPT2Config(n_embd = 16, n_layer = 2, n_head = 4, vocab_size = 64, n_positions = 32)+ model = GPT2LMHeadModel(config)+ # c_attn 16->48, attn c_proj 16->16, c_fc 16->64, mlp c_proj 64->16 per layer, plus the head.+ expected = 2 * 12 * 16 * 16 + 16 * 64+ total, parts = mfu.count_linear_flops_per_token(model)+ assert parts["forward"] == 2 * expected+++class _Expert(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.up = torch.nn.Linear(8, 16, bias = False)+ self.down = torch.nn.Linear(16, 8, bias = False)+++class _MoE(torch.nn.Module):+ def __init__(+ self,+ top_k = None,+ num_experts_per_tok = None,+ ):+ super().__init__()+ self.config = type("Config", (), {"num_experts_per_tok": num_experts_per_tok})()+ self.gate = torch.nn.Linear(8, 4, bias = False)+ self.experts = torch.nn.ModuleList(_Expert() for _ in range(4))+ if top_k is not None:+ self.top_k = top_k+++def test_moe_experts_scaled_by_routed_share():+ gate, expert = 8 * 4, 2 * 8 * 16+ total, parts = mfu.count_linear_flops_per_token(_MoE(top_k = 2))+ assert parts["forward"] == 2 * (gate + 2 * expert)+ total, parts = mfu.count_linear_flops_per_token(_MoE(num_experts_per_tok = 1))+ assert parts["forward"] == 2 * (gate + expert)+ total, parts = mfu.count_linear_flops_per_token(_MoE())+ assert parts["forward"] == 2 * gate+++class _State:+ def __init__(self):+ self.log_history = []+ self.global_step = 1+++def test_eval_and_save_time_excluded_from_window(monkeypatch):+ clock = iter([0.0, 1.0, 11.0, 12.0, 21.0, 22.0, 22.0])+ monkeypatch.setattr(mfu.time, "perf_counter", lambda: next(clock))+ monkeypatch.setenv("UNSLOTH_PEAK_TFLOPS", "1")+ callback = mfu.UnslothMFUCallback()+ callback.on_train_begin(None, _State(), None, model = _model())+ linear = callback._linear_per_token+ callback.on_step_begin(None, None, None)+ callback.on_step_end(None, None, None)+ callback.on_evaluate(None, None, None)+ callback.on_step_begin(None, None, None)+ callback.on_step_end(None, None, None)+ callback.on_save(None, None, None)+ callback.on_step_begin(None, None, None)+ callback.on_step_end(None, None, None)+ callback._tokens = torch.tensor(10**12 // linear)+ logs = {"loss": 1.0}+ callback.on_log(None, _State(), None, logs = logs)+ # 22 s of wall time minus 10 s of evaluation and 9 s of checkpointing.+ assert logs["train_tflops_per_gpu"] == pytest.approx((10**12 // linear) * linear / 3 / 1e12)+ callback.on_train_end(None, None, None)+++def test_model_split_over_gpus_reports_per_gpu_average(monkeypatch):+ monkeypatch.setenv("UNSLOTH_PEAK_TFLOPS", "1")+ model = _model()+ devices = [torch.device("cuda", 0), torch.device("cuda", 1)]+ fake = [type("P", (), {"device": devices[i % 2]})() for i in range(4)]+ monkeypatch.setattr(model, "parameters", lambda *a, **k: iter(fake))+ callback = mfu.UnslothMFUCallback()+ callback.on_train_begin(None, _State(), None, model = model)+ assert callback._num_devices == 2+ monkeypatch.setattr(mfu.time, "perf_counter", lambda: 1.0)+ callback._window_start = 0.0+ callback._tokens = 1000+ logs = {"loss": 1.0}+ callback.on_log(None, _State(), None, logs = logs)+ assert logs["train_tflops_per_gpu"] == pytest.approx(+ 1000 * callback._linear_per_token / 2 / 1e12+ )+ assert logs["train_mfu"] == pytest.approx(logs["train_tflops_per_gpu"])+ callback.on_train_end(None, None, None)+++def test_encoder_decoder_models_are_not_reported(monkeypatch):+ from transformers import T5Config, T5ForConditionalGeneration++ monkeypatch.setenv("UNSLOTH_PEAK_TFLOPS", "1")+ config = T5Config(vocab_size = 64, d_model = 16, d_kv = 4, d_ff = 32, num_layers = 1, num_heads = 4)+ model = T5ForConditionalGeneration(config)+ callback = mfu.UnslothMFUCallback()+ callback.on_train_begin(None, _State(), None, model = model)+ assert callback._handle is None+ callback.on_step_begin(None, None, None)+ callback._tokens = 1000+ logs = {"loss": 1.0}+ callback.on_log(None, _State(), None, logs = logs)+ assert logs == {"loss": 1.0}+++def test_modules_to_save_counts_only_the_active_copy():+ peft = pytest.importorskip("peft")+ model = peft.get_peft_model(+ _model(),+ peft.LoraConfig(+ r = 2, target_modules = ["q_proj", "v_proj"], modules_to_save = ["lm_head"], lora_dropout = 0.0+ ),+ )+ total, parts = mfu.count_linear_flops_per_token(model)+ assert parts["forward"] == 2 * (N + LORA)+ assert parts["weight_grad"] == 2 * (LORA + HEAD)+++def test_on_log_synchronizes_every_participating_gpu(monkeypatch):+ calls = []+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "synchronize", lambda device = None: calls.append(device))+ callback = mfu.UnslothMFUCallback(peak_tflops = 1)+ callback._devices = [0, 1]+ callback._linear_per_token = 1+ callback._window_start = 0.0+ callback._tokens = 10+ callback.on_log(None, _State(), None, logs = {"loss": 1.0})+ assert calls == [0, 1]+++def test_vision_tower_is_not_charged_per_text_token():+ from transformers import (+ CLIPVisionConfig,+ LlamaConfig,+ LlavaConfig,+ LlavaForConditionalGeneration,+ )++ text = _model().config+ vision = CLIPVisionConfig(+ hidden_size = 16,+ intermediate_size = 32,+ num_hidden_layers = 1,+ num_attention_heads = 4,+ image_size = 8,+ patch_size = 4,+ )+ model = LlavaForConditionalGeneration(LlavaConfig(text_config = text, vision_config = vision))+ total, parts = mfu.count_linear_flops_per_token(model)+ assert parts["forward"] == 2 * N+++def test_bidirectional_encoder_counts_square_pairs():+ from transformers import BertConfig, BertModel++ config = BertConfig(+ vocab_size = 64,+ hidden_size = 16,+ num_hidden_layers = 1,+ num_attention_heads = 4,+ intermediate_size = 32,+ )+ model = BertModel(config).train()+ callback = mfu.UnslothMFUCallback(peak_tflops = 1)+ callback.on_train_begin(None, _State(), None, model = model)+ callback._count_batch(model, (), {"attention_mask": torch.tensor([[1, 1, 1, 0]])})+ assert int(callback._pairs) == 9+ causal = mfu.UnslothMFUCallback(peak_tflops = 1)+ causal.on_train_begin(None, _State(), None, model = _model().train())+ causal._count_batch(model, (), {"attention_mask": torch.tensor([[1, 1, 1, 0]])})+ assert int(causal._pairs) == 6+ callback.on_train_end(None, None, None)+ causal.on_train_end(None, None, None)+++def test_output_head_charged_only_for_logits_to_keep(monkeypatch):+ model = _model().train()+ callback = mfu.UnslothMFUCallback(peak_tflops = 1)+ callback.on_train_begin(None, _State(), None, model = model)+ assert callback._head_per_token == 6 * HEAD+ assert callback._linear_per_token == 6 * LAYERS+ mask = torch.ones(2, 4, dtype = torch.long)+ callback._count_batch(model, (), {"attention_mask": mask, "logits_to_keep": 1})+ callback._count_batch(model, (), {"attention_mask": mask})+ assert int(callback._tokens) == 16+ assert int(callback._head_tokens) == 2 + 8+ monkeypatch.setattr(mfu.time, "perf_counter", lambda: 1.0)+ callback._window_start = 0.0+ callback._pairs = 0+ logs = {"loss": 1.0}+ callback.on_log(None, _State(), None, logs = logs)+ assert logs["train_tflops_per_gpu"] == pytest.approx((16 * 6 * LAYERS + 10 * 6 * HEAD) / 1e12)+ callback.on_train_end(None, None, None)+++def test_add_mfu_callback_moves_an_existing_callback_first(tmp_path):+ from transformers import Trainer, TrainingArguments++ existing = mfu.UnslothMFUCallback()+ trainer = Trainer(+ model = _model(),+ args = TrainingArguments(output_dir = str(tmp_path), report_to = [], use_cpu = True),+ callbacks = [existing],+ )+ assert trainer.callback_handler.callbacks[0] is not existing+ assert mfu.add_mfu_callback(trainer) is existing+ assert trainer.callback_handler.callbacks[0] is existing+ assert (+ sum(isinstance(c, mfu.UnslothMFUCallback) for c in trainer.callback_handler.callbacks) == 1+ )+++def test_l40_is_not_matched_as_l4(monkeypatch):+ monkeypatch.delenv("UNSLOTH_PEAK_TFLOPS", raising = False)+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ for name, peak in (("NVIDIA L40S", 362.05), ("NVIDIA L40", 181.05), ("NVIDIA L4", 121.0)):+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda device = None, n = name: n)+ assert mfu.get_peak_tflops(dtype = torch.bfloat16) == peak, name+++def test_longer_model_number_is_not_matched_as_a_table_entry(monkeypatch):+ monkeypatch.delenv("UNSLOTH_PEAK_TFLOPS", raising = False)+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ for name, peak in (("NVIDIA T400 4GB", None), ("NVIDIA T400", None), ("Tesla T4", 65.0)):+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda device = None, n = name: n)+ assert mfu.get_peak_tflops(dtype = torch.float16) == peak, name+++def test_inactive_lora_adapters_are_not_counted():+ peft = pytest.importorskip("peft")+ config = peft.LoraConfig(r = 2, target_modules = ["q_proj", "v_proj"], lora_dropout = 0.0)+ model = peft.get_peft_model(_model(), config)+ model.add_adapter("other", config)+ model.set_adapter("default")+ _, parts = mfu.count_linear_flops_per_token(model)+ assert parts["forward"] == 2 * (N + LORA)+ with model.disable_adapter():+ _, parts = mfu.count_linear_flops_per_token(model)+ assert parts["forward"] == 2 * N+++def test_hybrid_layer_types_charge_pairs_only_for_softmax_attention():+ from types import SimpleNamespace++ config = SimpleNamespace(+ num_hidden_layers = 4,+ num_attention_heads = 4,+ hidden_size = 16,+ head_dim = 4,+ layer_types = ["linear_attention", "linear_attention", "linear_attention", "full_attention"],+ )+ assert mfu.count_attention_flops_per_pair(config) == 4 * 1 * 4 * 4 * 3+ config.layer_types = ["sliding_attention", "full_attention", "full_attention", "full_attention"]+ assert mfu.count_attention_flops_per_pair(config) == 4 * 4 * 4 * 4 * 3+++def test_unsloth_forward_head_window_matches_both_keep_spellings(monkeypatch):+ model = _model().train()+ callback = mfu.UnslothMFUCallback(peak_tflops = 1)+ monkeypatch.setattr(mfu, "_runs_unsloth_head_window", lambda m: True)+ callback.on_train_begin(None, _State(), None, model = model)+ mask = torch.ones(2, 4, dtype = torch.long)+ callback._count_batch(model, (), {"attention_mask": mask, "num_logits_to_keep": 1})+ assert int(callback._head_tokens) == 2+ callback._count_batch(+ model,+ (),+ {"attention_mask": mask, "logits_to_keep": torch.tensor([3]), "num_logits_to_keep": 0},+ )+ assert int(callback._head_tokens) == 2 + 8+ callback.on_train_end(None, None, None)+++def test_runs_unsloth_head_window_reads_the_base_model_forward():+ model = _model()+ assert not mfu._runs_unsloth_head_window(model)++ def forward(self, *args, **kwargs):+ pass++ forward.__module__ = "unsloth.models.llama"+ patched = type("Patched", (type(model),), {"forward": forward})+ model.__class__ = patched+ assert mfu._runs_unsloth_head_window(model)+++def test_pause_after_a_step_excludes_only_time_after_the_gpu_finished(monkeypatch):+ # Step ends at CPU t=1 with 3 s of kernels still queued; eval until t=11.+ clock = iter([0.0, 1.0, 11.0, 12.0, 12.0])+ monkeypatch.setattr(mfu.time, "perf_counter", lambda: next(clock))+ events = []++ class Event:+ def __init__(self, enable_timing = False):+ self.t = None+ events.append(self)++ def record(self, stream = None):+ # GPU completion times: step end at 4 s, resume probe at 11 s.+ self.t = 4.0 if len(events) == 1 else 11.0++ def synchronize(self):+ pass++ def elapsed_time(self, other):+ return (other.t - self.t) * 1000++ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "Event", Event)+ monkeypatch.setattr(torch.cuda, "current_stream", lambda device = None: None)+ monkeypatch.setattr(torch.cuda, "synchronize", lambda device = None: None)+ callback = mfu.UnslothMFUCallback(peak_tflops = 1)+ callback._devices = [0]+ callback._linear_per_token = 10**12+ callback.on_step_begin(None, None, None)+ callback.on_step_end(None, None, None)+ callback.on_evaluate(None, None, None)+ callback.on_step_begin(None, None, None)+ callback._tokens = 5+ logs = {"loss": 1.0}+ callback.on_log(None, _State(), None, logs = logs)+ # 12 s of wall time minus the 7 s from GPU completion (4 s) to resume (11 s).+ assert logs["train_tflops_per_gpu"] == pytest.approx(5 / 5)+++def test_positional_feature_dict_is_counted():+ # SentenceTransformer losses call model(features) with one feature dict.+ callback = mfu.UnslothMFUCallback(peak_tflops = 1)+ model = _model().train()+ callback.on_train_begin(None, _State(), None, model = model)+ features = {+ "input_ids": torch.zeros(2, 4, dtype = torch.long),+ "attention_mask": torch.tensor([[1, 1, 1, 0], [1, 1, 0, 0]]),+ }+ callback._count_batch(model, (features,), {})+ assert int(callback._tokens) == 5+ callback.on_train_end(None, None, None)+++def test_mla_attention_uses_separate_qk_and_value_dims():+ from types import SimpleNamespace+ config = SimpleNamespace(+ num_hidden_layers = 2,+ num_attention_heads = 4,+ hidden_size = 64,+ head_dim = 64,+ qk_nope_head_dim = 128,+ qk_rope_head_dim = 64,+ v_head_dim = 128,+ )+ assert mfu.count_attention_flops_per_pair(config) == 3 * 2 * 2 * 4 * (192 + 128)+++def test_sentence_transformer_attention_uses_the_inner_config():+ # SentenceTransformer is an nn.Sequential whose first module holds the HF model as auto_model.+ inner = _model()+ wrapper = torch.nn.Sequential(torch.nn.Module())+ wrapper[0].auto_model = inner+ plain = mfu.UnslothMFUCallback(peak_tflops = 1)+ plain.on_train_begin(None, _State(), None, model = inner)+ wrapped = mfu.UnslothMFUCallback(peak_tflops = 1)+ wrapped.on_train_begin(None, _State(), None, model = wrapper)+ assert wrapped._attention_per_pair == plain._attention_per_pair > 0+ plain.on_train_end(None, None, None)+ wrapped.on_train_end(None, None, None)+++def test_model_off_the_gpu_takes_no_gpu_peak(monkeypatch):+ monkeypatch.delenv("UNSLOTH_PEAK_TFLOPS", raising = False)+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda device = None: "NVIDIA H100 80GB HBM3")+ callback = mfu.UnslothMFUCallback()+ callback.on_train_begin(None, _State(), None, model = _model())+ assert callback.peak_tflops is None and callback._devices == []+ callback.on_train_end(None, None, None)+ monkeypatch.setenv("UNSLOTH_PEAK_TFLOPS", "100")+ callback = mfu.UnslothMFUCallback()+ callback.on_train_begin(None, _State(), None, model = _model())+ assert callback.peak_tflops == 100+ callback.on_train_end(None, None, None)+++def test_sentence_transformer_dense_after_pooling_is_not_per_token():+ inner = _model()+ plain = mfu.count_linear_flops_per_token(inner)[0]+ wrapper = torch.nn.Sequential(torch.nn.Module(), torch.nn.Module(), torch.nn.Linear(16, 16))+ wrapper[0].auto_model = inner+ assert mfu.count_linear_flops_per_token(wrapper)[0] == plain+++def test_diffusion_and_data_parallel_report_nothing():+ from types import SimpleNamespace++ model = _model()+ assert not mfu._unsupported_setup(model, SimpleNamespace(n_gpu = 1))+ assert mfu._unsupported_setup(model, SimpleNamespace(n_gpu = 2))+ assert mfu._unsupported_setup(model, SimpleNamespace(n_gpu = 1), "DiffusionTrainer")+ model.config.model_type = "diffusion_gemma"+ assert mfu._unsupported_setup(model, SimpleNamespace(n_gpu = 1))+ callback = mfu.UnslothMFUCallback(peak_tflops = 1)+ callback.on_train_begin(SimpleNamespace(n_gpu = 1), _State(), None, model = model)+ assert not callback._enabled and callback._handle is Nonediff --git a/tests/test_warnings_issued_guard.py b/tests/test_warnings_issued_guard.pyindex 5d52a25f684..e26023eef10 100644--- a/tests/test_warnings_issued_guard.py+++ b/tests/test_warnings_issued_guard.py@@ -3,6 +3,7 @@import astimport dataclassesimport inspect+import osfrom functools import wrapsfrom pathlib import Path@@ -21,6 +22,7 @@ def _load(*names):missing = set(names) - {n.name for n in wanted}assert not missing, f"not found in trainer.py: {sorted(missing)}"ns = {+ "os": os,"torch": torch,"inspect": inspect,"dataclasses": dataclasses,diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.pyindex efbfb6c5bec..d6e5aebde6c 100644--- a/unsloth/models/sentence_transformer.py+++ b/unsloth/models/sentence_transformer.py@@ -3223,6 +3223,13 @@ def _patch_sentence_transformer_trainer():if hasattr(self.args, "fp16_full_eval"):self.args.fp16_full_eval = False+ if os.environ.get("UNSLOTH_LOG_MFU", "0") == "1":+ try:+ from ..utils.mfu import add_mfu_callback+ add_mfu_callback(self)+ except Exception as exc:+ print(f"Unsloth: could not enable MFU logging ({exc}).")+SentenceTransformerTrainer.__init__ = _patched_initSentenceTransformerTrainer._unsloth_auto_compile_patched = Truediff --git a/unsloth/trainer.py b/unsloth/trainer.pyindex a238efcdb14..27c4234b21d 100644--- a/unsloth/trainer.py+++ b/unsloth/trainer.py@@ -1791,6 +1791,12 @@ def _backwards_compatible_trainer(trainer_class, config_class):kwargs["args"] = config_ensure_warnings_issued(args[0] if args else kwargs.get("model"))original_init(self, *args, **kwargs)+ if os.environ.get("UNSLOTH_LOG_MFU", "0") == "1":+ try:+ from .utils.mfu import add_mfu_callback+ add_mfu_callback(self)+ except Exception as exc:+ logger.warning(f"Unsloth: could not enable MFU logging ({exc}).")return new_initdiff --git a/unsloth/utils/mfu.py b/unsloth/utils/mfu.pynew file mode 100644index 00000000000..4d4c2a5ace5--- /dev/null+++ b/unsloth/utils/mfu.py@@ -0,0 +1,581 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Opt-in achieved TFLOPs and MFU logging with LoRA-aware FLOP counts.++Turn on with `UNSLOTH_LOG_MFU=1` before building the trainer, or call `add_mfu_callback(trainer)`.+Each training log then gains `train_tflops_per_gpu` and, when the GPU peak is known,+`train_mfu`. Set `UNSLOTH_PEAK_TFLOPS` to the per GPU dense peak to override the table+(for example a measured MAMF number).++Model FLOPs per non padding token, summed over every linear layer with n = in * out weights:+ forward 2n every linear, frozen or trainable+ backward input grads 2n every linear (gradients flow through frozen weights to LoRA)+ backward weight grads 2n only linears whose weight requires grad+ recompute 2n every linear except the output head, when checkpointing+Attention adds 4 * layers * heads * head_dim FLOPs per causal (query, key) pair in the forward+(QK^T and AV), L * (L + 1) / 2 pairs for a sequence of length L (L * L when every attention+layer is bidirectional), times 3 for forward plus backward and times 4 with checkpointing. The+output head is charged only for the last `logits_to_keep` positions when the forward passes it.+Only the active copy of a PEFT `modules_to_save` wrapper and the active LoRA adapters are+counted. Experts held as `nn.Linear` in an `experts` ModuleList count top_k / num_experts of+their weights; experts stored as 3D tensors (transformers 5), sliding windows, convolutions,+embedding lookups and the vision / audio towers of multimodal models (only the text decoder and+head are walked) are not counted, and layers shared across depth (ALBERT) are counted once, so+those models report a lower bound. Only `layer_types` entries that are softmax attention get the+pair term. Backward input grads are charged to every linear, so layouts whose lowest trainable+parameter sits above a frozen block (head-only training, linear probing) are overstated by up to+2n per frozen linear below it. Encoder-decoder models are not reported. A model split over+several GPUs with `device_map` reports the average per participating GPU.+"""++__all__ = [+ "count_linear_flops_per_token",+ "count_attention_flops_per_pair",+ "get_peak_tflops",+ "UnslothMFUCallback",+ "add_mfu_callback",+]++import os+import re+import time++from collections.abc import Mapping++import torch+from transformers import TrainerCallback++# Dense (no sparsity) 16 bit tensor core TFLOPs per GPU, from the vendor datasheets.+# Order matters: the first substring found in the device name wins.+_PEAK_TFLOPS_16BIT = (+ ("H100 PCIE", 756.0),+ ("H100 NVL", 835.0),+ ("H100", 989.0),+ ("H200", 989.0),+ ("GH200", 989.0),+ ("B200", 2250.0),+ ("A100", 312.0),+ ("L40S", 362.05),+ ("L40", 181.05),+ ("L4", 121.0),+ ("T4", 65.0),+ ("MI300A", 980.6),+ ("MI300X", 1307.4),+ ("MI325X", 1307.4),+)+_NO_BF16 = ("T4",)+++def _linear_size(module):+ # PEFT LoRA wrappers expose in/out_features too but own no weight; their base_layer counts.+ if "weight" not in getattr(module, "_parameters", {}):+ return None+ for fan_in, fan_out in (("in_features", "out_features"), ("nx", "nf")):+ fan_in = getattr(module, fan_in, None)+ fan_out = getattr(module, fan_out, None)+ if isinstance(fan_in, int) and isinstance(fan_out, int):+ return fan_in * fan_out+ return None+++def _is_linear_leaf(module):+ return _linear_size(module) is not None+++def _model_config(model):+ """The HF config; a SentenceTransformer keeps it on its first module's auto_model."""+ config = getattr(model, "config", None)+ if config is None and isinstance(model, torch.nn.Sequential) and len(model) > 0:+ config = getattr(getattr(model[0], "auto_model", None), "config", None)+ return config+++def _expert_fractions(model):+ """id(linear) -> share of tokens routed to it, for experts kept as a ModuleList of linears."""+ config = _text_config(_model_config(model))+ default_top_k = getattr(config, "num_experts_per_tok", None)+ fractions = {}+ for module in model.modules():+ experts = getattr(module, "experts", None)+ if not isinstance(experts, torch.nn.ModuleList) or len(experts) == 0:+ continue+ top_k = getattr(module, "top_k", None) or default_top_k+ fraction = 0+ if isinstance(top_k, int) and 0 < top_k <= len(experts):+ fraction = top_k / len(experts)+ for leaf in experts.modules():+ if _is_linear_leaf(leaf):+ fractions[id(leaf)] = fraction+ return fractions+++def _output_head(model):+ try:+ head = model.get_output_embeddings()+ except Exception:+ head = None+ if head is not None:+ return head+ for name, module in model.named_modules():+ if name.endswith("lm_head"):+ return module+ return None+++def _inactive_leaves(model):+ """ids of modules a PEFT modules_to_save wrapper holds but does not run this forward."""+ skipped = set()+ for module in model.modules():+ copies = getattr(module, "modules_to_save", None)+ original = getattr(module, "original_module", None)+ if not isinstance(copies, torch.nn.ModuleDict) or not isinstance(original, torch.nn.Module):+ continue+ active = getattr(module, "active_adapters", None) or []+ if isinstance(active, str):+ active = [active]+ # Mirrors ModulesToSaveWrapper.forward: any missing or disabled adapter runs the original.+ if (+ getattr(module, "disable_adapters", False)+ or not active+ or any(a not in copies for a in active)+ ):+ used = original+ else:+ used = copies[active[0]]+ held = {id(m) for m in original.modules()} | {id(m) for m in copies.modules()}+ skipped |= held - {id(m) for m in used.modules()}+ for module in model.modules():+ branches = [getattr(module, k, None) for k in ("lora_A", "lora_B")]+ if not all(isinstance(b, torch.nn.ModuleDict) for b in branches):+ continue+ active = getattr(module, "active_adapters", None) or []+ if isinstance(active, str):+ active = [active]+ # Mirrors LoraLayer.forward: disabled or merged adapters run only the base layer.+ if getattr(module, "disable_adapters", False) or getattr(module, "merged", False):+ active = []+ for branch in branches:+ for name, adapter in branch.items():+ if name not in active:+ skipped |= {id(m) for m in adapter.modules()}+ return skipped+++def _non_text_leaves(model):+ """ids of modules outside the text decoder and head of a multimodal model."""+ config = _model_config(model)+ if config is None or _text_config(config) is config:+ return set()+ try:+ decoder = model.get_decoder()+ except Exception:+ decoder = None+ get_base_model = getattr(model, "get_base_model", None)+ root = get_base_model() if callable(get_base_model) else model+ if not isinstance(decoder, torch.nn.Module) or decoder is root or decoder is model:+ return set()+ keep = {id(m) for m in decoder.modules()}+ head = _output_head(model)+ if head is not None:+ keep |= {id(m) for m in head.modules()}+ return {id(m) for m in model.modules() if id(m) not in keep}+++def _post_pooling_leaves(model):+ """ids of a SentenceTransformer's modules after the transformer (Pooling, Dense, Normalize):+ they run once per sequence, not per token, so they are left out (negligible per sequence)."""+ if not isinstance(model, torch.nn.Sequential) or len(model) < 2:+ return set()+ if getattr(model[0], "auto_model", None) is None:+ return set()+ return {id(m) for module in list(model)[1:] for m in module.modules()}+++def _linear_flops(model, gradient_checkpointing = False):+ head = _output_head(model)+ head_leaves = set()+ if head is not None:+ head_leaves = {id(m) for m in head.modules() if _is_linear_leaf(m)}+ skipped = _inactive_leaves(model) | _non_text_leaves(model) | _post_pooling_leaves(model)+ experts = _expert_fractions(model)+ forward = input_grad = weight_grad = recompute = head_total = 0+ for module in model.modules():+ n = _linear_size(module)+ if n is None or id(module) in skipped:+ continue+ if id(module) in experts:+ n = n * experts[id(module)]+ forward += 2 * n+ input_grad += 2 * n+ if module.weight.requires_grad:+ weight_grad += 2 * n+ if id(module) in head_leaves:+ head_total += 2 * n+ if id(module) in head_leaves:+ head_total += 4 * n+ elif gradient_checkpointing:+ recompute += 2 * n+ breakdown = {+ "forward": forward,+ "input_grad": input_grad,+ "weight_grad": weight_grad,+ "recompute": recompute,+ }+ return forward + input_grad + weight_grad + recompute, breakdown, head_total+++def count_linear_flops_per_token(model, gradient_checkpointing = False):+ total, breakdown, _ = _linear_flops(model, gradient_checkpointing)+ return total, breakdown+++def _all_attention_bidirectional(model):+ flags = [+ m.is_causal for m in model.modules() if isinstance(getattr(m, "is_causal", None), bool)+ ]+ if not flags:+ # transformers 4.x encoders (BERT, XLM-R) expose only is_decoder on their attention.+ flags = [+ m.is_decoder+ for m in model.modules()+ if isinstance(getattr(m, "is_decoder", None), bool)+ ]+ return bool(flags) and not any(flags)+++def _text_config(config):+ if config is None:+ return None+ get_text_config = getattr(config, "get_text_config", None)+ if callable(get_text_config):+ try:+ return get_text_config()+ except Exception:+ pass+ return config+++def count_attention_flops_per_pair(config, gradient_checkpointing = False):+ config = _text_config(config)+ layers = getattr(config, "num_hidden_layers", None)+ heads = getattr(config, "num_attention_heads", None)+ if not layers or not heads:+ return 0+ layer_types = getattr(config, "layer_types", None)+ if isinstance(layer_types, (list, tuple)) and len(layer_types) == layers:+ # Hybrids (Qwen3-Next, LFM2, ...) run linear attention, convolutions or recurrences elsewhere.+ layers = sum(+ 1 for t in layer_types if isinstance(t, str) and "attention" in t and "linear" not in t+ )+ head_dim = getattr(config, "head_dim", None) or (config.hidden_size // heads)+ # MLA (DeepSeek V2 / V3) scores with nope + rope dims and mixes values with v_head_dim.+ qk_dim, v_dim = head_dim, head_dim+ nope, rope = (+ getattr(config, "qk_nope_head_dim", None),+ getattr(config, "qk_rope_head_dim", None),+ )+ if isinstance(nope, int) and isinstance(rope, int):+ qk_dim = nope + rope+ if isinstance(getattr(config, "v_head_dim", None), int):+ v_dim = config.v_head_dim+ forward = 2 * layers * heads * (qk_dim + v_dim)+ return forward * (4 if gradient_checkpointing else 3)+++def get_peak_tflops(device = None, dtype = torch.float16):+ """Per GPU dense peak for 16 bit training, `UNSLOTH_PEAK_TFLOPS` first; None if unknown."""+ override = os.environ.get("UNSLOTH_PEAK_TFLOPS", "").strip()+ if override:+ try:+ value = float(override)+ if value > 0:+ return value+ except ValueError:+ pass+ return None+ if dtype not in (torch.float16, torch.bfloat16):+ return None+ try:+ if not torch.cuda.is_available():+ return None+ name = torch.cuda.get_device_name(device).upper()+ except Exception:+ return None+ for key, value in _PEAK_TFLOPS_16BIT:+ # A trailing digit is a different model (Quadro T400 is not a T4).+ if re.search(re.escape(key) + r"(?!\d)", name):+ if dtype == torch.bfloat16 and key in _NO_BF16:+ return None+ return value+ return None+++def _runs_unsloth_head_window(model):+ get_base_model = getattr(model, "get_base_model", None)+ base = get_base_model() if callable(get_base_model) else model+ forward = getattr(type(base), "forward", None)+ return getattr(forward, "__module__", "").startswith("unsloth.")+++def _gradient_checkpointing_on(model, args):+ if getattr(args, "gradient_checkpointing", False):+ return True+ if getattr(model, "is_gradient_checkpointing", False) is True:+ return True+ return any(getattr(m, "gradient_checkpointing", False) is True for m in model.modules())+++def _training_dtype(model, args):+ if getattr(args, "bf16", False):+ return torch.bfloat16+ if getattr(args, "fp16", False):+ return torch.float16+ return getattr(model, "dtype", torch.float32)+++def _sequence_lengths(kwargs, args):+ attention_mask = kwargs.get("attention_mask")+ input_ids = kwargs.get("input_ids")+ if input_ids is None and args:+ input_ids = args[0] if torch.is_tensor(args[0]) else None+ if input_ids is None:+ input_ids = kwargs.get("inputs_embeds")+ if input_ids is not None:+ input_ids = input_ids[..., 0]+ for key in ("packed_seq_lengths", "seq_lens"):+ lengths = kwargs.get(key)+ if torch.is_tensor(lengths) and lengths.numel() > 0:+ return lengths.reshape(-1)+ if torch.is_tensor(attention_mask) and attention_mask.dim() == 2:+ return attention_mask.sum(dim = -1)+ position_ids = kwargs.get("position_ids")+ if torch.is_tensor(position_ids) and position_ids.dim() == 2 and position_ids.shape[0] == 1:+ # Padding free packing: each document restarts its positions at 0.+ position_ids = position_ids[0]+ starts = torch.nonzero(position_ids == 0).reshape(-1)+ if starts.numel() > 0:+ ends = torch.cat([starts[1:], starts.new_tensor([position_ids.numel()])])+ return ends - starts+ if torch.is_tensor(input_ids) and input_ids.dim() >= 2:+ return torch.full((input_ids.shape[0],), input_ids.shape[1], device = input_ids.device)+ return None+++def _unsupported_setup(+ model,+ args,+ trainer_name = "",+):+ """True where the per-token count does not describe the step, so nothing is reported:+ diffusion objectives (extra no-grad passes, encoder + canvas, recomputed heads) and+ single-process DataParallel (the hook runs once per replica, concurrently)."""+ model_type = str(getattr(_model_config(model), "model_type", "") or "")+ if "diffusion" in model_type.lower() or "Diffusion" in trainer_name:+ return True+ # Trainer sets n_gpu > 1 only for DataParallel; distributed processes see 1.+ return (getattr(args, "n_gpu", 1) or 1) > 1+++class UnslothMFUCallback(TrainerCallback):+ """Adds `train_tflops_per_gpu` and `train_mfu` to training logs. Prefer `add_mfu_callback`."""++ def __init__(+ self,+ peak_tflops = None,+ gradient_checkpointing = None,+ ):+ self.peak_tflops = peak_tflops+ self.gradient_checkpointing = gradient_checkpointing+ self._handle = None+ self._linear_per_token = 0+ self._head_per_token = 0+ self._attention_per_pair = 0+ self._bidirectional = False+ self._num_devices = 1+ self._devices = []+ self._unsloth_head_window = False+ self._enabled = True+ self._trainer_name = ""+ self._reset()++ def _reset(self):+ self._tokens = 0+ self._head_tokens = 0+ self._pairs = 0+ self._window_start = None+ self._excluded = 0.0+ self._last_step_end = None+ self._step_end_events = None+ self._paused = False++ def _count_batch(self, module, args, kwargs):+ # Generation, reference and evaluation forwards run without grad and are not training FLOPs.+ if not module.training or not torch.is_grad_enabled():+ return+ if args and isinstance(args[0], Mapping):+ # SentenceTransformer losses call model(features) with one feature dict.+ kwargs = {**args[0], **kwargs}+ args = args[1:]+ lengths = _sequence_lengths(kwargs, args)+ if lengths is None:+ return+ lengths = lengths.to(torch.int64)+ # Kept on device: one host sync per log window, not per micro batch.+ self._tokens = self._tokens + lengths.sum()+ keep = kwargs.get("logits_to_keep")+ if self._unsloth_head_window:+ # Unsloth's Llama / Mistral forwards take the larger int spelling and run the full+ # head when either spelling is a tensor (models/llama.py CausalLM_fast_forward).+ legacy = kwargs.get("num_logits_to_keep")+ if torch.is_tensor(keep) or torch.is_tensor(legacy):+ keep = 0+ elif isinstance(legacy, int) and not isinstance(legacy, bool):+ keep = max(keep if isinstance(keep, int) else 0, legacy)+ if torch.is_tensor(keep) and keep.dim() == 1 and keep.numel() > 0:+ keep = keep.numel()+ if isinstance(keep, int) and not isinstance(keep, bool) and keep > 0:+ self._head_tokens = self._head_tokens + lengths.clamp(max = keep).sum()+ else:+ self._head_tokens = self._head_tokens + lengths.sum()+ if self._bidirectional:+ self._pairs = self._pairs + (lengths * lengths).sum()+ else:+ self._pairs = self._pairs + (lengths * (lengths + 1) // 2).sum()++ def on_train_begin(+ self,+ args,+ state,+ control,+ model = None,+ **kwargs,+ ):+ if model is None:+ return+ config = _model_config(model)+ # One length per sequence cannot describe separate source and target lengths.+ self._enabled = not getattr(config, "is_encoder_decoder", False) and not _unsupported_setup(+ model, args, self._trainer_name+ )+ if not self._enabled:+ return+ checkpointing = self.gradient_checkpointing+ if checkpointing is None:+ checkpointing = _gradient_checkpointing_on(model, args)+ total, _, self._head_per_token = _linear_flops(model, checkpointing)+ self._linear_per_token = total - self._head_per_token+ self._bidirectional = _all_attention_bidirectional(model)+ self._unsloth_head_window = _runs_unsloth_head_window(model)+ self._attention_per_pair = (+ count_attention_flops_per_pair(config, checkpointing) if config is not None else 0+ )+ devices = sorted(+ {p.device.index for p in model.parameters() if p.device.type == "cuda"},+ key = lambda index: -1 if index is None else index,+ )+ self._num_devices = max(len(devices), 1)+ self._devices = [index for index in devices if index is not None]+ if self.peak_tflops is None:+ dtype = _training_dtype(model, args)+ # A model off the GPU (use_cpu) has no GPU peak; only UNSLOTH_PEAK_TFLOPS describes it.+ peaks = [get_peak_tflops(index, dtype) for index in devices] or [+ get_peak_tflops(None, dtype)+ if os.environ.get("UNSLOTH_PEAK_TFLOPS", "").strip()+ else None+ ]+ if all(peaks):+ self.peak_tflops = sum(peaks) / len(peaks)+ if self._handle is None:+ self._handle = model.register_forward_pre_hook(self._count_batch, with_kwargs = True)+ self._reset()++ def on_step_begin(self, args, state, control, **kwargs):+ now = time.perf_counter()+ if self._window_start is None:+ self._window_start = now+ elif self._paused and self._last_step_end is not None:+ paused = now - self._last_step_end+ if self._step_end_events:+ # The step's kernels may still be queued at on_step_end: exclude only the time+ # after every GPU finished them.+ gaps = []+ for index, start in self._step_end_events:+ end = torch.cuda.Event(enable_timing = True)+ end.record(torch.cuda.current_stream(index))+ end.synchronize()+ gaps.append(start.elapsed_time(end) / 1000)+ paused = min([paused] + gaps)+ self._excluded += paused+ self._paused = False++ def on_step_end(self, args, state, control, **kwargs):+ self._last_step_end = time.perf_counter()+ self._step_end_events = None+ if self._devices and torch.cuda.is_available():+ # Recording is asynchronous; only a later evaluation or save waits on them.+ self._step_end_events = []+ for index in self._devices:+ event = torch.cuda.Event(enable_timing = True)+ event.record(torch.cuda.current_stream(index))+ self._step_end_events.append((index, event))++ def on_evaluate(self, args, state, control, **kwargs):+ self._paused = True++ def on_save(self, args, state, control, **kwargs):+ self._paused = True++ def on_log(+ self,+ args,+ state,+ control,+ logs = None,+ **kwargs,+ ):+ if not self._enabled or logs is None or "loss" not in logs or self._window_start is None:+ return+ tokens = int(self._tokens)+ head_tokens = int(self._head_tokens)+ pairs = int(self._pairs)+ if torch.cuda.is_available():+ # A model split with device_map may still be running kernels on the other GPUs.+ for index in self._devices or [None]:+ torch.cuda.synchronize(index)+ elapsed = time.perf_counter() - self._window_start - self._excluded+ self._reset()+ if tokens <= 0 or elapsed <= 0:+ return+ flops = (+ tokens * self._linear_per_token+ + head_tokens * self._head_per_token+ + pairs * self._attention_per_pair+ )+ flops = flops / self._num_devices+ tflops = flops / elapsed / 1e12+ extra = {"train_tflops_per_gpu": tflops}+ if self.peak_tflops:+ extra["train_mfu"] = tflops / self.peak_tflops+ logs.update(extra)+ # Trainer.log appended a copy of logs to log_history before calling the callbacks.+ if state.log_history and state.log_history[-1].get("step") == state.global_step:+ state.log_history[-1].update(extra)++ def on_train_end(self, args, state, control, **kwargs):+ if self._handle is not None:+ self._handle.remove()+ self._handle = None+++def add_mfu_callback(trainer, **kwargs):+ """Register an UnslothMFUCallback first, so reporting callbacks see the fields it adds."""+ callbacks = trainer.callback_handler.callbacks+ for index, callback in enumerate(callbacks):+ if isinstance(callback, UnslothMFUCallback):+ callbacks.insert(0, callbacks.pop(index))+ return callback+ callback = UnslothMFUCallback(**kwargs)+ callback._trainer_name = type(trainer).__name__+ trainer.callback_handler.callbacks.insert(0, callback)+ return callback