Skip to content

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.

Opt-in torchao float8 training for full finetuning (#15007)

Daniel Han7b70f094aae0
diff --git a/tests/test_float8_training.py b/tests/test_float8_training.py
new file mode 100644
index 00000000000..a83824664c1
--- /dev/null
+++ b/tests/test_float8_training.py
@@ -0,0 +1,409 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Opt-in torchao float8 training for full finetuning: layer selection, refusals, emulated numerics (CPU)."""
+
+from __future__ import annotations
+
+import importlib.util
+
+import pytest
+import torch
+
+pytestmark = pytest.mark.skipif(
+ importlib.util.find_spec("torchao") is None, reason = "require torchao"
+)
+
+from unsloth.models import float8_training as f8t
+
+
+def _tiny_qwen3(dtype = torch.float32):
+ from transformers import Qwen3Config, Qwen3ForCausalLM
+
+ torch.manual_seed(0)
+ config = Qwen3Config(
+ vocab_size = 256,
+ hidden_size = 128,
+ intermediate_size = 256,
+ num_hidden_layers = 2,
+ num_attention_heads = 4,
+ num_key_value_heads = 2,
+ head_dim = 32,
+ tie_word_embeddings = False,
+ )
+ return Qwen3ForCausalLM(config).to(dtype)
+
+
+def _float8_linear():
+ from torchao.float8.float8_linear import Float8Linear
+ return Float8Linear
+
+
+def _emulated_config(recipe = "rowwise"):
+ from torchao.float8 import Float8LinearConfig
+
+ config = Float8LinearConfig.from_recipe_name(recipe)
+ object.__setattr__(config, "emulate", True)
+ return config
+
+
+def test_resolve_values():
+ assert f8t.resolve_float8_training(None) is None
+ assert f8t.resolve_float8_training(False) is None
+ assert f8t.resolve_float8_training(True) == "tensorwise"
+ assert f8t.resolve_float8_training("TensorWise") == "tensorwise"
+ with pytest.raises(ValueError, match = "slower than bfloat16"):
+ f8t.resolve_float8_training("rowwise")
+ with pytest.raises(ValueError):
+ f8t.resolve_float8_training("mxfp8")
+ config = _emulated_config("rowwise")
+ assert f8t.resolve_float8_training(config) is config
+ with pytest.raises(TypeError):
+ f8t.resolve_float8_training(3)
+
+
+def test_off_is_a_no_op():
+ model = _tiny_qwen3()
+ before = {k: v.clone() for k, v in model.state_dict().items()}
+ assert f8t.convert_model_to_float8_training(model, None) == []
+ assert f8t.convert_model_to_float8_training(model, False) == []
+ assert not any(isinstance(m, _float8_linear()) for m in model.modules())
+ assert not hasattr(model, "_unsloth_float8_linears")
+ after = model.state_dict()
+ assert before.keys() == after.keys()
+ assert all(torch.equal(before[k], after[k]) for k in before)
+
+
+def test_filter_skips_head_router_odd_dims_and_frozen():
+ model = _tiny_qwen3()
+ model.model.layers[0].mlp.gate = torch.nn.Linear(128, 16, bias = False) # MoE router name
+ model.model.layers[0].odd = torch.nn.Linear(128, 40, bias = False) # 40 % 16 != 0
+ model.model.layers[1].self_attn.o_proj.weight.requires_grad_(False)
+ converted = f8t.convert_model_to_float8_training(
+ model, _emulated_config(), size_filter = False, check_hardware = False
+ )
+ assert "lm_head" not in converted
+ assert "model.layers.0.mlp.gate" not in converted
+ assert "model.layers.0.odd" not in converted
+ assert "model.layers.1.self_attn.o_proj" not in converted
+ for name in ("q_proj", "k_proj", "v_proj", "o_proj"):
+ assert f"model.layers.0.self_attn.{name}" in converted
+ for name in ("gate_proj", "up_proj", "down_proj"):
+ assert f"model.layers.0.mlp.{name}" in converted
+ assert f"model.layers.1.mlp.{name}" in converted
+ assert len(converted) == 13
+ assert model._unsloth_float8_linears == converted
+ assert type(model.lm_head) is torch.nn.Linear
+
+
+def test_size_filter_matches_torchao_rowwise_thresholds():
+ keep = f8t.float8_training_filter(torch.nn.Module(), "rowwise")
+ big = torch.nn.Linear(4096, 14336, bias = False, device = "meta")
+ # meta weights are refused; check the size rule directly
+ assert f8t._size_ok("rowwise", 14336, 4096)
+ assert not f8t._size_ok("rowwise", 2048, 4096) # N <= 2048
+ assert not f8t._size_ok("rowwise", 6144, 1024) # K <= 1024
+ assert not f8t._size_ok("rowwise", 4096, 2048) # N <= 4096 and K <= 2048
+ assert f8t._size_ok("tensorwise", 2048, 1024)
+ assert not f8t._size_ok("tensorwise", 1024, 4096)
+ assert keep(big, "model.layers.0.mlp.up_proj") is False
+
+
+def test_tiny_model_size_filter_converts_nothing_and_warns():
+ model = _tiny_qwen3()
+ with pytest.warns(UserWarning, match = "no eligible Linear"):
+ converted = f8t.convert_model_to_float8_training(
+ model, _emulated_config(), check_hardware = False
+ )
+ assert converted == []
+
+
+def test_state_dict_keys_unchanged():
+ model = _tiny_qwen3()
+ keys = list(model.state_dict().keys())
+ f8t.convert_model_to_float8_training(
+ model, _emulated_config(), size_filter = False, check_hardware = False
+ )
+ assert list(model.state_dict().keys()) == keys
+
+
[email protected]("recipe", ["rowwise", "tensorwise"])
+def test_emulated_loss_and_grad_parity_vs_fp32(recipe):
+ ids = torch.randint(0, 256, (2, 32), generator = torch.Generator().manual_seed(1))
+ ref = _tiny_qwen3()
+ out = ref(input_ids = ids, labels = ids)
+ out.loss.backward()
+ ref_grads = {n: p.grad.clone() for n, p in ref.named_parameters()}
+
+ model = _tiny_qwen3()
+ converted = f8t.convert_model_to_float8_training(
+ model, _emulated_config(recipe), size_filter = False, check_hardware = False
+ )
+ calls = []
+ for name, m in model.named_modules():
+ if isinstance(m, _float8_linear()):
+ m.register_forward_hook(lambda *a, _n = name: calls.append(_n))
+ out8 = model(input_ids = ids, labels = ids)
+ out8.loss.backward()
+ assert sorted(set(calls)) == sorted(converted) # every converted layer ran in fp8
+ assert abs(out8.loss.item() - out.loss.item()) / out.loss.item() < 2e-2
+ for n, p in model.named_parameters():
+ cos = torch.nn.functional.cosine_similarity(
+ p.grad.flatten().double(), ref_grads[n].flatten().double(), dim = 0
+ )
+ assert cos > 0.98, (n, cos.item())
+
+
+def test_refuses_without_cuda():
+ model = _tiny_qwen3()
+ with pytest.raises(RuntimeError, match = "compute capability 8.9"):
+ f8t.convert_model_to_float8_training(model, True, size_filter = False)
+ assert not any(isinstance(m, _float8_linear()) for m in model.modules())
+
+
+def test_refuses_pre_sm89(monkeypatch):
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *a: (8, 6))
+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda *a: "NVIDIA A10G")
+ monkeypatch.setattr(torch.version, "hip", None)
+ with pytest.raises(RuntimeError, match = "A10G is 8.6"):
+ f8t._check_hardware(torch.device("cuda", 0), "tensorwise")
+ with pytest.raises(RuntimeError, match = "A10G is 8.6"):
+ f8t._check_hardware(torch.device("cuda", 0), _emulated_config("tensorwise"))
+
+
+def test_recipe_scaling_of_configs():
+ assert f8t._recipe_scaling("tensorwise") == "tensorwise"
+ assert f8t._recipe_scaling(_emulated_config("tensorwise")) == "tensorwise"
+ assert f8t._recipe_scaling(_emulated_config("rowwise")) == "rowwise"
+
+
+ "cap, name, hip, allowed",
+ [
+ ((12, 0), "NVIDIA RTX PRO 6000 Blackwell", None, True), # measured 15% faster
+ ((12, 1), "NVIDIA RTX 5090 class", None, True),
+ ((10, 0), "NVIDIA B200", None, False), # not timed
+ ((9, 0), "NVIDIA H100", None, False), # not timed
+ ((9, 4), "AMD Instinct MI300X", "6.4", False), # ROCm not timed
+ ],
+)
+def test_named_recipe_only_where_measured_faster(monkeypatch, cap, name, hip, allowed):
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *a: cap)
+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda *a: name)
+ monkeypatch.setattr(torch.version, "hip", hip)
+ probed = []
+ monkeypatch.setattr(
+ f8t, "_probe_float8_gemm", lambda d, r: probed.append(f8t._recipe_scaling(r))
+ )
+ if allowed:
+ f8t._check_hardware(torch.device("cuda", 0), "tensorwise")
+ assert probed == ["tensorwise"]
+ else:
+ with pytest.raises(RuntimeError, match = "not been measured faster") as e:
+ f8t._check_hardware(torch.device("cuda", 0), "tensorwise")
+ assert "Float8LinearConfig.from_recipe_name('tensorwise')" in str(e.value)
+ assert probed == []
+ # An explicit Float8LinearConfig is the opt in for any fp8 GPU; only the GEMM probe gates it.
+ probed.clear()
+ f8t._check_hardware(torch.device("cuda", 0), _emulated_config("rowwise"))
+ assert probed == ["rowwise"]
+
+
+def test_refuses_tensorwise_on_sm89(monkeypatch):
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *a: (8, 9))
+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda *a: "NVIDIA L4")
+ monkeypatch.setattr(torch.version, "hip", None)
+ monkeypatch.setattr(f8t, "_probe_float8_gemm", lambda *a: None)
+ with pytest.raises(RuntimeError, match = "NaN gradients"):
+ f8t._check_hardware(torch.device("cuda", 0), "tensorwise")
+ f8t._check_hardware(torch.device("cuda", 0), _emulated_config("rowwise"))
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *a: (12, 0))
+ f8t._check_hardware(torch.device("cuda", 0), "tensorwise")
+
+
+def test_refuses_when_scaled_mm_probe_fails(monkeypatch):
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *a: (12, 0))
+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda *a: "NVIDIA RTX PRO 6000 Blackwell")
+ monkeypatch.setattr(torch.version, "hip", None)
+
+ def boom(*a, **k):
+ raise RuntimeError("scaled_mm not built for sm120")
+
+ monkeypatch.setattr(f8t, "_probe_float8_gemm", boom)
+ with pytest.raises(RuntimeError, match = "tensorwise scaling\\) is not supported"):
+ f8t._check_hardware(torch.device("cuda", 0), "tensorwise")
+ with pytest.raises(RuntimeError, match = "rowwise scaling\\) is not supported"):
+ f8t._check_hardware(torch.device("cuda", 0), _emulated_config("rowwise"))
+
+
+def test_loader_rejects_float8_training_for_lora():
+ from unsloth import FastLanguageModel, FastModel
+ for loader in (FastLanguageModel, FastModel):
+ with pytest.raises(ValueError, match = "full_finetuning = True"):
+ loader.from_pretrained(
+ "trl-internal-testing/tiny-Qwen3ForCausalLM", float8_training = True
+ )
+
+
[email protected]("qat_scheme", ["int8-int4", "fp8-fp8", "phone-deployment"])
+def test_loader_rejects_float8_training_with_qat(monkeypatch, qat_scheme):
+ # QAT replaces nn.Linear with FakeQuantizedLinear before float8 conversion, which then matches nothing.
+ from unsloth import FastLanguageModel, FastModel
+
+ converted = []
+ monkeypatch.setattr(
+ "unsloth.models.loader.convert_model_to_float8_training",
+ lambda *a, **k: converted.append(1) or [],
+ )
+ for loader in (FastLanguageModel, FastModel):
+ with pytest.raises(ValueError, match = "cannot be combined"):
+ loader.from_pretrained(
+ "trl-internal-testing/tiny-Qwen3ForCausalLM",
+ full_finetuning = True,
+ load_in_4bit = False,
+ float8_training = True,
+ qat_scheme = qat_scheme,
+ )
+ assert converted == []
+
+
+def _cuda_like(monkeypatch, cap, name):
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *a: cap)
+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda *a: name)
+ monkeypatch.setattr(torch.version, "hip", None)
+ monkeypatch.setattr(f8t, "_probe_float8_gemm", lambda *a: None)
+
+
+def test_explicit_tensorwise_config_refused_on_sm89(monkeypatch):
+ # The NaN refusal is about the scaling, so an explicit config gets it too; rowwise configs stay allowed.
+ _cuda_like(monkeypatch, (8, 9), "NVIDIA L4")
+ with pytest.raises(RuntimeError, match = "NaN gradients"):
+ f8t._check_hardware(torch.device("cuda", 0), _emulated_config("tensorwise"))
+ f8t._check_hardware(torch.device("cuda", 0), _emulated_config("rowwise"))
+
+
[email protected]("recipe", ["rowwise", "tensorwise"])
+def test_converted_layers_pad_the_inner_dim(recipe):
+ # Variable-length batches flatten to token counts not divisible by 16; the fp8 backward GEMM needs them padded.
+ model = _tiny_qwen3()
+ config = _emulated_config(recipe)
+ assert not config.pad_inner_dim
+ f8t.convert_model_to_float8_training(model, config, size_filter = False)
+ layers = [m for m in model.modules() if isinstance(m, _float8_linear())]
+ assert layers and all(m.config.pad_inner_dim for m in layers)
+ assert not config.pad_inner_dim # the caller's config is not mutated
+
+
+def test_fsdp_float8_all_gather_refused_before_conversion():
+ # It wraps weights in a tensor subclass that splits shared parameters (doubled AdamW updates) and that
+ # safetensors cannot save, so it is refused before any layer is swapped.
+ from dataclasses import replace
+
+ model = _tiny_qwen3()
+ config = replace(_emulated_config("tensorwise"), enable_fsdp_float8_all_gather = True)
+ with pytest.raises(ValueError, match = "enable_fsdp_float8_all_gather"):
+ f8t.convert_model_to_float8_training(model, config, size_filter = False)
+ assert not any(isinstance(m, _float8_linear()) for m in model.modules())
+
+
+def test_shared_weights_stay_shared():
+ model = _tiny_qwen3()
+ model.model.layers[1].mlp.up_proj.weight = model.model.layers[0].mlp.up_proj.weight
+ before = len(list(model.parameters()))
+ f8t.convert_model_to_float8_training(model, _emulated_config("tensorwise"), size_filter = False)
+ assert len(list(model.parameters())) == before
+ assert model.model.layers[1].mlp.up_proj.weight is model.model.layers[0].mlp.up_proj.weight
+
+
+def _probe_calls(monkeypatch, recipe):
+ seen = []
+
+ def fake_scaled_mm(a, b, scale_a, scale_b, **kwargs):
+ seen.append((a.dtype, b.dtype, tuple(scale_a.shape), tuple(scale_b.shape)))
+
+ monkeypatch.setattr(torch, "_scaled_mm", fake_scaled_mm)
+ f8t._probe_float8_gemm(torch.device("cpu"), recipe)
+ return seen
+
+
+def _probe_dtypes(monkeypatch, recipe):
+ seen = []
+
+ def fake_scaled_mm(a, b, **kwargs):
+ seen.append((a.dtype, b.dtype))
+
+ monkeypatch.setattr(torch, "_scaled_mm", fake_scaled_mm)
+ f8t._probe_float8_gemm(torch.device("cpu"), recipe)
+ return seen
+
+
+def _fnuz_config():
+ from dataclasses import replace
+
+ # What torchao's from_recipe_name builds on MI300, where its e4m3 / e5m2 dtypes are the fnuz variants.
+ base = _emulated_config("tensorwise")
+ casts = {}
+ for name in ("input", "input_for_grad_weight", "weight", "weight_for_grad_input"):
+ casts[f"cast_config_{name}"] = replace(
+ getattr(base, f"cast_config_{name}"), target_dtype = torch.float8_e4m3fnuz
+ )
+ for name in ("grad_output", "grad_output_for_grad_weight"):
+ casts[f"cast_config_{name}"] = replace(
+ getattr(base, f"cast_config_{name}"), target_dtype = torch.float8_e5m2fnuz
+ )
+ return replace(base, **casts)
+
+
+def test_probe_uses_the_config_fp8_dtypes(monkeypatch):
+ # MI300 (gfx942): torchao configs carry the fnuz types; probing e4m3fn there would refuse a supported layer.
+ assert _probe_dtypes(monkeypatch, _fnuz_config()) == [
+ (torch.float8_e4m3fnuz, torch.float8_e4m3fnuz),
+ (torch.float8_e5m2fnuz, torch.float8_e4m3fnuz),
+ ]
+
+
+def test_rocm_explicit_fnuz_config_reaches_the_probe_with_its_dtypes(monkeypatch):
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *a: (9, 4))
+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda *a: "AMD Instinct MI300X")
+ monkeypatch.setattr(torch.version, "hip", "6.4")
+ seen = []
+ monkeypatch.setattr(
+ f8t, "_probe_float8_gemm", lambda d, r: seen.extend(f8t._probe_dtype_pairs(r))
+ )
+ f8t._check_hardware(torch.device("cuda", 0), _fnuz_config())
+ assert (torch.float8_e4m3fnuz, torch.float8_e4m3fnuz) in seen
+ assert torch.float8_e4m3fn not in {d for pair in seen for d in pair}
+
+
+def test_probe_named_recipes_cover_forward_and_backward(monkeypatch):
+ assert _probe_dtypes(monkeypatch, "tensorwise") == [
+ (torch.float8_e4m3fn, torch.float8_e4m3fn),
+ (torch.float8_e5m2, torch.float8_e4m3fn),
+ ]
+ assert _probe_dtypes(monkeypatch, "rowwise") == [(torch.float8_e4m3fn, torch.float8_e4m3fn)]
+
+
+def test_probe_scales_follow_each_cast_config(monkeypatch):
+ # torchao's rowwise_with_gw_hp: rowwise forward; grad_input = rowwise grad_output x tensorwise
+ # weight_for_grad_input, which torchao runs rowwise by repeating the tensorwise scale; grad_weight in high
+ # precision (casts disabled, not probed).
+ from torchao.float8 import Float8LinearConfig
+
+ config = Float8LinearConfig.from_recipe_name("rowwise_with_gw_hp")
+ e4m3 = torch.float8_e4m3fn
+ assert _probe_calls(monkeypatch, config) == [
+ (e4m3, e4m3, (16, 1), (1, 16)),
+ (e4m3, e4m3, (16, 1), (1, 16)),
+ ]
+ assert f8t._probe_gemms(config) == [((e4m3, True), (e4m3, True)), ((e4m3, True), (e4m3, False))]
+ assert _probe_calls(monkeypatch, "tensorwise") == [
+ (e4m3, e4m3, (), ()),
+ (torch.float8_e5m2, e4m3, (), ()),
+ ]
+ assert _probe_calls(monkeypatch, "rowwise") == [(e4m3, e4m3, (16, 1), (1, 16))]
diff --git a/tests/test_float8_training_cuda.py b/tests/test_float8_training_cuda.py
new file mode 100644
index 00000000000..818cc958149
--- /dev/null
+++ b/tests/test_float8_training_cuda.py
@@ -0,0 +1,67 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""float8_training on a real fp8 GPU: token counts not divisible by 16 train in eager and compiled mode,
+and an offloaded (CPU) embedding does not block conversion of the CUDA linears."""
+
+from __future__ import annotations
+
+import importlib.util
+
+import pytest
+import torch
+
+pytestmark = [
+ pytest.mark.skipif(importlib.util.find_spec("torchao") is None, reason = "require torchao"),
+ pytest.mark.skipif(
+ not torch.cuda.is_available() or torch.cuda.get_device_capability() < (8, 9),
+ reason = "require an fp8 GPU",
+ ),
+]
+
+from unsloth.models import float8_training as f8t # noqa: E402
+
+
+def _config(recipe):
+ from torchao.float8 import Float8LinearConfig
+ return Float8LinearConfig.from_recipe_name(recipe)
+
+
+def _mlp():
+ torch.manual_seed(0)
+ return torch.nn.Sequential(
+ torch.nn.Linear(256, 512, bias = False),
+ torch.nn.GELU(),
+ torch.nn.Linear(512, 256, bias = False),
+ ).to("cuda", torch.bfloat16)
+
+
[email protected]("recipe", ["tensorwise", "rowwise"])
[email protected]("compiled", [False, True])
[email protected]("tokens", [1, 7, 17, 33])
+def test_unaligned_token_counts_backward(recipe, compiled, tokens):
+ if recipe == "tensorwise" and torch.cuda.get_device_capability() < (9, 0):
+ pytest.skip("tensorwise is refused on 8.9")
+ model = _mlp()
+ names = f8t.convert_model_to_float8_training(model, _config(recipe), size_filter = False)
+ assert len(names) == 2
+ fn = torch.compile(model) if compiled else model
+ x = torch.randn(1, tokens, 256, device = "cuda", dtype = torch.bfloat16, requires_grad = True)
+ fn(x).float().square().mean().backward()
+ assert torch.isfinite(x.grad).all()
+ assert all(p.grad is not None and torch.isfinite(p.grad).all() for p in model.parameters())
+
+
+def test_offloaded_embedding_does_not_block_conversion():
+ class M(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.embed = torch.nn.Embedding(
+ 64, 256
+ ) # stays on the CPU, like offload_embedding = True
+ self.body = _mlp()
+
+ model = M()
+ assert next(model.parameters()).device.type == "cpu"
+ names = f8t.convert_model_to_float8_training(model, _config("rowwise"), size_filter = False)
+ assert names == ["body.0", "body.2"]
diff --git a/tests/test_float8_training_fsdp2_gloo.py b/tests/test_float8_training_fsdp2_gloo.py
new file mode 100644
index 00000000000..1a662233bb9
--- /dev/null
+++ b/tests/test_float8_training_fsdp2_gloo.py
@@ -0,0 +1,128 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""float8_training under native FSDP2 (UNSLOTH_FSDP2=1), gloo world of 2 on the CPU with torchao's
+emulated fp8: the converted Float8Linear layers survive shard_model, their weights become DTensors,
+and four AdamW steps give exactly the losses of the same fp8 model trained unsharded."""
+
+import importlib.util
+import json
+import multiprocessing
+import os
+import sys
+import types
+
+if multiprocessing.parent_process() is not None or getattr(
+ multiprocessing.current_process(), "_inheriting", False
+):
+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts
+
+import pytest # noqa: E402
+import torch # noqa: E402
+
+pytest.importorskip("torchao.float8")
+pytest.importorskip("torch.distributed.fsdp")
+
+REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+
+def _load(name, path):
+ spec = importlib.util.spec_from_file_location(name, path)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+def _native():
+ for name in ("unsloth", "unsloth.models"):
+ pkg = types.ModuleType(name)
+ pkg.__path__ = [os.path.join(REPO, *name.split("."))]
+ sys.modules.setdefault(name, pkg)
+ _load("unsloth.fsdp2_launch", os.path.join(REPO, "unsloth", "fsdp2_launch.py"))
+ return _load(
+ "unsloth.models.fsdp2_native", os.path.join(REPO, "unsloth", "models", "fsdp2_native.py")
+ )
+
+
+def _build():
+ from torchao.float8 import Float8LinearConfig
+ from transformers import LlamaConfig, LlamaForCausalLM
+
+ f8t = _load(
+ "_unsloth_float8_training_fsdp2",
+ os.path.join(REPO, "unsloth", "models", "float8_training.py"),
+ )
+ torch.manual_seed(0)
+ config = LlamaConfig(
+ vocab_size = 256,
+ hidden_size = 128,
+ intermediate_size = 256,
+ num_hidden_layers = 2,
+ num_attention_heads = 4,
+ num_key_value_heads = 2,
+ max_position_embeddings = 64,
+ )
+ model = LlamaForCausalLM(config).float()
+ fp8 = Float8LinearConfig.from_recipe_name("tensorwise")
+ object.__setattr__(fp8, "emulate", True)
+ names = f8t.convert_model_to_float8_training(model, fp8, size_filter = False)
+ return model, names
+
+
+def _train(model, steps = 4):
+ opt = torch.optim.AdamW(model.parameters(), lr = 1e-3)
+ g = torch.Generator().manual_seed(1)
+ losses = []
+ for _ in range(steps):
+ ids = torch.randint(0, 256, (2, 32), generator = g)
+ loss = model(input_ids = ids, labels = ids).loss
+ loss.backward()
+ opt.step()
+ opt.zero_grad()
+ losses.append(loss.item())
+ return losses
+
+
+def _worker(rank, port, out):
+ import torch.distributed as dist
+ from torchao.float8.float8_linear import Float8Linear
+
+ os.environ.update(
+ MASTER_ADDR = "127.0.0.1",
+ MASTER_PORT = str(port),
+ RANK = str(rank),
+ WORLD_SIZE = "2",
+ LOCAL_RANK = str(rank),
+ )
+ dist.init_process_group("gloo", rank = rank, world_size = 2)
+ try:
+ native = _native()
+ model, names = _build()
+ model = native.shard_model(
+ model, native.FSDP2Config(param_dtype = torch.float32, device = "cpu")
+ )
+ fp8 = [m for m in model.modules() if isinstance(m, Float8Linear)]
+ sharded = sum(type(m.weight).__name__ == "DTensor" for m in fp8)
+ losses = _train(model)
+ if rank == 0:
+ with open(out, "w") as f:
+ json.dump(
+ dict(converted = len(names), fp8 = len(fp8), sharded = sharded, losses = losses), f
+ )
+ finally:
+ dist.destroy_process_group()
+
+
+def test_float8_linear_trains_under_native_fsdp2(tmp_path):
+ import torch.multiprocessing as mp
+ from test_fsdp2_frozen_dtypes_gloo import _free_port
+
+ reference = _train(_build()[0])
+ out = str(tmp_path / "fsdp2_fp8.json")
+ mp.spawn(_worker, args = (_free_port(), out), nprocs = 2, join = True)
+ result = json.load(open(out))
+ assert result["converted"] == 14
+ assert result["fp8"] == 14 and result["sharded"] == 14
+ assert result["losses"] == pytest.approx(reference, rel = 1e-5, abs = 1e-6)
diff --git a/unsloth/models/float8_training.py b/unsloth/models/float8_training.py
new file mode 100644
index 00000000000..38fcf9c65d3
--- /dev/null
+++ b/unsloth/models/float8_training.py
@@ -0,0 +1,291 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Opt-in torchao float8 training for full finetuning: eligible nn.Linear layers become torchao Float8Linear (fp8 matmuls in forward and backward, high precision master weights).
+
+Usage: `FastModel.from_pretrained(..., full_finetuning = True, float8_training = True)`. True means the
+tensorwise recipe. By name it runs only on compute capability 12.x (RTX PRO 6000 / RTX 50 class), where it
+was measured faster than bfloat16 at equal loss. Other fp8 GPUs (H100, B200, ROCm) need an explicit
+`torchao.float8.Float8LinearConfig`. Works with native FSDP2 (UNSLOTH_FSDP2=1): convert, then shard."""
+
+from __future__ import annotations
+
+import torch
+
+__all__ = [
+ "FLOAT8_TRAINING_RECIPES",
+ "resolve_float8_training",
+ "float8_training_filter",
+ "convert_model_to_float8_training",
+]
+
+FLOAT8_TRAINING_RECIPES = ("tensorwise",)
+
+# Named recipes run only where they were timed faster than bfloat16 at equal loss (Qwen3-1.7B / 4B full
+# finetuning). tensorwise: RTX PRO 6000 (12.0) 15% faster; L4 (8.9) NaN gradients with gradient
+# checkpointing. rowwise: 3% slower on the RTX PRO 6000 and 2% slower on the L4, so it is not offered by
+# name. Any other GPU needs an explicit torchao Float8LinearConfig.
+_MEASURED_FASTER = {"tensorwise": ((12, 0), (12, 1))}
+
+# Never fp8: output heads (Unsloth's fused CE reads lm_head.weight directly), MoE routers (tiny, precision sensitive).
+_SKIP_NAME_PARTS = ("lm_head", "embed_out", "output_projection", "router")
+_SKIP_LEAF_NAMES = ("gate", "router", "score", "classifier")
+
+
+def resolve_float8_training(float8_training):
+ """`float8_training` kwarg -> recipe name or a torchao Float8LinearConfig; None when off."""
+ if float8_training is None or float8_training is False:
+ return None
+ if float8_training is True:
+ return "tensorwise"
+ if isinstance(float8_training, str):
+ recipe = float8_training.strip().lower()
+ if recipe == "rowwise":
+ raise ValueError(
+ "Unsloth: float8_training = 'rowwise' trained slower than bfloat16 on every GPU it was "
+ "timed on (L4, RTX PRO 6000). Use float8_training = True (tensorwise), or pass "
+ "torchao.float8.Float8LinearConfig.from_recipe_name('rowwise') to force it."
+ )
+ if recipe not in FLOAT8_TRAINING_RECIPES:
+ raise ValueError(
+ f"Unsloth: float8_training = '{float8_training}' is not supported. "
+ f"Use True or one of {FLOAT8_TRAINING_RECIPES}."
+ )
+ return recipe
+ if type(float8_training).__name__ == "Float8LinearConfig":
+ return float8_training
+ raise TypeError(
+ "Unsloth: float8_training must be True / False, a recipe name "
+ f"{FLOAT8_TRAINING_RECIPES} or a torchao Float8LinearConfig, got {type(float8_training)}."
+ )
+
+
+def _size_ok(recipe, out_features, in_features):
+ # torchao's H100 thresholds (torchao/float8 README); below them the casts cost more than the fp8 GEMM saves.
+ N, K = out_features, in_features
+ if recipe == "tensorwise":
+ return not (K <= 4096 and N <= 1024)
+ if N <= 2048 or K <= 1024:
+ return False
+ return not (N <= 4096 and K <= 2048)
+
+
+def float8_training_filter(
+ model,
+ recipe = "tensorwise",
+ size_filter = True,
+):
+ """Filter for convert_to_float8_training: plain nn.Linear, dims divisible by 16, trainable floating weight, not an output head or router."""
+ out_heads = set()
+ try:
+ out = model.get_output_embeddings()
+ if out is not None:
+ out_heads.add(id(out))
+ except Exception:
+ pass
+ size_recipe = _recipe_scaling(recipe)
+
+ def module_filter_fn(module, fqn):
+ # Exact type: bitsandbytes / QAT / fp8 / PEFT linears subclass nn.Linear and must stay as they are.
+ if type(module) is not torch.nn.Linear:
+ return False
+ if id(module) in out_heads or any(p in fqn for p in _SKIP_NAME_PARTS):
+ return False
+ if fqn.rsplit(".", 1)[-1] in _SKIP_LEAF_NAMES:
+ return False
+ weight = module.weight
+ if not weight.is_floating_point() or weight.element_size() < 2 or not weight.requires_grad:
+ return False
+ if weight.dim() != 2 or weight.is_meta:
+ return False
+ out_features, in_features = weight.shape
+ if out_features % 16 != 0 or in_features % 16 != 0:
+ return False
+ return not size_filter or _size_ok(size_recipe, out_features, in_features)
+
+ return module_filter_fn
+
+
+def _probe_gemms(recipe):
+ """The fp8 GEMMs torchao runs for this recipe / config, as ((mat1 dtype, rowwise?), (mat2 dtype, rowwise?)):
+ forward input x weight, grad_input grad_output x weight_for_grad_input, grad_weight
+ grad_output_for_grad_weight x input_for_grad_weight. Each operand keeps its own cast config's dtype
+ (torchao picks e4m3fnuz / e5m2fnuz on MI300) and scaling granularity; a GEMM with a disabled cast runs
+ in high precision and is not probed."""
+ config = recipe
+ if isinstance(recipe, str):
+ from torchao.float8 import Float8LinearConfig
+ config = Float8LinearConfig.from_recipe_name(recipe)
+
+ def operand(name, fallback, default_dtype):
+ cast = getattr(config, name, None)
+ if cast is None:
+ cast = getattr(config, fallback, None) if fallback else None
+ if cast is not None and "DISABLED" in str(getattr(cast, "scaling_type", "")).upper():
+ return None
+ dtype = getattr(cast, "target_dtype", None)
+ dtype = dtype if isinstance(dtype, torch.dtype) else default_dtype
+ rowwise = "AXIS" in str(getattr(cast, "scaling_granularity", "")).upper()
+ return dtype, rowwise
+
+ e4m3, e5m2 = torch.float8_e4m3fn, torch.float8_e5m2
+ x = operand("cast_config_input", None, e4m3)
+ w = operand("cast_config_weight", None, e4m3)
+ g = operand("cast_config_grad_output", None, e5m2)
+ w_gi = operand("cast_config_weight_for_grad_input", "cast_config_weight", e4m3)
+ g_gw = operand("cast_config_grad_output_for_grad_weight", "cast_config_grad_output", e5m2)
+ x_gw = operand("cast_config_input_for_grad_weight", "cast_config_input", e4m3)
+ gemms = []
+ for gemm in ((x, w), (g, w_gi), (g_gw, x_gw)):
+ if None not in gemm and gemm not in gemms:
+ gemms.append(gemm)
+ return gemms
+
+
+def _probe_dtype_pairs(recipe):
+ """(mat1, mat2) fp8 dtypes of the GEMMs `_probe_gemms` lists."""
+ pairs = []
+ for (dtype_a, _), (dtype_b, _) in _probe_gemms(recipe):
+ if (dtype_a, dtype_b) not in pairs:
+ pairs.append((dtype_a, dtype_b))
+ return pairs
+
+
+def _probe_float8_gemm(device, recipe):
+ """Tiny torch._scaled_mm calls with each GEMM's own fp8 dtypes and scaling, so an unsupported GPU / torch refuses here, not mid-training."""
+ M, K, N = 16, 32, 16
+ for (dtype_a, rowwise_a), (dtype_b, rowwise_b) in _probe_gemms(recipe):
+ a = torch.ones(M, K, device = device).to(dtype_a)
+ b = torch.ones(N, K, device = device).to(dtype_b).t()
+ # torch._scaled_mm takes one granularity for both operands; torchao (float8_ops.preprocess_addmm)
+ # repeats a tensorwise scale along the axis when the other operand is rowwise, so the probe does too.
+ rowwise = rowwise_a or rowwise_b
+ sa = torch.ones(M, 1, device = device) if rowwise else torch.ones((), device = device)
+ sb = torch.ones(1, N, device = device) if rowwise else torch.ones((), device = device)
+ torch._scaled_mm(a, b, scale_a = sa, scale_b = sb, out_dtype = torch.bfloat16)
+
+
+def _recipe_scaling(recipe):
+ """'tensorwise' or 'rowwise' for a recipe name or a Float8LinearConfig (by its input cast granularity)."""
+ if isinstance(recipe, str):
+ return recipe
+ try:
+ granularity = recipe.cast_config_input.scaling_granularity
+ return (
+ "rowwise"
+ if "AXIS" in str(getattr(granularity, "name", granularity)).upper()
+ else "tensorwise"
+ )
+ except Exception:
+ return "rowwise"
+
+
+def _selected_devices(model, module_filter_fn):
+ """Devices of the Linear weights that will be converted (an offloaded CPU embedding is not one of them)."""
+ devices = []
+ for name, module in model.named_modules():
+ if isinstance(module, torch.nn.Linear) and module_filter_fn(module, name):
+ if module.weight.device not in devices:
+ devices.append(module.weight.device)
+ return devices
+
+
+def _check_hardware(device, recipe):
+ if device is None or device.type != "cuda" or not torch.cuda.is_available():
+ raise RuntimeError(
+ "Unsloth: float8_training needs the model on an NVIDIA GPU with compute capability 8.9+; "
+ f"the model is on {device}."
+ )
+ major, minor = torch.cuda.get_device_capability(device)
+ name = torch.cuda.get_device_name(device)
+ if torch.version.hip is None and (major, minor) < (8, 9):
+ raise RuntimeError(
+ "Unsloth: float8_training needs compute capability 8.9+ (fp8 tensor cores); "
+ f"{name} is {major}.{minor}. Train in bfloat16 / float16 instead."
+ )
+ if (
+ torch.version.hip is None
+ and _recipe_scaling(recipe) == "tensorwise"
+ and (major, minor) < (9, 0)
+ ):
+ # Measured on an L4: every gradient is NaN from the first step once gradient checkpointing runs.
+ # The scaling is what fails, so explicit Float8LinearConfigs are refused too.
+ raise RuntimeError(
+ "Unsloth: float8_training with tensorwise scaling gives NaN gradients on compute capability "
+ f"8.9 ({name}). Train in bfloat16 instead."
+ )
+ if isinstance(recipe, str):
+ if torch.version.hip is not None or (major, minor) not in _MEASURED_FASTER.get(recipe, ()):
+ where = (
+ "ROCm" if torch.version.hip is not None else f"compute capability {major}.{minor}"
+ )
+ raise RuntimeError(
+ f"Unsloth: float8_training = {recipe!r} has not been measured faster than bfloat16 on "
+ f"{name} ({where}); it is enabled by name only on RTX PRO 6000 / RTX 50 class GPUs "
+ "(compute capability 12.x). To try it here, pass "
+ f"torchao.float8.Float8LinearConfig.from_recipe_name({recipe!r}) as float8_training."
+ )
+ probe_recipe = _recipe_scaling(recipe)
+ try:
+ _probe_float8_gemm(device, recipe)
+ except Exception as e:
+ raise RuntimeError(
+ f"Unsloth: float8_training ({probe_recipe} scaling) is not supported by torch {torch.__version__} on "
+ f"{torch.cuda.get_device_name(device)} ({type(e).__name__}: {str(e)[:200]})."
+ ) from e
+
+
+def convert_model_to_float8_training(
+ model,
+ float8_training = True,
+ *,
+ size_filter = True,
+ module_filter_fn = None,
+ check_hardware = True,
+):
+ """Swap eligible nn.Linear layers of a full finetuning model for torchao Float8Linear in place. Returns the converted module names (also on `model._unsloth_float8_linears`)."""
+ recipe = resolve_float8_training(float8_training)
+ if recipe is None:
+ return []
+ try:
+ from torchao.float8 import Float8LinearConfig, convert_to_float8_training
+ from torchao.float8.float8_linear import Float8Linear
+ except Exception as e:
+ raise ImportError(
+ "Unsloth: float8_training needs torchao with torchao.float8: `pip install torchao`. "
+ f"({type(e).__name__}: {e})"
+ ) from e
+ from dataclasses import replace
+
+ config = Float8LinearConfig.from_recipe_name(recipe) if isinstance(recipe, str) else recipe
+ if getattr(config, "enable_fsdp_float8_all_gather", False):
+ # Its weight subclass gives a shared (tied) weight one parameter per user, so AdamW updates it twice,
+ # and safetensors cannot save it. Refused before any layer is swapped.
+ raise ValueError(
+ "Unsloth: float8_training does not support enable_fsdp_float8_all_gather = True (shared weights "
+ "would be updated twice and checkpoints cannot be saved). Use a config with it set to False."
+ )
+ # Flattened token counts of variable-length batches are rarely multiples of 16, which the fp8 GEMM of the
+ # weight gradient needs; torchao pads the inner dim when asked. The caller's config is left untouched.
+ if not getattr(config, "pad_inner_dim", True):
+ config = replace(config, pad_inner_dim = True)
+ if module_filter_fn is None:
+ module_filter_fn = float8_training_filter(model, recipe, size_filter = size_filter)
+ if check_hardware and not getattr(config, "emulate", False):
+ devices = _selected_devices(model, module_filter_fn)
+ for device in devices or [next((p.device for p in model.parameters()), None)]:
+ _check_hardware(device, recipe)
+ convert_to_float8_training(model, module_filter_fn = module_filter_fn, config = config)
+ converted = [name for name, m in model.named_modules() if isinstance(m, Float8Linear)]
+ if not converted:
+ import warnings
+ warnings.warn(
+ "Unsloth: float8_training found no eligible Linear layer (dims divisible by 16 and large enough "
+ "for fp8 to pay off); the model trains in its original precision.",
+ stacklevel = 2,
+ )
+ try:
+ model._unsloth_float8_linears = converted
+ except Exception:
+ pass
+ return converted
diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py
index 412dd6fcebd..fcd5554ae04 100644
--- a/unsloth/models/loader.py
+++ b/unsloth/models/loader.py
@@ -35,6 +35,7 @@ from transformers import __version__ as transformers_version
from peft import PeftConfig, PeftModel
from .grouped_linear_lora import register_grouped_linear_lora_for_adapter
from .fp8_to_nf4 import track_explicit_4bit_request
+from .float8_training import convert_model_to_float8_training, resolve_float8_training
from .mistral_format import (
MistralFormatRedirect,
is_mistral_format_view,
@@ -1297,6 +1298,18 @@ class FastLanguageModel(FastLlamaModel):
device_map = distributed_device_map
# @_offline_aware_load already forced offline when needed; delegations inherit it.
+ if kwargs.get("float8_training", None) not in (None, False) and not full_finetuning:
+ raise ValueError(
+ "Unsloth: `float8_training` is for `full_finetuning = True` only; LoRA / QLoRA keep "
+ "their base weights frozen, so there is no fp8 training step to take."
+ )
+ if kwargs.get("float8_training", None) not in (None, False) and qat_scheme is not None:
+ raise ValueError(
+ "Unsloth: `float8_training` and `qat_scheme` cannot be combined. QAT swaps the Linear "
+ "layers for fake-quantized ones first, so float8 training would convert nothing. Pick one."
+ )
+ if not full_finetuning:
+ kwargs.pop("float8_training", None)
if load_in_8bit or full_finetuning or qat_scheme is not None:
delegated, tokenizer = FastModel.from_pretrained(
on_model_resolved = on_model_resolved,
@@ -2204,6 +2217,17 @@ class FastModel(FastBaseModel):
**kwargs,
):
user_config = kwargs.pop("config", None)
+ float8_training = resolve_float8_training(kwargs.pop("float8_training", None))
+ if float8_training is not None and not full_finetuning:
+ raise ValueError(
+ "Unsloth: `float8_training` is for `full_finetuning = True` only; LoRA / QLoRA keep "
+ "their base weights frozen, so there is no fp8 training step to take."
+ )
+ if float8_training is not None and qat_scheme is not None:
+ raise ValueError(
+ "Unsloth: `float8_training` and `qat_scheme` cannot be combined. QAT swaps the Linear "
+ "layers for fake-quantized ones first, so float8 training would convert nothing. Pick one."
+ )
quantization_config = kwargs.get("quantization_config", None)
if quantization_config is not None:
if isinstance(quantization_config, dict):
@@ -2481,6 +2505,9 @@ class FastModel(FastBaseModel):
**({"config": user_config} if user_config is not None else {}),
**kwargs,
)
+ if float8_training is not None:
+ converted = convert_model_to_float8_training(model, float8_training)
+ print(f"Unsloth: float8 training on {len(converted)} Linear layers.")
# Returns before the FORCE_FLOAT32 scan and no diffusion type is on that list, so False. Stamped, not left unset, or the trainer reads whatever an earlier load wrote.
model = _mark_forced_float32(model, False)
model = _mark_full_finetuning(model, full_finetuning)
@@ -3536,6 +3563,9 @@ class FastModel(FastBaseModel):
model = _drop_float16_overflowing_attention_dropout(model, dtype)
# Loaded adapters skip get_peft_model.
_ignore_block_swap_params_for_ddp(model)
+ if float8_training is not None:
+ converted = convert_model_to_float8_training(model, float8_training)
+ print(f"Unsloth: float8 training on {len(converted)} Linear layers.")
model = _mark_forced_float32(model, do_forced_float32)
model = _mark_full_finetuning(model, full_finetuning)
return _mark_requested_float32(model, user_float32), tokenizer