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 rope_scaling_type where no setup applies it (#1697) (#1730)
Yang Baia95bd38ccdf8
diff --git a/changelog.d/0.75.1/1730.fixed.md b/changelog.d/0.75.1/1730.fixed.mdnew file mode 100644index 00000000..c6cdf7cf--- /dev/null+++ b/changelog.d/0.75.1/1730.fixed.md@@ -0,0 +1 @@+- **`training.rope_scaling_type` is refused at load where no setup applies it (#1697 by @ybai08 in #1730).** The field loaded on all 23 tasks and every path, but only the transformers setups of `sft`, `tts` and `pretrain` read it; everywhere else the run trained on the checkpoint's own RoPE and printed nothing. **This is a breaking change: a config that sets the field on one of these loaded before and now stops at load**: any of the other 20 tasks; `task: sft` with `backend: mlx`, `modality: vision`, `modality: audio` or `training.stream_layers: true`; and `sft`, `tts` or `pretrain` with `backend: unsloth`. The message names the field, the task or every setting that leaves the reading setup, and what to change (for example `Use backend: transformers, or remove the key.`); a `yarn_*` key set beside it is named too, since it is legal only with `rope_scaling_type: yarn`. `soup doctor --config` exits 2. Removing the key changes nothing about what trains. The `longcontext` template no longer suggests `# backend: unsloth`, which it would now be refused with. Text configs on `backend: transformers`, `pretrain` on `backend: transformers` with any modality, and dumped configs (which write the field as `null`) are unchanged.diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.mdindex 5e842f4a..d904d9db 100644--- a/docs/peft-and-efficiency.md+++ b/docs/peft-and-efficiency.md@@ -149,7 +149,7 @@ training:**Llama 3.1 NTK-aware.** Use `rope_scaling_type: llama3` for Llama 3.1-style frequency-band scaling. On a checkpoint without RoPE scaling it emits `factor = data.max_length / max_position_embeddings` over `original_max_position_embeddings = max_position_embeddings`, with `low_freq_factor` 1 and `high_freq_factor` 4, so an 8k checkpoint extended to 64k gets Llama 3.1's own factor 8 over 8192. `detect_llama3_rope_in_config` can identify the block in an HF model config dict, but `soup train` changes RoPE only when `rope_scaling_type` is explicit; omitting it preserves the checkpoint's native RoPE configuration. On a checkpoint that already ships a `llama3` block (Llama 3.1, 3.2 and 3.3 do), `rope_scaling_type: llama3` composes with it instead of replacing it: the checkpoint's `original_max_position_embeddings`, `low_freq_factor` and `high_freq_factor` are kept, and its `factor` is multiplied by `data.max_length / max_position_embeddings`. Llama-3.1-8B extended from 131072 to 262144 tokens trains with factor 16 over 8192, so no frequency pair rotates faster than it did in pretraining.-RoPE scaling is applied before model construction for the Transformers text paths of `task: sft` and `task: pretrain`. Vision, audio, layer-streaming and Unsloth setup paths do not consume these fields, nor do other training tasks. Existing type-independent model parameters such as `rope_theta` are preserved; tunables belonging to a previous RoPE algorithm are removed when the type changes. A checkpoint whose RoPE block is already scaled (any `rope_type` other than `default`, for example `yarn`, `longrope` or `llama3`) is never replaced: apart from `llama3` on a `llama3` block, extending it is refused before the model is built, and the error names the checkpoint's `rope_type` and `factor`. A `data.max_length` at or below the checkpoint's `max_position_embeddings` extends nothing, so none of these refusals applies to it. Models such as Gemma 3 that use nested per-layer RoPE sections are refused rather than partially modified. `rope_scaling_type: longrope` is refused at config load, whatever `data.max_length` is. Its per-dimension `short_factor` and `long_factor` vectors exist only on checkpoints already scaled with LongRoPE, and extending those is refused, so it cannot extend any checkpoint. To extend a checkpoint without RoPE scaling, use `linear`, `dynamic`, `yarn` or `llama3`. To fine-tune a LongRoPE checkpoint such as Phi-3-mini-128k at its native length, leave `rope_scaling_type` unset: the checkpoint's own RoPE block is used as shipped.+RoPE scaling is applied before model construction on `task: sft` (the text path with `backend: transformers` and no layer streaming) and on `task: tts` and `task: pretrain` with `backend: transformers`. Everywhere else `rope_scaling_type` is refused at config load ([#1697](https://github.com/MakazhanAlpamys/Soup/issues/1697)): on the other 20 tasks, on `sft` with `backend: mlx`, `modality: vision`, `modality: audio` or `training.stream_layers: true`, and on any of the three with `backend: unsloth`. Those setups build the model with the checkpoint's own RoPE; the message names each setting to change, and the `yarn_*` keys set beside it. Existing type-independent model parameters such as `rope_theta` are preserved; tunables belonging to a previous RoPE algorithm are removed when the type changes. A checkpoint whose RoPE block is already scaled (any `rope_type` other than `default`, for example `yarn`, `longrope` or `llama3`) is never replaced: apart from `llama3` on a `llama3` block, extending it is refused before the model is built, and the error names the checkpoint's `rope_type` and `factor`. A `data.max_length` at or below the checkpoint's `max_position_embeddings` extends nothing, so none of these refusals applies to it. Models such as Gemma 3 that use nested per-layer RoPE sections are refused rather than partially modified. `rope_scaling_type: longrope` is refused at config load, whatever `data.max_length` is. Its per-dimension `short_factor` and `long_factor` vectors exist only on checkpoints already scaled with LongRoPE, and extending those is refused, so it cannot extend any checkpoint. To extend a checkpoint without RoPE scaling, use `linear`, `dynamic`, `yarn` or `llama3`. To fine-tune a LongRoPE checkpoint such as Phi-3-mini-128k at its native length, leave `rope_scaling_type` unset: the checkpoint's own RoPE block is used as shipped.**LongLoRA S².** `training.use_longlora: true` is refused at config load ([#1240](https://github.com/MakazhanAlpamys/Soup/issues/1240)): the override it installed leaked future tokens into earlier positions and applied no S² grouping (see [LongLoRA Forward Override](#longlora-forward-override)). Use one of the RoPE-scaling strategies above with plain LoRA instead.diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.mdindex 049b7a47..67921c70 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -1192,7 +1192,7 @@ training:gradient_checkpointing: true # Required for long sequences# Long-context (128k+ tokens)- rope_scaling_type: dynamic # RoPE scaling: linear, dynamic, yarn, llama3+ rope_scaling_type: dynamic # RoPE scaling: linear, dynamic, yarn, llama3; sft/tts/pretrain on backend: transformers only# use_ring_attention: true # Sequence parallelism across GPUsdata:diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 31bdd502..ab4d08d0 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -3036,7 +3036,10 @@ class TrainingConfig(BaseModel):default=None,description=("RoPE scaling method for long-context: linear, dynamic, yarn or llama3 "- "(v0.49.0). 'longrope' is refused at config load (#1239)."+ "(v0.49.0). 'longrope' is refused at config load (#1239). Applied by "+ "task sft, tts and pretrain on backend: transformers (sft: the text "+ "path without layer streaming); refused at config load anywhere else "+ "(#1697)."),)# v0.49.0 Part A — YaRN-specific tunables (only meaningful when@@ -4822,6 +4825,13 @@ UNSLOTH_SETUP_TASKS: frozenset[str] = frozenset({#: layer streaming reaches that method; the other paths are refused too (#1581).FREEZE_APPLYING_TASKS: frozenset[str] = frozenset({"sft", "tts"})+#: #1697 — the tasks whose trainer reads ``training.rope_scaling_type``:+#: ``SFTTrainerWrapper._setup_transformers`` (inherited by ``tts``) and+#: ``PretrainTrainerWrapper._setup_transformers``. Every other trainer builds+#: the model with the checkpoint's own RoPE, so the field is refused there, and+#: within these tasks on every path that does not reach those two methods.+ROPE_SCALING_APPLYING_TASKS: frozenset[str] = frozenset({"sft", "tts", "pretrain"})+#: The bitsandbytes values: ``4bit`` was the default, so every config Soup dumped#: for these tasks carries one of them literally (#795 review)._BNB_QUANTIZATION_VALUES = frozenset({"4bit", "8bit"})@@ -8190,6 +8200,60 @@ class SoupConfig(BaseModel):f"Use {changes}, or remove {keys}.")+ @model_validator(mode="after")+ def _validate_rope_scaling_is_applied(self) -> "SoupConfig":+ """#1697 — ``rope_scaling_type`` loaded on every task and path, but only+ the ``_setup_transformers`` of the SFT and pretrain wrappers reads it.+ Everywhere else the run trained on the checkpoint's own RoPE without a+ word. The ``yarn_*`` keys are named with it: they are legal only beside+ ``rope_scaling_type: yarn``, so removing one key alone would be refused+ next. Settings are named in the order ``resolve_trainer`` and the+ wrapper's ``setup`` check them, as in :meth:`_validate_freeze_is_applied`."""+ tcfg = self.training+ if tcfg.rope_scaling_type is None:+ return self+ fields = ["training.rope_scaling_type"] + [+ f"training.{name}"+ for name in ("yarn_factor", "yarn_attn_factor", "yarn_beta_fast", "yarn_beta_slow")+ if getattr(tcfg, name) is not None+ ]+ named = fields[0] if len(fields) == 1 else f"{', '.join(fields[:-1])} and {fields[-1]}"+ verb = "is" if len(fields) == 1 else "are"+ keys = {1: "the key", 2: "both keys"}.get(len(fields), f"the {len(fields)} keys")+ if self.task not in ROPE_SCALING_APPLYING_TASKS:+ raise ValueError(+ f"{named} {verb} not applied by task={self.task!r}: only task='sft', "+ "'tts' and 'pretrain' rescale RoPE, so this run would train on the "+ f"checkpoint's own RoPE. Use one of those tasks, or remove {keys}."+ )+ off_path = []+ # PretrainTrainerWrapper.setup branches on the backend only; sft and tts+ # share SFTTrainerWrapper.setup.+ if self.task != "pretrain":+ if self.backend == "mlx":+ off_path.append(("backend='mlx'", "backend: transformers"))+ if self.modality in ("vision", "audio"):+ off_path.append((f"modality={self.modality!r}", "modality: text"))+ if tcfg.stream_layers:+ off_path.append(("training.stream_layers=true", "stream_layers: false"))+ if self.backend == "unsloth":+ off_path.append(("backend='unsloth'", "backend: transformers"))+ if not off_path:+ return self+ settings = " and ".join(setting for setting, _ in off_path)+ changes = " and ".join(change for _, change in off_path)+ # Only sft has a modality or a streaming setup to leave.+ where = (+ "on the text path with backend: transformers and no layer streaming"+ if self.task == "sft"+ else "with backend: transformers"+ )+ raise ValueError(+ f"{named} {verb} not applied by task={self.task!r} with {settings}: "+ f"RoPE is rescaled only {where}, so this run would train on the "+ f"checkpoint's own RoPE. Use {changes}, or remove {keys}."+ )+@model_validator(mode="after")def _validate_unsloth_has_a_setup(self) -> "SoupConfig":"""#1357 — ``backend: unsloth`` on a task outside@@ -8576,7 +8640,6 @@ output: ./outputbase: meta-llama/Llama-3.1-8B-Instructtask: sft-# backend: unsloth # 2-5x faster, pip install "soup-cli[fast]"data:train: ./data/long_context_train.jsonldiff --git a/src/soup_cli/templates/longcontext.yaml b/src/soup_cli/templates/longcontext.yamlindex bc35adc5..ca22d2a6 100644--- a/src/soup_cli/templates/longcontext.yaml+++ b/src/soup_cli/templates/longcontext.yaml@@ -6,7 +6,6 @@base: meta-llama/Llama-3.1-8B-Instructtask: sft-# backend: unsloth # 2-5x faster, pip install "soup-cli[fast]"data:train: ./data/long_context_train.jsonldiff --git a/tests/test_issue1697_rope_scaling_refused_where_unapplied.py b/tests/test_issue1697_rope_scaling_refused_where_unapplied.pynew file mode 100644index 00000000..0f35afcb--- /dev/null+++ b/tests/test_issue1697_rope_scaling_refused_where_unapplied.py@@ -0,0 +1,523 @@+"""#1697 — ``training.rope_scaling_type`` is refused at load where nothing applies it.++The field loaded on all 23 tasks and every path, and two methods read it:+``SFTTrainerWrapper._setup_transformers`` (``tts`` reaches it through ``super()``)+and ``PretrainTrainerWrapper._setup_transformers``. Everywhere else the run+trained on the checkpoint's own RoPE and said nothing. Those configs now stop at+load, naming the field, the task or the setting that leaves the reading setup,+and what to change.++Nothing is trained here: the gate is a config validator, and the two ratchet+classes tie it to the trainers by reading their source.+"""++from __future__ import annotations++import ast+import importlib+import inspect+import textwrap+import typing+from pathlib import Path++import pytest+import yaml++from soup_cli.config.loader import load_config_from_string+from soup_cli.config.schema import ROPE_SCALING_APPLYING_TASKS, TEMPLATES, SoupConfig+from soup_cli.trainer.mlx_sft import MLXSFTTrainerWrapper+from soup_cli.trainer.pretrain import PretrainTrainerWrapper+from soup_cli.trainer.sft import SFTTrainerWrapper++_TASKS = tuple(typing.get_args(SoupConfig.model_fields["task"].annotation))+# Written out, not read from ROPE_SCALING_APPLYING_TASKS: a task dropped from or+# added to the constant must not move its own tests with it.+_APPLYING = ("sft", "tts", "pretrain")+_REFUSED = tuple(task for task in _TASKS if task not in _APPLYING)+_TYPES = ("linear", "dynamic", "yarn", "llama3")+_YARN_FIELDS = ("yarn_factor", "yarn_attn_factor", "yarn_beta_fast", "yarn_beta_slow")++# The minimum each task needs to load at all (as in the #1497 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"},+}+# preference builds one of these per preference_loss (trainer/preference.py).+_PREFERENCE_DELEGATES = ("dpo", "simpo", "orpo", "ipo", "bco")+++def _yaml(task="sft", top=None, **training):+ raw = {+ "base": "org/m", "task": task, **_TOP.get(task, {}), **(top or {}),+ "data": {"train": "./x.jsonl", **_DATA.get(task, {})},+ "training": {**_TRAINING.get(task, {}), **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())+++def test_the_task_list_is_the_one_this_file_was_written_for():+ assert len(_TASKS) == 23+ assert set(_APPLYING) <= set(_TASKS)+ assert ROPE_SCALING_APPLYING_TASKS == frozenset({"sft", "tts", "pretrain"})+++class TestRefusedOutsideTheThreeTasks:+ @pytest.mark.parametrize("rope_type", _TYPES)+ @pytest.mark.parametrize("task", _REFUSED)+ def test_the_message_names_the_field_the_task_and_the_fix(self, task, rope_type):+ message = _refusal(_yaml(task, rope_scaling_type=rope_type))++ assert (+ f"training.rope_scaling_type is not applied by task={task!r}: only "+ "task='sft', 'tts' and 'pretrain' rescale RoPE"+ ) in message, message+ assert "would train on the checkpoint's own RoPE" in message+ assert message.endswith("Use one of those tasks, or remove the key.")++ @pytest.mark.parametrize("task", _REFUSED)+ def test_without_the_field_the_task_still_loads(self, task):+ assert load_config_from_string(_yaml(task)).training.rope_scaling_type is None++ @pytest.mark.parametrize("backend", ["transformers", "unsloth"])+ def test_the_task_refusal_does_not_depend_on_the_backend(self, backend):+ """``dpo`` on unsloth is refused for the task, not for the path."""+ message = _refusal(_yaml("dpo", {"backend": backend}, rope_scaling_type="yarn"))++ assert "is not applied by task='dpo': only task='sft'" in message, message++ def test_a_dumped_config_still_reloads(self):+ """A dumped config writes the field out as null; that is not a request."""+ dumped = yaml.safe_dump(+ load_config_from_string(_yaml("dpo")).model_dump(mode="json")+ )++ assert "rope_scaling_type: null" in dumped+ assert load_config_from_string(dumped).task == "dpo"+++# The paths of the issue's table that load today: (task, top-level keys, training+# keys, the setting the message names, the change it asks for).+_OFF_PATH = {+ "sft-mlx": (+ "sft", {"backend": "mlx"}, {}, "backend='mlx'", "backend: transformers",+ ),+ "sft-vision": (+ "sft", {"modality": "vision"}, {}, "modality='vision'", "modality: text",+ ),+ "sft-audio": (+ "sft", {"modality": "audio"}, {}, "modality='audio'", "modality: text",+ ),+ "sft-stream": (+ "sft", {}, {"stream_layers": True, "batch_size": 1},+ "training.stream_layers=true", "stream_layers: false",+ ),+ "sft-unsloth": (+ "sft", {"backend": "unsloth"}, {}, "backend='unsloth'", "backend: transformers",+ ),+ "tts-unsloth": (+ "tts", {"backend": "unsloth"}, {}, "backend='unsloth'", "backend: transformers",+ ),+ "pretrain-unsloth": (+ "pretrain", {"backend": "unsloth"}, {}, "backend='unsloth'",+ "backend: transformers",+ ),+}+# Only sft has a modality or a streaming setup to leave.+_WHERE = {+ "sft": "on the text path with backend: transformers and no layer streaming",+ "tts": "with backend: transformers",+ "pretrain": "with backend: transformers",+}+++class TestRefusedOffTheReadingSetup:+ @pytest.mark.parametrize("rope_type", _TYPES)+ @pytest.mark.parametrize("case", list(_OFF_PATH))+ def test_the_message_names_the_field_the_path_and_the_fix(self, case, rope_type):+ task, top, training, setting, change = _OFF_PATH[case]++ message = _refusal(_yaml(task, top, **training, rope_scaling_type=rope_type))++ assert (+ f"training.rope_scaling_type is not applied by task={task!r} with {setting}: "+ f"RoPE is rescaled only {_WHERE[task]}, so"+ ) in message, message+ assert "would train on the checkpoint's own RoPE" in message+ assert message.endswith(f"Use {change}, or remove the key.")++ @pytest.mark.parametrize("case", list(_OFF_PATH))+ def test_without_the_field_the_path_still_loads(self, case):+ """The refusal is about the field, not about the path."""+ task, top, training, _, _ = _OFF_PATH[case]++ cfg = load_config_from_string(_yaml(task, top, **training))++ assert cfg.training.rope_scaling_type is None++ @pytest.mark.parametrize(+ ("top", "settings", "change"),+ [+ (+ {"backend": "unsloth", "modality": "vision"},+ "modality='vision' and backend='unsloth'",+ "modality: text and backend: transformers",+ ),+ (+ {"backend": "unsloth", "modality": "audio"},+ "modality='audio' and backend='unsloth'",+ "modality: text and backend: transformers",+ ),+ (+ {"backend": "mlx", "modality": "vision"},+ "backend='mlx' and modality='vision'",+ "backend: transformers and modality: text",+ ),+ ],+ )+ def test_every_setting_off_the_path_is_named(self, top, settings, change):+ """Changing one of two settings would still leave the run off the text+ path, so both are named, in the order the trainer checks them."""+ message = _refusal(_yaml("sft", top, rope_scaling_type="dynamic"))++ assert f"with {settings}:" in message, message+ assert message.endswith(f"Use {change}, or remove the key.")++ def test_the_template_with_its_unsloth_hint_taken_is_refused(self):+ """The issue's example: ``soup init --template longcontext``, then the+ ``# backend: unsloth`` line every other template suggests."""+ raw = yaml.safe_load(TEMPLATES["longcontext"])+ assert raw["training"]["rope_scaling_type"] == "dynamic"+ raw["backend"] = "unsloth"++ message = _refusal(yaml.safe_dump(raw))++ assert "is not applied by task='sft' with backend='unsloth'" in message, message+++class TestTheYarnKeysAreNamedWithIt:+ """The ``yarn_*`` keys are legal only with ``rope_scaling_type: yarn``, so a+ message that said to remove one key would send the config into the next+ refusal."""++ def test_on_a_task_that_does_not_apply_them(self):+ message = _refusal(_yaml("dpo", rope_scaling_type="yarn", yarn_factor=4.0))++ assert (+ "training.rope_scaling_type and training.yarn_factor are not applied by "+ "task='dpo'"+ ) in message, message+ assert message.endswith("Use one of those tasks, or remove both keys.")++ def test_on_a_path_that_does_not_apply_them(self):+ message = _refusal(+ _yaml(+ "sft", {"backend": "unsloth"}, rope_scaling_type="yarn",+ yarn_factor=4.0, yarn_attn_factor=1.0, yarn_beta_fast=32, yarn_beta_slow=1,+ )+ )++ assert (+ "training.rope_scaling_type, training.yarn_factor, training.yarn_attn_factor, "+ "training.yarn_beta_fast and training.yarn_beta_slow are not applied by "+ "task='sft' with backend='unsloth'"+ ) in message, message+ assert message.endswith("Use backend: transformers, or remove the 5 keys.")++ def test_following_the_message_loads(self):+ raw = yaml.safe_load(_yaml("dpo", rope_scaling_type="yarn", yarn_factor=4.0))+ for key in ("rope_scaling_type", "yarn_factor"):+ del raw["training"][key]++ assert load_config_from_string(yaml.safe_dump(raw)).task == "dpo"+++class TestTheReadingSetupsStillLoad:+ # Written out rather than derived from the tables above, so a bad table+ # cannot also remove its control.+ @pytest.mark.parametrize("rope_type", _TYPES)+ @pytest.mark.parametrize("task", ["sft", "tts", "pretrain"])+ def test_on_transformers(self, task, rope_type):+ cfg = load_config_from_string(+ _yaml(task, {"backend": "transformers"}, rope_scaling_type=rope_type)+ )++ assert cfg.training.rope_scaling_type == rope_type++ def test_yarn_with_its_tunables(self):+ cfg = load_config_from_string(_yaml("sft", rope_scaling_type="yarn", yarn_factor=4.0))++ assert cfg.training.yarn_factor == 4.0++ def test_stream_layers_false_is_not_streaming(self):+ cfg = load_config_from_string(+ _yaml("sft", stream_layers=False, rope_scaling_type="dynamic")+ )++ assert cfg.training.rope_scaling_type == "dynamic"++ @pytest.mark.parametrize("modality", ["vision", "audio"])+ def test_pretrain_has_one_transformers_setup_whatever_the_modality(self, modality):+ """``PretrainTrainerWrapper.setup`` branches on the backend only, so+ ``modality`` does not take a pretrain run away from the read."""+ cfg = load_config_from_string(+ _yaml("pretrain", {"modality": modality}, rope_scaling_type="dynamic")+ )++ assert cfg.training.rope_scaling_type == "dynamic"++ def test_the_longcontext_template(self):+ cfg = load_config_from_string(TEMPLATES["longcontext"])++ assert (cfg.task, cfg.backend) == ("sft", "transformers")+ assert cfg.training.rope_scaling_type == "dynamic"++ def test_the_longcontext_recipe(self):+ from soup_cli.recipes.catalog import get_recipe++ cfg = load_config_from_string(get_recipe("llama3.1-8b-longctx").yaml_str)++ assert (cfg.task, cfg.backend) == ("sft", "transformers")+ assert cfg.training.rope_scaling_type == "yarn"++ def test_the_longcontext_template_no_longer_suggests_unsloth(self):+ """Every other template carries the hint; this one sets a field that+ unsloth's setup does not read."""+ from importlib import resources++ packaged = (+ resources.files("soup_cli.templates").joinpath("longcontext.yaml").read_text("utf-8")+ )++ for text in (TEMPLATES["longcontext"], packaged):+ assert "rope_scaling_type: dynamic" in text+ assert "unsloth" not in text+++class TestAlreadyRefusedForAnotherReason:+ """Two rows of the issue's table never reached the new check, before or+ after: they are listed so nobody counts them as covered by it."""++ def test_pretrain_on_mlx(self):+ message = _refusal(_yaml("pretrain", {"backend": "mlx"}, rope_scaling_type="yarn"))++ assert "MLX backend only ships SFT" in message, message++ def test_pretrain_with_stream_layers(self):+ message = _refusal(+ _yaml("pretrain", stream_layers=True, batch_size=1, rope_scaling_type="yarn")+ )++ assert "training.stream_layers supports task in" in message, message+++class TestSoupDoctorReportsIt:+ @pytest.mark.parametrize(+ ("task", "top", "expected"),+ [+ ("dpo", {}, "training.rope_scaling_type is not applied by task='dpo'"),+ (+ "sft", {"backend": "mlx"},+ "training.rope_scaling_type is not applied by task='sft' with backend='mlx'",+ ),+ ],+ )+ def test_doctor_exits_2_naming_it(self, tmp_path, task, top, expected):+ from typer.testing import CliRunner++ from soup_cli.cli import app+ from tests.conftest import strip_ansi++ path = tmp_path / "soup.yaml"+ path.write_text(_yaml(task, top, rope_scaling_type="dynamic"), encoding="utf-8")++ result = CliRunner().invoke(app, ["doctor", "--config", str(path)])++ assert result.exit_code == 2, result.output+ assert expected in " ".join(strip_ansi(result.output).split())+++class TestValidatorOrder:+ def test_it_sits_before_the_backend_refusal(self):+ """#1357's backend refusal stays last; this one refuses on every+ backend, so it belongs in front of that."""+ validators = SoupConfig.__pydantic_decorators__.model_validators+ after = [name for name, dec in validators.items() if dec.info.mode == "after"]++ assert (+ after.index("_validate_freeze_is_applied")+ < after.index("_validate_rope_scaling_is_applied")+ < after.index("_validate_unsloth_has_a_setup")+ ), after[-4:]+ assert after[-1] == "_validate_unsloth_has_a_setup"+++def _reads_rope(source):+ """True when ``source`` reads the field as an attribute. Comments and+ docstrings do not count. Like the #1497 scan, a read through a helper+ outside the scanned code, or through ``getattr``, is not seen."""+ return any(+ isinstance(node, ast.Attribute) and node.attr == "rope_scaling_type"+ for node in ast.walk(ast.parse(textwrap.dedent(source)))+ )+++def _wrapper_reads_rope(cls):+ """The same question for a wrapper and the soup classes it inherits from."""+ return any(+ _reads_rope(inspect.getsource(klass))+ for klass in cls.__mro__+ if klass.__module__.startswith("soup_cli.")+ )+++def _dispatched_wrappers():+ """task -> wrapper class, read from the if-chain in ``trainer/dispatch.py``+ (the #1497 reader: a task added to the dispatcher is scanned without anyone+ remembering this file)."""+ from soup_cli.trainer import dispatch++ tree = ast.parse(Path(inspect.getsourcefile(dispatch)).read_text(encoding="utf-8"))+ found = {}+ for node in ast.walk(tree):+ if not isinstance(node, ast.If) or not isinstance(node.test, ast.Compare):+ continue+ test = node.test+ if not (isinstance(test.left, ast.Name) and test.left.id == "task"):+ continue+ right = test.comparators[0]+ if isinstance(test.ops[0], ast.Eq) and isinstance(right, ast.Constant):+ tasks = [right.value]+ elif isinstance(test.ops[0], ast.In) and isinstance(right, ast.Tuple):+ tasks = [elt.value for elt in right.elts]+ else:+ continue+ imports = [n for n in node.body if isinstance(n, ast.ImportFrom)]+ assert len(imports) == 1, f"expected one import under task={tasks}"+ module = importlib.import_module(imports[0].module)+ cls = getattr(module, imports[0].names[0].name)+ for task in tasks:+ found[task] = cls+ return found+++class TestTheTaskSplitFollowsTheTrainers:+ """A wrapper that reads the field must not have its task refused, and a+ wrapper that does not must."""++ def test_every_task_has_a_wrapper(self):+ assert set(_dispatched_wrappers()) == set(_TASKS)++ @pytest.mark.parametrize("task", _TASKS)+ def test_the_schema_list_matches_the_wrapper(self, task):+ wrappers = _dispatched_wrappers()+ if task == "preference":+ applies = all(_wrapper_reads_rope(wrappers[t]) for t in _PREFERENCE_DELEGATES)+ else:+ applies = _wrapper_reads_rope(wrappers[task])++ assert (task in ROPE_SCALING_APPLYING_TASKS) == applies, (+ f"task={task!r}: its trainer {'reads' if applies else 'does not read'} "+ "rope_scaling_type; move it in or out of ROPE_SCALING_APPLYING_TASKS"+ )+++def _setup_call(body):+ """The ``self._setup_*`` method a one-statement branch calls, or None."""+ if len(body) != 1 or not isinstance(body[0], ast.Expr):+ return None+ call = body[0].value+ if (+ isinstance(call, ast.Call)+ and isinstance(call.func, ast.Attribute)+ and call.func.attr.startswith("_setup_")+ ):+ return call.func.attr+ return None+++def _setup_dispatch_order(wrapper):+ """The ``self._setup_*`` methods of the if/else chain in ``wrapper.setup``+ that picks the load path, in order."""+ tree = ast.parse(textwrap.dedent(inspect.getsource(wrapper.setup)))+ for node in ast.walk(tree):+ if not isinstance(node, ast.If) or _setup_call(node.body) is None:+ continue+ order = []+ branch = node+ while True:+ order.append(_setup_call(branch.body))+ if len(branch.orelse) == 1 and isinstance(branch.orelse[0], ast.If):+ branch = branch.orelse[0]+ continue+ order.append(_setup_call(branch.orelse))+ break+ return order+ return []+++class TestThePathSplitFollowsTheSetups:+ """Each refused setting routes to a setup that does not read the field; the+ allowed ones do. A setup that starts rescaling RoPE fails here until its+ setting is dropped from the refusal."""++ @pytest.mark.parametrize("wrapper", [SFTTrainerWrapper, PretrainTrainerWrapper])+ def test_the_transformers_setups_read_the_field(self, wrapper):+ """Guard on the scan itself: if it stopped seeing these reads, every+ path would look refusable and the tests below would still pass."""+ assert _reads_rope(inspect.getsource(wrapper._setup_transformers))++ @pytest.mark.parametrize(+ ("wrapper", "method"),+ [+ (SFTTrainerWrapper, "_setup_vision_transformers"),+ (SFTTrainerWrapper, "_setup_audio_transformers"),+ (SFTTrainerWrapper, "_setup_streaming_transformers"),+ (SFTTrainerWrapper, "_setup_unsloth"),+ (PretrainTrainerWrapper, "_setup_unsloth"),+ ],+ )+ def test_the_refused_setups_do_not_read_it(self, wrapper, method):+ assert not _reads_rope(inspect.getsource(getattr(wrapper, method))), (+ f"{wrapper.__name__}.{method} now reads rope_scaling_type: drop its "+ "setting from the #1697 refusal in _validate_rope_scaling_is_applied"+ )++ def test_the_mlx_trainer_does_not_read_it(self):+ assert not _reads_rope(inspect.getsource(MLXSFTTrainerWrapper)), (+ "MLXSFTTrainerWrapper now reads rope_scaling_type: drop backend='mlx' "+ "from the #1697 refusal in _validate_rope_scaling_is_applied"+ )++ def test_the_sft_message_follows_the_dispatch_order(self):+ """The refusal names settings in the order ``setup`` checks them (MLX is+ resolved before the wrapper is built, so it comes first)."""+ assert _setup_dispatch_order(SFTTrainerWrapper) == [+ "_setup_vision_transformers",+ "_setup_audio_transformers",+ "_setup_streaming_transformers",+ "_setup_unsloth",+ "_setup_transformers",+ ]++ def test_pretrain_has_only_the_two_setups(self):+ assert _setup_dispatch_order(PretrainTrainerWrapper) == [+ "_setup_unsloth",+ "_setup_transformers",+ ]diff --git a/tests/test_unsloth.py b/tests/test_unsloth.pyindex b203ee12..435d3aac 100644--- a/tests/test_unsloth.py+++ b/tests/test_unsloth.py@@ -326,6 +326,11 @@ class TestTemplatesHaveUnslothHint:def test_templates_default_backend_commented(self):"""Templates should have unsloth commented out (not active by default)."""for name, template in TEMPLATES.items():+ if name == "longcontext":+ # #1697: it sets rope_scaling_type, which unsloth's setup does not+ # read, so the hint would suggest a line the loader refuses.+ assert "unsloth" not in template+ continueassert "# backend: unsloth" in template, f"{name} template missing unsloth hint"