Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(train): pre-flight the pre-quantized formats and price fp8 as bf16 (#1652) (#1729)
Yang Baid97ec4bde811
diff --git a/changelog.d/0.75.1/1655.fixed.md b/changelog.d/0.75.1/1655.fixed.mdindex 30898e8c..e7320f9f 100644--- a/changelog.d/0.75.1/1655.fixed.md+++ b/changelog.d/0.75.1/1655.fixed.md@@ -6,5 +6,4 @@parameter, and a run that does not fit is refused with one extra sentencesaying the estimate prices the bf16 model. This refuses `mxfp4` configs thatused to start on a card too small for the model; `--allow-oom-attempt`- launches them anyway. The other pre-quantized formats (`gptq`, `awq`,- `hqq:*`, `aqlm`, `eetq`, `fp8`) are still not pre-flighted.+ launches them anyway.diff --git a/changelog.d/0.75.1/1729.changed.md b/changelog.d/0.75.1/1729.changed.mdnew file mode 100644index 00000000..23941a66--- /dev/null+++ b/changelog.d/0.75.1/1729.changed.md@@ -0,0 +1,13 @@+- **The `soup train` VRAM pre-flight now checks the pre-quantized formats+ (#1652 by @ybai08 in #1729).** It used to build its estimate only for+ `none`, `4bit`, `8bit` and `mxfp4`; twelve other formats started without a+ check and without a word. `gptq`, `awq`, `aqlm` and `eetq` are now checked+ at the figures the predictor already had (0.55, 0.55, 0.5 and 1.0 bytes per+ parameter). `fp8` is checked as well, and its figure is corrected from 1.0+ to 2.0: an FP8 base is loaded with `dequantize=True` and trains in bf16, so+ the old figure promised half the memory the run needs. A refused `fp8` run+ gets the sentence an `mxfp4` run gets. `hqq:*` has no figure yet, so the run+ starts and the pre-flight prints `Pre-flight skipped: no memory model for+ quantization: hqq:4bit`. This refuses configs in those five formats that+ used to start on a card too small for the estimate; `--allow-oom-attempt`+ launches them anyway.diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.mdindex 9c8aba95..33e3adb8 100644--- a/docs/backends-and-ops.md+++ b/docs/backends-and-ops.md@@ -1174,6 +1174,8 @@ When it doesn't fit, the report names actionable knobs: `--batch-size halve`, `-The weights bucket assumes 2 bytes/param under `quant="none"` (a frozen base now really does load at the checkpoint's own dtype, typically bf16/fp16 — #339), except `peft="full"` (full fine-tuning), which explicitly loads fp32 master weights and so assumes 4 bytes/param instead.+`mxfp4` and `fp8` are dequantized on load, so they take the same 2 bytes/param. `gptq`, `awq`, `aqlm` and `eetq` stay packed and are priced at their own figures. `soup train` has no figure for `hqq:*` and says it skipped the check ([Quant Menu](performance-and-quantization.md#quant-menu--9-quantization-formats)).+## Shell Completions (`soup completions`)diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.mdindex 625bf0cc..049b7a47 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -368,7 +368,16 @@ training:| `aqlm` | 2 | Extreme compression. | aqlm || `eetq` | 8 | Fast 8-bit kernel for SM75+. | eetq || `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, an estimated 2 bytes per parameter (roughly 42 GB for a 20B base). The `soup train` VRAM pre-flight checks an `mxfp4` run against that estimate, as it does a `quantization: none` run, and `--allow-oom-attempt` launches one it refuses. | — |-| `fp8` | — | Train fp16/bf16 on top of FP8-released checkpoints. | transformers ≥ 4.45 |+| `fp8` | — | Train LoRA on top of an FP8-released checkpoint. Loaded with `FineGrainedFP8Config(dequantize=True)`, so it trains in bf16: budget memory for the bf16 model, an estimated 2 bytes per parameter, not for the FP8 file. | transformers ≥ 4.45 |++**VRAM pre-flight.** Before the model loads, `soup train` prices the weights+of the chosen format and refuses a run that does not fit the card+(`--allow-oom-attempt` launches it anyway). The figures are estimates, in bytes+per parameter: `4bit` 0.5, `8bit` 1.0, `none` 2.0, `gptq` and `awq` 0.55,+`aqlm` 0.5, `eetq` 1.0, and 2.0 for `mxfp4` and `fp8`, which are dequantized on+load. `hqq:*` has no figure yet, so the run starts and the pre-flight prints+`Pre-flight skipped: no memory model for quantization: hqq:4bit` (with the+format you set). No refusal there does not mean the run fits.**Compatibility matrix.** `soup train` runs `check_quant_distributed_compat()` atstartup. HQQ / EETQ / AQLM hard-fail with FSDP and ZeRO-3 (sourced fromdiff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.pyindex b3efa3ac..59fdcf95 100644--- a/src/soup_cli/commands/train.py+++ b/src/soup_cli/commands/train.py@@ -41,6 +41,26 @@ _HW_FIT_OPTIMIZERS = frozenset({"lomo", "adalomo", "schedule_free_adamw",})+# training.quantization -> the hardware-fit predictor's name for it. A value+# that is not here (``hqq:*``) has no memory model, and the pre-flight says it+# skipped the run (#1652).+_HW_FIT_QUANT = {+ "none": "none",+ "4bit": "4bit",+ "8bit": "8bit",+ # Stay packed on the card.+ "gptq": "gptq",+ "awq": "awq",+ "aqlm": "aqlm",+ "eetq": "eetq",+ # Dequantized on load, so priced (and gated) like "none" (#1631, #1652).+ "mxfp4": "mxfp4",+ "fp8": "fp8",+}++# The formats above that train in bf16, and how the gate's panel names them.+_HW_FIT_DEQUANTIZED_ON_LOAD = {"mxfp4": "MXFP4", "fp8": "FP8"}+_UNWIRED_TRAINING_TUNABLES = (# Group B tunables (forgetting_eval_steps, forgetting_benchmark, forgetting_stop,# checkpoint_eval_steps, checkpoint_eval_metric, checkpoint_eval_tasks,@@ -285,11 +305,7 @@ def _build_hardware_fit_input(cfg):seq_len = getattr(cfg.data, "max_length", None)if not isinstance(seq_len, int) or isinstance(seq_len, bool):return None- # #1631: mxfp4 is dequantized on load and trains in bf16, so it is priced- # (and gated) like "none". The formats that stay packed are still skipped.- quant = {"none": "none", "4bit": "4bit", "8bit": "8bit", "mxfp4": "mxfp4"}.get(- str(getattr(tcfg, "quantization", "none") or "none")- )+ quant = _HW_FIT_QUANT.get(str(getattr(tcfg, "quantization", "none") or "none"))if quant is None:return Nonetask = getattr(cfg, "task", None)@@ -349,8 +365,9 @@ def _hardware_fit_preflight(cfg, gpu_info, *, allow_oom_attempt: bool) -> None:"""Refuse (or warn) before launch when the predicted peak VRAM won't fit.Skips silently on CPU / when VRAM is unknown / when the run isn't- statically predictable, so CI and small runs are unaffected. Honors the- documented ``--allow-oom-attempt`` opt-out.+ statically predictable, so CI and small runs are unaffected. A quantization+ the predictor has no figure for is skipped with one line (#1652). Honors+ the documented ``--allow-oom-attempt`` opt-out."""# v0.72.0 — layer streaming bounds peak VRAM by ONE decoder layer, so the# resident prediction (full weights + optimizer + grads on the card) is the@@ -376,6 +393,13 @@ def _hardware_fit_preflight(cfg, gpu_info, *, allow_oom_attempt: bool) -> None:return # no CUDA VRAM to predict againstinp = _build_hardware_fit_input(cfg)if inp is None:+ quantization = str(getattr(cfg.training, "quantization", "none") or "none")+ if quantization not in _HW_FIT_QUANT:+ # #1652: silence here read as "fits".+ console.print(+ "[yellow]Pre-flight skipped:[/] no memory model for "+ f"quantization: {quantization}"+ )returnfrom soup_cli.utils.hardware_fit import VRAM_SAFETY_MARGIN, decide_hardware_fit@@ -384,10 +408,11 @@ def _hardware_fit_preflight(cfg, gpu_info, *, allow_oom_attempt: bool) -> None:returnb = report.breakdown# #1631: a "quantized" run priced like an unquantized one needs a word why.+ dequantized = _HW_FIT_DEQUANTIZED_ON_LOAD.get(inp.quant)note = (- "An MXFP4 base is dequantized on load, so this estimate prices the "- "bf16 model.\n"- if inp.quant == "mxfp4"+ f"An {dequantized} base is dequantized on load, so this estimate prices "+ "the bf16 model.\n"+ if dequantizedelse "")tail = (@@ -1411,7 +1436,8 @@ def train(# Hardware-fit preflight: refuse (unless --allow-oom-attempt) when the# analytical VRAM predictor says the run won't fit. Skips silently on CPU- # or when the config isn't statically predictable (e.g. batch_size='auto').+ # or when the config isn't statically predictable (e.g. batch_size='auto');+ # says so when the quantization has no memory model (hqq:*)._hardware_fit_preflight(cfg, gpu_info, allow_oom_attempt=allow_oom_attempt)backend_label = cfg.backenddiff --git a/src/soup_cli/utils/hardware_fit.py b/src/soup_cli/utils/hardware_fit.pyindex 175479bb..50e93df7 100644--- a/src/soup_cli/utils/hardware_fit.py+++ b/src/soup_cli/utils/hardware_fit.py@@ -194,7 +194,7 @@ _BYTES_PER_PARAM_BY_QUANT = {"none": 2.0, # bf16/fp16"4bit": 0.5,"8bit": 1.0,- "fp8": 1.0,+ "fp8": 2.0, # #1652: FineGrainedFP8Config(dequantize=True), so bf16 too"gptq": 0.55,"awq": 0.55,"aqlm": 0.5,diff --git a/tests/test_issue1631_mxfp4_preflight.py b/tests/test_issue1631_mxfp4_preflight.pyindex 0033b1db..01026b29 100644--- a/tests/test_issue1631_mxfp4_preflight.py+++ b/tests/test_issue1631_mxfp4_preflight.py@@ -72,10 +72,6 @@ class TestTheInput:none.peft,)- @pytest.mark.parametrize("quant", ["gptq", "awq", "aqlm", "eetq", "fp8", "hqq:4bit"])- def test_the_formats_that_stay_packed_are_still_skipped(self, quant):- assert _build_hardware_fit_input(_cfg(quant)) is None-@pytest.mark.parametrize("quant", ["mxfp4", "none"])class TestTheGate:diff --git a/tests/test_issue1652_preflight_prequantized.py b/tests/test_issue1652_preflight_prequantized.pynew file mode 100644index 00000000..0b14a613--- /dev/null+++ b/tests/test_issue1652_preflight_prequantized.py@@ -0,0 +1,311 @@+"""#1652 — the ``soup train`` VRAM pre-flight covers the pre-quantized formats.++``_build_hardware_fit_input`` mapped ``none`` / ``4bit`` / ``8bit`` (and ``mxfp4``+since #1631) and returned ``None`` for the rest, so twelve formats started without+a check and without a word. The predictor already had a figure for five of them.++- ``gptq`` / ``awq`` / ``aqlm`` / ``eetq`` stay packed: priced at the table's figure.+- ``fp8`` is dequantized on load, like ``mxfp4``: priced as bf16. The table said+ 1.0 byte per parameter; a load through the real config holds 2.0.+- ``hqq:*`` has no figure: the pre-flight says it skipped the run.++No GPU here: the gate is called with a card size, and the ``fp8`` load is a tiny+model on CPU.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest+import typer+from rich.text import Text++from soup_cli.commands import train as train_mod+from soup_cli.commands.train import _build_hardware_fit_input, _hardware_fit_preflight+from soup_cli.config.loader import load_config_from_string+from soup_cli.utils.hardware_fit import (+ _BYTES_PER_PARAM_BY_QUANT,+ HardwareFitInput,+ estimate_peak_vram_gb,+)++_YAML = """+base: openai/gpt-oss-20b+task: sft+data:+ train: train.jsonl+ max_length: 2048+training:+ batch_size: {batch_size}+ quantization: {quant}+"""++# A 20B base: 10 GB of weights at the smallest figure (aqlm), 40 GB at bf16.+SMALL_CARD = {"memory_total_bytes": int(8e9)}+LARGE_CARD = {"memory_total_bytes": int(96e9)}++STAY_PACKED = ["gptq", "awq", "aqlm", "eetq"]+PRICED = [*STAY_PACKED, "fp8"]+HQQ = ["hqq:1bit", "hqq:2bit", "hqq:3bit", "hqq:4bit", "hqq:5bit", "hqq:6bit", "hqq:8bit"]+++def _cfg(quant: str, *, batch_size: object = 1):+ return load_config_from_string(_YAML.format(batch_size=batch_size, quant=quant))+++class _Console:+ def __init__(self):+ self.printed = []++ def print(self, renderable):+ self.printed.append(renderable)+++def console(monkeypatch):+ fake = _Console()+ monkeypatch.setattr(train_mod, "console", fake)+ return fake+++def _weights_gb(quant: str) -> float:+ return estimate_peak_vram_gb(+ HardwareFitInput(+ params_b=20.0,+ seq_len=2048,+ batch_size=1,+ optimizer="adamw_torch",+ quant=quant,+ peft="lora",+ gradient_checkpointing=False,+ )+ ).weights_gb+++class TestTheInput:+ @pytest.mark.parametrize("quant", PRICED)+ def test_the_format_gets_an_input_under_its_own_name(self, quant):+ inp = _build_hardware_fit_input(_cfg(quant))+ assert inp is not None+ assert inp.quant == quant++ @pytest.mark.parametrize("quant", PRICED)+ def test_the_format_is_budgeted_the_way_8bit_is(self, quant):+ fmt, eight = _build_hardware_fit_input(_cfg(quant)), _build_hardware_fit_input(_cfg("8bit"))+ assert fmt.peft == eight.peft == "lora"+ assert (fmt.params_b, fmt.seq_len, fmt.batch_size, fmt.optimizer) == (+ eight.params_b,+ eight.seq_len,+ eight.batch_size,+ eight.optimizer,+ )++ @pytest.mark.parametrize("quant", HQQ)+ def test_hqq_still_gets_no_input(self, quant):+ assert _build_hardware_fit_input(_cfg(quant)) is None+++class TestThePrices:+ @pytest.mark.parametrize(+ "quant, bytes_per_param",+ [("gptq", 0.55), ("awq", 0.55), ("aqlm", 0.5), ("eetq", 1.0), ("fp8", 2.0)],+ )+ def test_the_weights_are_priced_at_the_format_s_figure(self, quant, bytes_per_param):+ assert _weights_gb(quant) == pytest.approx(20.0 * bytes_per_param)++ def test_fp8_weights_are_priced_as_bf16(self):+ assert _weights_gb("fp8") == pytest.approx(_weights_gb("none"))+ assert _weights_gb("fp8") == pytest.approx(_weights_gb("mxfp4"))+++def _fp8_checkpoint(path: Path) -> tuple[str, int]:+ """A two-layer Llama whose linear weights are FP8 on disk, written with+ transformers' own ``Fp8Quantize``. Returns the path and its parameter count."""+ import torch+ import transformers+ from safetensors.torch import load_file, save_file+ from transformers.integrations.finegrained_fp8 import Fp8Quantize++ torch.manual_seed(0)+ config = transformers.LlamaConfig(+ vocab_size=256,+ hidden_size=128, # the default 128 x 128 block must divide every linear+ intermediate_size=256,+ num_hidden_layers=2,+ num_attention_heads=4,+ max_position_embeddings=64,+ )+ model = transformers.LlamaForCausalLM(config).to(torch.bfloat16)+ model.save_pretrained(path)+ params = sum(p.numel() for p in model.parameters())++ quant_config = transformers.FineGrainedFP8Config()+ quantize = Fp8Quantize(type("Quantizer", (), {"quantization_config": quant_config})())+ linears = {+ f"{name}.weight"+ for name, module in model.named_modules()+ if isinstance(module, torch.nn.Linear) and name != "lm_head"+ }+ weights_file = path / "model.safetensors"+ tensors = {}+ for key, value in load_file(weights_file).items():+ tensors.update(quantize.convert({key: value}) if key in linears else {key: value})+ save_file(tensors, weights_file, metadata={"format": "pt"})+ # The checkpoint must really be FP8, or the load below proves nothing.+ assert sum(t.dtype == torch.float8_e4m3fn for t in tensors.values()) == len(linears) == 14++ config_file = path / "config.json"+ raw = json.loads(config_file.read_text(encoding="utf-8"))+ raw["quantization_config"] = quant_config.to_dict()+ config_file.write_text(json.dumps(raw), encoding="utf-8")+ return str(path), params+++class TestAnFp8BaseOnceLoaded:+ """The figure in the table is what a load through the real config holds."""++ def test_the_loader_s_config_dequantizes(self, tmp_path):+ import transformers++ from soup_cli.utils.quant_menu import build_quantization_config_for_loader++ base, _ = _fp8_checkpoint(tmp_path / "base")+ quant = build_quantization_config_for_loader(tcfg=_cfg("fp8").training, base=base)+ assert isinstance(quant, transformers.FineGrainedFP8Config)+ assert quant.dequantize is True++ def test_a_loaded_fp8_base_holds_the_bytes_per_parameter_the_table_charges(self, tmp_path):+ import torch+ import transformers+ from packaging.version import Version++ from soup_cli.utils.quant_menu import build_quantization_config_for_loader++ if Version(transformers.__version__) < Version("5.17.0"):+ # 5.16.1 raises AttributeError in the FP8 quantizer's update_tp_plan+ # for any model without MoE experts, before a weight is read.+ pytest.skip("transformers < 5.17.0 cannot load a dense model with an FP8 config")+ base, params = _fp8_checkpoint(tmp_path / "base")+ model = transformers.AutoModelForCausalLM.from_pretrained(+ base,+ torch_dtype="auto", # what Soup passes for a frozen base+ quantization_config=build_quantization_config_for_loader(+ tcfg=_cfg("fp8").training, base=base+ ),+ )+ assert sum(p.numel() for p in model.parameters()) == params+ assert {p.dtype for p in model.parameters()} == {torch.bfloat16}+ held = sum(p.numel() * p.element_size() for p in model.parameters())+ assert held / params == 2.0+ assert _BYTES_PER_PARAM_BY_QUANT["fp8"] == held / params+ assert _BYTES_PER_PARAM_BY_QUANT["fp8"] == _BYTES_PER_PARAM_BY_QUANT["none"]++[email protected]("quant", [*PRICED, "none"])+class TestTheGate:+ """``none`` runs beside the formats as the control."""++ def test_a_card_too_small_for_the_weights_is_refused(self, quant, console):+ with pytest.raises(typer.Exit) as exit_info:+ _hardware_fit_preflight(_cfg(quant), SMALL_CARD, allow_oom_attempt=False)+ assert exit_info.value.exit_code == 1+ assert len(console.printed) == 1+ assert "Predicted peak VRAM" in console.printed[0].renderable++ def test_allow_oom_attempt_warns_and_launches(self, quant, console):+ _hardware_fit_preflight(_cfg(quant), SMALL_CARD, allow_oom_attempt=True)+ assert len(console.printed) == 1+ assert "--allow-oom-attempt set" in console.printed[0].renderable++ def test_a_card_that_fits_is_let_through_without_a_word(self, quant, console):+ _hardware_fit_preflight(_cfg(quant), LARGE_CARD, allow_oom_attempt=False)+ assert console.printed == []+++def test_a_packed_base_fits_where_the_same_base_unquantized_does_not(console):+ # 24 GB: 11 GB of gptq weights fit, 40 GB of bf16 weights do not.+ card = {"memory_total_bytes": int(24e9)}+ _hardware_fit_preflight(_cfg("gptq"), card, allow_oom_attempt=False)+ assert console.printed == []+ with pytest.raises(typer.Exit):+ _hardware_fit_preflight(_cfg("none"), card, allow_oom_attempt=False)+++def _refusal(console, quant: str, *, allow_oom_attempt: bool = False) -> str:+ try:+ _hardware_fit_preflight(_cfg(quant), SMALL_CARD, allow_oom_attempt=allow_oom_attempt)+ except typer.Exit:+ pass+ return console.printed[-1].renderable+++FP8_NOTE = "An FP8 base is dequantized on load, so this estimate prices the bf16 model.\n"+MXFP4_NOTE = "An MXFP4 base is dequantized on load, so this estimate prices the bf16 model.\n"+++class TestTheDequantizedSentence:+ def test_fp8_and_none_are_refused_at_the_same_prediction(self, console):+ fp8, none = _refusal(console, "fp8"), _refusal(console, "none")+ assert "Predicted peak VRAM" in none+ assert fp8.replace(FP8_NOTE, "") == none++ @pytest.mark.parametrize("allow_oom_attempt", [False, True])+ def test_the_fp8_panel_says_the_base_is_dequantized(self, console, allow_oom_attempt):+ panel = _refusal(console, "fp8", allow_oom_attempt=allow_oom_attempt)+ assert panel.count(FP8_NOTE) == 1+ assert "MXFP4" not in panel++ def test_the_mxfp4_panel_keeps_its_own_name(self, console):+ panel = _refusal(console, "mxfp4")+ assert panel.count(MXFP4_NOTE) == 1+ assert "FP8" not in panel++ @pytest.mark.parametrize("quant", STAY_PACKED)+ def test_a_format_that_stays_packed_does_not_get_the_sentence(self, console, quant):+ panel = _refusal(console, quant)+ assert "Predicted peak VRAM" in panel+ assert "dequantized" not in panel+ assert " GB\n\nReduce batch_size" in panel+++def _plain(printed) -> str:+ return Text.from_markup(printed).plain+++class TestTheSkipLine:+ @pytest.mark.parametrize("quant", HQQ)+ @pytest.mark.parametrize("card", [SMALL_CARD, LARGE_CARD])+ @pytest.mark.parametrize("allow_oom_attempt", [False, True])+ def test_hqq_is_let_through_with_one_line_naming_the_format(+ self, console, quant, card, allow_oom_attempt+ ):+ _hardware_fit_preflight(_cfg(quant), card, allow_oom_attempt=allow_oom_attempt)+ assert [_plain(line) for line in console.printed] == [+ f"Pre-flight skipped: no memory model for quantization: {quant}"+ ]++ @pytest.mark.parametrize("quant", [*PRICED, "none", "4bit", "8bit", "mxfp4"])+ def test_a_priced_format_never_gets_the_line(self, console, quant):+ _hardware_fit_preflight(_cfg(quant), LARGE_CARD, allow_oom_attempt=False)+ assert console.printed == []++ @pytest.mark.parametrize("gpu_info", [{}, {"memory_total_bytes": 0}, None])+ def test_no_line_without_a_card_to_check_against(self, console, gpu_info):+ _hardware_fit_preflight(_cfg("hqq:4bit"), gpu_info, allow_oom_attempt=False)+ assert console.printed == []++ @pytest.mark.parametrize("quant", ["gptq", "none"])+ def test_the_other_reason_to_skip_stays_silent(self, console, quant):+ # The line is about the format. batch_size: auto is skipped as before.+ cfg = _cfg(quant, batch_size="auto")+ assert _build_hardware_fit_input(cfg) is None+ _hardware_fit_preflight(cfg, SMALL_CARD, allow_oom_attempt=False)+ assert console.printed == []++ def test_hqq_with_batch_size_auto_still_gets_the_line(self, console):+ _hardware_fit_preflight(+ _cfg("hqq:4bit", batch_size="auto"), SMALL_CARD, allow_oom_attempt=False+ )+ assert len(console.printed) == 1