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(train): apply FP8 on SFT audio and gate streaming and unsloth (#1124) (#1155)

Nurkhan Esenbekcb5bd026a660
diff --git a/changelog.d/0.75.1/1155.changed.md b/changelog.d/0.75.1/1155.changed.md
new file mode 100644
index 00000000..4fa69025
--- /dev/null
+++ b/changelog.d/0.75.1/1155.changed.md
@@ -0,0 +1 @@
+- **FP8 now applies on SFT's audio path, and `stream_layers: true` and `backend: unsloth` refuse FP8 and NVFP4 at config load (#1124 by @kok-o in #1155).** `quantization_aware: fp8` and `fp8_attention: true` loaded on audio SFT and were never applied; `SFTTrainerWrapper._setup_audio_transformers` now converts the model after the LoRA adapter is attached, as the text and vision setups do, so a card that cannot run FP8, or a missing torchao, stops the run at setup instead of training in bf16. `stream_layers: true` (on every task it supports) and `backend: unsloth` (on every task) now refuse `quantization_aware: fp8`, `fp8_attention` and `nvfp4` at config load, because neither path calls the converters: these configs loaded before and trained without the precision they asked for, except the `fp8` combinations on unsloth, which `soup train` already refused before training. The unsloth `fp8` message says to switch to `backend: transformers`.
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index 64812d0c..d2bfb14f 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -249,7 +249,7 @@ training:
Omitting `fp8_recipe` defaults to `tensorwise` (identical to v0.28.0 behavior).
-Bool `true` is not a spelling of FP8: it selected the int8 path, which is refused at config load ([#1222](https://github.com/MakazhanAlpamys/Soup/issues/1222)). FP8 requires CUDA + an Ada or newer GPU (compute capability ≥ 8.9) and is rejected at config load on the mlx backend. (`soup train` refuses it on the unsloth backend: "QAT is not compatible with the unsloth backend".) `soup train --dry-run` reports this machine's card as a note and exits 0, since FP8 configs are often written for another machine; a missing torchao still fails it. The `rowwise` and `rowwise_with_gw_hp` recipes run a separate torch kernel with its own limits: it needs a torch that dispatches it on the card (Ada 8.9: torch ≥ 2.7; Hopper 9.x and Blackwell datacenter 10.x: any supported torch; RTX 50-series 12.x: torch ≥ 2.8; 11.x: torch ≥ 2.10; no release through 2.14 runs it on 13.x), it is **never built on Windows**, and before torch 2.11 it is only built against CUDA 12 or newer. `tensorwise` has none of these limits. When FP8 is requested and this card, OS or torch build cannot run it, **the run stops at setup** with the reason (`FP8HardwareUnsupportedError`), before any layer is converted, on every trainer that reaches the converter; it never trains on without FP8. **A missing torchao stops the run the same way** (`FP8DependencyMissingError`, naming `pip install "soup-cli[qat]"`), on a card that could run FP8 too. So does a float8 conversion that fails: it quotes torchao's error and stops, instead of training in bf16 (#1152). Until this release the trainers printed a yellow advisory and trained in bf16 under a config that said FP8 (#835). `soup train` asks both questions, card first, before it loads the model, so it stops with the same reason and no download. (SFT's audio and layer-streaming setup branches do not call the converter at all, so they still accept the flag without applying it; tracked in #1124.) `fp8_attention` asks the same gate (#835). Wired across every transformer-backend trainer (SFT, DPO, GRPO, KTO, ORPO, SimPO, IPO, PPO, Reward-Model, Embedding, Pretrain).
+Bool `true` is not a spelling of FP8: it selected the int8 path, which is refused at config load ([#1222](https://github.com/MakazhanAlpamys/Soup/issues/1222)). FP8 requires CUDA + an Ada or newer GPU (compute capability ≥ 8.9) and is rejected at config load on the mlx and unsloth backends. `soup train --dry-run` reports this machine's card as a note and exits 0, since FP8 configs are often written for another machine; a missing torchao still fails it. The `rowwise` and `rowwise_with_gw_hp` recipes run a separate torch kernel with its own limits: it needs a torch that dispatches it on the card (Ada 8.9: torch ≥ 2.7; Hopper 9.x and Blackwell datacenter 10.x: any supported torch; RTX 50-series 12.x: torch ≥ 2.8; 11.x: torch ≥ 2.10; no release through 2.14 runs it on 13.x), it is **never built on Windows**, and before torch 2.11 it is only built against CUDA 12 or newer. `tensorwise` has none of these limits. When FP8 is requested and this card, OS or torch build cannot run it, **the run stops at setup** with the reason (`FP8HardwareUnsupportedError`), before any layer is converted, on every trainer that reaches the converter; it never trains on without FP8. **A missing torchao stops the run the same way** (`FP8DependencyMissingError`, naming `pip install "soup-cli[qat]"`), on a card that could run FP8 too. So does a float8 conversion that fails: it quotes torchao's error and stops, instead of training in bf16 (#1152). Until this release the trainers printed a yellow advisory and trained in bf16 under a config that said FP8 (#835). `soup train` asks both questions, card first, before it loads the model, so it stops with the same reason and no download. SFT's text, vision and audio setups all convert the model after the LoRA adapter is attached. `stream_layers: true` refuses `quantization_aware: fp8`, `fp8_attention` and `nvfp4` at config load on every task, and so does `backend: unsloth`: neither path calls the converters (#1124). `fp8_attention` asks the same gate (#835). Wired across every transformer-backend trainer (SFT, DPO, GRPO, KTO, ORPO, SimPO, IPO, PPO, Reward-Model, Embedding, Pretrain).
## Cut Cross-Entropy (Large-Vocab Models)
@@ -1199,8 +1199,8 @@ soup serve --model ./output --kv-cache-type q8_0 # 8-bit quantized KV cache
Three TrainingConfig bools extend the v0.28.0 FP8 menu. `fp8_attention` and `nvfp4` are LIVE
torchao converters as of v0.71.21 (hardware-gated):
-- `fp8_attention: true` — requires `quantization_aware: fp8` AND a non-MLX backend. Converts the attention projections (q/k/v/o and fused variants) to torchao float8 training on Ada or newer GPUs (the same gate as `quantization_aware: fp8`). A card, OS or torch build the gate refuses stops the run at setup, and so does a missing torchao (#835); a conversion-phase failure raises an honest "model may be PARTIALLY converted" error instead of training on a half-converted model, and a model with no attention projections stops too, instead of training on as a no-op (#1152).
-- `nvfp4: true` — Blackwell-only FP4 training via torchao `NVFP4TrainingConfig` + `quantize_`, which replaces `nn.Linear` with `NVFP4Linear` and quantises the forward **and backward** GEMMs. (Through v0.75.0 Soup asked for `NVFP4Config`, a name torchao has never exported, so the flag degraded to a yellow advisory and a bf16 run — #826.) Gated to supported tasks (rejected on `task: distill` and tasks without v0.28 speed/memory wiring) + non-MLX + `modality: text`; the SM ≥ 10 runtime check fires at trainer construction. The fix makes the flag **reach** NVFP4 training — the linears really are replaced by `NVFP4Linear`. A training step on top of that has torchao's own requirements, which Soup does not check for you: the kernels are triton, and `nvfp4_mm_triton` raises `ValueError: requires M, K, N all divisible by 128` for a shape it cannot serve (`torchao/prototype/moe_training/nvfp4_training/nvfp4_linear.py`), so a model whose hidden/intermediate sizes are not multiples of 128 will fail there rather than train slowly.
+- `fp8_attention: true` — requires `quantization_aware: fp8` AND a non-MLX, non-Unsloth backend (incompatible with `stream_layers: true`). Converts the attention projections (q/k/v/o and fused variants) to torchao float8 training on Ada or newer GPUs (the same gate as `quantization_aware: fp8`). A card, OS or torch build the gate refuses stops the run at setup, and so does a missing torchao (#835); a conversion-phase failure raises an honest "model may be PARTIALLY converted" error instead of training on a half-converted model, and a model with no attention projections stops too, instead of training on as a no-op (#1152).
+- `nvfp4: true` — Blackwell-only FP4 training via torchao `NVFP4TrainingConfig` + `quantize_`, which replaces `nn.Linear` with `NVFP4Linear` and quantises the forward **and backward** GEMMs. (Through v0.75.0 Soup asked for `NVFP4Config`, a name torchao has never exported, so the flag degraded to a yellow advisory and a bf16 run — #826.) Gated to supported tasks (rejected on `task: distill` and tasks without v0.28 speed/memory wiring) + non-MLX, non-Unsloth + `modality: text` (incompatible with `stream_layers: true`); the SM ≥ 10 runtime check fires at trainer construction. The fix makes the flag **reach** NVFP4 training — the linears really are replaced by `NVFP4Linear`. A training step on top of that has torchao's own requirements, which Soup does not check for you: the kernels are triton, and `nvfp4_mm_triton` raises `ValueError: requires M, K, N all divisible by 128` for a shape it cannot serve (`torchao/prototype/moe_training/nvfp4_training/nvfp4_linear.py`), so a model whose hidden/intermediate sizes are not multiples of 128 will fail there rather than train slowly.
- `unsloth_bnb_4bit: true` — promotes "Unsloth Dynamic 4-bit" from an implicit `backend=unsloth + quantization=4bit` combo to a named flag. Mutual rejection of inconsistent combos at config load.
Cross-validator ordering picks the most actionable error: `quantization_aware='fp8'` prerequisite fires before the MLX rejection on `fp8_attention`, and task compatibility checks fire at config load before runtime trainer construction.
diff --git a/src/soup_cli/config/backend_support.py b/src/soup_cli/config/backend_support.py
index 191d0c63..192268c2 100644
--- a/src/soup_cli/config/backend_support.py
+++ b/src/soup_cli/config/backend_support.py
@@ -18,8 +18,9 @@ drift -- every entry must name a real field, and every dotted field name in
``trainer/mlx_sft.py``'s own warning list must appear here. It cannot originate
the truth; it can only stop it rotting, which is the failure that produced #749.
-Scope today: ``task=sft`` on ``backend=mlx``, plus multimodal vision and audio
-on ``backend=transformers`` (#1156). Other combinations report nothing rather
+Scope today: ``task=sft`` on ``backend=mlx`` and on ``backend=unsloth`` (#1124;
+both apply to every modality), plus multimodal vision and audio on
+``backend=transformers`` (#1156). Other combinations report nothing rather
than guessing, which is the honest default for a table that has not been
reviewed for them.
"""
@@ -29,6 +30,10 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
+from soup_cli.utils.advanced_precision import (
+ UNSLOTH_PRECISION_INCOMPATIBLE_REASON,
+)
+
if TYPE_CHECKING: # pragma: no cover - typing only
from soup_cli.config.schema import SoupConfig
@@ -234,9 +239,34 @@ _TRANSFORMERS_AUDIO_SFT: tuple[SupportEntry, ...] = (
)
+_UNSLOTH_SFT: tuple[SupportEntry, ...] = (
+ SupportEntry(
+ "training.quantization_aware",
+ REJECTED,
+ f"QAT and FP8 training are not compatible with the unsloth backend "
+ f"({UNSLOTH_PRECISION_INCOMPATIBLE_REASON})",
+ issue=1124,
+ ),
+ SupportEntry(
+ "training.fp8_attention",
+ REJECTED,
+ f"fp8_attention is not supported on backend=unsloth "
+ f"({UNSLOTH_PRECISION_INCOMPATIBLE_REASON})",
+ issue=1124,
+ ),
+ SupportEntry(
+ "training.nvfp4",
+ REJECTED,
+ f"nvfp4 is not supported on backend=unsloth ({UNSLOTH_PRECISION_INCOMPATIBLE_REASON})",
+ issue=1124,
+ ),
+)
+
+
#: ``(task, backend, modality)`` -> the settings that combination does not honour.
REGISTRY: dict[tuple[str, str, str], tuple[SupportEntry, ...]] = {
("sft", "mlx", "text"): _MLX_SFT,
+ ("sft", "unsloth", "text"): _UNSLOTH_SFT,
("sft", "transformers", "vision"): _TRANSFORMERS_VISION_SFT,
("sft", "transformers", "audio"): _TRANSFORMERS_AUDIO_SFT,
}
@@ -265,6 +295,10 @@ TRAINER_MODULES: dict[tuple[str, str, str], tuple[str, ...]] = {
"soup_cli/trainer/rewind_mlx.py",
"soup_cli/trainer/loss_summary.py",
),
+ # utils/unsloth.py handles the loader path. trainer/sft.py::_setup_unsloth is not listed
+ # here because listing sft.py would cause the drift guard to inspect transformers-only
+ # precision reads; an AST test in test_issue1124 guards _setup_unsloth instead.
+ ("sft", "unsloth", "text"): ("soup_cli/utils/unsloth.py",),
("sft", "transformers", "vision"): _TRANSFORMERS_SFT_MODULES,
("sft", "transformers", "audio"): _TRANSFORMERS_SFT_MODULES,
}
@@ -276,8 +310,9 @@ def unsupported_for(
"""Every declared gap for a task/backend/modality combination, or ``()`` if unreviewed."""
if (task, backend, modality) in REGISTRY:
return REGISTRY[(task, backend, modality)]
- # MLX has no modality-specific trainers; its SFT gaps apply to any modality setting.
- if backend == "mlx":
+ # MLX and Unsloth have no modality-specific trainers; their SFT gaps
+ # apply to any modality setting.
+ if backend in ("mlx", "unsloth"):
return REGISTRY.get((task, backend, DEFAULT_MODALITY), ())
return ()
diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.py
index 4178fe4a..df43c888 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -5084,6 +5084,16 @@ class SoupConfig(BaseModel):
from soup_cli.utils.v028_features import supports_v028_features
if supports_v028_features(self.task) and self.backend != "mlx":
+ if self.backend == "unsloth" and self.training.quantization_aware == "fp8":
+ from soup_cli.utils.advanced_precision import (
+ UNSLOTH_PRECISION_INCOMPATIBLE_REASON,
+ )
+
+ raise ValueError(
+ 'v0.28.0 features [\'quantization_aware="fp8"\'] are not supported on the '
+ f"unsloth backend ({UNSLOTH_PRECISION_INCOMPATIBLE_REASON}). "
+ "Switch to backend='transformers' or remove these flags."
+ )
return self
tcfg = self.training
offenders: list[str] = []
@@ -6297,6 +6307,12 @@ class SoupConfig(BaseModel):
conflicts.append("train_router_only")
if tcfg.expand_layers is not None:
conflicts.append("expand_layers")
+ if tcfg.quantization_aware:
+ conflicts.append("quantization_aware")
+ if tcfg.fp8_attention:
+ conflicts.append("fp8_attention")
+ if tcfg.nvfp4:
+ conflicts.append("nvfp4")
if conflicts:
raise ValueError(
f"training.stream_layers is mutually exclusive with "
diff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.py
index c5e8be30..1ae6c3a3 100644
--- a/src/soup_cli/trainer/sft.py
+++ b/src/soup_cli/trainer/sft.py
@@ -2111,6 +2111,8 @@ class SFTTrainerWrapper(StreamingSetupMixin):
)
self.model = get_peft_model(self.model, lora_config)
+ self._apply_quantization_aware(tcfg)
+
def _prepare_audio_dataset(self, dataset: dict):
"""Prepare dataset for audio fine-tuning with audio loading."""
from datasets import Dataset
diff --git a/src/soup_cli/utils/advanced_precision.py b/src/soup_cli/utils/advanced_precision.py
index 861d53c7..99e1eeaa 100644
--- a/src/soup_cli/utils/advanced_precision.py
+++ b/src/soup_cli/utils/advanced_precision.py
@@ -47,6 +47,9 @@ _ATTENTION_PROJ_NAMES: frozenset[str] = frozenset({
# Blackwell-family; Hopper is SM 9.x.
_BLACKWELL_MIN_CC_MAJOR = 10
+#: Shared diagnostic explanation for precision feature incompatibility with Unsloth (#1124).
+UNSLOTH_PRECISION_INCOMPATIBLE_REASON: str = "unsloth uses its own fused kernels"
+
def is_attention_projection(fqn: object) -> bool:
"""Return True when ``fqn``'s last component names an attention projection.
@@ -136,6 +139,11 @@ def validate_fp8_attention_compat(
raise ValueError(
"fp8_attention=true is not supported on backend=mlx"
)
+ if backend == "unsloth":
+ raise ValueError(
+ "fp8_attention=true is not supported on backend=unsloth "
+ f"({UNSLOTH_PRECISION_INCOMPATIBLE_REASON})"
+ )
def validate_nvfp4_compat(
@@ -164,6 +172,11 @@ def validate_nvfp4_compat(
"nvfp4=true is not supported on backend=mlx "
"(NVFP4 is CUDA-only — requires Blackwell)"
)
+ if backend == "unsloth":
+ raise ValueError(
+ "nvfp4=true is not supported on backend=unsloth "
+ f"({UNSLOTH_PRECISION_INCOMPATIBLE_REASON})"
+ )
if modality != "text":
raise ValueError(
f"nvfp4=true is wired for modality='text' only; "
diff --git a/tests/test_issue1124_sft_audio_stream_unsloth_fp8.py b/tests/test_issue1124_sft_audio_stream_unsloth_fp8.py
new file mode 100644
index 00000000..a5a50b56
--- /dev/null
+++ b/tests/test_issue1124_sft_audio_stream_unsloth_fp8.py
@@ -0,0 +1,451 @@
+"""Tests for issue #1124 - SFT audio FP8 wiring and stream_layers/unsloth gating.
+
+Validates that:
+1. SFTTrainerWrapper._setup_audio_transformers calls _apply_quantization_aware(tcfg)
+ post-LoRA, bringing audio SFT to parity with text SFT for FP8/NVFP4.
+2. stream_layers: true is mutually exclusive with quantization_aware, fp8_attention,
+ and nvfp4 at schema validation time.
+3. backend: unsloth rejects quantization_aware: fp8, fp8_attention, and nvfp4
+ at schema validation time with actionable diagnostics.
+4. validate_fp8_attention_compat and validate_nvfp4_compat reject unsloth.
+5. backend_support declares ("sft", "unsloth", "text") with REJECTED status for precision knobs.
+"""
+
+from __future__ import annotations
+
+import ast
+import sys
+import types
+from pathlib import Path
+from unittest.mock import MagicMock
+
+import pytest
+
+from soup_cli.config.backend_support import (
+ REGISTRY,
+ TRAINER_MODULES,
+ check_config,
+ unsupported_for,
+)
+from soup_cli.config.schema import SoupConfig
+from soup_cli.trainer.sft import SFTTrainerWrapper
+from soup_cli.utils.advanced_precision import (
+ validate_fp8_attention_compat,
+ validate_nvfp4_compat,
+)
+
+
+class TestSFTAudioFP8Wiring:
+ """Test that SFTTrainerWrapper applies quantization_aware post-LoRA on audio."""
+
+ def test_audio_sft_stops_at_setup_on_unsupported_card(self, monkeypatch) -> None:
+ """Driving the real setup (Issue #1124 AC2): on an sm86 card, SFT audio setup
+ with quantization_aware='fp8' must stop at setup with FP8HardwareUnsupportedError.
+ On main, this silently ran without error because _apply_quantization_aware was never called.
+ """
+ import torch
+ import torch.nn as nn
+
+ from soup_cli.utils.fp8 import FP8HardwareUnsupportedError
+
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *_a, **_k: (8, 6))
+
+ cfg = SoupConfig(
+ base="test/audio-model",
+ task="sft",
+ modality="audio",
+ data={"train": "tests/fixtures/sample_train.jsonl", "format": "audio"},
+ training={"quantization_aware": "fp8"},
+ )
+
+ class _MockModel(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.proj = nn.Linear(4, 4)
+
+ fake_model = _MockModel()
+ fake_processor = MagicMock()
+
+ fake_peft = types.SimpleNamespace(
+ LoraConfig=lambda **kwargs: types.SimpleNamespace(**kwargs),
+ get_peft_model=lambda m, *a, **kw: m,
+ prepare_model_for_kbit_training=lambda m, **kw: m,
+ )
+ fake_transformers = types.SimpleNamespace(
+ AutoModel=types.SimpleNamespace(from_pretrained=MagicMock(return_value=fake_model)),
+ AutoProcessor=types.SimpleNamespace(
+ from_pretrained=MagicMock(return_value=fake_processor)
+ ),
+ TrainingArguments=MagicMock(),
+ )
+
+ monkeypatch.setitem(sys.modules, "peft", fake_peft)
+ monkeypatch.setitem(sys.modules, "transformers", fake_transformers)
+ monkeypatch.setattr(
+ "soup_cli.utils.quant_menu.build_quantization_config_for_loader",
+ lambda **kw: None,
+ )
+ monkeypatch.setattr(
+ "soup_cli.utils.data_pipeline.apply_vocab_expansion",
+ lambda *a, **kw: None,
+ )
+ monkeypatch.setattr(
+ "soup_cli.trainer.sft.resolve_device_map",
+ lambda d: None,
+ )
+
+ wrapper = object.__new__(SFTTrainerWrapper)
+ wrapper.config = cfg
+ wrapper.device = "cuda:0"
+ wrapper._trust_remote_code = False
+ wrapper.model = None
+ wrapper.processor = None
+ wrapper.tokenizer = None
+
+ with pytest.raises(FP8HardwareUnsupportedError, match="8.9"):
+ wrapper._setup_audio_transformers(cfg, cfg.training)
+
+ def test_audio_setup_converts_the_lora_wrapped_model(self, monkeypatch) -> None:
+ """The converter must see the post-LoRA wrapper, not the bare base model."""
+ import torch.nn as nn
+
+ cfg = SoupConfig(
+ base="test/audio-model",
+ task="sft",
+ modality="audio",
+ data={"train": "tests/fixtures/sample_train.jsonl", "format": "audio"},
+ training={"quantization_aware": "fp8"},
+ )
+
+ class _MockBaseModel(nn.Module):
+ pass
+
+ class _MockLoraWrapper(nn.Module):
+ def __init__(self, base):
+ super().__init__()
+ self.base = base
+
+ base_model = _MockBaseModel()
+ lora_wrapped = _MockLoraWrapper(base_model)
+
+ fake_peft = types.SimpleNamespace(
+ LoraConfig=lambda **kwargs: types.SimpleNamespace(**kwargs),
+ get_peft_model=lambda m, *a, **kw: lora_wrapped,
+ prepare_model_for_kbit_training=lambda m, **kw: m,
+ )
+ fake_transformers = types.SimpleNamespace(
+ AutoModel=types.SimpleNamespace(from_pretrained=MagicMock(return_value=base_model)),
+ AutoProcessor=types.SimpleNamespace(from_pretrained=MagicMock()),
+ TrainingArguments=MagicMock(),
+ )
+
+ monkeypatch.setitem(sys.modules, "peft", fake_peft)
+ monkeypatch.setitem(sys.modules, "transformers", fake_transformers)
+ monkeypatch.setattr(
+ "soup_cli.utils.quant_menu.build_quantization_config_for_loader",
+ lambda **kw: None,
+ )
+ monkeypatch.setattr(
+ "soup_cli.utils.data_pipeline.apply_vocab_expansion",
+ lambda *a, **kw: None,
+ )
+ monkeypatch.setattr(
+ "soup_cli.trainer.sft.resolve_device_map",
+ lambda d: None,
+ )
+
+ model_seen_by_converter = None
+
+ def fake_apply_qat(tcfg):
+ nonlocal model_seen_by_converter
+ model_seen_by_converter = wrapper.model
+
+ wrapper = object.__new__(SFTTrainerWrapper)
+ wrapper.config = cfg
+ wrapper.device = "cpu"
+ wrapper._trust_remote_code = False
+ wrapper.model = None
+ wrapper.processor = None
+ wrapper.tokenizer = None
+ wrapper._apply_quantization_aware = fake_apply_qat
+
+ wrapper._setup_audio_transformers(cfg, cfg.training)
+
+ assert model_seen_by_converter is lora_wrapped, (
+ "_apply_quantization_aware was called on base model instead of the "
+ "LoRA-wrapped model (must run after get_peft_model)"
+ )
+ assert model_seen_by_converter is not base_model
+
+ def test_audio_setup_source_structure(self) -> None:
+ """Kill mutation: ensure _setup_audio_transformers calls
+ _apply_quantization_aware post-LoRA.
+ """
+ sft_path = Path(__file__).resolve().parents[1] / "src/soup_cli/trainer/sft.py"
+ tree = ast.parse(sft_path.read_text(encoding="utf-8"))
+
+ setup_audio_func = None
+ for node in ast.walk(tree):
+ if isinstance(node, ast.FunctionDef) and node.name == "_setup_audio_transformers":
+ setup_audio_func = node
+ break
+
+ assert setup_audio_func is not None, "_setup_audio_transformers not found in sft.py"
+
+ peft_idx = None
+ qat_idx = None
+ for i, node in enumerate(setup_audio_func.body):
+ if isinstance(node, ast.Assign):
+ if any(isinstance(t, ast.Attribute) and t.attr == "model" for t in node.targets):
+ if (
+ isinstance(node.value, ast.Call)
+ and getattr(node.value.func, "id", None) == "get_peft_model"
+ ):
+ peft_idx = i
+ if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):
+ if (
+ isinstance(node.value.func, ast.Attribute)
+ and node.value.func.attr == "_apply_quantization_aware"
+ ):
+ qat_idx = i
+
+ assert peft_idx is not None, "get_peft_model assignment not found"
+ assert qat_idx is not None, "_apply_quantization_aware call not found"
+ assert peft_idx < qat_idx, (
+ "Mutation kill: _apply_quantization_aware must be called after "
+ "get_peft_model in _setup_audio_transformers"
+ )
+
+
+class TestStreamLayersPrecisionConflicts:
+ """Test schema mutual exclusivity for stream_layers with FP8/NVFP4."""
+
+ def test_stream_layers_rejects_quantization_aware_fp8(self) -> None:
+ pattern = r"stream_layers is mutually exclusive with quantization_aware"
+ with pytest.raises(ValueError, match=pattern):
+ SoupConfig(
+ base="test/model",
+ task="sft",
+ data={"train": "tests/fixtures/sample_train.jsonl"},
+ training={
+ "stream_layers": True,
+ "batch_size": 1,
+ "quantization_aware": "fp8",
+ },
+ )
+
+ def test_stream_layers_with_quantization_aware_true_is_refused_by_1222(self) -> None:
+ """`true` never reaches the streaming guard: #1222 refuses it at the field."""
+ pattern = r"quantization_aware: true is refused \(#1222\)"
+ with pytest.raises(ValueError, match=pattern):
+ SoupConfig(
+ base="test/model",
+ task="sft",
+ data={"train": "tests/fixtures/sample_train.jsonl"},
+ training={
+ "stream_layers": True,
+ "batch_size": 1,
+ "quantization_aware": True,
+ },
+ )
+
+ def test_stream_layers_rejects_fp8_attention(self) -> None:
+ pattern = r"stream_layers is mutually exclusive with fp8_attention"
+ with pytest.raises(ValueError, match=pattern):
+ SoupConfig(
+ base="test/model",
+ task="sft",
+ data={"train": "tests/fixtures/sample_train.jsonl"},
+ training={
+ "stream_layers": True,
+ "batch_size": 1,
+ "fp8_attention": True,
+ },
+ )
+
+ def test_stream_layers_rejects_nvfp4(self) -> None:
+ pattern = r"stream_layers is mutually exclusive with nvfp4"
+ with pytest.raises(ValueError, match=pattern):
+ SoupConfig(
+ base="test/model",
+ task="sft",
+ data={"train": "tests/fixtures/sample_train.jsonl"},
+ training={
+ "stream_layers": True,
+ "batch_size": 1,
+ "nvfp4": True,
+ },
+ )
+
+
+class TestUnslothPrecisionRejections:
+ """Test unsloth backend rejection of quantization_aware: fp8, fp8_attention, nvfp4."""
+
+ def test_unsloth_rejects_quantization_aware_fp8(self) -> None:
+ pattern = r"quantization_aware.*not supported on the unsloth backend"
+ with pytest.raises(ValueError, match=pattern):
+ SoupConfig(
+ base="test/model",
+ task="sft",
+ backend="unsloth",
+ data={"train": "tests/fixtures/sample_train.jsonl"},
+ training={"quantization_aware": "fp8"},
+ )
+
+ def test_unsloth_rejects_fp8_attention(self) -> None:
+ pattern = r"quantization_aware.*not supported on the unsloth backend"
+ with pytest.raises(ValueError, match=pattern):
+ SoupConfig(
+ base="test/model",
+ task="sft",
+ backend="unsloth",
+ data={"train": "tests/fixtures/sample_train.jsonl"},
+ training={"quantization_aware": "fp8", "fp8_attention": True},
+ )
+
+ def test_unsloth_rejects_fp8_attention_without_qa_reports_qa_prereq_first(
+ self,
+ ) -> None:
+ """Actionable order: prerequisite quantization_aware='fp8' fires first."""
+ with pytest.raises(ValueError, match=r"requires training\.quantization_aware='fp8'"):
+ SoupConfig(
+ base="test/model",
+ task="sft",
+ backend="unsloth",
+ data={"train": "tests/fixtures/sample_train.jsonl"},
+ training={"fp8_attention": True},
+ )
+
+ def test_unsloth_rejects_nvfp4(self) -> None:
+ with pytest.raises(ValueError, match=r"nvfp4=true is not supported on backend=unsloth"):
+ SoupConfig(
+ base="test/model",
+ task="sft",
+ backend="unsloth",
+ data={"train": "tests/fixtures/sample_train.jsonl"},
+ training={"nvfp4": True},
+ )
+
+ def test_validate_fp8_attention_compat_rejects_unsloth(self) -> None:
+ pattern = r"backend=unsloth.*unsloth uses its own fused kernels"
+ with pytest.raises(ValueError, match=pattern):
+ validate_fp8_attention_compat(
+ fp8_attention=True,
+ quantization_aware="fp8",
+ backend="unsloth",
+ )
+
+ def test_validate_nvfp4_compat_rejects_unsloth(self) -> None:
+ pattern = r"backend=unsloth.*unsloth uses its own fused kernels"
+ with pytest.raises(ValueError, match=pattern):
+ validate_nvfp4_compat(
+ nvfp4=True,
+ backend="unsloth",
+ modality="text",
+ )
+
+ def test_unsloth_permits_cut_ce_and_activation_offloading(self) -> None:
+ """Control: unsloth validation only refuses FP8/NVFP4, NOT cut_ce
+ or activation offloading.
+ """
+ cfg_cut_ce = SoupConfig(
+ base="test/model",
+ backend="unsloth",
+ task="sft",
+ data={"train": "tests/fixtures/sample_train.jsonl"},
+ training={"use_cut_ce": True},
+ )
+ assert cfg_cut_ce.training.use_cut_ce is True
+
+ cfg_offload = SoupConfig(
+ base="test/model",
+ backend="unsloth",
+ task="sft",
+ data={"train": "tests/fixtures/sample_train.jsonl"},
+ training={"activation_offloading": "cpu"},
+ )
+ assert cfg_offload.training.activation_offloading == "cpu"
+
+
+class TestBackendSupportRegistryUnsloth:
+ """Test that backend_support registers unsloth SFT rejected entries."""
+
+ def test_unsloth_sft_registered(self) -> None:
+ assert ("sft", "unsloth", "text") in REGISTRY
+ entries = unsupported_for("sft", "unsloth")
+ fields = {e.field: e.status for e in entries}
+ assert fields.get("training.quantization_aware") == "rejected"
+ assert fields.get("training.fp8_attention") == "rejected"
+ assert fields.get("training.nvfp4") == "rejected"
+ assert all(e.issue == 1124 for e in entries)
+
+ entries_vision = unsupported_for("sft", "unsloth", "vision")
+ assert len(entries_vision) == len(entries)
+ fields_vision = {e.field: e.status for e in entries_vision}
+ assert fields_vision.get("training.quantization_aware") == "rejected"
+
+ def test_unsloth_sft_in_trainer_modules(self) -> None:
+ assert ("sft", "unsloth", "text") in TRAINER_MODULES
+ modules = TRAINER_MODULES[("sft", "unsloth", "text")]
+ assert "soup_cli/utils/unsloth.py" in modules
+
+ @pytest.mark.parametrize(
+ ("value", "reason"),
+ [
+ (True, r"quantization_aware: true is refused \(#1222\)"),
+ ("fp8", r"not supported on the unsloth backend"),
+ ("quest", r"quantization_aware='quest' requires backend='transformers'"),
+ ],
+ )
+ @pytest.mark.parametrize("modality", ["text", "vision"])
+ def test_no_loadable_unsloth_config_sets_quantization_aware(
+ self, value, reason, modality
+ ) -> None:
+ """Every value of the field is refused at load on unsloth, so the REJECTED
+ row documents the gap rather than reporting it (as the MLX row for #961)."""
+ data = {"train": "tests/fixtures/sample_train.jsonl"}
+ if modality == "vision":
+ data["format"] = "multimodal"
+ with pytest.raises(ValueError, match=reason):
+ SoupConfig(
+ base="test/model",
+ task="sft",
+ backend="unsloth",
+ modality=modality,
+ data=data,
+ training={"quantization_aware": value},
+ )
+
+ @pytest.mark.parametrize("modality", ["text", "vision"])
+ def test_check_config_on_a_loadable_unsloth_config_reports_no_precision_gap(
+ self, modality
+ ) -> None:
+ data = {"train": "tests/fixtures/sample_train.jsonl"}
+ if modality == "vision":
+ data["format"] = "multimodal"
+ cfg = SoupConfig(
+ base="test/model", task="sft", backend="unsloth", modality=modality, data=data
+ )
+ assert unsupported_for("sft", "unsloth", modality), "fallback must cover the modality"
+ assert check_config(cfg) == []
+
+ def test_setup_unsloth_does_not_wire_fp8_silently(self) -> None:
+ """AST guard: SFTTrainerWrapper._setup_unsloth must not wire precision knobs
+ while ("sft", "unsloth", "text") declares them REJECTED in backend_support.
+ """
+ sft_path = Path(__file__).resolve().parents[1] / "src/soup_cli/trainer/sft.py"
+ tree = ast.parse(sft_path.read_text(encoding="utf-8"))
+
+ setup_unsloth = None
+ for node in ast.walk(tree):
+ if isinstance(node, ast.FunctionDef) and node.name == "_setup_unsloth":
+ setup_unsloth = node
+ break
+
+ assert setup_unsloth is not None, "_setup_unsloth not found in sft.py"
+ unsloth_source = ast.unparse(setup_unsloth)
+ for forbidden in ("quantization_aware", "fp8_attention", "nvfp4", "apply_fp8"):
+ assert forbidden not in unsloth_source, (
+ f"Precision knob {forbidden} found in _setup_unsloth; update backend_support!"
+ )
diff --git a/tests/test_issue1222_refuse_int8_qat.py b/tests/test_issue1222_refuse_int8_qat.py
index 82481f93..0c3a294a 100644
--- a/tests/test_issue1222_refuse_int8_qat.py
+++ b/tests/test_issue1222_refuse_int8_qat.py
@@ -313,9 +313,9 @@ def test_the_unsloth_refusal_points_at_the_transformers_backend_only():
assert not any("quantization_aware: true" in error for error in errors), errors
-def test_fp8_on_unsloth_prints_the_new_refusal(tmp_path, monkeypatch):
- """``fp8`` with ``backend: unsloth`` still loads, and ``soup train``'s QAT
- check refuses it; that refusal must not name ``quantization_aware: true``."""
+def test_fp8_on_unsloth_is_refused_without_recommending_true(tmp_path, monkeypatch):
+ """``fp8`` with ``backend: unsloth`` is refused at config load (#1124); the
+ refusal must not send the user to ``quantization_aware: true``."""
from soup_cli.cli import app
monkeypatch.setenv("HF_HUB_OFFLINE", "1")
@@ -326,8 +326,9 @@ def test_fp8_on_unsloth_prints_the_new_refusal(tmp_path, monkeypatch):
output = _plain(result.output)
assert result.exit_code == 1, (result.output, repr(result.exception))
- assert f"QAT error: {UNSLOTH_REFUSAL}" in output, output
+ assert "not supported on the unsloth backend" in output, output
assert "quantization_aware: true" not in output, output
+ assert "pip install" not in output, output
# --------------------------------------------------------------------------
diff --git a/tests/test_v0530.py b/tests/test_v0530.py
index 10e1f0a8..ad4aa6f4 100644
--- a/tests/test_v0530.py
+++ b/tests/test_v0530.py
@@ -988,24 +988,55 @@ class TestSaveFormats:
class TestCrossCutting:
def test_full_v053_roundtrip(self):
- yaml_text = (
+ # Transformers backend roundtrip with FP8 attention + KV cache + double quant
+ yaml_tf = (
"base: a/b\n"
"task: sft\n"
- "backend: unsloth\n"
+ "backend: transformers\n"
"data: {train: x.jsonl}\n"
"training:\n"
" quantization: 4bit\n"
" quantization_aware: fp8\n"
" fp8_attention: true\n"
" kv_cache_type: q8_0\n"
+ " bnb_4bit_use_double_quant: true\n"
+ )
+ cfg_tf = load_config_from_string(yaml_tf)
+ assert cfg_tf.training.fp8_attention is True
+ assert cfg_tf.training.kv_cache_type == "q8_0"
+ assert cfg_tf.training.bnb_4bit_use_double_quant is True
+
+ # Unsloth backend roundtrip with unsloth_bnb_4bit + KV cache (FP8 rejected on unsloth #1124)
+ yaml_unsloth = (
+ "base: a/b\n"
+ "task: sft\n"
+ "backend: unsloth\n"
+ "data: {train: x.jsonl}\n"
+ "training:\n"
+ " quantization: 4bit\n"
+ " kv_cache_type: q8_0\n"
" unsloth_bnb_4bit: true\n"
" bnb_4bit_use_double_quant: true\n"
)
- cfg = load_config_from_string(yaml_text)
- assert cfg.training.fp8_attention is True
- assert cfg.training.kv_cache_type == "q8_0"
- assert cfg.training.unsloth_bnb_4bit is True
- assert cfg.training.bnb_4bit_use_double_quant is True
+ cfg_unsloth = load_config_from_string(yaml_unsloth)
+ assert cfg_unsloth.training.kv_cache_type == "q8_0"
+ assert cfg_unsloth.training.unsloth_bnb_4bit is True
+ assert cfg_unsloth.training.bnb_4bit_use_double_quant is True
+
+ # Inverted assertion (#1124): unsloth + fp8 combination is refused at config load
+ yaml_rejected = (
+ "base: a/b\n"
+ "task: sft\n"
+ "backend: unsloth\n"
+ "data: {train: x.jsonl}\n"
+ "training:\n"
+ " quantization: 4bit\n"
+ " quantization_aware: fp8\n"
+ " fp8_attention: true\n"
+ " unsloth_bnb_4bit: true\n"
+ )
+ with pytest.raises(ValueError, match="not supported on the unsloth backend"):
+ load_config_from_string(yaml_rejected)
def test_gguf_metadata_immutable(self):
from soup_cli.utils.gguf_quant import _GGUF_METADATA