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.

QAT: qat_scheme = "mxfp8", and let MX QAT linears take float32 activations under autocast (#14607)

Daniel Han890ea71a3bd1
diff --git a/tests/test_qat_microscaling_schemes.py b/tests/test_qat_microscaling_schemes.py
index 13a2c76672c..8694533ad22 100644
--- a/tests/test_qat_microscaling_schemes.py
+++ b/tests/test_qat_microscaling_schemes.py
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-"""qat_scheme = "nvfp4" shorthand and saving torchao NVFP4 / MX QAT linears, CPU only."""
+"""qat_scheme = "nvfp4" / "mxfp8" shorthands and saving torchao NVFP4 / MX QAT linears, CPU only."""
from __future__ import annotations
@@ -84,7 +84,62 @@ def test_nvfp4_plain_module_without_hf_heads(monkeypatch):
def test_unknown_scheme_still_rejected():
with pytest.raises(ValueError, match = "Unexpected QAT scheme"):
- _prepare_model_for_qat(_tiny_qwen3(), "mxfp8")
+ _prepare_model_for_qat(_tiny_qwen3(), "mxfp6")
+
+
+def test_mxfp8_scheme_refuses_without_mx_gemm():
+ model = _tiny_qwen3()
+ with pytest.raises(RuntimeError, match = "MX tensor cores"):
+ _prepare_model_for_qat(model, "mxfp8")
+ assert not any(isinstance(m, _mx_linear()) for m in model.modules())
+
+
+def test_mxfp8_scheme_layers_where_mx_gemm_runs(monkeypatch):
+ from torchao.prototype.mx_formats import MXDynamicActivationMXWeightConfig
+
+ monkeypatch.setattr(qat_utils, "_qat_forward_runs", lambda *a: True)
+ model = _tiny_qwen3()
+ model.model.layers[0].odd = torch.nn.Linear(128, 48, bias = False)
+ with warnings.catch_warnings(record = True) as caught:
+ warnings.simplefilter("always")
+ model = _prepare_model_for_qat(model, "mxfp8")
+ ((base_config, _),) = model._torchao_config.base_config_and_filter_fns
+ assert isinstance(base_config, MXDynamicActivationMXWeightConfig)
+ assert base_config.activation_dtype == base_config.weight_dtype == torch.float8_e4m3fn
+ layer = model.model.layers[0]
+ for proj in (layer.self_attn.q_proj, layer.self_attn.k_proj, layer.mlp.down_proj):
+ assert isinstance(proj, _mx_linear())
+ assert type(model.lm_head) is torch.nn.Linear
+ assert type(layer.odd) is torch.nn.Linear # 48 is not a multiple of the 32-element block
+ assert any("32-element scale blocks" in str(w.message) for w in caught)
+
+
[email protected]("dtype", [torch.float32, torch.float16])
+def test_mxfp8_refuses_non_bfloat16_layers(monkeypatch, dtype):
+ _probe_ok(monkeypatch)
+ model = _tiny_qwen3().to(dtype)
+ with pytest.raises(RuntimeError, match = "bfloat16 layers only"):
+ _prepare_model_for_qat(model, "mxfp8")
+ assert not any(isinstance(m, _mx_linear()) for m in model.modules())
+
+
[email protected]("weight_dtype", [torch.bfloat16, torch.float32])
+def test_mx_qat_linear_takes_float32_activations_under_autocast(weight_dtype):
+ # Autocast feeds float32 activations into bfloat16 (or float32) linears.
+ # torchao's CPU fake-quant backward cannot mix a float32 weight with bfloat16 activations.
+ device = "cpu" if weight_dtype == torch.bfloat16 else "cuda"
+ if device == "cuda" and not torch.cuda.is_available():
+ pytest.skip("float32 weights under autocast need the CUDA MX path")
+ model = torch.nn.Sequential(torch.nn.Linear(64, 128, bias = False)).to(device, weight_dtype)
+ model = _prepare_model_for_qat(model, _mx_torchao_config())
+ assert isinstance(model[0], _mx_linear())
+ x = torch.randn(2, 3, 64, device = device, requires_grad = True)
+ with torch.autocast(device, dtype = torch.bfloat16):
+ out = model(x)
+ assert out.dtype == torch.bfloat16 and out.shape == (2, 3, 128)
+ out.float().sum().backward()
+ assert x.grad is not None and x.grad.dtype == torch.float32
+ assert model[0].weight.grad is not None
def _mx_torchao_config():
@@ -222,17 +277,19 @@ def test_nvfp4_probes_opted_in_adapter_placements(monkeypatch):
assert ("cpu", torch.float32) in calls
[email protected]("scheme", ["nvfp4", "mxfp8"])
@pytest.mark.parametrize("bias_grad", [False, True])
-def test_nvfp4_biased_layers_need_bias_grad(monkeypatch, bias_grad):
+def test_nvfp4_biased_layers_need_bias_grad(monkeypatch, bias_grad, scheme):
_probe_ok(monkeypatch, bias_grad = bias_grad)
+ linear_cls = _nvfp4_linear() if scheme == "nvfp4" else _mx_linear()
model = _tiny_qwen3()
layer = model.model.layers[0]
layer.self_attn.q_proj = torch.nn.Linear(128, 128, bias = True).to(torch.bfloat16)
with warnings.catch_warnings(record = True) as caught:
warnings.simplefilter("always")
- model = _prepare_model_for_qat(model, "nvfp4")
- assert isinstance(layer.self_attn.q_proj, _nvfp4_linear()) is bias_grad
- assert isinstance(layer.mlp.down_proj, _nvfp4_linear())
+ model = _prepare_model_for_qat(model, scheme)
+ assert isinstance(layer.self_attn.q_proj, linear_cls) is bias_grad
+ assert isinstance(layer.mlp.down_proj, linear_cls)
assert any("no bias" in str(w.message) for w in caught) is not bias_grad
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 04e8e58fefa..ab721351ff7 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -7972,6 +7972,80 @@ def _eligible_layer_placements(model, filter_fn):
return placements
+def _microscaling_qat_filter(
+ model, qat_scheme, base_config, block_size, dtypes, dtype_msg, gemm_msg
+):
+ """NVFP4 / MX QAT layer filter; raises at prepare time if this GPU / dtype cannot run the GEMM."""
+ candidates = _block_linear_filter(model, block_size, qat_scheme, skip_output_head = True)
+ placements = _eligible_layer_placements(model, candidates)
+ unsupported = sorted({str(dtype) for _, dtype in placements if dtype not in dtypes})
+ if unsupported:
+ raise RuntimeError(
+ f"Unsloth: qat_scheme='{qat_scheme}' quantizes {dtype_msg}; this model has "
+ f"{', '.join(unsupported)} layers. Load it with dtype = torch.bfloat16."
+ )
+ for device, dtype in placements:
+ if not _qat_forward_runs(base_config, device, dtype):
+ raise RuntimeError(
+ f"Unsloth: qat_scheme='{qat_scheme}' runs {gemm_msg} and a torch / torchao that "
+ f"support it. Layers of this model are on {device}. Use qat_scheme='fp8-fp8' instead."
+ )
+ # torchao's own NVFP4 filter skips out_features <= 64 (cuBLAS): probe each such width instead.
+ small_widths = sorted(
+ {
+ module.out_features
+ for name, module in model.named_modules()
+ if candidates(module, name) and module.out_features <= 64
+ }
+ )
+ bad_widths = {
+ n
+ for n in small_widths
+ if not all(_qat_forward_runs(base_config, d, t, n) for d, t in placements)
+ }
+ if bad_widths:
+ narrow = [
+ name
+ for name, module in model.named_modules()
+ if not _is_lora_adapter_name(name)
+ and candidates(module, name)
+ and module.out_features in bad_widths
+ ]
+ warnings.warn(
+ f"Unsloth: qat_scheme='{qat_scheme}': the low precision matmul fails for out_features "
+ f"{sorted(bad_widths)} here, so these Linear layers stay in full precision: "
+ + ", ".join(narrow[:8])
+ + (f", ... ({len(narrow) - 8} more)" if len(narrow) > 8 else ""),
+ stacklevel = 3,
+ )
+ candidates = lambda m, fqn, _c = candidates, _bad = frozenset(bad_widths): (
+ _c(m, fqn) and m.out_features not in _bad
+ )
+ biased = [
+ name
+ for name, module in model.named_modules()
+ if not _is_lora_adapter_name(name) and candidates(module, name) and module.bias is not None
+ ]
+ if biased and not all(_qat_bias_grad_supported(base_config, d, t) for d, t in placements):
+ warnings.warn(
+ f"Unsloth: qat_scheme='{qat_scheme}': this torchao's QAT backward returns no bias "
+ "gradient, so these biased Linear layers stay in full precision: "
+ + ", ".join(biased[:8])
+ + (f", ... ({len(biased) - 8} more)" if len(biased) > 8 else ""),
+ stacklevel = 3,
+ )
+ return lambda m, fqn, _c = candidates: _c(m, fqn) and m.bias is None
+ return candidates
+
+
+def _mx_autocast_forward(self, x):
+ # torchao's MX QAT matmul returns bfloat16 under autocast and asserts it matches x, whatever the weight dtype.
+ from torchao.prototype.qat import MXFakeQuantizedLinear
+ if x.dtype != torch.bfloat16 and torch.is_autocast_enabled(x.device.type):
+ x = x.to(torch.bfloat16)
+ return MXFakeQuantizedLinear.forward(self, x)
+
+
def _nvfp4_any_rank_forward(self, x):
# torchao's NVFP4FakeQuantizedLinear flattens only rank-3 inputs; vision layers see rank 4+.
from torchao.prototype.qat import NVFP4FakeQuantizedLinear
@@ -7982,15 +8056,25 @@ def _nvfp4_any_rank_forward(self, x):
return out.view(*x.shape[:-1], out.shape[-1])
-def _accept_any_rank_nvfp4_inputs(model) -> None:
+def _patch_microscaling_qat_forwards(model) -> None:
import types
+
try:
- from torchao.prototype.qat import NVFP4FakeQuantizedLinear
+ from torchao.prototype import qat as prototype_qat
except Exception:
return
+ forwards = [
+ (getattr(prototype_qat, name, None), forward)
+ for name, forward in (
+ ("NVFP4FakeQuantizedLinear", _nvfp4_any_rank_forward),
+ ("MXFakeQuantizedLinear", _mx_autocast_forward),
+ )
+ ]
+ forwards = [(cls, forward) for cls, forward in forwards if isinstance(cls, type)]
for module in model.modules():
- if isinstance(module, NVFP4FakeQuantizedLinear):
- module.forward = types.MethodType(_nvfp4_any_rank_forward, module)
+ for cls, forward in forwards:
+ if isinstance(module, cls):
+ module.forward = types.MethodType(forward, module)
def _is_lora_adapter_name(fqn: str) -> bool:
@@ -8065,79 +8149,42 @@ def _prepare_model_for_qat(
base_config = NVFP4DynamicActivationNVFP4WeightConfig(use_triton_kernel = False)
except TypeError: # older torchao without the knob
base_config = NVFP4DynamicActivationNVFP4WeightConfig()
- candidates = _block_linear_filter(model, 16, qat_scheme, skip_output_head = True)
- placements = _eligible_layer_placements(model, candidates)
- unsupported = sorted(
- {
- str(dtype)
- for _, dtype in placements
- if dtype not in (torch.bfloat16, torch.float32)
- }
+ filter_fn = _microscaling_qat_filter(
+ model,
+ qat_scheme,
+ base_config,
+ block_size = 16,
+ dtypes = (torch.bfloat16, torch.float32),
+ dtype_msg = "bfloat16 or float32 activations only (torchao's NVFP4 quantizer)",
+ gemm_msg = "NVFP4 matmuls in the forward pass and needs a GPU with FP4 tensor cores "
+ "(compute capability 10.0+: B200, GB200, RTX 50 series)",
)
- if unsupported:
- raise RuntimeError(
- "Unsloth: qat_scheme='nvfp4' quantizes bfloat16 or float32 activations only (torchao's "
- f"NVFP4 quantizer); this model has {', '.join(unsupported)} layers. Load it with "
- "dtype = torch.bfloat16."
- )
- for device, dtype in placements:
- if not _qat_forward_runs(base_config, device, dtype):
- raise RuntimeError(
- "Unsloth: qat_scheme='nvfp4' runs NVFP4 matmuls in the forward pass and needs a GPU "
- "with FP4 tensor cores (compute capability 10.0+: B200, GB200, RTX 50 series) and a "
- f"torch / torchao that support it. Layers of this model are on {device}. Use "
- "qat_scheme='fp8-fp8' instead."
- )
- # torchao's own NVFP4 filter skips out_features <= 64 (cuBLAS): probe each such width instead.
- small_widths = sorted(
- {
- module.out_features
- for name, module in model.named_modules()
- if candidates(module, name) and module.out_features <= 64
- }
+ torchao_config = TorchAOConfig(
+ qat_scheme = qat_scheme,
+ base_config_and_filter_fns = [(base_config, filter_fn)],
)
- bad_widths = {
- n
- for n in small_widths
- if not all(_qat_forward_runs(base_config, d, t, n) for d, t in placements)
- }
- if bad_widths:
- narrow = [
- name
- for name, module in model.named_modules()
- if not _is_lora_adapter_name(name)
- and candidates(module, name)
- and module.out_features in bad_widths
- ]
- warnings.warn(
- "Unsloth: qat_scheme='nvfp4': the NVFP4 matmul fails for out_features "
- f"{sorted(bad_widths)} here, so these Linear layers stay in full precision: "
- + ", ".join(narrow[:8])
- + (f", ... ({len(narrow) - 8} more)" if len(narrow) > 8 else ""),
- stacklevel = 2,
- )
- candidates = lambda m, fqn, _c = candidates, _bad = frozenset(bad_widths): (
- _c(m, fqn) and m.out_features not in _bad
- )
- biased = [
- name
- for name, module in model.named_modules()
- if not _is_lora_adapter_name(name)
- and candidates(module, name)
- and module.bias is not None
- ]
- filter_fn = candidates
- if biased and not all(
- _qat_bias_grad_supported(base_config, d, t) for d, t in placements
- ):
- warnings.warn(
- "Unsloth: qat_scheme='nvfp4': this torchao's NVFP4 QAT backward returns no bias "
- "gradient, so these biased Linear layers stay in full precision: "
- + ", ".join(biased[:8])
- + (f", ... ({len(biased) - 8} more)" if len(biased) > 8 else ""),
- stacklevel = 2,
+ elif qat_scheme == "mxfp8":
+ try:
+ from torchao.prototype.mx_formats import MXDynamicActivationMXWeightConfig
+ from torchao.prototype.qat import MXFakeQuantizedLinear # noqa: F401, MX QAT is torchao 0.16+
+ except ImportError:
+ raise ImportError(
+ "Unsloth: qat_scheme='mxfp8' needs torchao 0.16 or newer: pip install --upgrade torchao"
)
- filter_fn = lambda m, fqn, _c = candidates: _c(m, fqn) and m.bias is None
+ base_config = MXDynamicActivationMXWeightConfig(
+ activation_dtype = torch.float8_e4m3fn,
+ weight_dtype = torch.float8_e4m3fn,
+ )
+ filter_fn = _microscaling_qat_filter(
+ model,
+ qat_scheme,
+ base_config,
+ block_size = 32,
+ dtypes = (torch.bfloat16,),
+ dtype_msg = "bfloat16 layers only (torchao's MX matmul always returns bfloat16)",
+ gemm_msg = "MXFP8 matmuls in the forward pass and needs a GPU with MX tensor cores "
+ "(compute capability 10.0+, e.g. B200 / GB200)",
+ )
torchao_config = TorchAOConfig(
qat_scheme = qat_scheme,
base_config_and_filter_fns = [(base_config, filter_fn)],
@@ -8275,7 +8322,7 @@ def _prepare_model_for_qat(
for base_config, filter_fn in torchao_config.base_config_and_filter_fns:
quantize_(model, QATConfig(base_config, step = "prepare"), filter_fn = filter_fn)
_restore_fake_quantized_embedding_subclasses(model, embedding_subclasses)
- _accept_any_rank_nvfp4_inputs(model)
+ _patch_microscaling_qat_forwards(model)
return model