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(config): refuse auto_mixed_precision on tasks whose trainer never reads it (#1618) (#1627)
vaputa7016df2b3e0e
diff --git a/changelog.d/0.75.1/1627.fixed.md b/changelog.d/0.75.1/1627.fixed.mdnew file mode 100644index 00000000..a46fa933--- /dev/null+++ b/changelog.d/0.75.1/1627.fixed.md@@ -0,0 +1 @@+- **`training.auto_mixed_precision` is now refused at config load on every task whose trainer never reads it (#1618).** The field loaded on all 23 tasks while only the SFT trainer applied it (inherited by `tts`), so a DPO, GRPO, KTO or any other non-SFT run carrying the key trained at its trainer's default bf16/fp16 choice with nothing said, and `soup autopilot` wrote the key into generated non-SFT configs. Setting it on any task outside `sft`/`tts` now fails config validation naming the task and the way out, `generate_config` no longer emits it there, the GRPO `grpo_fp16` + `auto_mixed_precision` refusal now says `grpo_fp16` is the only dtype pick on that task, and the field description and GRPO docstring no longer promise a picker that never ran. **This is a breaking change:** a config that sets the field on a task other than `sft`/`tts` used to load and is now refused — removing the key changes nothing about how such a run trains (#1618 by @vaputa in #1627).diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.mdindex 9c46374c..9c8d6c69 100644--- a/docs/peft-and-efficiency.md+++ b/docs/peft-and-efficiency.md@@ -681,6 +681,8 @@ training:Picks `bf16` on Ampere+, `fp16` on Turing or known fp16-stable models (Qwen2 / Qwen2.5 / Phi-3 / Phi-3.5), `no` on pre-Pascal. Multi-version pairs (`qwen2.5` vs `qwen2`, `phi-3.5` vs `phi-3`) match the longest substring deterministically.+Only `task: sft` reads the field (and `task: tts`, which trains through the SFT trainer); since #1618, setting it on any other task is refused at config load, because those trainers pick bf16/fp16 on their own and would train at their default precision regardless of this key.+The experimental QuEST route (`quantization_aware: quest`) refuses this flag atconfig load because its evidence covers BF16, not FP16; see the[QuEST evidence boundary](performance-and-quantization.md#evidence-boundary).diff --git a/src/soup_cli/autopilot/generate_config.py b/src/soup_cli/autopilot/generate_config.pyindex 6437e7b5..a8597804 100644--- a/src/soup_cli/autopilot/generate_config.py+++ b/src/soup_cli/autopilot/generate_config.py@@ -24,6 +24,7 @@ from soup_cli.autopilot.decisions import (detect_prequantized_format_from_path,)from soup_cli.config.schema import (+ AMP_APPLYING_TASKS,SFT_KERNEL_AWARE_TASKS,DataConfig,LoraConfig,@@ -175,7 +176,13 @@ def generate_config(),"gradient_checkpointing": perf.get("gradient_checkpointing", False),"warmup_auto": bool(decisions.get("warmup_auto", False)),- "auto_mixed_precision": bool(decisions.get("mixed_precision") is not None),+ # #1618: only the SFT trainer reads auto_mixed_precision, so scope it+ # like the two kernel flags above — otherwise a DPO/PPO config the+ # flat generator writes would be refused at load.+ "auto_mixed_precision": (+ bool(decisions.get("mixed_precision") is not None)+ and decisions["task"] in AMP_APPLYING_TASKS+ ),}cfg = SoupConfig(base=base,diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 43516e68..038e948e 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -3326,12 +3326,14 @@ class TrainingConfig(BaseModel):"Overrides any manual warmup_steps in the trainer."),)- # Auto mixed-precision (v0.32.0 Part C)+ # Auto mixed-precision (v0.32.0 Part C); refused on every task outside+ # AMP_APPLYING_TASKS since #1618 — only the SFT trainer reads it.auto_mixed_precision: bool = Field(default=False,description=(- "Pick bf16/fp16 based on model + GPU compute capability. "- "Overrides manual --bf16 / --fp16 trainer flags."+ "Pick bf16/fp16 based on model + GPU compute capability. Applied by "+ "task='sft' (and 'tts', which trains through the SFT trainer); refused "+ "on every other task, whose trainers pick their own precision."),)# Live grad-accum monitoring (v0.32.0 Part B)@@ -4768,6 +4770,14 @@ def remap_root_level_misplaced_keys(values):# inherited by tts.py via super()). Every other task ignores both fields.SFT_KERNEL_AWARE_TASKS: frozenset[str] = frozenset({"sft", "tts"})+# #1618: task values whose trainer reads training.auto_mixed_precision+# (sft.py:_resolve_mixed_precision, inherited by tts.py through super()).+# Every other task's trainer picks bf16/fp16 on its own and never looks at+# the field. Its own name, not SFT_KERNEL_AWARE_TASKS, so that the two sets+# cannot become coupled by accident (the #1532 FREEZE_APPLYING_TASKS+# precedent).+AMP_APPLYING_TASKS: frozenset[str] = frozenset({"sft", "tts"})+# #795: trainers that load the base unquantised and never read# ``training.quantization``.@@ -5537,16 +5547,13 @@ class SoupConfig(BaseModel):@model_validator(mode="after")def _validate_grpo_fp16_amp_exclusive(self) -> "SoupConfig":- """v0.53.3 #128 — ``grpo_fp16`` and ``auto_mixed_precision`` are- mutually exclusive.-- Both flags pick the mixed-precision dtype but go through different- codepaths (``grpo_fp16`` forces ``fp16=True, bf16=False`` on- GRPOConfig directly; ``auto_mixed_precision`` runs the v0.32.0- per-model + per-GPU picker). Combining them is a footgun where the- downstream behaviour depends on order-of-evaluation — fail fast at- config-load with a friendly message naming both flags so the user- picks one.+ """v0.53.3 #128 — ``grpo_fp16`` and ``auto_mixed_precision`` do not+ combine; #1618 sharpens why: the GRPO trainer never reads+ ``auto_mixed_precision`` at all (``_validate_auto_mixed_precision_task_gate``+ refuses the field on ``task='grpo'`` outright), so ``grpo_fp16`` is+ the only way to pick the dtype there. The combo is refused here first+ so a config carrying both flags is told to drop+ ``auto_mixed_precision`` rather than just handed the task-gate error."""# Short-circuit when task is not 'grpo' so the v0.50.0 stability# task-gate error fires first (code-review HIGH fix — keeps a@@ -5556,11 +5563,10 @@ class SoupConfig(BaseModel):return selfif self.training.grpo_fp16 and self.training.auto_mixed_precision:raise ValueError(- "grpo_fp16=True and auto_mixed_precision=True are mutually "- "exclusive — both pick the mixed-precision dtype but go "- "through different codepaths. Pick one: grpo_fp16 forces "- "FP16 (unsloth parity), auto_mixed_precision uses the "- "v0.32.0 per-GPU picker."+ "grpo_fp16=True and auto_mixed_precision=true cannot be "+ "combined on task='grpo': the GRPO trainer never reads "+ "auto_mixed_precision, so grpo_fp16 is the only way to pick "+ "the dtype there. Remove auto_mixed_precision.")return self@@ -5900,6 +5906,26 @@ class SoupConfig(BaseModel):)return self+ @model_validator(mode="after")+ def _validate_auto_mixed_precision_task_gate(self) -> "SoupConfig":+ """#1618: auto_mixed_precision is read only by the SFT trainer+ (sft.py:_resolve_mixed_precision, inherited by tts.py through+ super()); every other trainer picks bf16/fp16 on its own and never+ looks at the field, so refuse rather than silently run at the+ trainer's default precision. Only ``true`` is refused: dumped configs+ and recipe snapshots write the ``false`` default, and those must keep+ loading.+ """+ if self.training.auto_mixed_precision and self.task not in AMP_APPLYING_TASKS:+ raise ValueError(+ f"training.auto_mixed_precision=true is not applied by "+ f"task={self.task!r}: only task in {sorted(AMP_APPLYING_TASKS)} "+ f"picks bf16/fp16 from the model and GPU ('tts' trains through "+ f"the SFT trainer), so this run would train at the trainer's "+ f"default precision. Use task='sft', or remove the key."+ )+ return self+@model_validator(mode="after")def _validate_moe_flags_reach_a_trainer(self) -> "SoupConfig":"""#798 — refuse MoE flags on tasks whose trainer never reads them.diff --git a/src/soup_cli/trainer/grpo.py b/src/soup_cli/trainer/grpo.pyindex 471c4bb8..930c7e90 100644--- a/src/soup_cli/trainer/grpo.py+++ b/src/soup_cli/trainer/grpo.py@@ -297,10 +297,11 @@ class GRPOTrainerWrapper:#387; ``grpo_fp16`` was the only way to run GRPO there and nothingsaid so.- ``auto_mixed_precision`` is mutually exclusive with ``grpo_fp16``- (rejected at schema load via ``_validate_grpo_fp16_amp_exclusive``);- when only ``auto_mixed_precision`` is set, the v0.32.0 picker runs- elsewhere in the training loop and overrides this default.+ ``auto_mixed_precision`` is refused on ``task='grpo'`` at schema+ load (#1618 — this wrapper never reads the field, so it would train+ at whatever precision these lines pick); ``grpo_fp16`` is the only+ way to choose the dtype here, and the grpo_fp16 + auto_mixed_precision+ combo is rejected by ``_validate_grpo_fp16_amp_exclusive``."""device_name = str(self.device).lower()if device_name.startswith("mps"):diff --git a/tests/test_auto_mixed_precision_task_gate.py b/tests/test_auto_mixed_precision_task_gate.pynew file mode 100644index 00000000..9198a66a--- /dev/null+++ b/tests/test_auto_mixed_precision_task_gate.py@@ -0,0 +1,84 @@+"""#1618 — ``auto_mixed_precision`` is applied by ``task='sft'`` (and 'tts') only.++The field loaded on all 23 tasks while only the SFT trainer read it+(sft.py:_resolve_mixed_precision, inherited by tts.py through super()), so+every other run trained at its trainer's default precision with nothing said.+The task gate now refuses the field outside ``AMP_APPLYING_TASKS``; these+tests pin the refusal per task, the applying set's continued acceptance, and+the ``false`` default's continued acceptance on every task.+"""++from __future__ import annotations++import typing++import pytest+import yaml+from pydantic import ValidationError++from soup_cli.config.loader import load_config_from_string+from soup_cli.config.schema import SoupConfig++# The minimum each task needs to load at all (the same table as PR #1532's tests).+_TOP = {"tts": {"modality": "audio_out"}}+_DATA = {+ "dpo": {"format": "dpo"},+ "kto": {"format": "kto"},+ "pretrain": {"format": "plaintext"},+ "unlearn": {"forget_set": "./f.jsonl"},+}+_TRAINING = {+ "preference": {"preference_loss": "dpo"},+ "tts": {"tts_family": "orpheus"},+ "classifier": {"num_labels": 2},+ "reranker": {"num_labels": 2},+ "cross_encoder": {"num_labels": 2},+ "unlearn": {"unlearn_method": "npo"},+ "moe_lora_routing": {"mole_task_adapters": ["./a", "./b"]},+ "distill": {"teacher_model": "org/t"},+ "online_dpo": {"online_dpo_judge": "pairrm"},+}++TASKS = typing.get_args(SoupConfig.model_fields["task"].annotation)+# Listed literally, not read from AMP_APPLYING_TASKS: dropping a task from the+# constant must not also drop its control here.+APPLYING = ["sft", "tts"]+++def _config_for(task: str, training_extra: dict) -> str:+ raw = {+ "base": "org/m",+ "task": task,+ **_TOP.get(task, {}),+ "data": {"train": "./x.jsonl", **_DATA.get(task, {})},+ "training": {**_TRAINING.get(task, {}), **training_extra},+ }+ return yaml.safe_dump(raw)++[email protected]("task", [t for t in TASKS if t not in APPLYING])+def test_amp_true_is_refused_outside_the_applying_tasks(task):+ with pytest.raises((ValidationError, ValueError)) as exc:+ load_config_from_string(_config_for(task, {"auto_mixed_precision": True}))+ msg = str(exc.value)+ assert "auto_mixed_precision" in msg+ assert task in msg++[email protected]("task", [t for t in TASKS if t not in APPLYING])+def test_the_same_configs_load_without_the_field(task):+ cfg = load_config_from_string(_config_for(task, {}))+ assert cfg.task == task++[email protected]("task", APPLYING)+def test_the_applying_tasks_still_load_with_amp_true(task):+ cfg = load_config_from_string(_config_for(task, {"auto_mixed_precision": True}))+ assert cfg.training.auto_mixed_precision is True+ assert cfg.task == task++[email protected]("task", TASKS)+def test_amp_false_loads_on_every_task(task):+ cfg = load_config_from_string(_config_for(task, {"auto_mixed_precision": False}))+ assert cfg.training.auto_mixed_precision is Falsediff --git a/tests/test_auto_tuning.py b/tests/test_auto_tuning.pyindex edbe44aa..59df1baa 100644--- a/tests/test_auto_tuning.py+++ b/tests/test_auto_tuning.py@@ -784,6 +784,70 @@ class TestAutopilotConfigEmission:assert cfg["training"].get("use_flash_attn") is not Trueassert cfg["training"].get("use_liger") is not True+ def test_generated_config_scopes_auto_mixed_precision_to_sft_family(+ self, tmp_path, monkeypatch,+ ):+ """#1618: generate_config scopes auto_mixed_precision like the kernel+ flags. A dpo decisions dict with mixed_precision set must not raise,+ and the emitted config must not carry auto_mixed_precision: true —+ the task gate would refuse it at load."""+ from soup_cli.autopilot.generate_config import generate_config++ monkeypatch.chdir(tmp_path)+ decisions = {+ "task": "dpo",+ "format": "dpo",+ "max_length": 2048,+ "quantization": "4bit",+ "lora": {"r": 16, "alpha": 32, "use_dora": False},+ "lr": 2e-4,+ "epochs": 3,+ "batch_size": 4,+ "grad_accum": 2,+ "perf": {+ "use_flash_attn": False, "use_liger": False,+ "gradient_checkpointing": False,+ },+ "mixed_precision": "bf16",+ }+ out = Path("soup.yaml")+ generate_config(+ base="meta-llama/Llama-3-8B",+ data_path="data.jsonl",+ decisions=decisions,+ output_path=out,+ )+ cfg = yaml.safe_load(out.read_text(encoding="utf-8"))+ assert cfg["training"].get("auto_mixed_precision") is not True++ def test_generated_sft_config_keeps_auto_mixed_precision(self, tmp_path, monkeypatch):+ """#1618 control: the scoping must not drop the field where the+ trainer reads it — an SFT decisions dict with mixed_precision set+ still emits auto_mixed_precision: true."""+ from soup_cli.autopilot.generate_config import generate_config++ monkeypatch.chdir(tmp_path)+ decisions = {+ "task": "sft", "format": "alpaca", "max_length": 2048,+ "quantization": "4bit",+ "lora": {"r": 16, "alpha": 32, "use_dora": False},+ "lr": 2e-4, "epochs": 3, "batch_size": 4, "grad_accum": 2,+ "perf": {+ "use_flash_attn": False, "use_liger": False,+ "gradient_checkpointing": False,+ },+ "mixed_precision": "bf16",+ }+ out = Path("soup.yaml")+ generate_config(+ base="meta-llama/Llama-3-8B",+ data_path="data.jsonl",+ decisions=decisions,+ output_path=out,+ )+ cfg = yaml.safe_load(out.read_text(encoding="utf-8"))+ assert cfg["training"]["auto_mixed_precision"] is True+def test_decisions_output_must_stay_under_cwd(self, tmp_path, monkeypatch):from soup_cli.autopilot.generate_config import generate_configdiff --git a/tests/test_v0533.py b/tests/test_v0533.pyindex 7a292bad..7d9bd70c 100644--- a/tests/test_v0533.py+++ b/tests/test_v0533.py@@ -81,16 +81,22 @@ class TestGRPOFP16:assert cfg.training.grpo_fp16 is Trueassert cfg.training.auto_mixed_precision is False- def test_amp_alone_passes(self) -> None:- cfg = load_config_from_string(_minimal_grpo_yaml(+ def test_amp_alone_is_refused_on_grpo(self) -> None:+ """#1618 — the GRPO trainer never reads auto_mixed_precision, so a+ GRPO config carrying the field alone is refused, not silently run at+ the trainer's default precision."""+ yml = _minimal_grpo_yaml(training={"reward_fn": "accuracy","num_generations": 2,"auto_mixed_precision": True,},- ))- assert cfg.training.grpo_fp16 is False- assert cfg.training.auto_mixed_precision is True+ )+ with pytest.raises((ValidationError, ValueError)) as exc:+ load_config_from_string(yml)+ msg = str(exc.value)+ assert "auto_mixed_precision" in msg+ assert "grpo" in msgclass TestGRPOFP16Routing: