Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(migrate): map the fields soup migrate dropped or re-defaulted (#1901)

ndablizovdf640a4d1286
diff --git a/changelog.d/0.76.0/1901.fixed.md b/changelog.d/0.76.0/1901.fixed.md
new file mode 100644
index 00000000..9df7b437
--- /dev/null
+++ b/changelog.d/0.76.0/1901.fixed.md
@@ -0,0 +1 @@
+- `soup migrate` now writes what the source trained instead of Soup's defaults, and names what it cannot carry: axolotl `val_set_size` and LLaMA-Factory `val_size` map to `data.val_split` (`0` when absent, as both tools default); a LLaMA-Factory config without `lora_rank` / `lora_alpha` gets LLaMA-Factory's `r: 8, alpha: 2 * r`, a comma-separated `lora_target` becomes a list, and `lora_target: all` / axolotl `lora_target_linear: true` become `all-linear` rather than `auto` (two of seven projections on Llama); `pref_beta` under `pref_loss: ipo` maps to `training.ipo_tau` and `simpo_gamma` to `training.simpo_gamma`; the Unsloth migrator takes `base` from the training load, skipping the stock notebook's `if False:` reload, and reads `gradient_accumulation_steps`, `warmup_ratio`, `weight_decay` and `seed` from the final trainer's config. Every source key or trainer keyword a migrator does not map is listed in one "not migrated" warning (#1807 by @ndablizov in #1901)
diff --git a/docs/data.md b/docs/data.md
index 1ef97ba2..75e1c280 100644
--- a/docs/data.md
+++ b/docs/data.md
@@ -637,6 +637,33 @@ Earlier stages retain warnings but cannot supply settings, and unused configs ar
Aliases, conditional rebindings and unresolved `**kwargs` are not evaluated: migration
reports "Could not read the final trainer's args statically" and uses Soup defaults.
+A migrated config trains what the source trained, using the source tool's defaults
+where a key is absent (#1807):
+
+- **Validation split.** axolotl `val_set_size` and LLaMA-Factory `val_size` map to
+ `data.val_split`, and an absent key writes `0` (both tools train on every row by
+ default) rather than leaving Soup's default of 0.1 in force. A value `data.val_split`
+ cannot express (an absolute row count, or a fraction above 0.5) is named in a warning
+ and not written.
+- **LLaMA-Factory LoRA.** A missing `lora_rank` is 8 and a missing `lora_alpha` is
+ `2 * rank`, as LLaMA-Factory has them; a quoted rank (`lora_rank: "32"`) counts as the
+ integer. A comma-separated `lora_target` becomes a list,
+ and `lora_target: all` (also the default when the key is absent) becomes `all-linear`,
+ every linear layer; so does axolotl `lora_target_linear: true`. `auto` would have
+ resolved to `q_proj` / `v_proj` only on Llama.
+- **Preference strength.** `pref_beta` maps to `dpo_beta`, `kto_beta`, `orpo_beta`, or
+ `ipo_tau` under `pref_loss: ipo`; under `pref_loss: simpo` it has no Soup equivalent
+ and is named in a warning, while `simpo_gamma` maps to `training.simpo_gamma`.
+- **Unsloth notebooks.** `base` is the first `from_pretrained` call that names a model,
+ skipping code under `if False:` (the stock notebook's saved-adapter reload), so the
+ training model wins over the reload. `gradient_accumulation_steps`, `warmup_ratio`,
+ `weight_decay` and `seed` are read from the final trainer's `TrainingArguments` or
+ TRL `*Config`; `warmup_steps` has no Soup field (warmup comes from
+ `training.warmup_ratio`) and is named in a warning.
+- **Nothing is dropped in silence.** Every source key, `TrainingArguments` keyword or
+ `get_peft_model` keyword the migrator does not map is listed in one
+ "not migrated" warning.
+
## Data Formats
diff --git a/src/soup_cli/migrate/axolotl.py b/src/soup_cli/migrate/axolotl.py
index 2a4ce8cc..b47d5e83 100644
--- a/src/soup_cli/migrate/axolotl.py
+++ b/src/soup_cli/migrate/axolotl.py
@@ -4,7 +4,7 @@ from pathlib import Path
from typing import Any, Dict, List
from soup_cli.config.schema import SFT_KERNEL_AWARE_TASKS
-from soup_cli.migrate.common import to_number
+from soup_cli.migrate.common import to_number, unmapped_keys_warning, validation_split
from soup_cli.utils.yaml_limits import MAX_CONFIG_BYTES, load_yaml_file_limited
# Axolotl rl → Soup task mapping
@@ -31,6 +31,16 @@ _OPTIMIZER_MAP = {
"adamw_8bit": "adamw_bnb_8bit",
}
+# Every top-level key this migrator reads, mapped or warned about by name. Any
+# other key in the source is listed in one "not migrated" warning (#1807).
+_HANDLED_KEYS = frozenset({
+ "base_model", "rl", "datasets", "sequence_len", "val_set_size", "adapter", "lora_r",
+ "lora_alpha", "lora_dropout", "lora_target_linear", "lora_target_modules",
+ "micro_batch_size", "gradient_accumulation_steps", "num_epochs", "learning_rate",
+ "optimizer", "lr_scheduler", "warmup_ratio", "load_in_4bit", "load_in_8bit",
+ "flash_attention", "output_dir", "sample_packing", "wandb_project",
+})
+
# Task → default data format
_TASK_FORMAT_MAP = {
"sft": None, # Use dataset type
@@ -103,6 +113,11 @@ def migrate_axolotl(config_path: Path) -> Dict[str, Any]:
if "sequence_len" in raw:
data["max_length"] = raw["sequence_len"]
+ # val_set_size: axolotl's default is 0 (train on every row); without this
+ # mapping every migrated config got Soup's default of 0.1 (#1807).
+ val_split = validation_split(raw.get("val_set_size"), "val_set_size", warnings)
+ if val_split is not None:
+ data["val_split"] = val_split
# --- LoRA / Full Fine-tuning ---
adapter = raw.get("adapter")
@@ -121,7 +136,9 @@ def migrate_axolotl(config_path: Path) -> Dict[str, Any]:
if "lora_dropout" in raw:
lora_section["dropout"] = raw["lora_dropout"]
if raw.get("lora_target_linear"):
- lora_section["target_modules"] = "auto"
+ # Every linear layer; peft's spelling is ``all-linear``. ``auto`` would
+ # resolve to q_proj / v_proj on Llama, two of seven (#1807).
+ lora_section["target_modules"] = "all-linear"
elif "lora_target_modules" in raw:
lora_section["target_modules"] = raw["lora_target_modules"]
else:
@@ -197,6 +214,9 @@ def migrate_axolotl(config_path: Path) -> Dict[str, Any]:
warnings.append(
f"wandb_project: {raw['wandb_project']}. Use --wandb flag with soup train."
)
+ dropped = unmapped_keys_warning(raw, _HANDLED_KEYS, "axolotl")
+ if dropped is not None:
+ warnings.append(dropped)
result: Dict[str, Any] = {
"base": base,
diff --git a/src/soup_cli/migrate/common.py b/src/soup_cli/migrate/common.py
index 14aa634d..8884646e 100644
--- a/src/soup_cli/migrate/common.py
+++ b/src/soup_cli/migrate/common.py
@@ -1,7 +1,7 @@
"""Common utilities for config migration."""
from pathlib import Path
-from typing import Any, Dict
+from typing import Any, Dict, Iterable, List, Optional
# Max input file size for migration (10 MB — no legitimate config exceeds this)
MAX_CONFIG_FILE_SIZE = 10 * 1024 * 1024
@@ -41,6 +41,75 @@ def validate_output_path(path: Path) -> Path:
return resolved
+#: ``data.val_split`` is a ratio and the schema caps it at 0.5 (``le=0.5``).
+_MAX_VAL_SPLIT = 0.5
+
+
+def validation_split(value: Any, key: str, warnings: List[str]) -> Optional[float]:
+ """Map a source tool's validation-split setting to ``data.val_split`` (#1807).
+
+ axolotl (``val_set_size``) and LLaMA-Factory (``val_size``) default to 0 and
+ train on every row, so an absent key maps to ``0.0`` rather than to Soup's
+ default of 0.1. Both tools also accept an absolute row count (a value of 1
+ or more); ``data.val_split`` is a ratio capped at 0.5, so a value Soup cannot
+ express is named in ``warnings`` and ``None`` is returned, which leaves the
+ key out of the written config and Soup's default in force, with the warning
+ saying so.
+ """
+ if value is None:
+ return 0.0
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ warnings.append(
+ f"{key}: {value!r} could not be read as a number. Soup's default "
+ f"data.val_split 0.1 applies until you set it."
+ )
+ return None
+ if 0 <= value <= _MAX_VAL_SPLIT:
+ return float(value)
+ what = "an absolute row count" if value >= 1 else f"above {_MAX_VAL_SPLIT}"
+ warnings.append(
+ f"{key}: {value} is {what}; data.val_split is a ratio of at most "
+ f"{_MAX_VAL_SPLIT}, so it was not written. Soup's default 0.1 applies until "
+ f"you set data.val_split by hand."
+ )
+ return None
+
+
+def unmapped_keys_warning(
+ raw: Dict[str, Any], handled: Iterable[str], source: str
+) -> Optional[str]:
+ """One warning naming every top-level source key the migrator did not read (#1807).
+
+ ``handled`` is every key the migrator maps or already warns about by name;
+ anything else in ``raw`` would otherwise be dropped in silence. Returns
+ ``None`` when nothing was dropped.
+ """
+ handled_set = set(handled)
+ dropped = sorted(str(key) for key in raw if key not in handled_set)
+ if not dropped:
+ return None
+ return (
+ f"{len(dropped)} {source} key(s) not migrated (no Soup equivalent, or not read "
+ f"by soup migrate): {', '.join(dropped)}"
+ )
+
+
+def split_module_list(value: Any) -> Any:
+ """Normalise a LoRA target spelling to the list Soup and peft expect (#1807).
+
+ LLaMA-Factory takes ``lora_target`` as one comma-separated string
+ (``q_proj,v_proj``); peft matches a plain string against the whole module
+ name, so the string had to become a list. A single name becomes a one-item
+ list, a list is returned with its items stripped, and anything else is
+ returned unchanged for the schema to judge.
+ """
+ if isinstance(value, str):
+ return [part.strip() for part in value.split(",") if part.strip()]
+ if isinstance(value, (list, tuple)):
+ return [str(part).strip() for part in value]
+ return value
+
+
def to_number(value: Any) -> Any:
"""Convert string numeric values (e.g. '2e-4') to float/int.
diff --git a/src/soup_cli/migrate/llamafactory.py b/src/soup_cli/migrate/llamafactory.py
index 96baa30f..2d191638 100644
--- a/src/soup_cli/migrate/llamafactory.py
+++ b/src/soup_cli/migrate/llamafactory.py
@@ -3,9 +3,32 @@
from pathlib import Path
from typing import Any, Dict, List
-from soup_cli.migrate.common import to_number
+from soup_cli.migrate.common import (
+ split_module_list,
+ to_number,
+ unmapped_keys_warning,
+ validation_split,
+)
from soup_cli.utils.yaml_limits import MAX_CONFIG_BYTES, load_yaml_file_limited
+# LLaMA-Factory's own LoRA defaults (src/llamafactory/hparams/finetuning_args.py:
+# ``lora_rank`` 8, ``lora_alpha = lora_alpha or lora_rank * 2``). A migrated config
+# without the keys must train what LLaMA-Factory trained, not Soup's r 64 / alpha 16,
+# which is an 8x larger adapter at an 8x smaller alpha / r (#1807).
+_LF_DEFAULT_LORA_RANK = 8
+
+# Every top-level key this migrator reads, mapped or warned about by name. Any
+# other key in the source is listed in one "not migrated" warning (#1807).
+_HANDLED_KEYS = frozenset({
+ "model_name_or_path", "stage", "pref_loss", "finetuning_type", "lora_rank",
+ "lora_alpha", "lora_dropout", "lora_target", "use_dora", "num_train_epochs",
+ "learning_rate", "per_device_train_batch_size", "gradient_accumulation_steps",
+ "lr_scheduler_type", "warmup_ratio", "quantization_bit", "quantization_method",
+ "pref_beta", "simpo_gamma", "reward_model", "loraplus_lr_ratio", "dataset",
+ "cutoff_len", "val_size", "output_dir", "bf16", "fp16", "deepspeed", "report_to",
+ "neftune_noise_alpha", "template",
+})
+
# LLaMA-Factory stage → Soup task mapping
_STAGE_MAP = {
"sft": "sft",
@@ -39,6 +62,24 @@ _TASK_FORMAT_MAP = {
}
+def _lora_int(value: Any, key: str, warnings: List[str]) -> Any:
+ """``lora_rank: "8"`` (quoted in the YAML) is the integer 8.
+
+ LLaMA-Factory's parser does not coerce it, but the author meant 8, and the
+ ``alpha = 2 * rank`` default below needs the integer. Anything else that is
+ not an integer is copied as written and named, so the missing alpha default
+ is not a silent one (#1807).
+ """
+ if isinstance(value, bool) or not isinstance(value, str):
+ return value
+ text = value.strip()
+ if text.isdigit():
+ return int(text)
+ note = ", and lora_alpha was not defaulted from it" if key == "lora_rank" else ""
+ warnings.append(f"{key}: {value!r} is not an integer; copied as written{note}.")
+ return value
+
+
def migrate_llamafactory(config_path: Path) -> Dict[str, Any]:
"""Parse a LLaMA-Factory YAML config and return a Soup config dict.
@@ -116,16 +157,30 @@ def migrate_llamafactory(config_path: Path) -> Dict[str, Any]:
)
if include_lora:
- lora_section["r"] = raw.get("lora_rank", 64)
- lora_section["alpha"] = raw.get("lora_alpha", 16)
+ # LLaMA-Factory's defaults, not Soup's: r 8, alpha 2 * r (#1807).
+ rank = raw.get("lora_rank")
+ if rank is None:
+ rank = _LF_DEFAULT_LORA_RANK
+ else:
+ rank = _lora_int(rank, "lora_rank", warnings)
+ lora_section["r"] = rank
+ alpha = raw.get("lora_alpha")
+ if alpha is not None:
+ alpha = _lora_int(alpha, "lora_alpha", warnings)
+ if alpha is None and isinstance(rank, int) and not isinstance(rank, bool):
+ alpha = 2 * rank
+ if alpha is not None:
+ lora_section["alpha"] = alpha
if "lora_dropout" in raw:
lora_section["dropout"] = raw["lora_dropout"]
- # lora_target: "all" → auto
+ # lora_target: "all" (and LLaMA-Factory's default when the key is absent)
+ # means every linear layer; peft's spelling of that is ``all-linear``.
+ # ``auto`` would resolve to q_proj / v_proj on Llama, two of seven (#1807).
lora_target = raw.get("lora_target")
if lora_target == "all" or lora_target is None:
- lora_section["target_modules"] = "auto"
+ lora_section["target_modules"] = "all-linear"
else:
- lora_section["target_modules"] = lora_target
+ lora_section["target_modules"] = split_module_list(lora_target)
if raw.get("use_dora"):
lora_section["use_dora"] = True
@@ -199,6 +254,42 @@ def migrate_llamafactory(config_path: Path) -> Dict[str, Any]:
training["kto_beta"] = pref_beta
elif task == "orpo":
training["orpo_beta"] = pref_beta
+ elif task == "ipo":
+ # One knob under three names, shown rather than assumed (#1807):
+ # LLaMA-Factory 1fded91 src/llamafactory/train/dpo/trainer.py:79-80 keeps
+ # pref_beta as self.beta and pref_loss as self.loss_type, and for ipo
+ # (:205-207, use_ref_model is True) hands both to trl's dpo_loss;
+ # trl 0.29.1 trl/trainer/dpo_trainer.py:1241-1252 computes the IPO loss
+ # as (delta - 1 / (2 * self.beta)) ** 2, and trl/trainer/dpo_config.py:
+ # 252-256 documents that beta as IPO's regularisation parameter (tau);
+ # Soup's trainer/ipo.py:173-174 passes training.ipo_tau as that beta.
+ # All three default to 0.1 (finetuning_args.py:171-172, dpo_config.py:253,
+ # schema.py ipo_tau), so an absent pref_beta stays absent here and Soup's
+ # default applies.
+ training["ipo_tau"] = pref_beta
+ elif task == "simpo":
+ # Soup's SimPO trainer leaves trl's beta at its default and has no
+ # field for it, so the value cannot be carried; say so (#1807).
+ warnings.append(
+ f"pref_beta: {pref_beta} under pref_loss: simpo has no Soup equivalent "
+ "(task: simpo takes training.simpo_gamma and training.cpo_alpha; trl's "
+ "SimPO beta stays at its default). Dropped."
+ )
+ else:
+ warnings.append(
+ f"pref_beta: {pref_beta} is not read by LLaMA-Factory for stage: {stage}, "
+ "and Soup has no equivalent on task: "
+ f"{task}. Dropped."
+ )
+ simpo_gamma = raw.get("simpo_gamma")
+ if simpo_gamma is not None:
+ if task == "simpo":
+ training["simpo_gamma"] = simpo_gamma
+ else:
+ warnings.append(
+ f"simpo_gamma: {simpo_gamma} applies to pref_loss: simpo only "
+ f"(this config migrates to task: {task}). Dropped."
+ )
if "reward_model" in raw:
training["reward_model"] = raw["reward_model"]
@@ -227,6 +318,11 @@ def migrate_llamafactory(config_path: Path) -> Dict[str, Any]:
data["format"] = data_format
if "cutoff_len" in raw:
data["max_length"] = raw["cutoff_len"]
+ # val_size: LLaMA-Factory's default is 0 (train on every row); without this
+ # mapping every migrated config got Soup's default of 0.1 (#1807).
+ val_split = validation_split(raw.get("val_size"), "val_size", warnings)
+ if val_split is not None:
+ data["val_split"] = val_split
# --- Output ---
output = raw.get("output_dir", "./output")
@@ -249,6 +345,9 @@ def migrate_llamafactory(config_path: Path) -> Dict[str, Any]:
template_name = raw.get("template")
if template_name:
warnings.append(f"Original template: {template_name} (auto-detected in Soup)")
+ dropped = unmapped_keys_warning(raw, _HANDLED_KEYS, "LLaMA-Factory")
+ if dropped is not None:
+ warnings.append(dropped)
result: Dict[str, Any] = {
"base": base,
diff --git a/src/soup_cli/migrate/unsloth.py b/src/soup_cli/migrate/unsloth.py
index 0aaaf9dc..cd065957 100644
--- a/src/soup_cli/migrate/unsloth.py
+++ b/src/soup_cli/migrate/unsloth.py
@@ -9,6 +9,22 @@ import warnings
from pathlib import Path
from typing import Any, Dict, List, Optional
+from soup_cli.migrate.common import unmapped_keys_warning
+
+# The ``TrainingArguments`` / TRL ``*Config`` keywords the migrator maps or warns
+# about by name; any other keyword on the final stage's config is listed in one
+# "not migrated" warning so a dropped setting is never silent (#1807).
+_HANDLED_CONFIG_KWARGS = frozenset({
+ "per_device_train_batch_size", "num_train_epochs", "learning_rate", "optim",
+ "lr_scheduler_type", "output_dir", "beta", "max_steps", "gradient_accumulation_steps",
+ "weight_decay", "seed", "warmup_ratio", "warmup_steps", "loss_type",
+})
+
+# The ``get_peft_model`` keywords the migrator maps; the rest are listed the same way.
+_HANDLED_PEFT_KWARGS = frozenset({
+ "r", "lora_alpha", "lora_dropout", "target_modules", "use_dora", "use_rslora",
+})
+
# Trainer class → Soup task mapping. #1214: "cpo" is provisional; CPOTrainer
# migrates to simpo only with loss_type="simpo" and is refused otherwise.
_TRAINER_MAP = {
@@ -227,6 +243,11 @@ 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),
)
+ # Code under ``if False:`` never runs. The stock Unsloth notebook keeps its
+ # inference-time reload of the saved adapter there, after the training cell,
+ # and "last call wins" made ``base: lora_model`` out of it (#1807).
+ dead = _dead_code_spans(tree)
+ calls = [node for node in calls if not _in_dead_code(node, dead)]
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
@@ -253,21 +274,30 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:
continue
if func_name == "from_pretrained":
- # FastLanguageModel.from_pretrained(...)
+ # FastLanguageModel.from_pretrained(...). The FIRST live call that names
+ # a model is the load that trains; a later one at top level is the
+ # notebook reloading what it saved (#1807). Everything below is read
+ # from that one call.
+ if base is not None:
+ continue
unresolved: List[tuple[str, str]] = []
kwargs = _extract_kwargs(node, scope=assignments, unresolved_names=unresolved)
+ candidate: Optional[str] = None
+ if node.args:
+ arg_val = _ast_to_value(node.args[0])
+ if arg_val is not _SENTINEL and isinstance(arg_val, str):
+ candidate = arg_val
+ if isinstance(kwargs.get("model_name"), str):
+ candidate = kwargs["model_name"]
+ if candidate is None:
+ continue
+ base = candidate
for kw_arg, var_name in unresolved:
if kw_arg in ("load_in_4bit", "load_in_8bit", "load_in_16bit", "full_finetuning"):
warnings.append(
f"Could not read precision argument '{kw_arg}' "
f"(passed as variable '{var_name}')."
)
- if node.args:
- arg_val = _ast_to_value(node.args[0])
- if arg_val is not _SENTINEL and isinstance(arg_val, str):
- base = arg_val
- if "model_name" in kwargs:
- base = kwargs["model_name"]
if "max_seq_length" in kwargs:
max_seq_length = kwargs["max_seq_length"]
if "load_in_4bit" in kwargs:
@@ -294,6 +324,11 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:
lora_params["use_dora"] = kwargs["use_dora"]
if "use_rslora" in kwargs and kwargs["use_rslora"]:
lora_params["use_rslora"] = True
+ dropped = unmapped_keys_warning(
+ _keyword_names(node), _HANDLED_PEFT_KWARGS, "get_peft_model argument"
+ )
+ if dropped is not None:
+ warnings.append(dropped)
elif func_name in _TRAINER_MAP:
# SFTTrainer(...), DPOTrainer(...), etc.
@@ -341,6 +376,31 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:
training_params["dpo_beta"] = kwargs["beta"]
elif task == "kto":
training_params["kto_beta"] = kwargs["beta"]
+ # #1807: these four were never read, so GA 16 trained as Soup's 4,
+ # weight decay 0.1 as 0.01, and the seed was lost.
+ if "gradient_accumulation_steps" in kwargs:
+ training_params["gradient_accumulation_steps"] = (
+ kwargs["gradient_accumulation_steps"]
+ )
+ if "weight_decay" in kwargs:
+ training_params["weight_decay"] = kwargs["weight_decay"]
+ if "seed" in kwargs:
+ training_params["seed"] = kwargs["seed"]
+ if "warmup_ratio" in kwargs:
+ training_params["warmup_ratio"] = kwargs["warmup_ratio"]
+ if "warmup_steps" in kwargs:
+ # Soup derives the warmup length from training.warmup_ratio (and
+ # warmup_auto); a step count has no field to land in.
+ warnings.append(
+ f"warmup_steps={kwargs['warmup_steps']} has no Soup equivalent: Soup "
+ "sets warmup from training.warmup_ratio (default 0.03, in force until "
+ "you change it). Pick the ratio that matches your dataset size."
+ )
+ dropped = unmapped_keys_warning(
+ _keyword_names(node), _HANDLED_CONFIG_KWARGS, f"{func_name} argument"
+ )
+ if dropped is not None:
+ warnings.append(dropped)
if base is None:
raise ValueError("No FastLanguageModel.from_pretrained() call found in notebook")
@@ -483,6 +543,39 @@ def _cpo_loss_type(
return _extract_kwargs(config, scope=scope).get("loss_type")
+def _keyword_names(node: ast.Call) -> Dict[str, Any]:
+ """The explicit keyword names on a call, resolvable or not, for the unmapped listing.
+
+ ``_extract_kwargs`` keeps only values it can read; a dropped setting passed
+ as a variable is still dropped, so the listing works from names (#1807).
+ """
+ return {kw.arg: None for kw in node.keywords if kw.arg is not None}
+
+
+def _is_constant_false(test: ast.AST) -> bool:
+ """``if False:`` / ``if 0:`` / ``if None:`` — a suite that never runs."""
+ return isinstance(test, ast.Constant) and not test.value
+
+
+def _dead_code_spans(tree: ast.AST) -> List[tuple[int, int]]:
+ """Line spans of ``if <constant false>:`` bodies (not their ``else`` branches).
+
+ Unsloth's notebooks park the saved-adapter reload under ``if False:``; the
+ code is never executed, so nothing in it describes the run (#1807).
+ """
+ spans: List[tuple[int, int]] = []
+ for node in ast.walk(tree):
+ if isinstance(node, ast.If) and _is_constant_false(node.test) and node.body:
+ first, last = node.body[0], node.body[-1]
+ end = getattr(last, "end_lineno", None) or last.lineno
+ spans.append((first.lineno, end))
+ return spans
+
+
+def _in_dead_code(node: ast.AST, spans: List[tuple[int, int]]) -> bool:
+ return any(start <= node.lineno <= end for start, end in spans)
+
+
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_issue1215_migrate_quantization_none.py b/tests/test_issue1215_migrate_quantization_none.py
index 374d6a9d..bded2354 100644
--- a/tests/test_issue1215_migrate_quantization_none.py
+++ b/tests/test_issue1215_migrate_quantization_none.py
@@ -246,7 +246,8 @@ class TestLlamaFactoryQuantizationAndFullFinetuning:
assert any("oft" in w for w in res["_warnings"])
loaded = load_config_from_string(config_to_yaml(res))
assert loaded.training.quantization == "none"
- assert loaded.training.lora.r == 64
+ # LLaMA-Factory's own default rank (#1807), not Soup's 64.
+ assert loaded.training.lora.r == 8
class TestUnslothQuantizationAndFullFinetuning:
diff --git a/tests/test_migrate.py b/tests/test_migrate.py
index c4fcc0aa..26bdf461 100644
--- a/tests/test_migrate.py
+++ b/tests/test_migrate.py
@@ -546,13 +546,17 @@ class TestLlamaFactoryMigration:
assert result["output"] == "./output"
def test_sft_lora_target_all(self, tmp_path):
- """lora_target: all → auto (Soup auto-detects)."""
+ """lora_target: all → all-linear (every linear layer, as LLaMA-Factory trains it).
+
+ #1807: ``auto`` resolved to q_proj / v_proj on Llama, two of the seven
+ projections ``all`` names.
+ """
from soup_cli.migrate.llamafactory import migrate_llamafactory
cfg_file = tmp_path / "config.yaml"
cfg_file.write_text(LLAMA_FACTORY_SFT, encoding="utf-8")
result = migrate_llamafactory(cfg_file)
- assert result["training"]["lora"]["target_modules"] == "auto"
+ assert result["training"]["lora"]["target_modules"] == "all-linear"
def test_dpo_config(self, tmp_path):
"""DPO stage maps to task: dpo with dpo_beta."""
@@ -818,13 +822,14 @@ class TestAxolotlMigration:
assert result["training"]["quantization"] == "4bit"
def test_lora_target_linear(self, tmp_path):
- """lora_target_linear: true → target_modules: auto."""
+ """lora_target_linear: true → target_modules: all-linear (#1807; ``auto`` wrapped
+ q_proj / v_proj only on Llama)."""
from soup_cli.migrate.axolotl import migrate_axolotl
cfg_file = tmp_path / "config.yaml"
cfg_file.write_text(AXOLOTL_LORA_TARGET_LINEAR, encoding="utf-8")
result = migrate_axolotl(cfg_file)
- assert result["training"]["lora"]["target_modules"] == "auto"
+ assert result["training"]["lora"]["target_modules"] == "all-linear"
def test_adamw_8bit_mapping(self, tmp_path):
"""adamw_8bit → adamw_bnb_8bit."""
diff --git a/tests/test_migrate_axolotl_fields.py b/tests/test_migrate_axolotl_fields.py
new file mode 100644
index 00000000..e5b2fbad
--- /dev/null
+++ b/tests/test_migrate_axolotl_fields.py
@@ -0,0 +1,112 @@
+"""#1807 — the axolotl migrator maps the validation split and every-linear targets.
+
+Before: ``val_set_size`` was never read, so every migrated config got Soup's
+default ``val_split: 0.1`` where axolotl's default is 0 (the source trained on
+every row), and ``lora_target_linear: true`` (every linear layer) became
+``auto``, which on Llama wraps q_proj / v_proj only. Keys with no mapping were
+dropped without a word.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from soup_cli.config.loader import load_config_from_string
+from soup_cli.migrate.axolotl import migrate_axolotl
+from soup_cli.migrate.common import config_to_yaml
+
+_BASE = (
+ "base_model: meta-llama/Llama-3.1-8B\nadapter: lora\nlora_r: 16\nlora_alpha: 32\n"
+ "datasets:\n - path: d.jsonl\n type: alpaca\n"
+)
+
+
+def _migrate(tmp_path: Path, text: str):
+ path = tmp_path / "ax.yaml"
+ path.write_text(text, encoding="utf-8")
+ result = migrate_axolotl(path)
+ cfg = load_config_from_string(config_to_yaml(result))
+ return result, cfg
+
+
+def test_the_reported_config_now_trains_what_axolotl_trains(tmp_path: Path) -> None:
+ _, cfg = _migrate(tmp_path, _BASE + "lora_target_linear: true\nval_set_size: 0\n")
+ assert cfg.training.lora.target_modules == "all-linear"
+ assert cfg.data.val_split == 0
+
+
+ "line,expected",
+ [("val_set_size: 0\n", 0.0), ("val_set_size: 0.0\n", 0.0), ("val_set_size: 0.05\n", 0.05),
+ ("", 0.0)],
+)
+def test_val_set_size_round_trips_and_is_zero_when_absent(tmp_path: Path, line, expected) -> None:
+ result, cfg = _migrate(tmp_path, _BASE + line)
+ assert result["data"]["val_split"] == expected
+ assert cfg.data.val_split == expected
+
+
+def test_a_row_count_is_named_not_defaulted_silently(tmp_path: Path) -> None:
+ # axolotl accepts an absolute number of rows; data.val_split is a ratio <= 0.5.
+ result, cfg = _migrate(tmp_path, _BASE + "val_set_size: 500\n")
+ assert "val_split" not in result["data"]
+ assert any("val_set_size" in w and "500" in w for w in result["_warnings"])
+ assert cfg.data.val_split == 0.1
+
+
+def test_a_fraction_above_one_half_is_named_not_written(tmp_path: Path) -> None:
+ # The same shared helper as LLaMA-Factory's val_size: the "above 0.5" branch,
+ # pinned apart from the row-count one (#1901 review).
+ result, cfg = _migrate(tmp_path, _BASE + "val_set_size: 0.7\n")
+ assert "val_split" not in result["data"]
+ assert any(w.startswith("val_set_size: 0.7") and "above 0.5" in w and "not written" in w
+ for w in result["_warnings"])
+ assert cfg.data.val_split == 0.1
+
+
+def test_lora_target_modules_list_is_still_copied(tmp_path: Path) -> None:
+ _, cfg = _migrate(tmp_path, _BASE + "lora_target_modules:\n - q_proj\n - k_proj\n")
+ assert cfg.training.lora.target_modules == ["q_proj", "k_proj"]
+
+
+def test_without_either_target_key_the_default_stays_auto(tmp_path: Path) -> None:
+ result, _ = _migrate(tmp_path, _BASE)
+ assert "target_modules" not in result["training"]["lora"]
+
+
+def test_unmapped_source_keys_are_listed_in_one_warning(tmp_path: Path) -> None:
+ result, _ = _migrate(
+ tmp_path, _BASE + "logging_steps: 1\nsaves_per_epoch: 1\nspecial_tokens:\n pad_token: x\n"
+ )
+ listing = [w for w in result["_warnings"] if "not migrated" in w]
+ assert len(listing) == 1, result["_warnings"]
+ for key in ("logging_steps", "saves_per_epoch", "special_tokens"):
+ assert key in listing[0]
+ for key in ("base_model", "adapter", "lora_r", "datasets"):
+ assert key not in listing[0]
+
+
+def test_a_fully_mapped_config_has_no_unmapped_listing(tmp_path: Path) -> None:
+ result, _ = _migrate(tmp_path, _BASE + "val_set_size: 0\nsequence_len: 1024\nnum_epochs: 1\n")
+ assert not any("not migrated" in w for w in result["_warnings"])
+
+
+def test_all_linear_wraps_every_linear_projection_of_a_tiny_llama(tmp_path: Path) -> None:
+ import torch
+ from peft import get_peft_model
+ from transformers import LlamaConfig, LlamaForCausalLM
+
+ from soup_cli.utils.peft_wiring import build_lora_config
+
+ _, cfg = _migrate(tmp_path, _BASE + "lora_target_linear: true\n")
+ torch.manual_seed(0)
+ tiny = LlamaForCausalLM(LlamaConfig(
+ vocab_size=128, hidden_size=32, intermediate_size=64, num_hidden_layers=2,
+ num_attention_heads=4, num_key_value_heads=4, max_position_embeddings=64,
+ ))
+ model = get_peft_model(tiny, build_lora_config(
+ cfg.training.lora, target_modules=cfg.training.lora.target_modules, task_type=None))
+ adapted = {n.rsplit(".", 1)[-1] for n, m in model.named_modules() if hasattr(m, "lora_A")}
+ assert adapted == {"q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"}
diff --git a/tests/test_migrate_llamafactory_fields.py b/tests/test_migrate_llamafactory_fields.py
new file mode 100644
index 00000000..0b968967
--- /dev/null
+++ b/tests/test_migrate_llamafactory_fields.py
@@ -0,0 +1,303 @@
+"""#1807 — the LLaMA-Factory migrator maps what the source trains with, or says what it drops.
+
+Before: ``val_size`` was never read (every migrated config got Soup's default
+``val_split: 0.1`` where LLaMA-Factory trains on every row), a missing
+``lora_rank`` / ``lora_alpha`` fell back to Soup's ``r: 64, alpha: 16`` where
+LLaMA-Factory uses ``r: 8, alpha: 2 * r``, a comma-separated ``lora_target`` was
+copied as one string (peft then refused it), ``lora_target: all`` became ``auto``
+(two of seven projections on Llama), and ``pref_beta`` / ``simpo_gamma`` under
+``pref_loss: simpo`` vanished without a word.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+import yaml
+
+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
+
+_BASE = "model_name_or_path: meta-llama/Llama-3.1-8B\nfinetuning_type: lora\ndataset: alpaca_en\n"
+
+
+def _migrate(tmp_path: Path, text: str):
+ path = tmp_path / "lf.yaml"
+ path.write_text(text, encoding="utf-8")
+ result = migrate_llamafactory(path)
+ cfg = load_config_from_string(config_to_yaml(result))
+ return result, cfg
+
+
+# ---------------------------------------------------------------------------
+# The issue's reproduction
+# ---------------------------------------------------------------------------
+
+
+def test_the_reported_config_now_trains_what_llamafactory_trains(tmp_path: Path) -> None:
+ result, cfg = _migrate(
+ tmp_path,
+ "model_name_or_path: meta-llama/Llama-3.1-8B\nstage: dpo\npref_loss: simpo\n"
+ "pref_beta: 2.0\nsimpo_gamma: 1.0\nfinetuning_type: lora\n"
+ "lora_target: q_proj,v_proj\nval_size: 0\ndataset: prefs\n",
+ )
+ lora = cfg.training.lora
+ assert (lora.r, lora.alpha) == (8, 16)
+ assert lora.target_modules == ["q_proj", "v_proj"]
+ assert cfg.data.val_split == 0
+ assert cfg.training.simpo_gamma == 1.0
+ assert any("pref_beta" in w and "no Soup equivalent" in w for w in result["_warnings"])
+
+
+# ---------------------------------------------------------------------------
+# Validation split
+# ---------------------------------------------------------------------------
+
+
[email protected]("line,expected", [("val_size: 0\n", 0.0), ("val_size: 0.2\n", 0.2),
+ ("", 0.0)])
+def test_val_size_round_trips_and_is_zero_when_absent(tmp_path: Path, line, expected) -> None:
+ result, cfg = _migrate(tmp_path, _BASE + line)
+ assert result["data"]["val_split"] == expected
+ assert cfg.data.val_split == expected
+
+
+def test_a_val_size_soup_cannot_express_is_named_not_defaulted_silently(tmp_path: Path) -> None:
+ # LLaMA-Factory accepts an absolute row count; data.val_split is a ratio <= 0.5.
+ result, cfg = _migrate(tmp_path, _BASE + "val_size: 1000\n")
+ assert "val_split" not in result["data"]
+ assert any("val_size" in w and "1000" in w and "val_split" in w for w in result["_warnings"])
+ assert cfg.data.val_split == 0.1 # Soup's default, and the warning says so
+
+
+def test_a_fraction_above_one_half_is_named_not_written(tmp_path: Path) -> None:
+ # A ratio LLaMA-Factory accepts but data.val_split caps at 0.5: the "above 0.5"
+ # branch, pinned apart from the row-count one (#1901 review).
+ result, cfg = _migrate(tmp_path, _BASE + "val_size: 0.7\n")
+ assert "val_split" not in result["data"]
+ assert any(w.startswith("val_size: 0.7") and "above 0.5" in w and "not written" in w
+ for w in result["_warnings"])
+ assert cfg.data.val_split == 0.1
+
+
+def test_exactly_one_half_is_still_written(tmp_path: Path) -> None:
+ result, cfg = _migrate(tmp_path, _BASE + "val_size: 0.5\n")
+ assert result["data"]["val_split"] == 0.5
+ assert cfg.data.val_split == 0.5
+ assert not any(w.startswith("val_size:") for w in result["_warnings"])
+
+
+# ---------------------------------------------------------------------------
+# LoRA defaults and targets
+# ---------------------------------------------------------------------------
+
+
+def test_missing_rank_and_alpha_use_llamafactory_defaults(tmp_path: Path) -> None:
+ _, cfg = _migrate(tmp_path, _BASE)
+ assert (cfg.training.lora.r, cfg.training.lora.alpha) == (8, 16)
+
+
+def test_rank_alone_gives_alpha_twice_the_rank(tmp_path: Path) -> None:
+ _, cfg = _migrate(tmp_path, _BASE + "lora_rank: 32\n")
+ assert (cfg.training.lora.r, cfg.training.lora.alpha) == (32, 64)
+
+
+def test_alpha_alone_keeps_the_default_rank(tmp_path: Path) -> None:
+ _, cfg = _migrate(tmp_path, _BASE + "lora_alpha: 32\n")
+ assert (cfg.training.lora.r, cfg.training.lora.alpha) == (8, 32)
+
+
+def test_both_set_are_copied(tmp_path: Path) -> None:
+ _, cfg = _migrate(tmp_path, _BASE + "lora_rank: 64\nlora_alpha: 16\n")
+ assert (cfg.training.lora.r, cfg.training.lora.alpha) == (64, 16)
+
+
+def test_a_quoted_rank_is_the_integer_and_still_defaults_alpha(tmp_path: Path) -> None:
+ # YAML `lora_rank: "32"` is a str; the author meant 32, and alpha = 2 * rank needs it.
+ result, cfg = _migrate(tmp_path, _BASE + 'lora_rank: "32"\n')
+ assert result["training"]["lora"]["r"] == 32
+ assert (cfg.training.lora.r, cfg.training.lora.alpha) == (32, 64)
+ assert not any(w.startswith("lora_rank:") for w in result["_warnings"])
+
+
+def test_a_quoted_alpha_is_the_integer(tmp_path: Path) -> None:
+ result, cfg = _migrate(tmp_path, _BASE + 'lora_rank: 16\nlora_alpha: " 8 "\n')
+ assert result["training"]["lora"]["alpha"] == 8
+ assert (cfg.training.lora.r, cfg.training.lora.alpha) == (16, 8)
+
+
+def test_a_rank_that_is_not_an_integer_is_named_not_defaulted_silently(tmp_path: Path) -> None:
+ path = tmp_path / "lf.yaml"
+ path.write_text(_BASE + "lora_rank: eight\n", encoding="utf-8")
+ result = migrate_llamafactory(path)
+ assert result["training"]["lora"]["r"] == "eight"
+ assert "alpha" not in result["training"]["lora"]
+ assert any(w.startswith("lora_rank: 'eight'") and "lora_alpha was not defaulted" in w
+ for w in result["_warnings"])
+
+
+ "value,expected",
+ [
+ ("q_proj,v_proj", ["q_proj", "v_proj"]),
+ ("q_proj, v_proj", ["q_proj", "v_proj"]),
+ ("q_proj", ["q_proj"]),
+ ("[q_proj, k_proj]", ["q_proj", "k_proj"]),
+ ],
+)
+def test_lora_target_becomes_a_list(tmp_path: Path, value, expected) -> None:
+ _, cfg = _migrate(tmp_path, _BASE + f"lora_target: {value}\n")
+ assert cfg.training.lora.target_modules == expected
+
+
[email protected]("line", ["lora_target: all\n", ""])
+def test_all_and_the_absent_key_map_to_every_linear_layer(tmp_path: Path, line) -> None:
+ _, cfg = _migrate(tmp_path, _BASE + line)
+ assert cfg.training.lora.target_modules == "all-linear"
+
+
+def test_full_finetuning_writes_no_lora_defaults(tmp_path: Path) -> None:
+ result, cfg = _migrate(
+ tmp_path, "model_name_or_path: org/m\nfinetuning_type: full\ndataset: d\n"
+ )
+ assert result["training"]["lora"] == {"r": 0}
+ assert cfg.training.lora.r == 0
+
+
+# ---------------------------------------------------------------------------
+# Preference strength
+# ---------------------------------------------------------------------------
+
+
+def test_pref_beta_under_ipo_is_the_ipo_tau(tmp_path: Path) -> None:
+ # trainer/ipo.py passes training.ipo_tau as trl's beta, which is what pref_beta sets.
+ _, cfg = _migrate(tmp_path, "model_name_or_path: org/m\nstage: dpo\npref_loss: ipo\n"
+ "pref_beta: 0.3\nfinetuning_type: lora\ndataset: prefs\n")
+ assert cfg.task == "ipo"
+ assert cfg.training.ipo_tau == 0.3
+
+
+def test_ipo_without_pref_beta_leaves_ipo_tau_at_the_shared_default(tmp_path: Path) -> None:
+ # LLaMA-Factory's pref_beta, trl's DPOConfig.beta and Soup's ipo_tau all default to
+ # 0.1, so an absent pref_beta is left absent: no ipo_tau key, and the loaded config
+ # trains at 0.1 (#1807 review).
+ result, cfg = _migrate(tmp_path, "model_name_or_path: org/m\nstage: dpo\npref_loss: ipo\n"
+ "finetuning_type: lora\ndataset: prefs\n")
+ assert cfg.task == "ipo"
+ assert "ipo_tau" not in result["training"]
+ assert cfg.training.ipo_tau == 0.1
+ assert not any("pref_beta" in w for w in result["_warnings"])
+
+
+def test_the_upstream_default_the_equivalence_rests_on_is_still_0_1() -> None:
+ # The mapping above leaves an absent pref_beta absent because trl's beta (what
+ # trainer/ipo.py sets from ipo_tau) defaults to the same 0.1 as LLaMA-Factory's
+ # pref_beta. If trl moves its default, this names the assumption that broke.
+ import dataclasses
+
+ trl = pytest.importorskip("trl")
+ beta = next(f for f in dataclasses.fields(trl.DPOConfig) if f.name == "beta")
+ assert beta.default == 0.1
+
+
+def test_simpo_gamma_is_mapped_and_pref_beta_is_named(tmp_path: Path) -> None:
+ result, cfg = _migrate(tmp_path, "model_name_or_path: org/m\nstage: dpo\npref_loss: simpo\n"
+ "pref_beta: 2.0\nsimpo_gamma: 1.5\nfinetuning_type: lora\n"
+ "dataset: prefs\n")
+ assert cfg.task == "simpo"
+ assert cfg.training.simpo_gamma == 1.5
+ # Mapped, so neither dropped by name nor in the unmapped listing.
+ assert not any(w.startswith("simpo_gamma:") for w in result["_warnings"])
+ assert not any("not migrated" in w and "simpo_gamma" in w for w in result["_warnings"])
+ assert any(w.startswith("pref_beta: 2.0") and "no Soup equivalent" in w
+ for w in result["_warnings"])
+
+
[email protected]("stage,field", [("dpo", "dpo_beta"), ("kto", "kto_beta")])
+def test_pref_beta_still_reaches_the_existing_knobs(tmp_path: Path, stage, field) -> None:
+ _, cfg = _migrate(tmp_path, f"model_name_or_path: org/m\nstage: {stage}\npref_beta: 0.25\n"
+ "finetuning_type: lora\ndataset: prefs\n")
+ assert getattr(cfg.training, field) == 0.25
+
+
+# ---------------------------------------------------------------------------
+# Nothing is dropped silently
+# ---------------------------------------------------------------------------
+
+
+def test_unmapped_source_keys_are_listed_in_one_warning(tmp_path: Path) -> None:
+ result, _ = _migrate(tmp_path, _BASE + "logging_steps: 10\nsave_steps: 500\nplot_loss: true\n")
+ listing = [w for w in result["_warnings"] if "not migrated" in w]
+ assert len(listing) == 1, result["_warnings"]
+ for key in ("logging_steps", "plot_loss", "save_steps"):
+ assert key in listing[0]
+ # Keys that were mapped or warned about individually are not in the listing.
+ for key in ("model_name_or_path", "finetuning_type", "dataset"):
+ assert key not in listing[0]
+
+
+def test_a_fully_mapped_config_has_no_unmapped_listing(tmp_path: Path) -> None:
+ result, _ = _migrate(tmp_path, _BASE + "lora_rank: 8\nval_size: 0\ncutoff_len: 1024\n")
+ assert not any("not migrated" in w for w in result["_warnings"])
+
+
+# ---------------------------------------------------------------------------
+# The migrated targets build a real adapter
+# ---------------------------------------------------------------------------
+
+
+def _tiny_llama():
+ import torch
+ from transformers import LlamaConfig, LlamaForCausalLM
+
+ torch.manual_seed(0)
+ config = LlamaConfig(
+ vocab_size=128, hidden_size=32, intermediate_size=64, num_hidden_layers=2,
+ num_attention_heads=4, num_key_value_heads=4, max_position_embeddings=64,
+ )
+ return LlamaForCausalLM(config)
+
+
+def _adapted_module_names(cfg) -> set[str]:
+ from peft import get_peft_model
+
+ from soup_cli.utils.peft_wiring import build_lora_config
+
+ model = get_peft_model(
+ _tiny_llama(),
+ build_lora_config(cfg.training.lora, target_modules=cfg.training.lora.target_modules,
+ task_type=None),
+ )
+ return {name.rsplit(".", 1)[-1] for name, module in model.named_modules()
+ if hasattr(module, "lora_A")}
+
+
+def test_a_comma_target_builds_an_adapter_on_exactly_those_projections(tmp_path: Path) -> None:
+ _, cfg = _migrate(tmp_path, _BASE + "lora_target: q_proj,v_proj\n")
+ assert _adapted_module_names(cfg) == {"q_proj", "v_proj"}
+
+
+def test_all_wraps_every_linear_projection_of_a_tiny_llama(tmp_path: Path) -> None:
+ _, cfg = _migrate(tmp_path, _BASE + "lora_target: all\n")
+ assert _adapted_module_names(cfg) == {
+ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj",
+ }
+
+
+def test_the_old_default_target_would_have_wrapped_two(tmp_path: Path) -> None:
+ # The control for the test above: ``auto`` on this Llama is q_proj / v_proj only.
+ _, cfg = _migrate(tmp_path, _BASE + "lora_target: all\n")
+ cfg.training.lora.target_modules = "auto"
+ from peft import LoraConfig, get_peft_model
+
+ model = get_peft_model(_tiny_llama(), LoraConfig(r=8, lora_alpha=16, task_type=None))
+ adapted = {n.rsplit(".", 1)[-1] for n, m in model.named_modules() if hasattr(m, "lora_A")}
+ assert adapted == {"q_proj", "v_proj"}
+
+
+def test_yaml_round_trip_keeps_the_list(tmp_path: Path) -> None:
+ result, _ = _migrate(tmp_path, _BASE + "lora_target: q_proj,v_proj\n")
+ dumped = yaml.safe_load(config_to_yaml(result))
+ assert dumped["training"]["lora"]["target_modules"] == ["q_proj", "v_proj"]
diff --git a/tests/test_migrate_unsloth_fields.py b/tests/test_migrate_unsloth_fields.py
new file mode 100644
index 00000000..86c49edf
--- /dev/null
+++ b/tests/test_migrate_unsloth_fields.py
@@ -0,0 +1,199 @@
+"""#1807 — the Unsloth migrator takes ``base`` from the model that trains and maps
+the trainer fields it used to drop.
+
+Before: every ``from_pretrained`` call overwrote ``base`` in source order, so the
+stock notebook's ``if False:`` reload of the local ``lora_model`` directory won
+over the training model; and ``gradient_accumulation_steps``, ``warmup_steps``,
+``weight_decay`` and ``seed`` were never read from ``TrainingArguments`` or the
+TRL ``*Config`` classes (an effective batch of 32 became 8).
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+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
+
+_LOAD = (
+ "from unsloth import FastLanguageModel\n"
+ "model, tokenizer = FastLanguageModel.from_pretrained("
+ "model_name='unsloth/Meta-Llama-3.1-8B-bnb-4bit', max_seq_length=2048, load_in_4bit=True)\n"
+ "model = FastLanguageModel.get_peft_model(model, r=16, lora_alpha=16)\n"
+)
+_TRAIN = (
+ "from trl import SFTTrainer\nfrom transformers import TrainingArguments\n"
+ "trainer = SFTTrainer(model=model, args=TrainingArguments(per_device_train_batch_size=2,"
+ " gradient_accumulation_steps=16, warmup_steps=5, num_train_epochs=1, learning_rate=2e-4,"
+ " weight_decay=0.1, seed=3407, output_dir='outputs'))\n"
+)
+_RELOAD_KW = (
+ "if False:\n model, tokenizer = FastLanguageModel.from_pretrained(model_name='lora_model',"
+ " max_seq_length=2048, load_in_4bit=True)\n"
+)
+_RELOAD_POS = (
+ "if False:\n from peft import AutoPeftModelForCausalLM\n"
+ " model = AutoPeftModelForCausalLM.from_pretrained('lora_model')\n"
+ " tokenizer = AutoTokenizer.from_pretrained('lora_model')\n"
+)
+
+
+def _notebook(*cells: str) -> dict:
+ return {
+ "cells": [{"cell_type": "code", "source": c, "metadata": {}, "outputs": []} for c in cells],
+ "metadata": {}, "nbformat": 4, "nbformat_minor": 5,
+ }
+
+
+def _migrate(tmp_path: Path, *cells: str):
+ path = tmp_path / "nb.ipynb"
+ path.write_text(json.dumps(_notebook(*cells)), encoding="utf-8")
+ result = migrate_unsloth(path)
+ cfg = load_config_from_string(config_to_yaml(result))
+ return result, cfg
+
+
+# ---------------------------------------------------------------------------
+# The issue's reproduction
+# ---------------------------------------------------------------------------
+
+
+def test_the_stock_notebook_migrates_to_the_training_model_and_arguments(tmp_path: Path) -> None:
+ result, cfg = _migrate(tmp_path, _LOAD, _TRAIN, _RELOAD_KW)
+ assert cfg.base == "unsloth/Meta-Llama-3.1-8B-bnb-4bit"
+ assert cfg.training.gradient_accumulation_steps == 16
+ assert cfg.training.weight_decay == 0.1
+ assert cfg.training.seed == 3407
+ assert cfg.training.batch_size == 2
+ assert any("warmup_steps" in w and "warmup_ratio" in w for w in result["_warnings"])
+
+
+# ---------------------------------------------------------------------------
+# base
+# ---------------------------------------------------------------------------
+
+
[email protected]("reload", [_RELOAD_KW, _RELOAD_POS], ids=["keyword", "positional"])
+def test_a_reload_under_if_false_never_becomes_base(tmp_path: Path, reload) -> None:
+ _, cfg = _migrate(tmp_path, _LOAD, _TRAIN, reload)
+ assert cfg.base == "unsloth/Meta-Llama-3.1-8B-bnb-4bit"
+
+
+def test_a_top_level_reload_after_training_does_not_become_base_either(tmp_path: Path) -> None:
+ # The first call in source order trains; a later one at top level is the
+ # inference reload the stock notebook runs after saving.
+ reload = ("model, tokenizer = FastLanguageModel.from_pretrained(model_name='lora_model',"
+ " max_seq_length=2048, load_in_4bit=True)\n")
+ _, cfg = _migrate(tmp_path, _LOAD, _TRAIN, reload)
+ assert cfg.base == "unsloth/Meta-Llama-3.1-8B-bnb-4bit"
+
+
+def test_a_reload_before_the_training_load_is_skipped_when_dead(tmp_path: Path) -> None:
+ _, cfg = _migrate(tmp_path, _RELOAD_KW, _LOAD, _TRAIN)
+ assert cfg.base == "unsloth/Meta-Llama-3.1-8B-bnb-4bit"
+
+
+def test_a_notebook_whose_only_load_is_dead_still_fails_loudly(tmp_path: Path) -> None:
+ with pytest.raises(ValueError, match="from_pretrained"):
+ _migrate(tmp_path, _RELOAD_KW, _TRAIN)
+
+
+def test_the_positional_form_of_the_training_load_is_read(tmp_path: Path) -> None:
+ load = ("from unsloth import FastLanguageModel\n"
+ "model, tokenizer = FastLanguageModel.from_pretrained('org/base',"
+ " max_seq_length=512)\n")
+ _, cfg = _migrate(tmp_path, load, _TRAIN, _RELOAD_KW)
+ assert cfg.base == "org/base"
+ assert cfg.data.max_length == 512
+
+
+# ---------------------------------------------------------------------------
+# Trainer arguments
+# ---------------------------------------------------------------------------
+
+
+ "config_cls", ["TrainingArguments", "SFTConfig", "DPOConfig", "GRPOConfig"]
+)
+def test_the_four_fields_are_read_from_every_config_class(tmp_path: Path, config_cls) -> None:
+ trainer = {"TrainingArguments": "SFTTrainer", "SFTConfig": "SFTTrainer",
+ "DPOConfig": "DPOTrainer", "GRPOConfig": "GRPOTrainer"}[config_cls]
+ train = (f"trainer = {trainer}(model=model, args={config_cls}(per_device_train_batch_size=2,"
+ " gradient_accumulation_steps=8, weight_decay=0.05, seed=7, warmup_ratio=0.1,"
+ " output_dir='outputs'))\n")
+ _, cfg = _migrate(tmp_path, _LOAD, train)
+ assert cfg.training.gradient_accumulation_steps == 8
+ assert cfg.training.weight_decay == 0.05
+ assert cfg.training.seed == 7
+ assert cfg.training.warmup_ratio == 0.1
+
+
+def test_warmup_steps_is_named_as_having_no_soup_equivalent(tmp_path: Path) -> None:
+ result, cfg = _migrate(tmp_path, _LOAD, _TRAIN)
+ assert cfg.training.warmup_ratio == 0.03 # Soup's default, and the warning says so
+ hits = [w for w in result["_warnings"] if "warmup_steps=5" in w]
+ assert len(hits) == 1 and "training.warmup_ratio" in hits[0]
+
+
+def test_the_fields_absent_from_the_notebook_keep_soup_defaults(tmp_path: Path) -> None:
+ train = ("trainer = SFTTrainer(model=model, args=TrainingArguments("
+ "per_device_train_batch_size=2, output_dir='outputs'))\n")
+ result, cfg = _migrate(tmp_path, _LOAD, train)
+ for key in ("gradient_accumulation_steps", "weight_decay", "seed", "warmup_ratio"):
+ assert key not in result["training"]
+ assert cfg.training.seed is None
+
+
+def test_only_the_final_stage_supplies_the_fields(tmp_path: Path) -> None:
+ warmup = ("trainer = SFTTrainer(model=model, args=SFTConfig(per_device_train_batch_size=1,"
+ " gradient_accumulation_steps=2, seed=1, output_dir='warm'))\n")
+ rl = ("trainer = GRPOTrainer(model=model, args=GRPOConfig(per_device_train_batch_size=4,"
+ " gradient_accumulation_steps=32, seed=9, output_dir='rl'))\n")
+ _, cfg = _migrate(tmp_path, _LOAD, warmup, rl)
+ assert cfg.task == "grpo"
+ assert (cfg.training.gradient_accumulation_steps, cfg.training.seed) == (32, 9)
+
+
+# ---------------------------------------------------------------------------
+# Nothing is dropped silently
+# ---------------------------------------------------------------------------
+
+
+def test_unmapped_trainer_arguments_are_listed_in_one_warning(tmp_path: Path) -> None:
+ train = ("trainer = SFTTrainer(model=model, args=TrainingArguments("
+ "per_device_train_batch_size=2, logging_steps=1, fp16=False, bf16=True,"
+ " report_to='none', output_dir='outputs'))\n")
+ result, _ = _migrate(tmp_path, _LOAD, train)
+ listing = [w for w in result["_warnings"] if "not migrated" in w and "TrainingArguments" in w]
+ assert len(listing) == 1, result["_warnings"]
+ for key in ("bf16", "fp16", "logging_steps", "report_to"):
+ assert key in listing[0]
+ assert "per_device_train_batch_size" not in listing[0]
+ assert "output_dir" not in listing[0]
+
+
+def test_unmapped_peft_arguments_are_listed_too(tmp_path: Path) -> None:
+ load = (
+ "from unsloth import FastLanguageModel\n"
+ "model, tokenizer = FastLanguageModel.from_pretrained(model_name='org/base')\n"
+ "model = FastLanguageModel.get_peft_model(model, r=16, lora_alpha=16, bias='none',"
+ " use_gradient_checkpointing='unsloth', random_state=3407)\n"
+ )
+ result, _ = _migrate(tmp_path, load, _TRAIN)
+ listing = [w for w in result["_warnings"] if "not migrated" in w and "get_peft_model" in w]
+ assert len(listing) == 1, result["_warnings"]
+ for key in ("bias", "random_state", "use_gradient_checkpointing"):
+ assert key in listing[0]
+ assert " r," not in listing[0] and "lora_alpha" not in listing[0]
+
+
+def test_a_fully_mapped_notebook_has_no_unmapped_listing(tmp_path: Path) -> None:
+ train = ("trainer = SFTTrainer(model=model, args=TrainingArguments("
+ "per_device_train_batch_size=2, gradient_accumulation_steps=4, num_train_epochs=1,"
+ " learning_rate=2e-4, weight_decay=0.0, seed=1, output_dir='outputs'))\n")
+ result, _ = _migrate(tmp_path, _LOAD, train)
+ assert not any("not migrated" in w for w in result["_warnings"])