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.

NVFP4 QAT: require in_features divisible by 32 (#14703)

Daniel Han68c62667e0e1
diff --git a/tests/test_qat_microscaling_schemes.py b/tests/test_qat_microscaling_schemes.py
index 8694533ad22..e1aee3bc2ef 100644
--- a/tests/test_qat_microscaling_schemes.py
+++ b/tests/test_qat_microscaling_schemes.py
@@ -75,6 +75,54 @@ def test_nvfp4_scheme_layers_where_fp4_gemm_runs(monkeypatch):
assert type(layer.odd) is torch.nn.Linear
[email protected]("lora", [False, True])
+def test_nvfp4_needs_in_features_divisible_by_32(monkeypatch, lora):
+ # _scaled_mm takes the packed FP4 K / 2 and needs it divisible by 16: K = 16, 48, 80 cannot run.
+ monkeypatch.setattr(qat_utils, "_qat_forward_runs", lambda *a: True)
+ if lora:
+ from peft import LoraConfig, get_peft_model
+
+ monkeypatch.setenv("UNSLOTH_QAT_FAKE_QUANTIZE_LORA", "1")
+ model = get_peft_model(
+ _tiny_qwen3(), LoraConfig(r = 16, lora_alpha = 16, target_modules = ["q_proj"])
+ )
+ model = _prepare_model_for_qat(model, "nvfp4")
+ q_proj = model.base_model.model.model.layers[0].self_attn.q_proj
+ assert isinstance(q_proj.base_layer, _nvfp4_linear())
+ assert isinstance(q_proj.lora_A["default"], _nvfp4_linear()) # K = 128
+ assert type(q_proj.lora_B["default"]) is torch.nn.Linear # K = r = 16
+ return
+ widths = (16, 32, 48, 64, 80, 96)
+ model = torch.nn.Sequential(*(torch.nn.Linear(k, 128, bias = False) for k in widths)).to(
+ torch.bfloat16
+ )
+ with warnings.catch_warnings(record = True) as caught:
+ warnings.simplefilter("always")
+ model = _prepare_model_for_qat(model, "nvfp4")
+ got = {k: isinstance(m, _nvfp4_linear()) for k, m in zip(widths, model)}
+ assert got == {k: k % 32 == 0 for k in widths}
+ assert any("in_features not divisible by 32" in str(w.message) for w in caught)
+
+
+ not torch.cuda.is_available() or torch.cuda.get_device_capability() < (10, 0),
+ reason = "needs an FP4 tensor core GPU",
+)
+def test_nvfp4_admitted_widths_run_on_gpu():
+ widths = (16, 32, 48, 64, 80, 96)
+ model = torch.nn.ModuleList(torch.nn.Linear(k, 128, bias = False) for k in widths).to(
+ "cuda", torch.bfloat16
+ )
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ model = _prepare_model_for_qat(model, "nvfp4")
+ for k, layer in zip(widths, model):
+ assert isinstance(layer, _nvfp4_linear()) == (k % 32 == 0), k
+ x = torch.randn(16, k, device = "cuda", dtype = torch.bfloat16, requires_grad = True)
+ layer(x).float().sum().backward()
+ assert x.grad is not None
+
+
def test_nvfp4_plain_module_without_hf_heads(monkeypatch):
monkeypatch.setattr(qat_utils, "_qat_forward_runs", lambda *a: True)
model = torch.nn.Sequential(torch.nn.Linear(64, 128, bias = False)).to(torch.bfloat16)
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 6aaba14d895..b2816779774 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -7889,15 +7889,23 @@ def _output_head_module_ids(model):
return {id(m) for m in out_head.modules()}
-def _block_linear_filter(model, block_size, qat_scheme, skip_output_head):
- """Linears with both dims divisible by the scale block, optionally excluding the output head."""
+def _block_linear_filter(
+ model,
+ block_size,
+ qat_scheme,
+ skip_output_head,
+ in_features_multiple = None,
+):
+ """Linears with both dims divisible by the scale block (in_features by in_features_multiple if given),
+ optionally excluding the output head."""
out_head_ids = _output_head_module_ids(model) if skip_output_head else set()
+ in_multiple = in_features_multiple or block_size
def eligible(m):
return isinstance(m, torch.nn.Linear) and id(m) not in out_head_ids
def blocks_ok(m):
- return m.in_features % block_size == 0 and m.out_features % block_size == 0
+ return m.in_features % in_multiple == 0 and m.out_features % block_size == 0
filter_fn = lambda m, _: eligible(m) and blocks_ok(m)
skipped = [
@@ -7906,9 +7914,14 @@ def _block_linear_filter(model, block_size, qat_scheme, skip_output_head):
if eligible(module) and not blocks_ok(module) and not _is_lora_adapter_name(name)
]
if skipped:
+ need = (
+ f"a dim not divisible by {block_size}"
+ if in_multiple == block_size
+ else f"in_features not divisible by {in_multiple} or out_features not divisible by {block_size}"
+ )
warnings.warn(
f"Unsloth: qat_scheme='{qat_scheme}' uses {block_size}-element scale blocks; these Linear "
- f"layers have a dim not divisible by {block_size} and stay in full precision: "
+ f"layers have {need} and stay in full precision: "
+ ", ".join(skipped[:8])
+ (f", ... ({len(skipped) - 8} more)" if len(skipped) > 8 else ""),
stacklevel = 3,
@@ -7973,10 +7986,23 @@ def _eligible_layer_placements(model, filter_fn):
def _microscaling_qat_filter(
- model, qat_scheme, base_config, block_size, dtypes, dtype_msg, gemm_msg
+ model,
+ qat_scheme,
+ base_config,
+ block_size,
+ dtypes,
+ dtype_msg,
+ gemm_msg,
+ in_features_multiple = None,
):
"""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)
+ candidates = _block_linear_filter(
+ model,
+ block_size,
+ qat_scheme,
+ skip_output_head = True,
+ in_features_multiple = in_features_multiple,
+ )
placements = _eligible_layer_placements(model, candidates)
unsupported = sorted({str(dtype) for _, dtype in placements if dtype not in dtypes})
if unsupported:
@@ -8154,6 +8180,8 @@ def _prepare_model_for_qat(
qat_scheme,
base_config,
block_size = 16,
+ # Two FP4 values per byte: _scaled_mm needs the packed K / 2 divisible by 16, so K by 32.
+ in_features_multiple = 32,
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 "