Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(quant): load mxfp4 with Mxfp4Config instead of a bitsandbytes config (#1558)

Yang Bai72dbea476455
diff --git a/changelog.d/0.75.1/1558.fixed.md b/changelog.d/0.75.1/1558.fixed.md
new file mode 100644
index 00000000..b931b9b0
--- /dev/null
+++ b/changelog.d/0.75.1/1558.fixed.md
@@ -0,0 +1,17 @@
+- **`training.quantization: mxfp4` passed config validation and then failed at
+ the model load (#1466 by @ybai08 in #1558).** Soup built
+ `BitsAndBytesConfig(bnb_4bit_quant_type="mxfp4")`, which bitsandbytes
+ rejects (it accepts `nf4` and `fp4` only) and which clashes with the
+ `Mxfp4Config` a pre-quantized MXFP4 checkpoint carries, including the bases
+ `soup autopilot` passes through as `mxfp4`. The loader now returns
+ transformers' `Mxfp4Config(dequantize=True)`, since transformers does not
+ train MXFP4 weights as loaded, so the model trains in bf16. `mxfp4` no
+ longer goes through `prepare_model_for_kbit_training`, which would cast the
+ dequantized model to fp32. Two configs that validated before are now
+ refused, neither of which could train: `bnb_4bit_quant_storage` with `mxfp4`
+ (it is a bitsandbytes argument), and `mxfp4` with a local base whose
+ `config.json` does not declare `quant_method: mxfp4`.
+ The hardware-fit calculator (`soup_cli.utils.hardware_fit`) now prices an
+ `mxfp4` base at 2 bytes per parameter, as the bf16 model it loads (it was
+ 0.55). The `soup train` pre-flight does not check `mxfp4` runs, so budget
+ the memory yourself: about 42 GB for a 20B base.
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index c78d9049..b9cd3240 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -350,7 +350,7 @@ training:
| `hqq:Nbit` | 1, 2, 3, 4, 5, 6, 8 | Wide bit range; compose with LoRA. | hqq |
| `aqlm` | 2 | Extreme compression. | aqlm |
| `eetq` | 8 | Fast 8-bit kernel for SM75+. | eetq |
-| `mxfp4` | 4 | Newer 4-bit type with better activation distribution. | bitsandbytes ≥ 0.45 |
+| `mxfp4` | 4 (stored) | Train LoRA on top of an MXFP4 pre-quantized checkpoint (for example GPT-OSS). Loaded with `Mxfp4Config(dequantize=True)`, so it trains in bf16: transformers does not train MXFP4 weights as loaded. Budget memory for the bf16 model, about 2 bytes per parameter (roughly 42 GB for a 20B base); the `soup train` pre-flight does not check `mxfp4` runs. | — |
| `fp8` | — | Train fp16/bf16 on top of FP8-released checkpoints. | transformers ≥ 4.45 |
**Compatibility matrix.** `soup train` runs `check_quant_distributed_compat()` at
diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.py
index 599e1cd2..b05bfff1 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -1218,7 +1218,7 @@ class TrainingConfig(BaseModel):
"gptq / awq (load pre-quantized checkpoint, train LoRA on top), "
"hqq:Nbit (HQQ 1-8 bit, N in {1..6, 8}), "
"aqlm (extreme 2-bit), eetq (8-bit fast), "
- "mxfp4 (BNB 4-bit MXFP4 quant_type), "
+ "mxfp4 (MXFP4 pre-quantized base, dequantized on load), "
"fp8 (load FP8 checkpoint with dequantize-on-load), "
"bitnet_1.58 (reserved until BitNet trainer routing is available)."
),
@@ -4069,17 +4069,16 @@ class TrainingConfig(BaseModel):
@model_validator(mode="after")
def _validate_bnb_quant_storage_only_with_4bit(self) -> "TrainingConfig":
- """v0.38.0 Part G — bnb_4bit_quant_storage applies only to BNB 4-bit
- and MXFP4 (which is a BNB 4-bit variant). Setting it on any other
- format is a silent no-op — fail fast.
+ """v0.38.0 Part G — bnb_4bit_quant_storage applies only to BNB 4-bit.
+ Setting it on any other format is a silent no-op — fail fast. MXFP4
+ is transformers' own format, not a BNB 4-bit variant (#1466).
"""
if self.bnb_4bit_quant_storage is None:
return self
- if self.quantization not in ("4bit", "mxfp4"):
+ if self.quantization != "4bit":
raise ValueError(
f"bnb_4bit_quant_storage={self.bnb_4bit_quant_storage!r} "
- f"requires quantization in {{'4bit', 'mxfp4'}}, got "
- f"{self.quantization!r}."
+ f"requires quantization '4bit', got {self.quantization!r}."
)
return self
diff --git a/src/soup_cli/trainer/bco.py b/src/soup_cli/trainer/bco.py
index 93aba9d4..e37910bb 100644
--- a/src/soup_cli/trainer/bco.py
+++ b/src/soup_cli/trainer/bco.py
@@ -299,7 +299,7 @@ class BCOTrainerWrapper:
self.model,
cfg.data,
)
- if tcfg.quantization in ("4bit", "8bit", "mxfp4"):
+ if tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
self.model = prepare_model_for_kbit_training(
diff --git a/src/soup_cli/trainer/dpo.py b/src/soup_cli/trainer/dpo.py
index 31e30c28..cd31695f 100644
--- a/src/soup_cli/trainer/dpo.py
+++ b/src/soup_cli/trainer/dpo.py
@@ -318,7 +318,7 @@ class DPOTrainerWrapper(StreamingSetupMixin):
self.model,
cfg.data,
)
- if tcfg.quantization in ("4bit", "8bit", "mxfp4"):
+ if tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
self.model = prepare_model_for_kbit_training(
diff --git a/src/soup_cli/trainer/embedding.py b/src/soup_cli/trainer/embedding.py
index b159d3f2..6217144b 100644
--- a/src/soup_cli/trainer/embedding.py
+++ b/src/soup_cli/trainer/embedding.py
@@ -292,7 +292,7 @@ class EmbeddingTrainerWrapper:
# Use AutoModel (not AutoModelForCausalLM) for embedding models
self.model = AutoModel.from_pretrained(cfg.base, **model_kwargs)
- if tcfg.quantization in ("4bit", "8bit", "mxfp4"):
+ if tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
self.model = prepare_model_for_kbit_training(
diff --git a/src/soup_cli/trainer/grpo.py b/src/soup_cli/trainer/grpo.py
index c759dcc1..471c4bb8 100644
--- a/src/soup_cli/trainer/grpo.py
+++ b/src/soup_cli/trainer/grpo.py
@@ -670,7 +670,7 @@ class GRPOTrainerWrapper:
self.model,
cfg.data,
)
- if tcfg.quantization in ("4bit", "8bit", "mxfp4"):
+ if tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
self.model = prepare_model_for_kbit_training(
diff --git a/src/soup_cli/trainer/ipo.py b/src/soup_cli/trainer/ipo.py
index 76f0e0ae..daf92b4b 100644
--- a/src/soup_cli/trainer/ipo.py
+++ b/src/soup_cli/trainer/ipo.py
@@ -245,7 +245,7 @@ class IPOTrainerWrapper:
self.model,
cfg.data,
)
- if tcfg.quantization in ("4bit", "8bit", "mxfp4"):
+ if tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
self.model = prepare_model_for_kbit_training(
diff --git a/src/soup_cli/trainer/kto.py b/src/soup_cli/trainer/kto.py
index 8fc3989f..9b7b1b1e 100644
--- a/src/soup_cli/trainer/kto.py
+++ b/src/soup_cli/trainer/kto.py
@@ -283,7 +283,7 @@ class KTOTrainerWrapper(StreamingSetupMixin):
self.model,
cfg.data,
)
- if tcfg.quantization in ("4bit", "8bit", "mxfp4"):
+ if tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
self.model = prepare_model_for_kbit_training(
diff --git a/src/soup_cli/trainer/online_dpo.py b/src/soup_cli/trainer/online_dpo.py
index 37b13eb4..c4ade074 100644
--- a/src/soup_cli/trainer/online_dpo.py
+++ b/src/soup_cli/trainer/online_dpo.py
@@ -410,7 +410,7 @@ class OnlineDPOTrainerWrapper:
# QLoRA stabilization: k-bit-loaded models need fp32 layer-norm casting +
# input-grad enabling BEFORE LoRA. OnlineDPOTrainer's peft_config path
# does NOT do this internally (unlike DPOTrainer), so do it here.
- if tcfg.quantization in ("4bit", "8bit", "mxfp4"):
+ if tcfg.quantization in ("4bit", "8bit"):
from peft import prepare_model_for_kbit_training
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
diff --git a/src/soup_cli/trainer/orpo.py b/src/soup_cli/trainer/orpo.py
index d72fa35c..1ac42f59 100644
--- a/src/soup_cli/trainer/orpo.py
+++ b/src/soup_cli/trainer/orpo.py
@@ -302,7 +302,7 @@ class ORPOTrainerWrapper(StreamingSetupMixin):
self.model,
cfg.data,
)
- if tcfg.quantization in ("4bit", "8bit", "mxfp4"):
+ if tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
self.model = prepare_model_for_kbit_training(
diff --git a/src/soup_cli/trainer/ppo.py b/src/soup_cli/trainer/ppo.py
index f8e4c987..c115b0ca 100644
--- a/src/soup_cli/trainer/ppo.py
+++ b/src/soup_cli/trainer/ppo.py
@@ -709,7 +709,7 @@ class PPOTrainerWrapper:
self.model = AutoModelForCausalLM.from_pretrained(cfg.base, **model_kwargs)
- if tcfg.quantization in ("4bit", "8bit", "mxfp4"):
+ if tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
self.model = prepare_model_for_kbit_training(
diff --git a/src/soup_cli/trainer/pretrain.py b/src/soup_cli/trainer/pretrain.py
index d08be72c..1c90f91f 100644
--- a/src/soup_cli/trainer/pretrain.py
+++ b/src/soup_cli/trainer/pretrain.py
@@ -375,7 +375,7 @@ class PretrainTrainerWrapper:
f"[green]MoE detected:[/] aux_loss_coeff={tcfg.moe_aux_loss_coeff}"
)
- if tcfg.quantization in ("4bit", "8bit", "mxfp4"):
+ if tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
self.model = prepare_model_for_kbit_training(
diff --git a/src/soup_cli/trainer/reward_model.py b/src/soup_cli/trainer/reward_model.py
index 98489a89..2c385014 100644
--- a/src/soup_cli/trainer/reward_model.py
+++ b/src/soup_cli/trainer/reward_model.py
@@ -247,7 +247,7 @@ class RewardModelTrainerWrapper:
cfg.base, **model_kwargs,
)
- if tcfg.quantize_reward_model and tcfg.quantization in ("4bit", "8bit", "mxfp4"):
+ if tcfg.quantize_reward_model and tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
self.model = prepare_model_for_kbit_training(
diff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.py
index f0f4675f..3a3e10a2 100644
--- a/src/soup_cli/trainer/sft.py
+++ b/src/soup_cli/trainer/sft.py
@@ -1698,7 +1698,7 @@ class SFTTrainerWrapper(StreamingSetupMixin):
f"[green]MoE detected:[/] aux_loss_coeff={tcfg.moe_aux_loss_coeff}"
)
- if tcfg.quantization in ("4bit", "8bit", "mxfp4"):
+ if tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
self.model = prepare_model_for_kbit_training(
@@ -1964,7 +1964,7 @@ class SFTTrainerWrapper(StreamingSetupMixin):
self.model,
cfg.data,
)
- if tcfg.quantization in ("4bit", "8bit", "mxfp4"):
+ if tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
self.model = prepare_model_for_kbit_training(
@@ -2095,7 +2095,7 @@ class SFTTrainerWrapper(StreamingSetupMixin):
self.model,
cfg.data,
)
- if tcfg.quantization in ("4bit", "8bit", "mxfp4"):
+ if tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
self.model = prepare_model_for_kbit_training(
diff --git a/src/soup_cli/trainer/simpo.py b/src/soup_cli/trainer/simpo.py
index 8731f599..bc11e03d 100644
--- a/src/soup_cli/trainer/simpo.py
+++ b/src/soup_cli/trainer/simpo.py
@@ -297,7 +297,7 @@ class SimPOTrainerWrapper(StreamingSetupMixin):
self.model,
cfg.data,
)
- if tcfg.quantization in ("4bit", "8bit", "mxfp4"):
+ if tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
self.model = prepare_model_for_kbit_training(
diff --git a/src/soup_cli/utils/hardware_fit.py b/src/soup_cli/utils/hardware_fit.py
index 8ab38119..175479bb 100644
--- a/src/soup_cli/utils/hardware_fit.py
+++ b/src/soup_cli/utils/hardware_fit.py
@@ -199,7 +199,7 @@ _BYTES_PER_PARAM_BY_QUANT = {
"awq": 0.55,
"aqlm": 0.5,
"eetq": 1.0,
- "mxfp4": 0.55,
+ "mxfp4": 2.0, # #1466: loaded with Mxfp4Config(dequantize=True), so bf16
}
# Optimiser-state bytes per trainable parameter. AdamW = 8 (m + v fp32),
diff --git a/src/soup_cli/utils/quant_menu.py b/src/soup_cli/utils/quant_menu.py
index 84618acc..9daac55b 100644
--- a/src/soup_cli/utils/quant_menu.py
+++ b/src/soup_cli/utils/quant_menu.py
@@ -18,6 +18,7 @@ project-wide input-hardening policy.
from __future__ import annotations
+import json
import os
from typing import TYPE_CHECKING, Any
@@ -231,13 +232,46 @@ def build_eetq_config() -> dict[str, Any]:
def build_mxfp4_config() -> dict[str, Any]:
- """BNB 4-bit MXFP4 quant_type — newer-than-NF4 4-bit format with better
- activation distribution. Requires bitsandbytes >= 0.45 + CUDA.
+ """Dequantize-on-load for MXFP4 checkpoints (transformers ``Mxfp4Config``).
+
+ MXFP4 is not a bitsandbytes ``quant_type`` (bitsandbytes accepts ``nf4``
+ and ``fp4`` only), and transformers will not train an MXFP4 model as
+ loaded: its quantizer points at ``Mxfp4Config(dequantize=True)``. The
+ model then trains in bf16 (#1466).
"""
- return {
- "load_in_4bit": True,
- "bnb_4bit_quant_type": "mxfp4",
- }
+ return {"dequantize": True}
+
+
+def validate_mxfp4_checkpoint(ref: str) -> None:
+ """Best-effort check that ``ref`` resolves to an MXFP4-quantized model.
+
+ A local path must say so in ``config.json``; HF repo IDs are accepted on
+ faith, as for GPTQ and AWQ. Dequantizing a base that was never MXFP4
+ loads it unchanged, so without this a plain local base would train
+ unquantized under a config that says otherwise. Raises ``ValueError``.
+ """
+ if not isinstance(ref, str):
+ raise TypeError(f"MXFP4 ref must be str, got {type(ref).__name__}")
+ _reject_null_bytes(ref, "MXFP4 ref")
+ if not _looks_like_local_path(ref):
+ return
+ method = None
+ try:
+ with open(os.path.join(ref, "config.json"), encoding="utf-8") as handle:
+ quant = json.load(handle).get("quantization_config")
+ if isinstance(quant, dict):
+ method = quant.get("quant_method")
+ except (OSError, ValueError, AttributeError):
+ method = None
+ if method != "mxfp4":
+ # Basename only, matching _check_local_marker.
+ displayed = os.path.basename(os.path.normpath(ref)) or ref
+ raise ValueError(
+ f"quantization: mxfp4 needs an MXFP4 pre-quantized base, but "
+ f"{displayed!r} does not declare quant_method 'mxfp4' in its "
+ "config.json. Point at an MXFP4 checkpoint, or pick another "
+ "quantization (4bit quantizes a plain base at load time)."
+ )
def build_fp8_dequant_config() -> dict[str, Any]:
@@ -467,15 +501,14 @@ def build_quantization_config_for_loader(
)
return EetqConfig()
if quantization == "mxfp4":
- from transformers import BitsAndBytesConfig
+ from transformers import Mxfp4Config
- kwargs = build_mxfp4_config()
- storage = getattr(tcfg, "bnb_4bit_quant_storage", None)
- if storage:
- kwargs["bnb_4bit_quant_storage"] = _resolve_torch_dtype(storage)
+ validate_mxfp4_checkpoint(base)
if console is not None:
- console.print("[green]MXFP4:[/] BNB 4-bit quant_type='mxfp4'")
- return BitsAndBytesConfig(**kwargs)
+ console.print(
+ "[green]MXFP4:[/] pre-quantized checkpoint, dequantize-on-load"
+ )
+ return Mxfp4Config(**build_mxfp4_config())
if quantization == "fp8":
try:
from transformers import FineGrainedFP8Config as _FP8Cfg
diff --git a/tests/test_issue1466_mxfp4.py b/tests/test_issue1466_mxfp4.py
new file mode 100644
index 00000000..b6b803a1
--- /dev/null
+++ b/tests/test_issue1466_mxfp4.py
@@ -0,0 +1,213 @@
+"""#1466: `quantization: mxfp4` must load, not die after the model load.
+
+MXFP4 is transformers' own format (`Mxfp4Config`), not a bitsandbytes
+`quant_type`: bitsandbytes accepts only `nf4` and `fp4`, so the
+`BitsAndBytesConfig(bnb_4bit_quant_type="mxfp4")` Soup used to build was
+rejected for every linear layer, and clashed with the `Mxfp4Config` a
+pre-quantized checkpoint (the one Autopilot passes through) carries.
+transformers also refuses to train an MXFP4 model as loaded and points at
+`Mxfp4Config(dequantize=True)`, which is what the loader now returns.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from soup_cli.config.loader import load_config_from_string
+
+_MXFP4_YAML = """
+base: {base}
+task: sft
+data: {{train: d.jsonl}}
+training: {{quantization: mxfp4}}
+"""
+
+
+def _tiny_llama(path: Path, *, mxfp4: bool) -> str:
+ """A two-layer Llama on disk; `mxfp4` marks its config as the checkpoint
+ of a pre-quantized base does."""
+ import torch
+ import transformers
+
+ config = transformers.LlamaConfig(
+ vocab_size=128,
+ hidden_size=64,
+ intermediate_size=128,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ num_key_value_heads=4,
+ )
+ transformers.LlamaForCausalLM(config).to(torch.bfloat16).save_pretrained(path)
+ if mxfp4:
+ config_path = path / "config.json"
+ raw = json.loads(config_path.read_text(encoding="utf-8"))
+ raw["quantization_config"] = {"quant_method": "mxfp4"}
+ config_path.write_text(json.dumps(raw), encoding="utf-8")
+ return str(path)
+
+
+def _loader_config(base: str):
+ from soup_cli.utils.quant_menu import build_quantization_config_for_loader
+
+ cfg = load_config_from_string(_MXFP4_YAML.format(base=base))
+ return build_quantization_config_for_loader(tcfg=cfg.training, base=cfg.base)
+
+
+class TestLoaderConfig:
+ def test_mxfp4_is_transformers_own_config_dequantized(self, tmp_path):
+ from transformers import BitsAndBytesConfig, Mxfp4Config
+
+ quant = _loader_config(_tiny_llama(tmp_path / "base", mxfp4=True))
+
+ assert isinstance(quant, Mxfp4Config)
+ assert not isinstance(quant, BitsAndBytesConfig)
+ # transformers cannot train an MXFP4 model as loaded.
+ assert quant.dequantize is True
+
+ def test_a_base_marked_mxfp4_loads_with_the_loader_config(self, tmp_path):
+ """The Autopilot pass-through case: the checkpoint says Mxfp4Config."""
+ import torch
+ import transformers
+
+ base = _tiny_llama(tmp_path / "base", mxfp4=True)
+
+ model = transformers.AutoModelForCausalLM.from_pretrained(
+ base, quantization_config=_loader_config(base), dtype=torch.bfloat16
+ )
+
+ assert model.model.layers[0].self_attn.q_proj.weight.dtype == torch.bfloat16
+
+ def test_autopilot_pass_through_round_trips_to_the_same_config(self, tmp_path):
+ from transformers import Mxfp4Config
+
+ from soup_cli.autopilot.decisions import (
+ decide_quantization,
+ detect_prequantized_format,
+ )
+
+ fmt = decide_quantization(
+ 20.0,
+ 80.0,
+ prequantized=detect_prequantized_format(
+ "openai/gpt-oss-20b", {"quantization_config": {"quant_method": "mxfp4"}}
+ ),
+ )
+
+ assert fmt == "mxfp4"
+ base = _tiny_llama(tmp_path / "base", mxfp4=True)
+ assert isinstance(_loader_config(base), Mxfp4Config)
+
+ def test_a_hub_id_is_taken_on_faith(self):
+ from transformers import Mxfp4Config
+
+ assert isinstance(_loader_config("openai/gpt-oss-20b"), Mxfp4Config)
+
+
+class TestLocalBaseThatIsNotMxfp4:
+ def test_a_plain_local_base_is_refused(self, tmp_path):
+ """Dequantizing a base that was never MXFP4 loads it as it is, so the
+ run would train unquantized while the config says otherwise."""
+ base = _tiny_llama(tmp_path / "plain", mxfp4=False)
+
+ with pytest.raises(ValueError, match="mxfp4") as raised:
+ _loader_config(base)
+
+ # The directory name, not the absolute path.
+ # The message shows the name with repr(), which doubles a Windows
+ # path's backslashes: undo that so the check can fail there too.
+ assert str(tmp_path) not in str(raised.value).replace("\\\\", "\\")
+
+ def test_a_local_base_of_another_format_is_refused(self, tmp_path):
+ base = Path(_tiny_llama(tmp_path / "other", mxfp4=False))
+ raw = json.loads((base / "config.json").read_text(encoding="utf-8"))
+ raw["quantization_config"] = {"quant_method": "gptq"}
+ (base / "config.json").write_text(json.dumps(raw), encoding="utf-8")
+
+ with pytest.raises(ValueError, match="mxfp4"):
+ _loader_config(str(base))
+
+
+class TestSchema:
+ def test_quant_storage_is_bitsandbytes_only(self):
+ """`bnb_4bit_quant_storage` is a BitsAndBytesConfig argument; MXFP4
+ has no such field, so it would be a silent no-op."""
+ with pytest.raises(ValueError, match="bnb_4bit_quant_storage"):
+ load_config_from_string(
+ """
+base: m
+task: sft
+data: {train: d.jsonl}
+training: {quantization: mxfp4, bnb_4bit_quant_storage: bfloat16}
+"""
+ )
+
+ def test_the_field_no_longer_calls_mxfp4_a_bnb_type(self):
+ from soup_cli.config.schema import TrainingConfig
+
+ description = TrainingConfig.model_fields["quantization"].description or ""
+ assert "BNB 4-bit MXFP4" not in description
+
+
+class TestKbitPrep:
+ def test_kbit_prep_would_upcast_a_dequantized_model(self, tmp_path):
+ """Why `mxfp4` left the trainers' k-bit tuple (pinned per trainer in
+ test_v0405_part_a.py): the dequantized model is plain bf16, and peft
+ casts every bf16 parameter of a model that is not k-bit to fp32."""
+ import torch
+ import transformers
+ from peft import prepare_model_for_kbit_training
+
+ base = _tiny_llama(tmp_path / "base", mxfp4=True)
+ model = transformers.AutoModelForCausalLM.from_pretrained(
+ base, quantization_config=_loader_config(base), dtype=torch.bfloat16
+ )
+
+ prepared = prepare_model_for_kbit_training(
+ model, use_gradient_checkpointing=False
+ )
+
+ weight = prepared.model.layers[0].self_attn.q_proj.weight
+ assert weight.dtype == torch.float32
+
+
+_TRAINER_DIR = Path(__file__).resolve().parent.parent / "src" / "soup_cli" / "trainer"
+
+
[email protected]("filename", ["sft.py", "online_dpo.py"])
+def test_sft_and_online_dpo_keep_mxfp4_out_of_kbit_prep(filename):
+ """The two trainers `_TRAINER_FILES` in test_v0405_part_a.py does not list."""
+ import re
+
+ src = (_TRAINER_DIR / filename).read_text(encoding="utf-8")
+ assert re.search(r'\(\s*"4bit"\s*,\s*"8bit"\s*\)', src)
+ assert not re.search(r'\(\s*"4bit"\s*,\s*"8bit"\s*,\s*"mxfp4"\s*\)', src)
+
+
+class TestHardwareFit:
+ """The hardware-fit calculator prices what is loaded: a dequantized model is bf16."""
+
+ @staticmethod
+ def _weights_gb(quant: str) -> float:
+ from soup_cli.utils.hardware_fit import HardwareFitInput, estimate_peak_vram_gb
+
+ return estimate_peak_vram_gb(
+ HardwareFitInput(
+ params_b=20.9,
+ seq_len=2048,
+ batch_size=1,
+ optimizer="adamw_torch",
+ quant=quant,
+ peft="lora",
+ gradient_checkpointing=True,
+ )
+ ).weights_gb
+
+ def test_mxfp4_weights_are_priced_as_bf16(self):
+ assert self._weights_gb("mxfp4") == pytest.approx(self._weights_gb("none"))
+
+ def test_a_gpt_oss_20b_sized_base_does_not_pass_as_a_12_gb_load(self):
+ # 20.9B parameters at 2 bytes each; 0.55 bytes each said about 11.5 GB.
+ assert self._weights_gb("mxfp4") == pytest.approx(41.8, rel=0.08)
diff --git a/tests/test_quant_menu.py b/tests/test_quant_menu.py
index 35e15f69..e85ef60f 100644
--- a/tests/test_quant_menu.py
+++ b/tests/test_quant_menu.py
@@ -289,12 +289,11 @@ training: {quantization: mxfp4}
)
assert cfg.training.quantization == "mxfp4"
- def test_build_mxfp4_config_uses_bnb_4bit(self):
+ def test_build_mxfp4_config_dequantizes_on_load(self):
+ # #1466: MXFP4 is transformers' Mxfp4Config, not a BNB quant_type.
from soup_cli.utils.quant_menu import build_mxfp4_config
- cfg = build_mxfp4_config()
- assert cfg["load_in_4bit"] is True
- assert cfg["bnb_4bit_quant_type"] == "mxfp4"
+ assert build_mxfp4_config() == {"dequantize": True}
class TestFP8Dequant:
@@ -355,16 +354,17 @@ training: {quantization: 8bit, bnb_4bit_quant_storage: bfloat16}
"""
)
- def test_quant_storage_with_mxfp4_accepted(self):
- cfg = load_config_from_string(
- """
+ def test_quant_storage_with_mxfp4_rejected(self):
+ # #1466: the storage dtype is a BitsAndBytesConfig argument.
+ with pytest.raises(ValueError, match="bnb_4bit_quant_storage"):
+ load_config_from_string(
+ """
base: m
task: sft
data: {train: d.jsonl}
training: {quantization: mxfp4, bnb_4bit_quant_storage: bfloat16}
"""
- )
- assert cfg.training.bnb_4bit_quant_storage == "bfloat16"
+ )
def test_quant_storage_invalid_dtype_rejected(self):
with pytest.raises(ValueError, match="quant_storage|Input should"):
diff --git a/tests/test_v0405_part_a.py b/tests/test_v0405_part_a.py
index cfb54e99..dd6a2e04 100644
--- a/tests/test_v0405_part_a.py
+++ b/tests/test_v0405_part_a.py
@@ -140,22 +140,24 @@ class TestTrainerSourceWiring:
)
@pytest.mark.parametrize("filename", _TRAINER_FILES)
- def test_trainer_handles_mxfp4_in_kbit_prep(self, filename: str) -> None:
- # mxfp4 is a BNB 4-bit variant — must run through
- # prepare_model_for_kbit_training. Strict regex match on the literal
- # tuple so a stray comment containing "mxfp4" cannot pass the guard.
+ def test_trainer_keeps_mxfp4_out_of_kbit_prep(self, filename: str) -> None:
+ # #1466: mxfp4 is dequantized on load (transformers Mxfp4Config), so
+ # the model is plain bf16 and prepare_model_for_kbit_training would
+ # cast it to fp32. Strict regex match on the literal tuple so a stray
+ # comment containing "mxfp4" cannot pass the guard.
import re
src = (_TRAINER_DIR / filename).read_text(encoding="utf-8")
if "prepare_model_for_kbit_training" not in src:
pytest.skip(f"{filename} doesn't use kbit prep")
- # Match: ("4bit", "8bit", "mxfp4") with arbitrary whitespace.
- pattern = re.compile(
- r'\(\s*"4bit"\s*,\s*"8bit"\s*,\s*"mxfp4"\s*\)'
- )
+ # Match: ("4bit", "8bit") with arbitrary whitespace.
+ pattern = re.compile(r'\(\s*"4bit"\s*,\s*"8bit"\s*\)')
assert pattern.search(src), (
- f"{filename} kbit-prep tuple must be (\"4bit\", \"8bit\", \"mxfp4\")"
+ f"{filename} kbit-prep tuple must be (\"4bit\", \"8bit\")"
)
+ assert not re.search(
+ r'\(\s*"4bit"\s*,\s*"8bit"\s*,\s*"mxfp4"\s*\)', src
+ ), f"{filename} must not run mxfp4 through kbit prep"
# ---------------------------------------------------------------------------
diff --git a/tests/test_v07119.py b/tests/test_v07119.py
index 28caad50..ff41b96c 100644
--- a/tests/test_v07119.py
+++ b/tests/test_v07119.py
@@ -139,7 +139,7 @@ class TestVisionAudioQuantMenuWiring:
def test_vision_setup_still_prepares_kbit(self):
# prepare_model_for_kbit_training is still gated on bnb formats so
- # 4bit/8bit/mxfp4 still run through kbit-prep in vision/audio.
+ # 4bit/8bit still run through kbit-prep in vision/audio.
vision_block = _SFT_SRC.split("def _setup_vision_transformers")[1].split(
"def _prepare_vision_dataset"
)[0]