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 add_new_tokens / new_special_tokens where no setup applies them (#1358) (#1622)
Srinivasan Ra36631f52ad6
diff --git a/changelog.d/0.75.1/1622.fixed.md b/changelog.d/0.75.1/1622.fixed.mdnew file mode 100644index 00000000..7a78332e--- /dev/null+++ b/changelog.d/0.75.1/1622.fixed.md@@ -0,0 +1 @@+- `data.add_new_tokens` / `data.new_special_tokens` are refused at config load wherever no trainer setup adds them to the tokenizer, naming what does not apply them: every `backend: unsloth` setup (`tts` with `new_special_tokens` included; SFT's vision and audio paths excepted), `backend: mlx`, `training.stream_layers: true`, and the tasks whose trainers never call the expansion helper (`pretrain`, `embedding`, `ppo`, `reward_model`, `prm`, `classifier`, `reranker`, `cross_encoder`, `unlearn`, `moe_lora_routing`, `distill`, `asr`). They used to load there and be dropped, so the tokens never reached the tokenizer. On `backend: transformers` for `sft`, `dpo`, `kto`, `orpo`, `ipo`, `simpo`, `bco`, `grpo`, `online_dpo`, `preference` and `tts` nothing changes (#1358 by @Srinivasan8888 in #1622).diff --git a/docs/data.md b/docs/data.mdindex 200624e4..c765379d 100644--- a/docs/data.md+++ b/docs/data.md@@ -895,6 +895,14 @@ data:# video_dir: ./videos```+`add_new_tokens` / `new_special_tokens` are added to the tokenizer, with the embeddings+resized, on `backend: transformers` for `sft` (text, vision and audio), `dpo`, `kto`,+`orpo`, `ipo`, `simpo`, `bco`, `grpo`, `online_dpo`, `preference` and `tts`, and on SFT's+vision and audio paths whatever the backend (they run their transformers setup before the+backend is read). Any other task, `backend: unsloth` (text SFT and every other task) or+`mlx`, and `training.stream_layers` never add them, so a config setting them there is+refused at load, naming which of those applies (#1358).+`mask_history: true` keeps only the **last** assistant turn in the loss: everyearlier assistant turn is masked alongside the user and system turns theassistant-only path already excludes. It never adds tokens to the loss.diff --git a/docs/training.md b/docs/training.mdindex d7174c13..67d48c66 100644--- a/docs/training.md+++ b/docs/training.md@@ -1923,7 +1923,9 @@ training:Operator-supplied `data.new_special_tokens` are registered (deduplicated, onlytokens not already in the vocab) and the embedding matrix is resized through the-(possibly PEFT-wrapped) model so the codec-token ids have rows. Orpheus + Oute+(possibly PEFT-wrapped) model so the codec-token ids have rows. That happens on+`backend: transformers` only: the unsloth setup has no step that adds tokens, so+`backend: unsloth` with `new_special_tokens` is refused at load (#1358). Orpheus + Outesupport emotion conditioning via `training.tts_emotion` from a per-familyallowlist (Orpheus: neutral / happy / sad / angry / excited / calm / whisper /laugh; Oute: neutral / happy / sad / angry / calm / excited) — the wrapperdiff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 9d6e317e..89a90a9c 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -4766,6 +4766,16 @@ def remap_root_level_misplaced_keys(values):return new_values+#: #1358 — the tasks whose transformers setup adds ``data.add_new_tokens`` /+#: ``data.new_special_tokens`` to the tokenizer (``apply_vocab_expansion``):+#: SFT's text / vision / audio paths and the DPO/GRPO family, ``preference``+#: through the trainers it delegates to and ``tts`` through SFT's text path.+VOCAB_EXPANSION_TASKS: frozenset[str] = frozenset({+ "sft", "dpo", "kto", "orpo", "ipo", "simpo", "bco", "grpo", "online_dpo",+ "preference", "tts",+})++# task values whose trainer wrapper subclasses SFTTrainerWrapper and so reads# training.use_flash_attn / training.use_liger (sft.py:_setup_transformers,# inherited by tts.py via super()). Every other task ignores both fields.@@ -5128,6 +5138,52 @@ class SoupConfig(BaseModel):"every base parameter. Remove the lora block (or set lora.r: 0).")+ @model_validator(mode="after")+ def _validate_vocab_expansion_is_applied(self) -> "SoupConfig":+ """#1358 — ``data.add_new_tokens`` / ``data.new_special_tokens`` are added+ only by ``apply_vocab_expansion``, which only transformers setups call.+ Anywhere else they loaded and were dropped. The task check comes first:+ it holds on every backend, so switching backend never meets a second+ refusal from this check."""+ data = self.data+ fields = [f"data.{name}" for name in ("add_new_tokens", "new_special_tokens")+ if getattr(data, name)]+ if not fields:+ return self+ field = fields[0]+ if self.task not in VOCAB_EXPANSION_TASKS:+ raise ValueError(+ f"{field} is not applied by task={self.task!r}: that trainer never adds "+ "tokens to its tokenizer or resizes its embeddings. Remove it."+ )+ if self.training.stream_layers:+ raise ValueError(+ f"{field} is not applied with training.stream_layers: the streamed "+ "model is built without the step that adds tokens and resizes the "+ "embeddings. Remove it, or turn off stream_layers."+ )+ if (self.backend == "unsloth" and self.task == "sft"+ and self.modality in ("vision", "audio")):+ # SFT's setup() sends vision / audio to their transformers setups before+ # it reads the backend, and both of those call apply_vocab_expansion+ # (review of #1622); the unsloth reason below would be the wrong one.+ return self+ if self.backend == "unsloth" and self.task not in UNSLOTH_SETUP_TASKS:+ return self # that task's own backend refusal names the real problem+ if self.backend == "mlx" and self.task != "sft":+ return self # _validate_mlx_task_support refuses the task itself+ why = {+ "unsloth": "its setup loads the model and attaches LoRA in one call, with "+ "no step that adds tokens",+ "mlx": "the MLX trainer never adds tokens to its tokenizer",+ }.get(self.backend)+ if why is not None:+ raise ValueError(+ f"{field} is not applied on backend={self.backend!r}: {why}. Use "+ "backend: transformers, or remove it."+ )+ return self+@model_validator(mode="after")def _validate_moe_lora_task(self) -> "SoupConfig":"""#1151 — ``moe_lora`` selects expert-FFN LoRA targets, so it is refuseddiff --git a/tests/test_issue1358_vocab_expansion_refused.py b/tests/test_issue1358_vocab_expansion_refused.pynew file mode 100644index 00000000..dfeebe38--- /dev/null+++ b/tests/test_issue1358_vocab_expansion_refused.py@@ -0,0 +1,275 @@+"""#1358 — ``data.add_new_tokens`` / ``data.new_special_tokens`` load only where a+trainer adds the tokens.++``apply_vocab_expansion`` is the one helper that adds them to the tokenizer and+resizes the embeddings. It runs only in transformers setups: SFT's text / vision /+audio paths and the DPO/GRPO family (``preference`` through the trainers it+delegates to, ``tts`` through SFT's text path). Everywhere else the fields loaded+and were dropped: every ``backend: unsloth`` setup, ``backend: mlx``, SFT's layer+streaming, and ten tasks whose trainers never call it. They are now refused at+load, naming what does not apply them.+"""++from __future__ import annotations++import ast+import importlib+import importlib.resources+import inspect+import textwrap+import typing++import pytest+import yaml++from soup_cli.config.loader import load_config_from_string+from soup_cli.config.schema import SoupConfig++_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"},+}+_WRAPPERS = {+ "sft": "sft:SFTTrainerWrapper", "dpo": "dpo:DPOTrainerWrapper",+ "grpo": "grpo:GRPOTrainerWrapper", "ppo": "ppo:PPOTrainerWrapper",+ "reward_model": "reward_model:RewardModelTrainerWrapper",+ "kto": "kto:KTOTrainerWrapper", "orpo": "orpo:ORPOTrainerWrapper",+ "simpo": "simpo:SimPOTrainerWrapper", "ipo": "ipo:IPOTrainerWrapper",+ "bco": "bco:BCOTrainerWrapper", "preference": "preference:PreferenceTrainerWrapper",+ "pretrain": "pretrain:PretrainTrainerWrapper",+ "embedding": "embedding:EmbeddingTrainerWrapper", "prm": "prm:PRMTrainerWrapper",+ "tts": "tts:TTSTrainerWrapper", "classifier": "classifier:ClassifierTrainerWrapper",+ "reranker": "classifier:ClassifierTrainerWrapper",+ "cross_encoder": "classifier:ClassifierTrainerWrapper",+ "distill": "distill:DistillTrainerWrapper", "unlearn": "unlearn:UnlearnTrainerWrapper",+ "moe_lora_routing": "mole_routing:MoleRoutingTrainerWrapper",+ "online_dpo": "online_dpo:OnlineDPOTrainerWrapper", "asr": "asr:AsrTrainerWrapper",+}+_PREFERENCE_DELEGATES = ("dpo", "simpo", "orpo", "ipo", "bco")++_APPLIES = (+ "sft", "dpo", "kto", "orpo", "ipo", "simpo", "bco", "grpo", "online_dpo",+ "preference", "tts",+)+_NEVER = (+ "pretrain", "embedding", "ppo", "reward_model", "prm", "classifier", "reranker",+ "cross_encoder", "unlearn", "moe_lora_routing", "distill", "asr",+)+_FIELDS = ("add_new_tokens", "new_special_tokens")+++def _yaml(task, backend="transformers", field="add_new_tokens", tokens=("<x>",), **extra):+ top = dict(_TOP.get(task, {}))+ data = {"train": "./x.jsonl", **_DATA.get(task, {}), field: list(tokens)}+ training = dict(_TRAINING.get(task, {}))+ training.update(extra.pop("training", {}))+ data.update(extra.pop("data", {}))+ raw = {"base": "org/m", "task": task, "backend": backend, **top, **extra,+ "data": data, "training": training}+ return yaml.safe_dump(raw)+++def _refusal(text):+ with pytest.raises(ValueError) as info:+ load_config_from_string(text)+ return " ".join(str(info.value).split())+++class TestWhereTheyApplyTheyStillLoad:+ @pytest.mark.parametrize("field", _FIELDS)+ @pytest.mark.parametrize("task", _APPLIES)+ def test_a_task_that_adds_the_tokens_loads(self, task, field):+ cfg = load_config_from_string(_yaml(task, field=field))++ assert getattr(cfg.data, field) == ["<x>"]++ @pytest.mark.parametrize("task", _NEVER + ("sft",))+ def test_an_empty_list_asks_for_nothing_and_loads_anywhere(self, task):+ load_config_from_string(_yaml(task, backend="transformers", tokens=()))+++class TestGap2TasksThatNeverAddThem:+ @pytest.mark.parametrize("field", _FIELDS)+ @pytest.mark.parametrize("task", _NEVER)+ def test_refused_naming_the_task(self, task, field):+ message = _refusal(_yaml(task, field=field))++ assert f"data.{field} is not applied by task={task!r}" in message, message+++class TestGap1Unsloth:+ @pytest.mark.parametrize("field", _FIELDS)+ @pytest.mark.parametrize("task", ["sft", "dpo", "tts"])+ def test_refused_naming_the_backend(self, task, field):+ message = _refusal(_yaml(task, backend="unsloth", field=field))++ assert f"data.{field} is not applied on backend='unsloth'" in message, message+ assert "Use backend: transformers" in message++ def test_a_task_that_never_adds_them_gets_its_task_refusal_on_both_backends(self):+ """The task refusal holds on every backend, so it comes first: switching to+ transformers must not surface a second, different refusal (#1323's lesson)."""+ on_unsloth = _refusal(_yaml("reward_model", backend="unsloth"))++ assert "not applied by task='reward_model'" in on_unsloth, on_unsloth+ assert on_unsloth == _refusal(_yaml("reward_model"))+++class TestTheOtherPathsThatDropThem:+ """Found while mapping the call sites; not in the issue's list."""++ def test_mlx_sft(self):+ message = _refusal(_yaml("sft", backend="mlx", data={"format": "chatml"}))++ assert "data.add_new_tokens is not applied on backend='mlx'" in message, message++ def test_sft_layer_streaming(self):+ message = _refusal(_yaml(+ "sft",+ training={"stream_layers": True, "batch_size": 1, "quantization": "none",+ "lora": {"r": 8}},+ ))++ assert "data.add_new_tokens is not applied with training.stream_layers" in message, message+++# --- the ratchet: the schema's task list must follow the trainers ------------------+++def _calls_helper(func) -> bool:+ tree = ast.parse(textwrap.dedent(inspect.getsource(func)))+ return any(+ isinstance(node, ast.Call)+ and getattr(node.func, "id", getattr(node.func, "attr", None)) == "apply_vocab_expansion"+ for node in ast.walk(tree)+ )+++def _calls_super(func, name) -> bool:+ tree = ast.parse(textwrap.dedent(inspect.getsource(func)))+ return any(+ isinstance(node, ast.Call) and getattr(node.func, "attr", None) == name+ and isinstance(node.func.value, ast.Call)+ and getattr(node.func.value.func, "id", None) == "super"+ for node in ast.walk(tree)+ )+++def _method_applies(cls, name) -> bool:+ """Whether ``cls.<name>`` reaches ``apply_vocab_expansion``, following+ ``super().<name>`` up the MRO (``tts`` extends SFT's text setup that way)."""+ for klass in cls.__mro__:+ func = klass.__dict__.get(name)+ if func is None:+ continue+ if _calls_helper(func):+ return True+ if not _calls_super(func, name):+ return False+ return False+++def _wrapper(task):+ module, name = _WRAPPERS[task].split(":")+ return getattr(importlib.import_module(f"soup_cli.trainer.{module}"), name)+++class TestTheSplitMatchesTheTrainers:+ def test_every_task_is_classified(self):+ tasks = set(typing.get_args(SoupConfig.model_fields["task"].annotation))++ assert tasks == set(_WRAPPERS) == set(_APPLIES) | set(_NEVER)++ @pytest.mark.parametrize("task", sorted(_WRAPPERS))+ def test_the_schema_list_matches_the_transformers_setup(self, task):+ pytest.importorskip("transformers")+ from soup_cli.config.schema import VOCAB_EXPANSION_TASKS++ if task == "preference":+ applies = all(+ _method_applies(_wrapper(t), "_setup_transformers") for t in _PREFERENCE_DELEGATES+ )+ else:+ applies = _method_applies(_wrapper(task), "_setup_transformers")++ assert (task in VOCAB_EXPANSION_TASKS) == applies++ @pytest.mark.parametrize("task", sorted(_WRAPPERS))+ def test_no_unsloth_setup_applies_them_yet(self, task):+ """If one is wired, this fails: lift that task's unsloth refusal."""+ pytest.importorskip("transformers")+ cls = _wrapper(task)++ assert not (hasattr(cls, "_setup_unsloth") and _method_applies(cls, "_setup_unsloth"))++ def test_neither_streaming_nor_mlx_applies_them_yet(self):+ pytest.importorskip("transformers")+ from soup_cli.trainer.sft import SFTTrainerWrapper++ assert not _method_applies(SFTTrainerWrapper, "_setup_streaming_transformers")+ for path in importlib.resources.files("soup_cli.trainer").iterdir():+ if path.name.startswith("mlx_") and path.name.endswith(".py"):+ assert "apply_vocab_expansion" not in path.read_text(encoding="utf-8"), path.name+++class TestSftVisionAndAudioOnUnsloth:+ """SFT's setup() sends vision / audio to their transformers setups before it+ reads the backend, and both of those call apply_vocab_expansion (review of+ #1622); only the text path reaches _setup_unsloth. MLX stays refused: it+ ignores modality."""++ @pytest.mark.parametrize("field", _FIELDS)+ @pytest.mark.parametrize(("modality", "fmt"), [("vision", "llava"), ("audio", "audio")])+ def test_they_still_load(self, modality, fmt, field):+ cfg = load_config_from_string(+ _yaml("sft", backend="unsloth", field=field, modality=modality,+ data={"format": fmt})+ )++ assert getattr(cfg.data, field) == ["<x>"]++ @pytest.mark.parametrize("modality", ["vision", "audio"])+ def test_mlx_is_still_refused_whatever_the_modality(self, modality):+ message = _refusal(_yaml("sft", backend="mlx", modality=modality,+ data={"format": "chatml"}))++ assert "is not applied on backend='mlx'" in message, message+++class TestOnlySftsVisionAndAudioPathsAreExempt:+ """``DPOTrainerWrapper.setup`` has no vision branch and runs ``_setup_unsloth``, so+ the exemption is SFT's alone (review of #1622)."""++ @pytest.mark.parametrize("field", _FIELDS)+ @pytest.mark.parametrize("modality", ["vision", "audio"])+ def test_dpo_on_unsloth_stays_refused_whatever_the_modality(self, modality, field):+ message = _refusal(_yaml("dpo", backend="unsloth", field=field, modality=modality))++ assert "is not applied on backend='unsloth'" in message, message+++class TestABackendTheTaskCannotRunOnIsNamedFirst:+ """Where the task has no setup on the backend at all, that refusal speaks, so+ following "remove it" never meets a second, different refusal (review of #1622)."""++ @pytest.mark.parametrize(("task", "backend", "expected"), [+ ("online_dpo", "unsloth", "task='online_dpo' requires backend='transformers'"),+ ("dpo", "mlx", "MLX backend only ships SFT"),+ ("kto", "mlx", "MLX backend only ships SFT"),+ ])+ def test_the_backend_refusal_comes_first(self, task, backend, expected):+ message = _refusal(_yaml(task, backend=backend))++ assert expected in message, message+ assert "add_new_tokens" not in message, message