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(migrate): map every LLaMA-Factory pref_loss and TRL trainer class, refuse the rest by name (#1214) (#1560)
Srinivasan R0548438de235
diff --git a/changelog.d/0.75.1/1560.fixed.md b/changelog.d/0.75.1/1560.fixed.mdnew file mode 100644index 00000000..e3717a80--- /dev/null+++ b/changelog.d/0.75.1/1560.fixed.md@@ -0,0 +1 @@+- **`soup migrate` maps every LLaMA-Factory `pref_loss` and TRL trainer class to its Soup task, and refuses the rest by name (#1214 by @Srinivasan8888 in #1560).** LLaMA-Factory `stage: dpo` with `pref_loss: ipo` now migrates to `task: ipo` instead of plain `dpo`; `hinge`, `kto_pair` and any other value with no Soup task make `soup migrate` exit 1 naming the value and the supported list, instead of loading as `dpo` with no warning. Unsloth notebooks: `RewardTrainer` -> `reward_model`, `BCOTrainer` -> `bco`, `OnlineDPOTrainer` -> `online_dpo` (with a warning that the judge / reward model is not carried over), and `CPOTrainer` -> `simpo` only when the `loss_type="simpo"` on that trainer's own call or its `args=` config; other CPO losses are refused. `SFTConfig` and the other TRL `*Config` classes are now read for hyperparameters, so a notebook passing `args=SFTConfig(...)` keeps its batch size, epochs, learning rate and output directory. `OnlineDPOTrainer` notebooks migrate with `training.online_dpo_judge: ollama://REPLACE-ME` as a placeholder (TRL's judge is a Python object with no string form) and a warning naming it; replace it, or set `training.reward_model` instead. Migrations that used to produce a config and now stop with exit 1: LLaMA-Factory `stage: dpo` with `pref_loss: hinge`, `kto_pair`, any other unlisted value, or a scalar that is not a string such as `5` or `true` (they loaded as `task: dpo`; a list or mapping already stopped on `main`, with a `TypeError` traceback instead of the by-name message), and an Unsloth notebook whose `CPOTrainer` does not set `loss_type="simpo"` on its own call or its `args=` config, or whose `args=` cannot be read statically (they loaded as `task: sft`). Migrations whose result changes: LLaMA-Factory `pref_loss: orpo` / `simpo` under a stage other than `dpo` now keeps that stage's task, as LLaMA-Factory itself does (they loaded as `orpo` / `simpo`); and because `SFTConfig` is now in the config table, a notebook with a later `SFTTrainer(args=SFTConfig(...))` after another trainer migrates as `sft` (the last `*Config` call decides, as it already did for the other config classes). The axolotl migrator was settled by #1254.diff --git a/docs/data.md b/docs/data.mdindex 5e75077c..c6e105ac 100644--- a/docs/data.md+++ b/docs/data.md@@ -615,6 +615,17 @@ Automatically maps model, LoRA, training params, quantization, and task type. WaAn axolotl `rl:` value with no Soup task (for example `rl: ebft`) stops the migration: `soup migrate` exits 1 and names the value instead of writing a `task: sft` config.+The same rule holds for the other two sources. A LLaMA-Factory `stage: dpo` with+a `pref_loss` that has no Soup task (`hinge`, `kto_pair`, anything else) stops+the migration with exit 1 naming the value; `ipo` migrates to `task: ipo`, and+`pref_loss` is read only under `stage: dpo`, as LLaMA-Factory does. In an Unsloth+notebook `RewardTrainer` migrates to `reward_model`, `BCOTrainer` to `bco`,+`OnlineDPOTrainer` to `online_dpo` (with a placeholder `training.online_dpo_judge`+to replace), and `CPOTrainer` to `simpo` only when `loss_type="simpo"` is set on+its own call or its `args=` config; any other CPO loss, or an `args=` that cannot+be read statically, stops the migration naming the value. `SFTConfig` and the+other TRL `*Config` classes are read for hyperparameters.+## Data Formatsdiff --git a/src/soup_cli/migrate/llamafactory.py b/src/soup_cli/migrate/llamafactory.pyindex 9b364786..15acfa44 100644--- a/src/soup_cli/migrate/llamafactory.py+++ b/src/soup_cli/migrate/llamafactory.py@@ -17,9 +17,11 @@ _STAGE_MAP = {"ppo": "ppo",}-# LLaMA-Factory pref_loss → Soup task override (when stage=dpo)+# LLaMA-Factory pref_loss → Soup task override (when stage=dpo). #1214: a value+# with no Soup task (hinge, kto_pair) is refused by name, never defaulted to dpo._PREF_LOSS_MAP = {"sigmoid": "dpo",+ "ipo": "ipo","orpo": "orpo","simpo": "simpo",}@@ -61,9 +63,21 @@ def migrate_llamafactory(config_path: Path) -> Dict[str, Any]:stage = raw.get("stage", "sft")task = _STAGE_MAP.get(stage, "sft")- # Override task if pref_loss is specified (LF unifies under stage:dpo)+ # Override task if pref_loss is specified (LF unifies under stage:dpo, and+ # reads pref_loss only there).pref_loss = raw.get("pref_loss")- if pref_loss and pref_loss in _PREF_LOSS_MAP:+ if stage == "dpo" and pref_loss is not None:+ if not isinstance(pref_loss, str):+ raise ValueError(+ f"LLaMA-Factory pref_loss must name one loss as a string, got "+ f"{type(pref_loss).__name__}: {pref_loss!r}."+ )+ if pref_loss not in _PREF_LOSS_MAP:+ supported = ", ".join(sorted(_PREF_LOSS_MAP))+ raise ValueError(+ f"No Soup task matches LLaMA-Factory pref_loss: {pref_loss}. "+ f"Supported pref_loss values are {supported}."+ )task = _PREF_LOSS_MAP[pref_loss]data_format = _TASK_FORMAT_MAP.get(task, "auto")diff --git a/src/soup_cli/migrate/unsloth.py b/src/soup_cli/migrate/unsloth.pyindex 4f8e564d..76021a98 100644--- a/src/soup_cli/migrate/unsloth.py+++ b/src/soup_cli/migrate/unsloth.py@@ -8,7 +8,8 @@ import jsonfrom pathlib import Pathfrom typing import Any, Dict, List, Optional-# Trainer class → Soup task mapping+# Trainer class → Soup task mapping. #1214: "cpo" is provisional; CPOTrainer+# migrates to simpo only with loss_type="simpo" and is refused otherwise._TRAINER_MAP = {"SFTTrainer": "sft","DPOTrainer": "dpo",@@ -16,15 +17,25 @@ _TRAINER_MAP = {"KTOTrainer": "kto","ORPOTrainer": "orpo","PPOTrainer": "ppo",+ "RewardTrainer": "reward_model",+ "BCOTrainer": "bco",+ "OnlineDPOTrainer": "online_dpo",+ "CPOTrainer": "cpo",}-# Trainer config class → Soup task mapping+# Trainer config class → Soup task mapping (and the hyperparameter table: a+# call to any of these is read like TrainingArguments)._CONFIG_MAP = {+ "SFTConfig": "sft","DPOConfig": "dpo","GRPOConfig": "grpo","KTOConfig": "kto","ORPOConfig": "orpo","PPOConfig": "ppo",+ "RewardConfig": "reward_model",+ "BCOConfig": "bco",+ "OnlineDPOConfig": "online_dpo",+ "CPOConfig": "cpo",}# Task → default data format@@ -34,7 +45,11 @@ _TASK_FORMAT_MAP = {"grpo": "auto","kto": "kto","orpo": "dpo",+ "simpo": "dpo","ppo": "auto",+ "reward_model": "dpo",+ "bco": "dpo",+ "online_dpo": "auto",}@@ -85,11 +100,17 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:lora_params: Dict[str, Any] = {}training_params: Dict[str, Any] = {}task = "sft"+ cpo_loss_type: Optional[str] = Noneoutput_dir = "./output"# Collect variable assignments from notebook code (module-level only, in source order)assignments: Dict[str, Any] = {}ambiguous: set = set()+ # name -> every module-level binding of it, in source order, so a trainer call can+ # be resolved to the latest binding that precedes it (cells run top to bottom). Any+ # value counts, not only calls: a later `cfg = something_else` must shadow an earlier+ # `cfg = CPOConfig(...)`, and then the loss cannot be read.+ name_bindings: Dict[str, List[ast.AST]] = {}for stmt in tree.body:if not isinstance(stmt, ast.Assign):continue@@ -97,6 +118,7 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:for target in stmt.targets:if not isinstance(target, ast.Name):continue+ name_bindings.setdefault(target.id, []).append(stmt.value)if val is _SENTINEL or assignments.get(target.id, val) != val:ambiguous.add(target.id)else:@@ -104,10 +126,15 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:for name in ambiguous:assignments.pop(name, None)- # Walk AST to extract function call arguments- for node in ast.walk(tree):- if not isinstance(node, ast.Call):- continue+ # Visit every call in source order. ast.walk is breadth-first (by nesting depth),+ # which let a module-level `cfg = GRPOConfig(...)` be visited after an inline+ # `SFTTrainer(args=SFTConfig(...))` written earlier, so the SFT warm-up stage won+ # (#1560 review): the shape of Unsloth's GRPO notebooks.+ calls = sorted(+ (n for n in ast.walk(tree) if isinstance(n, ast.Call)),+ key=lambda n: (n.lineno, n.col_offset),+ )+ for node in calls:func_name = _get_func_name(node)if func_name is None:@@ -160,6 +187,8 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:# SFTTrainer(...), DPOTrainer(...), etc.task = _TRAINER_MAP[func_name]kwargs = _extract_kwargs(node, scope=assignments)+ if func_name == "CPOTrainer":+ cpo_loss_type = _cpo_loss_type(node, kwargs, assignments, name_bindings)if kwargs.get("packing"):warnings.append("packing=True is not supported in Soup. "@@ -197,6 +226,31 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:if base is None:raise ValueError("No FastLanguageModel.from_pretrained() call found in notebook")+ if task == "cpo":+ # TRL's CPOTrainer is SimPO only under loss_type="simpo"; its other losses+ # (sigmoid, hinge, ipo over CPO's reference-free objective) have no Soup task.+ if cpo_loss_type is _UNREAD:+ raise ValueError(+ "No Soup task matches CPOTrainer: its loss_type could not be read statically "+ "(args= is not a CPOConfig(...) call at module level, or uses **kwargs); "+ "only loss_type='simpo' migrates, to task: simpo."+ )+ if cpo_loss_type != "simpo":+ raise ValueError(+ f"No Soup task matches CPOTrainer with loss_type={cpo_loss_type!r} "+ "(TRL's default is 'sigmoid'); only loss_type='simpo' migrates, to task: simpo."+ )+ task = "simpo"+ if task == "online_dpo":+ # The schema requires a judge or a reward model, and TRL's judge is a Python+ # object with no string form, so a placeholder is written the way data.train is.+ training_params.setdefault("online_dpo_judge", _ONLINE_DPO_JUDGE_PLACEHOLDER)+ warnings.append(+ "OnlineDPOTrainer's judge / reward model is not carried over: "+ f"training.online_dpo_judge is a placeholder ({_ONLINE_DPO_JUDGE_PLACEHOLDER}); "+ "set it to your judge, or replace it with training.reward_model."+ )+# Build resultdata_format = _TASK_FORMAT_MAP.get(task, "auto")@@ -251,6 +305,49 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:return result+class _UnreadType:+ """Marker: the trainer takes an ``args=`` that static reading cannot resolve."""+++_UNREAD = _UnreadType()+_ONLINE_DPO_JUDGE_PLACEHOLDER = "ollama://REPLACE-ME"+++def _cpo_loss_type(+ trainer_call: ast.Call,+ trainer_kwargs: Dict[str, Any],+ scope: Dict[str, Any],+ name_bindings: Dict[str, List[ast.AST]],+) -> Any:+ """The ``loss_type`` that governs *this* ``CPOTrainer``: on the call itself, else on+ the ``CPOConfig`` passed as its config, ``args=`` or the second positional argument+ (TRL's ``CPOTrainer(model, args, ...)``), inline or through a name whose latest+ module-level binding precedes the trainer call. A ``CPOConfig`` elsewhere in the+ notebook, or one bound to the name only after the trainer ran, does not count.+ ``None`` means omitted (TRL's default, ``sigmoid``); ``_UNREAD`` means a config was+ passed that cannot be read statically."""+ if "loss_type" in trainer_kwargs:+ return trainer_kwargs["loss_type"]+ config: Optional[ast.AST] = next(+ (kw.value for kw in trainer_call.keywords if kw.arg == "args"), None+ )+ if config is None and len(trainer_call.args) >= 2:+ config = trainer_call.args[1]+ if config is None:+ return None+ if isinstance(config, ast.Name):+ preceding = [+ value for value in name_bindings.get(config.id, [])+ if value.lineno < trainer_call.lineno+ ]+ config = preceding[-1] if preceding else None+ if not (isinstance(config, ast.Call) and _get_func_name(config) == "CPOConfig"):+ return _UNREAD+ if any(k.arg is None for k in config.keywords): # CPOConfig(**kw)+ return _UNREAD+ return _extract_kwargs(config, scope=scope).get("loss_type")++def _get_func_name(node: ast.Call) -> Optional[str]:"""Extract the function name from a Call node."""if isinstance(node.func, ast.Name):diff --git a/tests/test_issue1214_migrators_pref_tasks.py b/tests/test_issue1214_migrators_pref_tasks.pynew file mode 100644index 00000000..a50466ef--- /dev/null+++ b/tests/test_issue1214_migrators_pref_tasks.py@@ -0,0 +1,443 @@+"""#1214, LLaMA-Factory and Unsloth halves: every preference objective the source tool+documents either migrates to its named Soup task or is refused by name.++#1254 settled the axolotl migrator. On ``main`` the other two still took a default:+LLaMA-Factory ``pref_loss: ipo`` loaded as ``task: dpo`` and ``hinge`` / ``kto_pair``+did the same with no warning; the Unsloth migrator kept ``task: sft`` for ``CPOTrainer``,+``RewardTrainer``, ``BCOTrainer`` and ``OnlineDPOTrainer``, and dropped every+hyperparameter passed through ``SFTConfig`` because only ``TrainingArguments`` and five+``*Config`` classes were read.+"""++from __future__ import annotations++import json+import re+from pathlib import Path++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.config.loader import load_config_from_string+from soup_cli.migrate.common import config_to_yaml+from soup_cli.migrate.llamafactory import migrate_llamafactory+from soup_cli.migrate.unsloth import migrate_unsloth+++def _plain(text: str) -> str:+ return re.sub(r"\s+", " ", re.sub(r"\x1b\[[0-9;?]*[A-Za-z]", "", text))+++def _loaded_task(result: dict) -> str:+ return load_config_from_string(config_to_yaml(result)).task+++# ---------------------------------------------------------------------------+# LLaMA-Factory: stage: dpo + pref_loss+# ---------------------------------------------------------------------------++_LF_BASE = (+ "model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"+ "stage: dpo\n"+ "finetuning_type: lora\n"+ "lora_rank: 16\n"+ "dataset: dpo_data\n"+ "cutoff_len: 2048\n"+ "per_device_train_batch_size: 2\n"+ "num_train_epochs: 1\n"+ "learning_rate: 5e-6\n"+ "output_dir: ./output_dpo\n"+)+++def _lf(tmp_path: Path, extra: str) -> dict:+ cfg = tmp_path / "lf.yaml"+ cfg.write_text(_LF_BASE + extra, encoding="utf-8")+ return migrate_llamafactory(cfg)+++class TestLlamaFactoryPrefLoss:+ @pytest.mark.parametrize(+ "pref_loss,soup_task",+ [("sigmoid", "dpo"), ("ipo", "ipo"), ("orpo", "orpo"), ("simpo", "simpo")],+ )+ def test_every_mapped_pref_loss_loads_as_its_soup_task(+ self, tmp_path: Path, pref_loss: str, soup_task: str+ ) -> None:+ result = _lf(tmp_path, f"pref_loss: {pref_loss}\n")+ assert _loaded_task(result) == soup_task+ assert result["data"]["format"] == "dpo"++ def test_a_pref_loss_that_is_not_a_string_is_refused_not_a_traceback(+ self, tmp_path: Path+ ) -> None:+ with pytest.raises(ValueError, match=r"pref_loss.*list.*hinge"):+ _lf(tmp_path, "pref_loss: [hinge]\n")++ @pytest.mark.parametrize("pref_loss", ["orpo", "simpo"])+ def test_pref_loss_under_another_stage_keeps_that_stage_task(+ self, tmp_path: Path, pref_loss: str+ ) -> None:+ # Changed behaviour, listed in the fragment: main overrode `stage: sft` to orpo /+ # simpo; LLaMA-Factory reads pref_loss only in its dpo stage.+ cfg = tmp_path / "lf.yaml"+ cfg.write_text(+ _LF_BASE.replace("stage: dpo", "stage: sft") + f"pref_loss: {pref_loss}\n",+ encoding="utf-8",+ )+ assert _loaded_task(migrate_llamafactory(cfg)) == "sft"++ @pytest.mark.parametrize("pref_loss", ["hinge", "kto_pair", "bogus"])+ def test_a_pref_loss_without_a_soup_task_is_refused_by_name(+ self, tmp_path: Path, pref_loss: str+ ) -> None:+ with pytest.raises(ValueError, match=pref_loss) as info:+ _lf(tmp_path, f"pref_loss: {pref_loss}\n")+ assert "ipo" in str(info.value) and "simpo" in str(info.value) # the supported list++ def test_control_stage_dpo_without_pref_loss_is_plain_dpo(self, tmp_path: Path) -> None:+ assert _loaded_task(_lf(tmp_path, "")) == "dpo"++ def test_pref_loss_outside_stage_dpo_is_ignored_as_llamafactory_does(+ self, tmp_path: Path+ ) -> None:+ # LLaMA-Factory reads pref_loss only in its dpo stage; a stray value under+ # stage: sft must neither change the task nor be refused.+ cfg = tmp_path / "lf.yaml"+ cfg.write_text(+ _LF_BASE.replace("stage: dpo", "stage: sft") + "pref_loss: hinge\n", encoding="utf-8"+ )+ assert _loaded_task(migrate_llamafactory(cfg)) == "sft"++ def test_cli_refuses_hinge_and_names_it(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.chdir(tmp_path)+ (tmp_path / "lf.yaml").write_text(_LF_BASE + "pref_loss: hinge\n", encoding="utf-8")+ result = CliRunner().invoke(+ app, ["migrate", "--from", "llamafactory", "lf.yaml", "--dry-run"]+ )+ assert result.exit_code == 1, result.output+ assert "hinge" in _plain(result.output)+++# ---------------------------------------------------------------------------+# Unsloth notebooks: TRL trainer classes and *Config hyperparameters+# ---------------------------------------------------------------------------+++def _notebook(trainer_cell: str) -> dict:+ return {+ "cells": [+ {+ "cell_type": "code",+ "source": [+ "from unsloth import FastLanguageModel\n",+ "model, tokenizer = FastLanguageModel.from_pretrained(\n",+ " model_name='meta-llama/Llama-3.1-8B-Instruct',\n",+ " max_seq_length=2048,\n",+ " load_in_4bit=True,\n",+ ")\n",+ "model = FastLanguageModel.get_peft_model(model, r=16, lora_alpha=32)\n",+ ],+ },+ {"cell_type": "code", "source": [trainer_cell]},+ ]+ }+++def _unsloth(tmp_path: Path, trainer_cell: str) -> dict:+ nb = tmp_path / "nb.ipynb"+ nb.write_text(json.dumps(_notebook(trainer_cell)), encoding="utf-8")+ return migrate_unsloth(nb)+++_TRAINERS = [+ # (trainer class, config class, loss kwarg on the config, Soup task)+ ("SFTTrainer", "SFTConfig", "", "sft"),+ ("DPOTrainer", "DPOConfig", "", "dpo"),+ ("GRPOTrainer", "GRPOConfig", "", "grpo"),+ ("KTOTrainer", "KTOConfig", "", "kto"),+ ("ORPOTrainer", "ORPOConfig", "", "orpo"),+ ("PPOTrainer", "PPOConfig", "", "ppo"),+ ("RewardTrainer", "RewardConfig", "", "reward_model"),+ ("BCOTrainer", "BCOConfig", "", "bco"),+ ("OnlineDPOTrainer", "OnlineDPOConfig", "", "online_dpo"),+ ("CPOTrainer", "CPOConfig", "loss_type='simpo', ", "simpo"),+]+# The data.format each task is written with; everything else is `auto`.+_FORMATS = {"dpo": "dpo", "orpo": "dpo", "simpo": "dpo", "reward_model": "dpo", "bco": "dpo",+ "kto": "kto"}+++class TestUnslothTrainerClasses:+ @pytest.mark.parametrize("trainer,config,loss_kwarg,soup_task", _TRAINERS)+ def test_every_trainer_class_migrates_to_its_soup_task_and_reads_its_config(+ self, tmp_path: Path, trainer: str, config: str, loss_kwarg: str, soup_task: str+ ) -> None:+ cell = (+ f"from trl import {trainer}, {config}\n"+ f"trainer = {trainer}(model=model, train_dataset=dataset,\n"+ f" args={config}({loss_kwarg}per_device_train_batch_size=2, num_train_epochs=3,\n"+ f" learning_rate=2e-4, output_dir='outputs'))\n"+ )+ result = _unsloth(tmp_path, cell)+ assert result["task"] == soup_task+ assert result["data"]["format"] == _FORMATS.get(soup_task, "auto")+ assert result["training"]["batch_size"] == 2+ assert result["training"]["epochs"] == 3+ assert result["training"]["lr"] == 2e-4+ assert result["output"] == "outputs"++ @pytest.mark.parametrize("trainer,config,loss_kwarg,soup_task", _TRAINERS)+ def test_the_migrated_config_loads_with_that_task(+ self, tmp_path: Path, trainer: str, config: str, loss_kwarg: str, soup_task: str+ ) -> None:+ cell = (+ f"from trl import {trainer}, {config}\n"+ f"trainer = {trainer}(model=model, train_dataset=dataset,\n"+ f" args={config}({loss_kwarg}per_device_train_batch_size=2))\n"+ )+ assert _loaded_task(_unsloth(tmp_path, cell)) == soup_task++ @pytest.mark.parametrize(+ "trainer,soup_task",+ [(t, task) for t, _c, loss, task in _TRAINERS if not loss],+ )+ def test_the_trainer_class_alone_sets_the_task_with_plain_training_arguments(+ self, tmp_path: Path, trainer: str, soup_task: str+ ) -> None:+ # No *Config class in sight: the trainer table must carry the task by itself.+ cell = (+ f"from trl import {trainer}\n"+ "from transformers import TrainingArguments\n"+ f"trainer = {trainer}(model=model, train_dataset=dataset,\n"+ " args=TrainingArguments(per_device_train_batch_size=2, output_dir='o'))\n"+ )+ result = _unsloth(tmp_path, cell)+ assert result["task"] == soup_task+ assert result["training"]["batch_size"] == 2++ def test_online_dpo_writes_a_placeholder_judge_and_says_so(self, tmp_path: Path) -> None:+ # The schema needs a judge or a reward model and TRL's judge is a Python object,+ # so the migrator writes a placeholder the way it writes data.train.+ cell = (+ "from trl import OnlineDPOTrainer, OnlineDPOConfig\n"+ "trainer = OnlineDPOTrainer(model=model, judge=judge, train_dataset=dataset,\n"+ " args=OnlineDPOConfig(per_device_train_batch_size=2))\n"+ )+ result = _unsloth(tmp_path, cell)+ assert result["training"]["online_dpo_judge"] == "ollama://REPLACE-ME"+ assert any("online_dpo_judge" in w and "placeholder" in w for w in result["_warnings"])+ assert any("training.reward_model" in w for w in result["_warnings"])+ assert _loaded_task(result) == "online_dpo"++ def test_cli_online_dpo_notebook_produces_a_loadable_config(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.chdir(tmp_path)+ cell = (+ "from trl import OnlineDPOTrainer, OnlineDPOConfig\n"+ "trainer = OnlineDPOTrainer(model=model, judge=judge, train_dataset=dataset,\n"+ " args=OnlineDPOConfig(per_device_train_batch_size=2))\n"+ )+ (tmp_path / "nb.ipynb").write_text(json.dumps(_notebook(cell)), encoding="utf-8")+ result = CliRunner().invoke(+ app, ["migrate", "--from", "unsloth", "nb.ipynb", "-o", "soup.yaml"]+ )+ assert result.exit_code == 0, result.output+ assert "online_dpo_judge" in _plain(result.output)+ written = (tmp_path / "soup.yaml").read_text(encoding="utf-8")+ assert load_config_from_string(written).task == "online_dpo"++ @pytest.mark.parametrize(+ "loss_kwarg,expected",+ [("", None), ("loss_type='sigmoid', ", "sigmoid"), ("loss_type='hinge', ", "hinge")],+ )+ def test_cpo_without_the_simpo_loss_is_refused_naming_the_value(+ self, tmp_path: Path, loss_kwarg: str, expected+ ) -> None:+ cell = (+ "from trl import CPOTrainer, CPOConfig\n"+ "trainer = CPOTrainer(model=model, train_dataset=dataset,\n"+ f" args=CPOConfig({loss_kwarg}per_device_train_batch_size=2))\n"+ )+ with pytest.raises(ValueError, match="CPOTrainer") as info:+ _unsloth(tmp_path, cell)+ assert f"loss_type={expected!r}" in str(info.value)+ assert "simpo" in str(info.value)++ @pytest.mark.parametrize(+ "args_expr",+ ["cfgs.cpo", "make_config()", "CPOConfig(**kw)", "later_name"],+ ids=["attribute", "factory call", "double-star kwargs", "name bound only later"],+ )+ def test_an_args_that_cannot_be_read_statically_is_refused_saying_so(+ self, tmp_path: Path, args_expr: str+ ) -> None:+ cell = (+ "from trl import CPOTrainer, CPOConfig\n"+ f"trainer = CPOTrainer(model=model, train_dataset=dataset, args={args_expr})\n"+ "later_name = CPOConfig(loss_type='simpo')\n"+ )+ with pytest.raises(ValueError, match="could not be read statically"):+ _unsloth(tmp_path, cell)++ def test_the_last_stage_in_source_order_decides_not_the_deepest_call(+ self, tmp_path: Path+ ) -> None:+ # An SFT warm-up with an inline SFTConfig, then GRPO with its config bound to a+ # name (the shape of Unsloth's GRPO notebooks). ast.walk is breadth-first, so the+ # nested SFTConfig used to be visited after the module-level GRPOConfig.+ cell = (+ "from trl import SFTTrainer, SFTConfig, GRPOTrainer, GRPOConfig\n"+ "t1 = SFTTrainer(model=model, train_dataset=ds,\n"+ " args=SFTConfig(per_device_train_batch_size=1, learning_rate=2e-4))\n"+ "cfg = GRPOConfig(per_device_train_batch_size=4, learning_rate=5e-6)\n"+ "t2 = GRPOTrainer(model=model, reward_funcs=[f], args=cfg)\n"+ )+ result = _unsloth(tmp_path, cell)+ assert result["task"] == "grpo"+ assert result["training"]["lr"] == 5e-6+ assert result["training"]["batch_size"] == 4++ def test_a_later_sft_config_call_now_decides_the_task(self, tmp_path: Path) -> None:+ # Changed behaviour, listed in the fragment: SFTConfig is in the config table,+ # so the last *Config call in the notebook decides, as it already did for the+ # other config classes.+ cell = (+ "from trl import GRPOTrainer, GRPOConfig, SFTTrainer, SFTConfig\n"+ "t1 = GRPOTrainer(model=model, train_dataset=dataset, args=GRPOConfig())\n"+ "t2 = SFTTrainer(model=model, train_dataset=dataset, args=SFTConfig())\n"+ )+ assert _unsloth(tmp_path, cell)["task"] == "sft"++ def test_an_unrelated_cpo_config_elsewhere_does_not_decide_the_trainer(+ self, tmp_path: Path+ ) -> None:+ # CodeRabbit on #1214: a leftover experiment cell with loss_type="simpo" must not+ # make the trainer that actually runs (default CPOConfig) migrate as simpo.+ cell = (+ "from trl import CPOTrainer, CPOConfig\n"+ "unused = CPOConfig(loss_type='simpo', per_device_train_batch_size=8)\n"+ "trainer = CPOTrainer(model=model, train_dataset=dataset, args=CPOConfig())\n"+ )+ with pytest.raises(ValueError, match="CPOTrainer"):+ _unsloth(tmp_path, cell)++ def test_cpo_config_assigned_to_a_name_then_passed_as_args_counts(+ self, tmp_path: Path+ ) -> None:+ cell = (+ "from trl import CPOTrainer, CPOConfig\n"+ "training_args = CPOConfig(loss_type='simpo', per_device_train_batch_size=2)\n"+ "trainer = CPOTrainer(model=model, train_dataset=dataset, args=training_args)\n"+ )+ result = _unsloth(tmp_path, cell)+ assert result["task"] == "simpo" and result["training"]["batch_size"] == 2++ def test_a_config_bound_to_the_name_only_after_the_trainer_does_not_count(+ self, tmp_path: Path+ ) -> None:+ # CodeRabbit on #1214, second round: cells run top to bottom, so the trainer+ # saw the first binding; the simpo one came later.+ cell = (+ "from trl import CPOTrainer, CPOConfig\n"+ "training_args = CPOConfig()\n"+ "trainer = CPOTrainer(model=model, train_dataset=dataset, args=training_args)\n"+ "training_args = CPOConfig(loss_type='simpo')\n"+ )+ with pytest.raises(ValueError, match="CPOTrainer"):+ _unsloth(tmp_path, cell)++ def test_the_latest_binding_before_the_trainer_wins(self, tmp_path: Path) -> None:+ cell = (+ "from trl import CPOTrainer, CPOConfig\n"+ "training_args = CPOConfig()\n"+ "training_args = CPOConfig(loss_type='simpo')\n"+ "trainer = CPOTrainer(model=model, train_dataset=dataset, args=training_args)\n"+ "training_args = CPOConfig(loss_type='hinge')\n"+ )+ assert _unsloth(tmp_path, cell)["task"] == "simpo"++ @pytest.mark.parametrize("rebinding", ["other_cfg", "cfgs.cpo", "None"])+ def test_a_config_name_rebound_to_a_non_call_cannot_be_read(+ self, tmp_path: Path, rebinding: str+ ) -> None:+ # CodeRabbit on round 2: the latest binding before the trainer is a name, an+ # attribute or a constant, not the earlier CPOConfig, so the loss cannot be read+ # and the trainer is refused. Recording only call bindings would miss this.+ cell = (+ "from trl import CPOTrainer, CPOConfig\n"+ "cfg = CPOConfig(loss_type='simpo')\n"+ f"cfg = {rebinding}\n"+ "trainer = CPOTrainer(model=model, train_dataset=dataset, args=cfg)\n"+ )+ with pytest.raises(ValueError, match="could not be read statically"):+ _unsloth(tmp_path, cell)++ @pytest.mark.parametrize(+ "config_expr,expected",+ [+ ("CPOConfig(loss_type='simpo', per_device_train_batch_size=2)", "simpo"),+ ("cfg", "simpo"),+ ],+ ids=["inline", "by name"],+ )+ def test_the_config_as_second_positional_argument_counts(+ self, tmp_path: Path, config_expr: str, expected: str+ ) -> None:+ # TRL's signature is CPOTrainer(model, args, ...); a notebook may pass it positionally.+ cell = (+ "from trl import CPOTrainer, CPOConfig\n"+ "cfg = CPOConfig(loss_type='simpo', per_device_train_batch_size=2)\n"+ f"trainer = CPOTrainer(model, {config_expr}, train_dataset=dataset)\n"+ )+ result = _unsloth(tmp_path, cell)+ assert result["task"] == expected and result["training"]["batch_size"] == 2++ def test_the_config_as_second_positional_without_simpo_is_refused(self, tmp_path: Path) -> None:+ cell = (+ "from trl import CPOTrainer, CPOConfig\n"+ "trainer = CPOTrainer(model, CPOConfig(per_device_train_batch_size=2),\n"+ " train_dataset=d)\n"+ )+ with pytest.raises(ValueError, match="loss_type=None"):+ _unsloth(tmp_path, cell)++ def test_cpo_loss_type_on_the_trainer_call_counts_too(self, tmp_path: Path) -> None:+ cell = (+ "from trl import CPOTrainer\n"+ "trainer = CPOTrainer(model=model, train_dataset=dataset, loss_type='simpo')\n"+ )+ assert _unsloth(tmp_path, cell)["task"] == "simpo"++ def test_sft_config_hyperparameters_are_read(self, tmp_path: Path) -> None:+ # The issue's third acceptance item, verbatim: the same kwargs under+ # TrainingArguments already survived; under SFTConfig they were dropped.+ cell = (+ "from trl import SFTTrainer, SFTConfig\n"+ "trainer = SFTTrainer(model=model, train_dataset=dataset,\n"+ " args=SFTConfig(per_device_train_batch_size=2, learning_rate=2e-4,\n"+ " num_train_epochs=3))\n"+ )+ training = _unsloth(tmp_path, cell)["training"]+ assert (training["batch_size"], training["lr"], training["epochs"]) == (2, 2e-4, 3)++ def test_control_training_arguments_still_read(self, tmp_path: Path) -> None:+ cell = (+ "from trl import SFTTrainer\n"+ "from transformers import TrainingArguments\n"+ "trainer = SFTTrainer(model=model, train_dataset=dataset,\n"+ " args=TrainingArguments(per_device_train_batch_size=4, output_dir='o'))\n"+ )+ result = _unsloth(tmp_path, cell)+ assert result["task"] == "sft"+ assert result["training"]["batch_size"] == 4 and result["output"] == "o"++ def test_an_unknown_trainer_class_still_defaults_to_sft(self, tmp_path: Path) -> None:+ # Not every call in a notebook is a TRL trainer; a class the table does not+ # list is not evidence of a different objective.+ cell = "trainer = MyTrainer(model=model, train_dataset=dataset)\n"+ assert _unsloth(tmp_path, cell)["task"] == "sft"