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): read the final trainer config instead of the last config call (#1711)
Aditya Pratap Singh28ec1f3c4e5e
diff --git a/changelog.d/0.75.1/1711.fixed.md b/changelog.d/0.75.1/1711.fixed.mdnew file mode 100644index 00000000..bf330510--- /dev/null+++ b/changelog.d/0.75.1/1711.fixed.md@@ -0,0 +1 @@+- **Unsloth migration reads the final trainer's config**: task, output directory and hyperparameters come from the config passed to the last trainer, whether inline, named or positional. SFT warm-ups and unused later configs no longer overwrite stage settings. Warm-up `num_train_epochs` and other settings no longer leak into the final stage; this removes inherited `training.epochs: 2` from four public Qwen3 4B GRPO notebook variants (including AMD, Kaggle and Hugging Face Course). Earlier-stage warnings and config-only notebook behavior are preserved. (#1603 by @akkupratap323 in #1711)diff --git a/docs/data.md b/docs/data.mdindex 61a57eea..6264fe1c 100644--- a/docs/data.md+++ b/docs/data.md@@ -630,6 +630,12 @@ to replace), and `CPOTrainer` to `simpo` only when `loss_type="simpo"` is set onits own call or its `args=` config; any other CPO loss, or an `args=` that cannotbe read statically, stops the migration naming the value. `SFTConfig` and theother TRL `*Config` classes are read for hyperparameters.+The final trainer determines the task; its inline or named config, passed as `args=`+or positionally, supplies output and hyperparameters using the latest module-level+binding before that trainer (including annotated assignments).+Earlier stages retain warnings but cannot supply settings, and unused configs are ignored.+Aliases, conditional rebindings and unresolved `**kwargs` are not evaluated: migration+reports "Could not read the final trainer's args statically" and uses Soup defaults.## Data Formatsdiff --git a/src/soup_cli/migrate/unsloth.py b/src/soup_cli/migrate/unsloth.pyindex 74eeb311..0aaaf9dc 100644--- a/src/soup_cli/migrate/unsloth.py+++ b/src/soup_cli/migrate/unsloth.py@@ -198,10 +198,17 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:# `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):+ if isinstance(stmt, (ast.If, ast.Try, ast.With, ast.For, ast.While)):+ # Conditional writes cannot be resolved without executing notebook code.+ for node in ast.walk(stmt):+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):+ name_bindings.setdefault(node.id, []).append(node)+ continue+ if not isinstance(stmt, (ast.Assign, ast.AnnAssign)) or stmt.value is None:continueval = _ast_to_value(stmt.value)- for target in stmt.targets:+ targets = stmt.targets if isinstance(stmt, ast.Assign) else [stmt.target]+ for target in targets:if not isinstance(target, ast.Name):continuename_bindings.setdefault(target.id, []).append(stmt.value)@@ -220,6 +227,25 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:(n for n in ast.walk(tree) if isinstance(n, ast.Call)),key=lambda n: (n.lineno, n.col_offset),)+ trainers = [node for node in calls if _get_func_name(node) in _TRAINER_MAP]+ trainer_configs = {_trainer_config(node, name_bindings) for node in trainers}+ last_trainer = trainers[-1] if trainers else None+ if last_trainer is not None:+ task = _TRAINER_MAP[_get_func_name(last_trainer)]+ stage_config = _trainer_config(last_trainer, name_bindings)+ if stage_config is not None and not (+ isinstance(stage_config, ast.Call)+ and (_get_func_name(stage_config) == "TrainingArguments"+ or _get_func_name(stage_config) in _CONFIG_MAP)+ ):+ warnings.append(+ "Could not read the final trainer's args statically; "+ "training settings use Soup defaults."+ )+ else:+ # Preserve config-only notebooks, but never borrow an unrelated config+ # when a trainer exists (including a trainer using its defaults).+ stage_config = Nonefor node in calls:func_name = _get_func_name(node)@@ -271,10 +297,11 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:elif func_name in _TRAINER_MAP:# 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 node is last_trainer:+ task = _TRAINER_MAP[func_name]+ 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. "@@ -282,10 +309,21 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:)elif func_name == "TrainingArguments" or func_name in _CONFIG_MAP:+ if last_trainer is not None and node not in trainer_configs:+ continue+ kwargs = _extract_kwargs(node, scope=assignments)+ # Keep notes about real earlier stages, while unused configs have+ # no effect on the result. Only the final stage supplies settings.+ if "max_steps" in kwargs:+ warnings.append(+ f"max_steps={kwargs['max_steps']}. "+ "Soup uses epochs; set training.epochs instead."+ )+ if last_trainer is not None and node is not stage_config:+ continue# TrainingArguments(...), DPOConfig(...), etc.- if func_name in _CONFIG_MAP:+ if last_trainer is None and func_name in _CONFIG_MAP:task = _CONFIG_MAP[func_name]- kwargs = _extract_kwargs(node, scope=assignments)if "per_device_train_batch_size" in kwargs:training_params["batch_size"] = kwargs["per_device_train_batch_size"]if "num_train_epochs" in kwargs:@@ -303,11 +341,6 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:training_params["dpo_beta"] = kwargs["beta"]elif task == "kto":training_params["kto_beta"] = kwargs["beta"]- if "max_steps" in kwargs:- warnings.append(- f"max_steps={kwargs['max_steps']}. "- "Soup uses epochs; set training.epochs instead."- )if base is None:raise ValueError("No FastLanguageModel.from_pretrained() call found in notebook")@@ -399,6 +432,32 @@ _UNREAD = _UnreadType()_ONLINE_DPO_JUDGE_PLACEHOLDER = "ollama://REPLACE-ME"+def _trainer_config(+ trainer_call: ast.Call, name_bindings: Dict[str, List[ast.AST]],+) -> Optional[ast.AST]:+ """Resolve explicit args, else the first positional config after the model."""+ def resolve(config: ast.AST) -> ast.AST:+ if isinstance(config, ast.Name):+ preceding = [value for value in name_bindings.get(config.id, [])+ if (value.lineno, value.col_offset)+ < (trainer_call.lineno, trainer_call.col_offset)]+ return max(preceding, key=lambda value: (value.lineno, value.col_offset)) \+ if preceding else config+ return config++ for keyword in trainer_call.keywords:+ if keyword.arg == "args":+ return resolve(keyword.value)+ for argument in trainer_call.args[1:]:+ config = resolve(argument)+ if isinstance(config, ast.Call) and (+ _get_func_name(config) == "TrainingArguments" or _get_func_name(config) in _CONFIG_MAP+ ):+ return config+ # Expanded keywords may contain args; do not silently claim defaults were requested.+ return next((kw.value for kw in trainer_call.keywords if kw.arg is None), None)++def _cpo_loss_type(trainer_call: ast.Call,trainer_kwargs: Dict[str, Any],@@ -414,19 +473,9 @@ def _cpo_loss_type(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]+ config = _trainer_config(trainer_call, name_bindings)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 Noneif not (isinstance(config, ast.Call) and _get_func_name(config) == "CPOConfig"):return _UNREADif any(k.arg is None for k in config.keywords): # CPOConfig(**kw)diff --git a/tests/test_issue1603_trainer_config.py b/tests/test_issue1603_trainer_config.pynew file mode 100644index 00000000..fea5fd81--- /dev/null+++ b/tests/test_issue1603_trainer_config.py@@ -0,0 +1,171 @@+"""The final trainer owns migration settings, not the last config constructor."""++import json+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.unsloth import migrate_unsloth++from .conftest import strip_ansi+++def _notebook(tmp_path: Path, source: str) -> Path:+ path = tmp_path / "stage.ipynb"+ model = "model = FastLanguageModel.from_pretrained(model_name='test/model')\n"+ path.write_text(json.dumps({"cells": [{"cell_type": "code", "source": model + source}]}),+ encoding="utf-8")+ return path+++def _stage(task: str = "GRPO", warmup: str = "SFTConfig", first: bool = True) -> str:+ learning_rate = "5e-6" if task == "GRPO" else "5e-7"+ cfg = (f"cfg = {task}Config(learning_rate={learning_rate}, "+ "per_device_train_batch_size=4, output_dir='stage_out')\n")+ warm = (f"warmup = SFTTrainer(model, args={warmup}(learning_rate=2e-4, "+ "per_device_train_batch_size=1, output_dir='warmup_out'))\n")+ return (cfg + warm if first else warm + cfg) + f"trainer = {task}Trainer(model, args=cfg)\n"+++def _migrate(tmp_path: Path, source: str) -> dict:+ result = migrate_unsloth(_notebook(tmp_path, source))+ load_config_from_string(config_to_yaml(result))+ return result++[email protected]("task,lr", [("GRPO", 5e-6), ("DPO", 5e-7)])[email protected]("warmup", ["SFTConfig", "TrainingArguments"])+def test_grpo_first_uses_stage_hyperparameters(tmp_path: Path, task: str, lr: float,+ warmup: str) -> None:+ result = _migrate(tmp_path, _stage(task, warmup))+ assert result["task"] == task.lower()+ assert result["training"]["lr"] == lr+ assert result["training"]["batch_size"] == 4++[email protected]("warmup", ["SFTConfig", "TrainingArguments"])+def test_grpo_first_uses_stage_output(tmp_path: Path, warmup: str) -> None:+ assert _migrate(tmp_path, _stage(warmup=warmup))["output"] == "stage_out"+++def test_unused_config_after_final_trainer_does_not_change_task(tmp_path: Path) -> None:+ baseline = _migrate(tmp_path, _stage())+ unused = ("unused = SFTConfig(learning_rate=0.1, per_device_train_batch_size=8, "+ "output_dir='unused', max_steps=999)\n")+ assert _migrate(tmp_path, _stage() + unused) == baseline+++def test_warmup_first_control_is_unchanged(tmp_path: Path) -> None:+ assert _migrate(tmp_path, _stage(first=False)) == _migrate(tmp_path, _stage())++[email protected]("trainer,arguments", [+ ("GRPO", "args=cfg"),+ ("GRPO", "args=GRPOConfig(learning_rate=5e-6)"),+ ("GRPO", "reward_fn, cfg"),+ ("GRPO", "[a, b], cfg"),+ ("DPO", "None, cfg"),+ ("DPO", "ref_model, cfg"),+ ("SFT", "cfg"),+ ("Reward", "cfg"),+])+def test_inline_named_and_positional_configs(tmp_path: Path, trainer: str,+ arguments: str) -> None:+ source = (f"cfg = {trainer}Config(learning_rate=5e-6)\n"+ "unused = SFTConfig(learning_rate=0.1)\n"+ f"trainer = {trainer}Trainer(model, {arguments})\n")+ assert _migrate(tmp_path, source)["training"]["lr"] == 5e-6++[email protected]("task", ["DPO", "KTO"])+def test_beta_mapping_uses_final_trainer_task_before_config(tmp_path: Path, task: str) -> None:+ source = f"cfg = {task}Config(beta=0.3)\ntrainer = {task}Trainer(model, args=cfg)"+ assert _migrate(tmp_path, source)["training"][f"{task.lower()}_beta"] == 0.3+++def test_final_trainer_task_wins_over_config_class(tmp_path: Path) -> None:+ source = "trainer = GRPOTrainer(model, args=SFTConfig(learning_rate=1e-4))"+ result = _migrate(tmp_path, source)+ assert result["task"] == "grpo"+ assert result["training"]["lr"] == 1e-4+++def test_annotated_config_binding_is_resolved(tmp_path: Path) -> None:+ source = "cfg: GRPOConfig = GRPOConfig(learning_rate=5e-6)\nGRPOTrainer(model, args=cfg)"+ assert _migrate(tmp_path, source)["training"]["lr"] == 5e-6++[email protected]("statement", [+ "if flag:\n cfg = GRPOConfig(learning_rate=0.1)",+ "try:\n cfg = GRPOConfig(learning_rate=0.1)\nexcept Exception:\n pass",+ "with context:\n cfg = GRPOConfig(learning_rate=0.1)",+])+def test_conditional_rebinding_is_not_silently_reused(tmp_path: Path, statement: str) -> None:+ source = f"cfg = GRPOConfig(learning_rate=5e-6)\n{statement}\nGRPOTrainer(model, args=cfg)"+ result = _migrate(tmp_path, source)+ assert "lr" not in result["training"]+ assert any("Could not read" in note for note in result["_warnings"])+++def test_expanded_trainer_keywords_report_unreadable_args(tmp_path: Path) -> None:+ result = _migrate(tmp_path, "GRPOTrainer(model, **opts)")+ assert any("Could not read" in note for note in result["_warnings"])+++def test_binding_at_trainer_and_no_settings_leak_from_warmup(tmp_path: Path) -> None:+ source = ("cfg = GRPOConfig(learning_rate=5e-6)\n"+ "warmup = SFTTrainer(model, args=SFTConfig(num_train_epochs=9))\n"+ "trainer = GRPOTrainer(model, args=cfg)\n"+ "cfg = SFTConfig(learning_rate=0.1)\n")+ result = _migrate(tmp_path, source)+ assert result["training"]["lr"] == 5e-6+ assert "epochs" not in result["training"]++[email protected]("binding", ["cfg = None", "cfg = other", "cfg = make_config()"])+def test_unreadable_config_does_not_reuse_a_shadowed_binding(tmp_path: Path, binding: str) -> None:+ source = (f"cfg = GRPOConfig(learning_rate=5e-6)\n{binding}\n"+ "trainer = GRPOTrainer(model, args=cfg)")+ result = _migrate(tmp_path, source)+ assert result["task"] == "grpo"+ assert "lr" not in result["training"]+ assert any("Could not read" in warning for warning in result["_warnings"])+++def test_later_trainer_without_args_uses_defaults(tmp_path: Path) -> None:+ result = _migrate(tmp_path, _stage() + "last = SFTTrainer(model)\n")+ assert result["task"] == "sft"+ assert result["output"] == "./output"+ assert "lr" not in result["training"]++[email protected]("force_color", [False, True])+def test_cli_dry_run_emits_the_final_stage_config(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, force_color: bool,+) -> None:+ monkeypatch.chdir(tmp_path)+ _notebook(tmp_path, _stage())+ runner = CliRunner(env={"FORCE_COLOR": str(int(force_color)), "COLUMNS": "300"})+ result = runner.invoke(+ app, ["migrate", "--from", "unsloth", "stage.ipynb", "--dry-run"], color=force_color,+ )+ assert result.exit_code == 0, result.output+ # The CLI preview includes notes around the YAML; pin the emitted values.+ assert "task: grpo" in strip_ansi(result.output)+ assert "output: stage_out" in strip_ansi(result.output)+ assert "lr: 5.0e-06" in strip_ansi(result.output)+ assert "batch_size: 4" in strip_ansi(result.output)+ assert not (tmp_path / "soup.yaml").exists()+++def test_real_warmup_warnings_are_preserved_without_borrowing_settings(tmp_path: Path) -> None:+ source = ("warmup = SFTTrainer(model, packing=True, args=SFTConfig(max_steps=100))\n"+ "trainer = GRPOTrainer(model, args=GRPOConfig(max_steps=10, learning_rate=5e-6))")+ result = _migrate(tmp_path, source)+ assert any("max_steps=100" in note for note in result["_warnings"])+ assert any("packing=True" in note for note in result["_warnings"])+ assert result["training"]["lr"] == 5e-6