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 #1269: refuse the ten optimizers transformers 5.x rejects at config load (#1283)
Kratos992284496e98
diff --git a/changelog.d/0.75.1/1283.changed.md b/changelog.d/0.75.1/1283.changed.mdnew file mode 100644index 00000000..48ac2f0b--- /dev/null+++ b/changelog.d/0.75.1/1283.changed.md@@ -0,0 +1 @@+- Refuse ten optimizer names at config load instead of crashing inside the trainer: transformers 5.x rejects `adam_mini`, `adamw_apex_fused`, `adamw_hf`, `ao_adamw_fp8`, `ao_adamw_4bit`, `ao_adamw_8bit`, `badam`, `came_pytorch`, `dion` and `muon` in `TrainingArguments`, so each used to pass config load and fail after the model had loaded. They are removed from the allowlist with a message naming working alternatives, the LoRA-FA validator no longer recommends `adamw_hf`, and a new test builds `TrainingArguments(optim=name)` for every allowlisted name so a rejected name fails the suite instead of a user's run. `muon` and `adamw_hf` still work on `backend: mlx` (the MLX backend builds them itself); every other backend refuses them with a message that names the backend (#1269 by @wanjinhao1 in #1283).diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.mdindex d904d9db..d6dde688 100644--- a/docs/peft-and-efficiency.md+++ b/docs/peft-and-efficiency.md@@ -193,9 +193,12 @@ Pick from a wider catalogue of optimizers and use quantization-aware LoRA initia```yamltraining:- # 30+ optimizers — HF-native, bnb, BAdam, APOLLO, Adam-mini, lomo,- # grokadamw, schedule_free, muon, dion, came_pytorch, ao_adamw_{fp8,4bit,8bit}- optimizer: badam+ # HF-native, bnb-8bit and v0.41.0 additions (lomo, apollo_adamw,+ # grokadamw, schedule_free). Ten retired names (badam, adam_mini, muon,+ # dion, came_pytorch, ao_adamw_{fp8,4bit,8bit}, ...) are refused at+ # config load because transformers 5.x rejects them (#1269);+ # muon and adamw_hf still work on backend: mlx.+ optimizer: adafactor# Friendly aliases for users coming from LlamaFactory / Axolotl# load_in_8bit: true # equivalent to quantization: 8bitdiff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex ab4d08d0..970a91e6 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -1260,9 +1260,12 @@ class TrainingConfig(BaseModel):optimizer: str = Field(default="adamw_torch",description=(- "Optimizer name. v0.41.0 expands the allowlist to cover BAdam, "- "APOLLO, Adam-mini, lomo/adalomo, grokadamw, schedule_free, "- "muon/dion/came_pytorch, and TorchAO ao_adamw_{fp8,4bit,8bit}. "+ "Optimizer name (v0.41.0 expanded the allowlist: HF-native, "+ "bnb-8bit, lomo/adalomo, apollo_adamw, grokadamw, "+ "schedule_free). Note: ten names transformers 5.x rejects in "+ "TrainingArguments (e.g. badam, adam_mini, muon, dion, "+ "came_pytorch, ao_adamw_{fp8,4bit,8bit}) are refused at config "+ "load (#1269); adamw_hf and muon still work on backend: mlx. ""See soup_cli.utils.optimizer_zoo.SUPPORTED_OPTIMIZERS for the ""full list."),@@ -4255,7 +4258,6 @@ class TrainingConfig(BaseModel):if self.use_lorafa and self.optimizer is not None and self.optimizer not in ("adamw_torch","adamw",- "adamw_hf","adamw_torch_fused",):raise ValueError(@@ -5363,6 +5365,32 @@ class SoupConfig(BaseModel):"""return remap_root_level_misplaced_keys(values)+ @model_validator(mode="after")+ def _validate_mlx_only_optimizers(self) -> "SoupConfig":+ """#1283 — `adamw_hf` and `muon` only build on ``backend: mlx``.++ transformers 5.x rejects both names in TrainingArguments+ (OptimizerNames), so a transformers/unsloth run would pass config+ load and crash inside the trainer after the model had loaded+ (#1269). The MLX backend never builds TrainingArguments — it has+ its own optimizer map (trainer/mlx_optim.py) with entries for both+ — so MLX keeps them and every other backend refuses them here.+ """+ from soup_cli.utils.optimizer_zoo import MLX_ONLY_OPTIMIZERS++ if self.backend == "mlx":+ return self+ opt = getattr(self.training, "optimizer", None)+ if opt is not None and opt in MLX_ONLY_OPTIMIZERS:+ raise ValueError(+ f"training.optimizer={opt!r} only works on backend: mlx "+ "(the MLX backend builds it itself); transformers 5.x "+ "rejects it in TrainingArguments on every other backend "+ "(#1269). Switch backend to 'mlx' or use one of "+ "adamw_torch, adamw_torch_fused, adamw_bnb_8bit, adafactor."+ )+ return self+@model_validator(mode="after")def _validate_v028_speed_memory_supported_tasks(self) -> "SoupConfig":"""v0.28.0 speed/memory features: every transformer-backend trainerdiff --git a/src/soup_cli/utils/optimizer_zoo.py b/src/soup_cli/utils/optimizer_zoo.pyindex cab6e03e..29d344f3 100644--- a/src/soup_cli/utils/optimizer_zoo.py+++ b/src/soup_cli/utils/optimizer_zoo.py@@ -22,16 +22,19 @@ import typesfrom typing import Optional# HF Trainer / transformers built-in optimizers (no extra dep required).+# adamw_apex_fused is NOT here: transformers 5.x rejects it in+# TrainingArguments (OptimizerNames) even though 4.x accepted it, so a config+# that loaded fine used to crash inside the trainer after the model was+# already loaded (#1269). It is refused at config load instead. (adamw_hf is+# allowlisted via MLX_ONLY_OPTIMIZERS — see below.)_HF_NATIVE: frozenset = frozenset({"adamw_torch","adamw_torch_fused","adamw_torch_xla",- "adamw_apex_fused","adamw_anyprecision","adafactor","sgd","adagrad",- "adamw_hf","rmsprop",})@@ -49,23 +52,40 @@ _BNB_BACKED: frozenset = frozenset({# v0.41.0 — new entries (require optional packages)._NEW_V0_41_0: frozenset = frozenset({- "badam","apollo_adamw",- "adam_mini","lomo","adalomo","grokadamw","schedule_free_adamw","schedule_free_sgd",- "muon",- "dion",- "came_pytorch",- "ao_adamw_fp8",+})++# Names that used to be in the allowlist but transformers 5.x rejects in+# TrainingArguments (verified on 5.17, #1269). Kept separately so the config+# loader can refuse them with a message that names working alternatives+# instead of letting the run die inside the trainer after the model loads.+# `adamw_hf` and `muon` are NOT here: the MLX backend builds them itself+# (trainer/mlx_optim.py _OPTIMIZER_MAP), so they stay allowlisted and are+# refused per-backend by SoupConfig instead (see MLX_ONLY_OPTIMIZERS).+_TORCH_REJECTED: frozenset = frozenset({+ "adam_mini",+ "adamw_apex_fused","ao_adamw_4bit","ao_adamw_8bit",+ "ao_adamw_fp8",+ "badam",+ "came_pytorch",+ "dion",})-SUPPORTED_OPTIMIZERS: frozenset = _HF_NATIVE | _BNB_BACKED | _NEW_V0_41_0+# transformers 5.x rejects these in TrainingArguments, but the MLX backend+# never builds TrainingArguments and has its own optimizer map for both+# names (trainer/mlx_optim.py), so only a non-MLX run refuses them (#1283).+MLX_ONLY_OPTIMIZERS: frozenset = frozenset({"adamw_hf", "muon"})++SUPPORTED_OPTIMIZERS: frozenset = (+ _HF_NATIVE | _BNB_BACKED | _NEW_V0_41_0 | MLX_ONLY_OPTIMIZERS+)# Optional package required for each new optimizer. None = HF/bnb native.# A user picking an entry whose package is missing gets a friendly "pip install"@@ -74,20 +94,12 @@ SUPPORTED_OPTIMIZERS: frozenset = _HF_NATIVE | _BNB_BACKED | _NEW_V0_41_0# in test environments. Wrapped in MappingProxyType to prevent runtime mutation# (matches v0.36.0 _REGISTRY policy)._OPTIMIZER_PACKAGES = types.MappingProxyType({- "badam": "badam","apollo_adamw": "apollo-torch",- "adam_mini": "adam-mini","lomo": "lomo-optim","adalomo": "lomo-optim","grokadamw": "grokadamw","schedule_free_adamw": "schedulefree","schedule_free_sgd": "schedulefree",- "muon": "muon-optimizer",- "dion": "dion-optimizer",- "came_pytorch": "came-pytorch",- "ao_adamw_fp8": "torchao",- "ao_adamw_4bit": "torchao",- "ao_adamw_8bit": "torchao",})_MAX_OPTIMIZER_NAME_LEN = 64@@ -112,6 +124,15 @@ def validate_optimizer_name(name: object) -> str:f"optimizer name exceeds {_MAX_OPTIMIZER_NAME_LEN} chars")normalised = name.lower()+ if normalised in _TORCH_REJECTED:+ raise ValueError(+ f"optimizer={name!r} is no longer supported: transformers 5.x "+ "rejects it in TrainingArguments after the model has loaded, so "+ "Soup refuses it at config load instead. Use one of: "+ "adamw_torch, adamw_torch_fused, adamw_bnb_8bit, adafactor. "+ "See soup_cli.utils.optimizer_zoo."+ "SUPPORTED_OPTIMIZERS for the complete list."+ )if normalised not in SUPPORTED_OPTIMIZERS:# Show a tight allowlist preview rather than dumping all 30+ names.suggestions = sorted(_NEW_V0_41_0)[:6]diff --git a/src/soup_cli/utils/peft_wiring.py b/src/soup_cli/utils/peft_wiring.pyindex 892fd0ee..b55d6fb3 100644--- a/src/soup_cli/utils/peft_wiring.py+++ b/src/soup_cli/utils/peft_wiring.py@@ -891,7 +891,6 @@ def attach_lorafa_optimizer(trainer: Any, tcfg: Any) -> bool:if opt_name is not None and opt_name not in ("adamw_torch","adamw",- "adamw_hf","adamw_torch_fused",):raise ValueError(diff --git a/tests/test_issue1269_optimizer_allowlist.py b/tests/test_issue1269_optimizer_allowlist.pynew file mode 100644index 00000000..d327e754--- /dev/null+++ b/tests/test_issue1269_optimizer_allowlist.py@@ -0,0 +1,139 @@+"""#1269 — every allowlisted optimizer must survive TrainingArguments.++transformers 5.x rejects ten names Soup used to accept, so a config that+loaded fine crashed inside the trainer after the model was already loaded.+This suite builds TrainingArguments(optim=name) for every entry of+SUPPORTED_OPTIMIZERS (minus the two MLX-only names, which never reach+TrainingArguments), so a name transformers refuses fails here instead of a+user's run, and checks the retired names are refused at config load with+an actionable message that only recommends names a run can actually build.+"""++from __future__ import annotations++import re++import pytest+from torch import nn+from transformers import Trainer, TrainingArguments++from soup_cli.utils.optimizer_zoo import (+ MLX_ONLY_OPTIMIZERS,+ SUPPORTED_OPTIMIZERS,+ validate_optimizer_name,+)++# Names transformers 5.x rejects (verified on 5.17, #1269). Retired from the+# allowlist; the config loader must refuse them before any model loads.+_RETIRED = (+ "adam_mini",+ "adamw_apex_fused",+ "ao_adamw_4bit",+ "ao_adamw_8bit",+ "ao_adamw_fp8",+ "badam",+ "came_pytorch",+ "dion",+)+++ "name", sorted(SUPPORTED_OPTIMIZERS - MLX_ONLY_OPTIMIZERS)+)+def test_every_allowlisted_optimizer_passes_trainingarguments(name, tmp_path):+ """Each allowlisted name must be accepted by transformers' own gate."""+ TrainingArguments(output_dir=str(tmp_path), optim=name, report_to=[])++[email protected]("name", _RETIRED)+def test_retired_optimizer_refused_at_config_load(name):+ """Retired names must fail fast with an actionable message."""+ with pytest.raises(ValueError, match="no longer supported"):+ validate_optimizer_name(name)+++def test_retired_names_not_in_allowlist():+ assert not (SUPPORTED_OPTIMIZERS & frozenset(_RETIRED))++[email protected]("name", ["BAdam", "Adam_Mini", "AO_ADAMW_8BIT"])+def test_retired_names_are_refused_case_insensitively(name):+ """The refusal must normalise the name before the lookup (#1269)."""+ with pytest.raises(ValueError, match="no longer supported"):+ validate_optimizer_name(name)+++def _recommended_alternatives() -> list[str]:+ with pytest.raises(ValueError) as excinfo:+ validate_optimizer_name("badam")+ match = re.search(r"Use one of: ([a-z0-9_, ]+)\.", str(excinfo.value))+ assert match, str(excinfo.value)+ return match.group(1).split(", ")++[email protected]("name", _recommended_alternatives())+def test_every_recommended_alternative_builds_an_optimizer(name, tmp_path):+ """#1269: no config-load message may recommend a name the run then rejects.++ TrainingArguments accepting a name is not enough: apollo_adamw passes it and+ then fails when the optimizer is built, because Soup never sets+ optim_target_modules.+ """+ assert name in SUPPORTED_OPTIMIZERS, name+ args = TrainingArguments(output_dir=str(tmp_path), optim=name, report_to=[])+ Trainer.get_optimizer_cls_and_kwargs(args, nn.Linear(4, 4))+++def test_mlx_backend_accepts_mlx_only_optimizers(tmp_path):+ """#1283: `muon` / `adamw_hf` map to native MLX optimizers, not transformers."""+ from soup_cli.config.schema import DataConfig, SoupConfig, TrainingConfig++ for name in sorted(MLX_ONLY_OPTIMIZERS):+ SoupConfig(+ base="mlx-community/Llama-3.1-8B-Instruct-4bit",+ task="sft",+ backend="mlx",+ data=DataConfig(train="./data/train.jsonl", format="chatml"),+ training=TrainingConfig(epochs=1, optimizer=name),+ output=str(tmp_path),+ )+++def test_transformers_backend_refuses_mlx_only_optimizers(tmp_path):+ """#1283: a non-MLX run must name the backend and refuse before load."""+ from soup_cli.config.schema import DataConfig, SoupConfig, TrainingConfig++ with pytest.raises(ValueError, match=r"only works on backend: mlx"):+ SoupConfig(+ base="hf-internal-testing/tiny-random-LlamaForCausalLM",+ task="sft",+ backend="transformers",+ data=DataConfig(train="./data/train.jsonl", format="chatml"),+ training=TrainingConfig(epochs=1, optimizer="muon"),+ output=str(tmp_path),+ )++[email protected]("backend", ["transformers", "unsloth"])[email protected]("optimizer", sorted(MLX_ONLY_OPTIMIZERS))+def test_every_non_mlx_backend_refuses_mlx_only_optimizers(backend, optimizer):+ """#1283: both TrainingArguments backends refuse `muon` / `adamw_hf` at load."""+ from soup_cli.config.loader import load_config_from_string++ text = (+ "base: some-org/some-model\n"+ "task: sft\n"+ f"backend: {backend}\n"+ "data:\n train: ./train.jsonl\n"+ f"training:\n optimizer: {optimizer}\n"+ )+ with pytest.raises(ValueError, match="only works on backend: mlx"):+ load_config_from_string(text)+++def test_lorafa_config_with_adamw_hf_is_refused_at_load():+ """The LoRA-FA compat tuple must not accept a non-AdamW-projection name."""+ from soup_cli.config.schema import TrainingConfig++ with pytest.raises(ValueError, match="incompatible"):+ TrainingConfig(use_lorafa=True, optimizer="adamw_hf")diff --git a/tests/test_issue686_mlx_optimizer_schedule.py b/tests/test_issue686_mlx_optimizer_schedule.pyindex 05743e78..a48f8ee4 100644--- a/tests/test_issue686_mlx_optimizer_schedule.py+++ b/tests/test_issue686_mlx_optimizer_schedule.py@@ -189,12 +189,16 @@ class TestWeightDecayIsActuallyPassed:class TestUnsupportedNamesAreRefusedNotSilentlyAdamW:def test_an_optimizer_with_no_mlx_equivalent_is_refused_by_name(self):- """`adam_mini` is a *valid* Soup optimizer, which is the point.+ """`grokadamw` is a *valid* Soup optimizer, which is the point.A name the schema already rejects would prove nothing about this layer."""- with pytest.raises(MlxOptimizerError, match="adam_mini"):- resolve_optimizer_name("adam_mini")+ from soup_cli.utils.optimizer_zoo import validate_optimizer_name++ assert validate_optimizer_name("grokadamw") == "grokadamw" # the premise above++ with pytest.raises(MlxOptimizerError, match="grokadamw"):+ resolve_optimizer_name("grokadamw")def test_the_refusal_names_what_is_available(self):with pytest.raises(MlxOptimizerError, match="adamw"):@@ -381,7 +385,7 @@ class TestTheWrapperPassesUpdatesNotIterations:_install_fake_mlx(monkeypatch)with pytest.raises(MlxOptimizerError, match="no MLX equivalent"):_run_wrapper(- tmp_path, rows=8, epochs=1, batch_size=1, optimizer="adam_mini",+ tmp_path, rows=8, epochs=1, batch_size=1, optimizer="grokadamw",gradient_accumulation_steps=1,)diff --git a/tests/test_v0410_part_a.py b/tests/test_v0410_part_a.pyindex 553d1101..fd52718e 100644--- a/tests/test_v0410_part_a.py+++ b/tests/test_v0410_part_a.py@@ -7,6 +7,7 @@ from pydantic import ValidationErrorfrom soup_cli.config.schema import TrainingConfigfrom soup_cli.utils.optimizer_zoo import (+ MLX_ONLY_OPTIMIZERS,SUPPORTED_OPTIMIZERS,is_new_v0_41_optimizer,required_package,@@ -19,24 +20,45 @@ class TestSupportedOptimizers:assert "adamw_torch" in SUPPORTED_OPTIMIZERSdef test_new_v0_41_entries(self):+ # The 4.x-era additions transformers 5.x rejects were retired (#1269);+ # only the survivors remain in the allowlist.for name in (- "badam","apollo_adamw",- "adam_mini","lomo","adalomo","grokadamw","schedule_free_adamw","schedule_free_sgd",- "muon",+ ):+ assert name in SUPPORTED_OPTIMIZERS, name+ assert is_new_v0_41_optimizer(name)++ def test_torch_rejected_entries_retired(self):+ # #1269: these eight used to be here but transformers 5.x refuses them+ # in TrainingArguments, so they are refused at config load instead.+ # (`muon` and `adamw_hf` are rejected by transformers too, but the MLX+ # backend builds them itself, so they stay allowlisted:+ # test_mlx_only_entries_stay_allowlisted.)+ for name in (+ "badam",+ "adam_mini","dion","came_pytorch","ao_adamw_fp8","ao_adamw_4bit","ao_adamw_8bit",+ "adamw_apex_fused",):+ assert name not in SUPPORTED_OPTIMIZERS, name+ with pytest.raises(ValueError, match="no longer supported"):+ validate_optimizer_name(name)++ def test_mlx_only_entries_stay_allowlisted(self):+ # #1283: refused per backend by SoupConfig, not by name.+ assert MLX_ONLY_OPTIMIZERS == {"adamw_hf", "muon"}+ for name in sorted(MLX_ONLY_OPTIMIZERS):assert name in SUPPORTED_OPTIMIZERS, name- assert is_new_v0_41_optimizer(name)+ assert validate_optimizer_name(name) == namedef test_bnb_entries_present(self):assert "adamw_bnb_8bit" in SUPPORTED_OPTIMIZERS@@ -52,7 +74,7 @@ class TestValidateOptimizerName:assert validate_optimizer_name("adamw_torch") == "adamw_torch"def test_uppercase_normalised(self):- assert validate_optimizer_name("BAdam") == "badam"+ assert validate_optimizer_name("GROKADAMW") == "grokadamw"def test_unknown_rejected(self):with pytest.raises(ValueError, match="not in the supported allowlist"):@@ -83,10 +105,8 @@ class TestRequiredPackage:assert required_package("adamw_bnb_8bit") is Nonedef test_new_returns_pkg(self):- assert required_package("badam") == "badam"assert required_package("apollo_adamw") == "apollo-torch"assert required_package("schedule_free_adamw") == "schedulefree"- assert required_package("ao_adamw_fp8") == "torchao"class TestSchemaIntegration:@@ -94,8 +114,8 @@ class TestSchemaIntegration:TrainingConfig()def test_new_optimizer_accepted(self):- cfg = TrainingConfig(optimizer="badam")- assert cfg.optimizer == "badam"+ cfg = TrainingConfig(optimizer="grokadamw")+ assert cfg.optimizer == "grokadamw"def test_unknown_optimizer_rejected(self):with pytest.raises(ValidationError) as exc:@@ -103,8 +123,8 @@ class TestSchemaIntegration:assert "not in the supported allowlist" in str(exc.value)def test_uppercase_normalised(self):- cfg = TrainingConfig(optimizer="BADAM")- assert cfg.optimizer == "badam"+ cfg = TrainingConfig(optimizer="GrokAdamW")+ assert cfg.optimizer == "grokadamw"def test_null_byte_rejected(self):with pytest.raises(ValidationError, match="null bytes"):@@ -127,20 +147,17 @@ class TestIsNewV041Optimizer:assert is_new_v0_41_optimizer(None) is Falsedef test_case_insensitive(self):- assert is_new_v0_41_optimizer("BADAM") is True+ assert is_new_v0_41_optimizer("GrokAdamW") is Trueclass TestRequiredPackageFull:+ # #1269: the transformers-5-rejected additions were retired, so only the+ # surviving v0.41.0 additions still map to a package.@pytest.mark.parametrize("name,pkg", [- ("adam_mini", "adam-mini"),("lomo", "lomo-optim"),("adalomo", "lomo-optim"),("grokadamw", "grokadamw"),- ("muon", "muon-optimizer"),- ("dion", "dion-optimizer"),- ("came_pytorch", "came-pytorch"),- ("ao_adamw_4bit", "torchao"),- ("ao_adamw_8bit", "torchao"),+ ("schedule_free_adamw", "schedulefree"),("schedule_free_sgd", "schedulefree"),])def test_each_pkg(self, name, pkg):diff --git a/tests/test_v0410_part_c.py b/tests/test_v0410_part_c.pyindex 25d6f46b..6db3f446 100644--- a/tests/test_v0410_part_c.py+++ b/tests/test_v0410_part_c.py@@ -310,12 +310,12 @@ class TestSoupConfigIntegration:training={"quantization": "none","lora": {"init_strategy": "loftq", "loftq_iter": 2, "loftq_bits": 4},- "optimizer": "badam",+ "optimizer": "grokadamw","lr_groups": {"q_proj": 1e-4},},)assert cfg.training.lora.init_strategy == "loftq"- assert cfg.training.optimizer == "badam"+ assert cfg.training.optimizer == "grokadamw"assert len(cfg.training.lr_groups) == 1def test_expand_layers_field_validator_rejects_bool(self):