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): explicitly write quantization: none and lora.r: 0 for full fine-tuning (#1215) (#1302)

Nurkhan Esenbekc0c43f6810ee
diff --git a/changelog.d/0.75.1/1302.fixed.md b/changelog.d/0.75.1/1302.fixed.md
new file mode 100644
index 00000000..8fd0245f
--- /dev/null
+++ b/changelog.d/0.75.1/1302.fixed.md
@@ -0,0 +1 @@
+- **`soup migrate` explicitly writes `quantization: none` and emits `lora.r: 0` for full fine-tuning (#1215 by @kok-o in #1302).** Previously, unquantized Axolotl, LLaMA-Factory, and Unsloth configurations omitted the quantization field, causing Soup to default them to 4-bit QLoRA upon loading, while full fine-tunes defaulted to LoRA `r=64`. Migrators now explicitly set `quantization: none` for unquantized sources, support HQQ/EETQ methods, map full fine-tunes to `lora.r: 0`, refuse full fine-tuning for unsupported tasks (e.g. DPO/PT/RM), resolve notebook variable assignments in Unsloth, and validate output with `load_config_from_string` before writing.
diff --git a/src/soup_cli/commands/migrate.py b/src/soup_cli/commands/migrate.py
index 472db3fd..78349aa1 100644
--- a/src/soup_cli/commands/migrate.py
+++ b/src/soup_cli/commands/migrate.py
@@ -1,4 +1,4 @@
-"""soup migrate — import configs from LLaMA-Factory, Axolotl, and Unsloth."""
+"""soup migrate - import configs from LLaMA-Factory, Axolotl, and Unsloth."""
import json
from pathlib import Path
@@ -125,10 +125,28 @@ def migrate(
# Generate YAML
yaml_str = config_to_yaml(result)
+ # Validate output with schema before printing / writing
+ from soup_cli.config.loader import load_config_from_string
+
+ try:
+ loaded_cfg = load_config_from_string(yaml_str)
+ except Exception as exc:
+ console.print(f"[red]Generated config failed schema validation: {for_terminal(exc)}[/]")
+ raise typer.Exit(1)
+
+ task_val = getattr(loaded_cfg, "task", "unknown")
+ quant_val = getattr(loaded_cfg.training, "quantization", "none")
+ lora_obj = getattr(loaded_cfg.training, "lora", None)
+ lora_r_val = getattr(lora_obj, "r", "none") if lora_obj is not None else "none"
+
# Show generated config
console.print(Panel(
Syntax(yaml_str, "yaml", theme="monokai"),
title=f"[bold green]Generated soup.yaml[/] (from {source})",
+ subtitle=(
+ f"[dim]Resolved: task={task_val}, "
+ f"quantization={quant_val}, lora.r={lora_r_val}[/]"
+ ),
))
if dry_run:
diff --git a/src/soup_cli/migrate/axolotl.py b/src/soup_cli/migrate/axolotl.py
index 6deda994..9b43a7cd 100644
--- a/src/soup_cli/migrate/axolotl.py
+++ b/src/soup_cli/migrate/axolotl.py
@@ -104,11 +104,15 @@ def migrate_axolotl(config_path: Path) -> Dict[str, Any]:
if "sequence_len" in raw:
data["max_length"] = raw["sequence_len"]
- # --- LoRA ---
+ # --- LoRA / Full Fine-tuning ---
adapter = raw.get("adapter")
lora_section: Dict[str, Any] = {}
include_lora = adapter in ("lora", "qlora")
+ if adapter and not include_lora:
+ warnings.append(f"adapter: {adapter} has no Soup equivalent. Using LoRA instead.")
+ include_lora = True
+
if include_lora:
if "lora_r" in raw:
lora_section["r"] = raw["lora_r"]
@@ -120,6 +124,20 @@ def migrate_axolotl(config_path: Path) -> Dict[str, Any]:
lora_section["target_modules"] = "auto"
elif "lora_target_modules" in raw:
lora_section["target_modules"] = raw["lora_target_modules"]
+ else:
+ # No adapter specified -> full fine-tuning requested
+ if task in ("sft", "embedding"):
+ warnings.append(
+ f"No adapter specified for task '{task}' - "
+ "full fine-tuning will be used (lora.r: 0)."
+ )
+ lora_section["r"] = 0
+ else:
+ raise ValueError(
+ f"No adapter specified for task '{task}', but Soup only supports full "
+ "fine-tuning (lora.r: 0) for sft and embedding tasks. "
+ "Specify an adapter (lora/qlora)."
+ )
# --- Training ---
training: Dict[str, Any] = {}
@@ -140,10 +158,14 @@ def migrate_axolotl(config_path: Path) -> Dict[str, Any]:
training["warmup_ratio"] = raw["warmup_ratio"]
# Quantization
- if adapter == "qlora" or raw.get("load_in_4bit"):
+ if lora_section.get("r") == 0:
+ training["quantization"] = "none"
+ elif adapter == "qlora" or raw.get("load_in_4bit"):
training["quantization"] = "4bit"
elif raw.get("load_in_8bit"):
training["quantization"] = "8bit"
+ else:
+ training["quantization"] = "none"
# Flash attention. use_flash_attn is only read by the SFT-family trainer
# (#806), so mapping it for any other task produces a config the loader
@@ -159,7 +181,7 @@ def migrate_axolotl(config_path: Path) -> Dict[str, Any]:
)
# Add lora section
- if include_lora and lora_section:
+ if lora_section:
training["lora"] = lora_section
# --- Output ---
diff --git a/src/soup_cli/migrate/llamafactory.py b/src/soup_cli/migrate/llamafactory.py
index 29597785..9b364786 100644
--- a/src/soup_cli/migrate/llamafactory.py
+++ b/src/soup_cli/migrate/llamafactory.py
@@ -68,9 +68,10 @@ def migrate_llamafactory(config_path: Path) -> Dict[str, Any]:
data_format = _TASK_FORMAT_MAP.get(task, "auto")
- # --- LoRA ---
+ # --- LoRA / Full Fine-tuning ---
finetuning_type = raw.get("finetuning_type", "lora")
include_lora = finetuning_type == "lora"
+ lora_section: Dict[str, Any] = {}
if finetuning_type == "freeze":
warnings.append(
@@ -79,13 +80,27 @@ def migrate_llamafactory(config_path: Path) -> Dict[str, Any]:
)
include_lora = True
- if finetuning_type == "full":
+ elif finetuning_type == "oft":
warnings.append(
- "finetuning_type: full — no LoRA will be used. "
- "Soup will train all parameters."
+ "finetuning_type: oft is not supported in Soup. "
+ "Using LoRA instead."
)
+ include_lora = True
+
+ elif finetuning_type == "full":
+ if task in ("sft", "embedding"):
+ warnings.append(
+ "finetuning_type: full — no LoRA will be used. "
+ "Soup will train all parameters."
+ )
+ lora_section = {"r": 0}
+ else:
+ raise ValueError(
+ f"finetuning_type: full is requested, but stage '{stage}' (task '{task}') "
+ "does not support full fine-tuning in Soup. "
+ "Only sft and embedding support full fine-tuning (lora.r=0)."
+ )
- lora_section = {}
if include_lora:
lora_section["r"] = raw.get("lora_rank", 64)
lora_section["alpha"] = raw.get("lora_alpha", 16)
@@ -116,13 +131,50 @@ def migrate_llamafactory(config_path: Path) -> Dict[str, Any]:
training["warmup_ratio"] = raw["warmup_ratio"]
# Quantization
- quant_bit = raw.get("quantization_bit")
- if quant_bit == 4:
- training["quantization"] = "4bit"
- elif quant_bit == 8:
- training["quantization"] = "8bit"
- elif quant_bit is not None:
+ quant_bit_raw = raw.get("quantization_bit")
+ quant_bit = None
+ if quant_bit_raw is not None:
+ if isinstance(quant_bit_raw, int):
+ quant_bit = quant_bit_raw
+ elif isinstance(quant_bit_raw, str) and quant_bit_raw.strip().isdigit():
+ quant_bit = int(quant_bit_raw.strip())
+ else:
+ raise ValueError(f"Invalid quantization_bit value: {quant_bit_raw!r}")
+
+ quant_method = raw.get("quantization_method")
+ if isinstance(quant_method, str):
+ quant_method = quant_method.lower().strip()
+
+ if finetuning_type == "full":
training["quantization"] = "none"
+ elif quant_bit is None:
+ training["quantization"] = "none"
+ elif quant_method in (None, "bitsandbytes", "bnb"):
+ if quant_bit == 4:
+ training["quantization"] = "4bit"
+ elif quant_bit == 8:
+ training["quantization"] = "8bit"
+ else:
+ method_name = quant_method or "bitsandbytes"
+ raise ValueError(
+ f"Unsupported quantization_bit={quant_bit} for method '{method_name}'"
+ )
+ elif quant_method == "hqq":
+ if quant_bit in (1, 2, 3, 4, 5, 6, 8):
+ training["quantization"] = f"hqq:{quant_bit}bit"
+ else:
+ raise ValueError(
+ f"Unsupported quantization_bit={quant_bit} for method 'hqq'"
+ )
+ elif quant_method == "eetq":
+ if quant_bit == 8:
+ training["quantization"] = "eetq"
+ else:
+ raise ValueError(
+ f"Unsupported quantization_bit={quant_bit} for method 'eetq' (expected 8)"
+ )
+ else:
+ raise ValueError(f"Unsupported quantization_method: '{quant_method}'")
# Task-specific params
pref_beta = raw.get("pref_beta")
@@ -142,7 +194,7 @@ def migrate_llamafactory(config_path: Path) -> Dict[str, Any]:
training["loraplus_lr_ratio"] = raw["loraplus_lr_ratio"]
# Add lora section
- if include_lora and lora_section:
+ if lora_section:
training["lora"] = lora_section
# --- Data ---
diff --git a/src/soup_cli/migrate/unsloth.py b/src/soup_cli/migrate/unsloth.py
index 0405b4b3..4f8e564d 100644
--- a/src/soup_cli/migrate/unsloth.py
+++ b/src/soup_cli/migrate/unsloth.py
@@ -69,7 +69,7 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:
else:
all_source += source + "\n"
- # Parse AST — safe, no execution
+ # Parse AST - safe, no execution
try:
tree = ast.parse(all_source)
except SyntaxError:
@@ -79,11 +79,31 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:
base: Optional[str] = None
max_seq_length: Optional[int] = None
load_in_4bit: Optional[bool] = None
+ load_in_8bit: Optional[bool] = None
+ load_in_16bit: Optional[bool] = None
+ full_finetuning: Optional[bool] = None
lora_params: Dict[str, Any] = {}
training_params: Dict[str, Any] = {}
task = "sft"
output_dir = "./output"
+ # Collect variable assignments from notebook code (module-level only, in source order)
+ assignments: Dict[str, Any] = {}
+ ambiguous: set = set()
+ for stmt in tree.body:
+ if not isinstance(stmt, ast.Assign):
+ continue
+ val = _ast_to_value(stmt.value)
+ for target in stmt.targets:
+ if not isinstance(target, ast.Name):
+ continue
+ if val is _SENTINEL or assignments.get(target.id, val) != val:
+ ambiguous.add(target.id)
+ else:
+ assignments[target.id] = val
+ 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):
@@ -95,17 +115,34 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:
if func_name == "from_pretrained":
# FastLanguageModel.from_pretrained(...)
- kwargs = _extract_kwargs(node)
+ unresolved: List[tuple[str, str]] = []
+ kwargs = _extract_kwargs(node, scope=assignments, unresolved_names=unresolved)
+ 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:
load_in_4bit = kwargs["load_in_4bit"]
+ if "load_in_8bit" in kwargs:
+ load_in_8bit = kwargs["load_in_8bit"]
+ if "load_in_16bit" in kwargs:
+ load_in_16bit = kwargs["load_in_16bit"]
+ if "full_finetuning" in kwargs:
+ full_finetuning = kwargs["full_finetuning"]
elif func_name == "get_peft_model":
# FastLanguageModel.get_peft_model(...)
- kwargs = _extract_kwargs(node)
+ kwargs = _extract_kwargs(node, scope=assignments)
if "r" in kwargs:
lora_params["r"] = kwargs["r"]
if "lora_alpha" in kwargs:
@@ -122,7 +159,7 @@ 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)
+ kwargs = _extract_kwargs(node, scope=assignments)
if kwargs.get("packing"):
warnings.append(
"packing=True is not supported in Soup. "
@@ -133,7 +170,7 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:
# TrainingArguments(...), DPOConfig(...), etc.
if func_name in _CONFIG_MAP:
task = _CONFIG_MAP[func_name]
- kwargs = _extract_kwargs(node)
+ 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:
@@ -162,12 +199,35 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:
# Build result
data_format = _TASK_FORMAT_MAP.get(task, "auto")
- training: Dict[str, Any] = {**training_params}
- if load_in_4bit:
- training["quantization"] = "4bit"
+ # Resolve quantization & full fine-tuning
+ if full_finetuning:
+ quantization = "none"
+ elif load_in_16bit:
+ quantization = "none"
+ elif load_in_8bit:
+ quantization = "8bit"
+ elif load_in_4bit is False:
+ quantization = "none"
+ else:
+ quantization = "4bit"
- if lora_params:
+ training: Dict[str, Any] = {**training_params}
+ training["quantization"] = quantization
+
+ if full_finetuning:
+ if task in ("sft", "embedding"):
+ warnings.append(
+ f"full_finetuning=True in Unsloth — no LoRA will be used "
+ f"for task '{task}' (lora.r: 0)."
+ )
+ training["lora"] = {"r": 0}
+ else:
+ raise ValueError(
+ f"full_finetuning is requested, but task '{task}' does not support full "
+ "fine-tuning in Soup. Only sft and embedding support full fine-tuning (lora.r=0)."
+ )
+ elif lora_params:
training["lora"] = lora_params
data: Dict[str, Any] = {
@@ -200,10 +260,15 @@ def _get_func_name(node: ast.Call) -> Optional[str]:
return None
-def _extract_kwargs(node: ast.Call) -> Dict[str, Any]:
+def _extract_kwargs(
+ node: ast.Call,
+ scope: Optional[Dict[str, Any]] = None,
+ unresolved_names: Optional[List[tuple[str, str]]] = None,
+) -> Dict[str, Any]:
"""Extract keyword arguments from a function Call node as Python values.
- Only extracts simple literal values (str, int, float, bool, list, None).
+ Extracts simple literal values (str, int, float, bool, list, None) or
+ resolves variable names present in scope.
"""
result: Dict[str, Any] = {}
for kw in node.keywords:
@@ -212,6 +277,12 @@ def _extract_kwargs(node: ast.Call) -> Dict[str, Any]:
value = _ast_to_value(kw.value)
if value is not _SENTINEL:
result[kw.arg] = value
+ elif isinstance(kw.value, ast.Name):
+ if scope and kw.value.id in scope:
+ result[kw.arg] = scope[kw.value.id]
+ else:
+ if unresolved_names is not None:
+ unresolved_names.append((kw.arg, kw.value.id))
return result
diff --git a/tests/test_issue1215_migrate_quantization_none.py b/tests/test_issue1215_migrate_quantization_none.py
new file mode 100644
index 00000000..374d6a9d
--- /dev/null
+++ b/tests/test_issue1215_migrate_quantization_none.py
@@ -0,0 +1,537 @@
+# -*- coding: utf-8 -*-
+"""Tests for Issue #1215: soup migrate explicitly writes quantization: none,
+supports full fine-tuning (lora.r: 0), handles quantization methods,
+and validates output with load_config_from_string.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+import yaml
+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.axolotl import migrate_axolotl
+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
+from tests.conftest import strip_ansi
+
+runner = CliRunner()
+
+
+def _plain(text: str) -> str:
+ """ANSI-stripped, whitespace-collapsed CLI output."""
+ return " ".join(strip_ansi(text).split())
+
+
+
+
+class TestAxolotlQuantizationAndFullFinetuning:
+ def test_axolotl_explicit_load_in_false_gives_none(self, tmp_path: Path) -> None:
+ cfg = tmp_path / "cfg.yaml"
+ cfg.write_text(
+ "base_model: meta-llama/Llama-3.1-8B-Instruct\n"
+ "adapter: lora\n"
+ "lora_r: 16\n"
+ "load_in_4bit: false\n"
+ "load_in_8bit: false\n"
+ "datasets:\n"
+ " - path: ./data/train.jsonl\n"
+ " type: alpaca\n",
+ encoding="utf-8",
+ )
+ res = migrate_axolotl(cfg)
+ loaded = load_config_from_string(config_to_yaml(res))
+ assert loaded.training.quantization == "none"
+ assert loaded.training.lora.r == 16
+
+ def test_axolotl_no_load_in_keys_gives_none(self, tmp_path: Path) -> None:
+ cfg = tmp_path / "cfg.yaml"
+ cfg.write_text(
+ "base_model: meta-llama/Llama-3.1-8B-Instruct\n"
+ "adapter: lora\n"
+ "lora_r: 32\n"
+ "datasets:\n"
+ " - path: ./data/train.jsonl\n"
+ " type: alpaca\n",
+ encoding="utf-8",
+ )
+ res = migrate_axolotl(cfg)
+ loaded = load_config_from_string(config_to_yaml(res))
+ assert loaded.training.quantization == "none"
+ assert loaded.training.lora.r == 32
+
+ def test_axolotl_no_adapter_sft_gives_full_finetuning(self, tmp_path: Path) -> None:
+ cfg = tmp_path / "cfg.yaml"
+ cfg.write_text(
+ "base_model: meta-llama/Llama-3.1-8B-Instruct\n"
+ "datasets:\n"
+ " - path: ./data/train.jsonl\n"
+ " type: alpaca\n",
+ encoding="utf-8",
+ )
+ res = migrate_axolotl(cfg)
+ loaded = load_config_from_string(config_to_yaml(res))
+ assert loaded.training.quantization == "none"
+ assert loaded.training.lora.r == 0
+
+ def test_axolotl_load_in_8bit_and_qlora(self, tmp_path: Path) -> None:
+ cfg8 = tmp_path / "cfg8.yaml"
+ cfg8.write_text(
+ "base_model: meta-llama/Llama-3.1-8B-Instruct\n"
+ "adapter: lora\n"
+ "lora_r: 16\n"
+ "load_in_8bit: true\n"
+ "datasets:\n"
+ " - path: ./data/train.jsonl\n"
+ " type: alpaca\n",
+ encoding="utf-8",
+ )
+ res8 = migrate_axolotl(cfg8)
+ loaded8 = load_config_from_string(config_to_yaml(res8))
+ assert loaded8.training.quantization == "8bit"
+
+ cfg4 = tmp_path / "cfg4.yaml"
+ cfg4.write_text(
+ "base_model: meta-llama/Llama-3.1-8B-Instruct\n"
+ "adapter: qlora\n"
+ "lora_r: 16\n"
+ "datasets:\n"
+ " - path: ./data/train.jsonl\n"
+ " type: alpaca\n",
+ encoding="utf-8",
+ )
+ res4 = migrate_axolotl(cfg4)
+ loaded4 = load_config_from_string(config_to_yaml(res4))
+ assert loaded4.training.quantization == "4bit"
+
+ def test_axolotl_no_adapter_dpo_refused(self, tmp_path: Path) -> None:
+ cfg = tmp_path / "cfg.yaml"
+ cfg.write_text(
+ "base_model: meta-llama/Llama-3.1-8B-Instruct\n"
+ "rl: dpo\n"
+ "datasets:\n"
+ " - path: ./data/train.jsonl\n"
+ " type: sharegpt\n",
+ encoding="utf-8",
+ )
+ with pytest.raises(ValueError, match="task 'dpo'"):
+ migrate_axolotl(cfg)
+
+
+class TestLlamaFactoryQuantizationAndFullFinetuning:
+ def test_plain_lora_no_quant_bit_gives_none(self, tmp_path: Path) -> None:
+ cfg = tmp_path / "cfg.yaml"
+ cfg.write_text(
+ "model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"
+ "stage: sft\n"
+ "finetuning_type: lora\n"
+ "lora_rank: 16\n"
+ "dataset: alpaca\n",
+ encoding="utf-8",
+ )
+ res = migrate_llamafactory(cfg)
+ loaded = load_config_from_string(config_to_yaml(res))
+ assert loaded.training.quantization == "none"
+ assert loaded.training.lora.r == 16
+
+ @pytest.mark.parametrize(
+ "quant_val, expected",
+ [(4, "4bit"), (8, "8bit"), ("4", "4bit"), ("8", "8bit")],
+ )
+ def test_quantization_bit_variants(
+ self, tmp_path: Path, quant_val: object, expected: str
+ ) -> None:
+ cfg = tmp_path / "cfg.yaml"
+ cfg.write_text(
+ f"model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"
+ f"stage: sft\n"
+ f"finetuning_type: lora\n"
+ f"lora_rank: 16\n"
+ f"quantization_bit: {quant_val}\n"
+ f"dataset: alpaca\n",
+ encoding="utf-8",
+ )
+ res = migrate_llamafactory(cfg)
+ loaded = load_config_from_string(config_to_yaml(res))
+ assert loaded.training.quantization == expected
+
+ def test_hqq_and_eetq_quantization_methods(self, tmp_path: Path) -> None:
+ # HQQ 2-bit
+ cfg_hqq = tmp_path / "cfg_hqq.yaml"
+ cfg_hqq.write_text(
+ "model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"
+ "stage: sft\n"
+ "finetuning_type: lora\n"
+ "quantization_bit: 2\n"
+ "quantization_method: hqq\n"
+ "dataset: alpaca\n",
+ encoding="utf-8",
+ )
+ res_hqq = migrate_llamafactory(cfg_hqq)
+ loaded_hqq = load_config_from_string(config_to_yaml(res_hqq))
+ assert loaded_hqq.training.quantization == "hqq:2bit"
+
+ # EETQ 8-bit
+ cfg_eetq = tmp_path / "cfg_eetq.yaml"
+ cfg_eetq.write_text(
+ "model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"
+ "stage: sft\n"
+ "finetuning_type: lora\n"
+ "quantization_bit: 8\n"
+ "quantization_method: eetq\n"
+ "dataset: alpaca\n",
+ encoding="utf-8",
+ )
+ res_eetq = migrate_llamafactory(cfg_eetq)
+ loaded_eetq = load_config_from_string(config_to_yaml(res_eetq))
+ assert loaded_eetq.training.quantization == "eetq"
+
+ # Unsupported method refused naming it
+ cfg_bad = tmp_path / "cfg_bad.yaml"
+ cfg_bad.write_text(
+ "model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"
+ "stage: sft\n"
+ "finetuning_type: lora\n"
+ "quantization_bit: 4\n"
+ "quantization_method: awq\n"
+ "dataset: alpaca\n",
+ encoding="utf-8",
+ )
+ with pytest.raises(ValueError, match="awq"):
+ migrate_llamafactory(cfg_bad)
+
+ def test_full_finetuning_sft(self, tmp_path: Path) -> None:
+ cfg = tmp_path / "cfg.yaml"
+ cfg.write_text(
+ "model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"
+ "stage: sft\n"
+ "finetuning_type: full\n"
+ "dataset: alpaca\n",
+ encoding="utf-8",
+ )
+ res = migrate_llamafactory(cfg)
+ loaded = load_config_from_string(config_to_yaml(res))
+ assert loaded.training.quantization == "none"
+ assert loaded.training.lora.r == 0
+
+ @pytest.mark.parametrize("stage", ["dpo", "pt", "kto", "rm", "ppo"])
+ def test_full_finetuning_unsupported_stages_refused(self, tmp_path: Path, stage: str) -> None:
+ cfg = tmp_path / "cfg.yaml"
+ cfg.write_text(
+ f"model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"
+ f"stage: {stage}\n"
+ f"finetuning_type: full\n"
+ f"dataset: data\n",
+ encoding="utf-8",
+ )
+ with pytest.raises(ValueError, match=f"'{stage}'"):
+ migrate_llamafactory(cfg)
+
+ def test_oft_warns_by_name(self, tmp_path: Path) -> None:
+ cfg = tmp_path / "cfg.yaml"
+ cfg.write_text(
+ "model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"
+ "stage: sft\n"
+ "finetuning_type: oft\n"
+ "dataset: alpaca\n",
+ encoding="utf-8",
+ )
+ res = migrate_llamafactory(cfg)
+ 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
+
+
+class TestUnslothQuantizationAndFullFinetuning:
+ def _make_notebook(self, from_pretrained_src: str, extra_code: str = "") -> dict:
+ cells = []
+ if extra_code:
+ cells.append({"cell_type": "code", "source": [extra_code + "\n"]})
+ cells.append({
+ "cell_type": "code",
+ "source": [
+ "from unsloth import FastLanguageModel\n",
+ from_pretrained_src + "\n",
+ ],
+ })
+ cells.append({
+ "cell_type": "code",
+ "source": [
+ "model = FastLanguageModel.get_peft_model(model, r=16)\n",
+ ],
+ })
+ return {"cells": cells}
+
+ def test_unsloth_load_in_4bit_false_gives_none(self, tmp_path: Path) -> None:
+ nb = self._make_notebook(
+ "model, tok = FastLanguageModel.from_pretrained(\n"
+ " 'meta-llama/Llama-3.1-8B', load_in_4bit=False\n"
+ ")"
+ )
+ nb_file = tmp_path / "test.ipynb"
+ nb_file.write_text(json.dumps(nb), encoding="utf-8")
+ res = migrate_unsloth(nb_file)
+ loaded = load_config_from_string(config_to_yaml(res))
+ assert loaded.training.quantization == "none"
+ assert loaded.training.lora.r == 16
+
+ def test_unsloth_load_in_16bit_gives_none(self, tmp_path: Path) -> None:
+ nb = self._make_notebook(
+ "model, tok = FastLanguageModel.from_pretrained(\n"
+ " 'meta-llama/Llama-3.1-8B', load_in_16bit=True\n"
+ ")"
+ )
+ nb_file = tmp_path / "test.ipynb"
+ nb_file.write_text(json.dumps(nb), encoding="utf-8")
+ res = migrate_unsloth(nb_file)
+ loaded = load_config_from_string(config_to_yaml(res))
+ assert loaded.training.quantization == "none"
+
+ def test_unsloth_load_in_8bit_gives_8bit(self, tmp_path: Path) -> None:
+ nb = self._make_notebook(
+ "model, tok = FastLanguageModel.from_pretrained(\n"
+ " 'meta-llama/Llama-3.1-8B', load_in_8bit=True\n"
+ ")"
+ )
+ nb_file = tmp_path / "test.ipynb"
+ nb_file.write_text(json.dumps(nb), encoding="utf-8")
+ res = migrate_unsloth(nb_file)
+ loaded = load_config_from_string(config_to_yaml(res))
+ assert loaded.training.quantization == "8bit"
+
+ def test_unsloth_full_finetuning_gives_none_and_r_zero(self, tmp_path: Path) -> None:
+ cells = [{
+ "cell_type": "code",
+ "source": [
+ "from unsloth import FastLanguageModel\n",
+ "model, tok = FastLanguageModel.from_pretrained(\n"
+ " 'meta-llama/Llama-3.1-8B', full_finetuning=True\n"
+ ")\n",
+ ],
+ }]
+ nb_file = tmp_path / "test.ipynb"
+ nb_file.write_text(json.dumps({"cells": cells}), encoding="utf-8")
+ res = migrate_unsloth(nb_file)
+ loaded = load_config_from_string(config_to_yaml(res))
+ assert loaded.training.quantization == "none"
+ assert loaded.training.lora.r == 0
+
+ @pytest.mark.parametrize("call_str", [
+ "model, tok = FastLanguageModel.from_pretrained('meta-llama/Llama-3.1-8B')",
+ "model, tok = FastLanguageModel.from_pretrained(\n"
+ " 'meta-llama/Llama-3.1-8B', load_in_4bit=True\n)",
+ ])
+ def test_unsloth_load_in_4bit_true_or_default(self, tmp_path: Path, call_str: str) -> None:
+ nb = self._make_notebook(call_str)
+ nb_file = tmp_path / "test.ipynb"
+ nb_file.write_text(json.dumps(nb), encoding="utf-8")
+ res = migrate_unsloth(nb_file)
+ loaded = load_config_from_string(config_to_yaml(res))
+ assert loaded.training.quantization == "4bit"
+
+ def test_unsloth_load_in_4bit_as_variable_resolved(self, tmp_path: Path) -> None:
+ nb = self._make_notebook(
+ "model, tok = FastLanguageModel.from_pretrained(\n"
+ " 'meta-llama/Llama-3.1-8B', load_in_4bit=load_in_4bit\n"
+ ")",
+ extra_code="load_in_4bit = False",
+ )
+ nb_file = tmp_path / "test.ipynb"
+ nb_file.write_text(json.dumps(nb), encoding="utf-8")
+ res = migrate_unsloth(nb_file)
+ loaded = load_config_from_string(config_to_yaml(res))
+ assert loaded.training.quantization == "none"
+
+ def test_unsloth_load_in_4bit_unresolved_variable_warns(self, tmp_path: Path) -> None:
+ nb = self._make_notebook(
+ "model, tok = FastLanguageModel.from_pretrained(\n"
+ " 'meta-llama/Llama-3.1-8B', load_in_4bit=load_in_4bit\n"
+ ")"
+ )
+ nb_file = tmp_path / "test.ipynb"
+ nb_file.write_text(json.dumps(nb), encoding="utf-8")
+ res = migrate_unsloth(nb_file)
+ assert any("load_in_4bit" in w for w in res["_warnings"])
+
+
+class TestMigrateCLIDryRunOutput:
+ def test_cli_dry_run_plain_lora_prints_quantization_none(
+ self, tmp_path: Path, monkeypatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ cfg_file = tmp_path / "plain_lora.yaml"
+ cfg_file.write_text(
+ "model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"
+ "stage: sft\n"
+ "finetuning_type: lora\n"
+ "lora_rank: 16\n"
+ "dataset: alpaca\n",
+ encoding="utf-8",
+ )
+ result = runner.invoke(app, [
+ "migrate",
+ "--from", "llamafactory",
+ str(cfg_file),
+ "--dry-run",
+ ])
+ assert result.exit_code == 0
+ clean = strip_ansi(result.output)
+ assert "quantization: none" in clean or "quantization=none" in clean
+
+ def test_cli_dry_run_full_finetune_prints_r_zero(self, tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.chdir(tmp_path)
+ cfg_file = tmp_path / "full_sft.yaml"
+ cfg_file.write_text(
+ "model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"
+ "stage: sft\n"
+ "finetuning_type: full\n"
+ "dataset: alpaca\n",
+ encoding="utf-8",
+ )
+ result = runner.invoke(app, [
+ "migrate",
+ "--from", "llamafactory",
+ str(cfg_file),
+ "--dry-run",
+ ])
+ assert result.exit_code == 0
+ clean = strip_ansi(result.output)
+ assert "lora.r=0" in clean or " r: 0" in clean
+
+ def test_cli_refuses_to_write_a_config_that_fails_schema_validation(
+ self, tmp_path: Path, monkeypatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ src = tmp_path / "negative_rank.yaml"
+ src.write_text(
+ "model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"
+ "stage: sft\nfinetuning_type: lora\nlora_rank: -5\ndataset: alpaca\n",
+ encoding="utf-8",
+ )
+ result = runner.invoke(
+ app, ["migrate", "--from", "llamafactory", str(src), "--output", "soup.yaml", "--yes"]
+ )
+ assert result.exit_code == 1, (result.output, repr(result.exception))
+ plain = _plain(result.output)
+ assert "failed schema validation" in plain
+ assert "lora -> r" in plain
+ assert not (tmp_path / "soup.yaml").exists()
+
+ def test_cli_subtitle_reports_the_resolved_values(
+ self, tmp_path: Path, monkeypatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ src = tmp_path / "full_sft.yaml"
+ src.write_text(
+ "model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"
+ "stage: sft\nfinetuning_type: full\ndataset: alpaca\n",
+ encoding="utf-8",
+ )
+ result = runner.invoke(app, ["migrate", "--from", "llamafactory", str(src), "--dry-run"])
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+ assert "Resolved: task=sft, quantization=none, lora.r=0" in _plain(result.output)
+
+
[email protected]("yaml_value, expected", [("'4'", "4bit"), ('"8"', "8bit")])
+def test_llamafactory_quoted_quantization_bit_is_coerced(
+ tmp_path: Path, yaml_value: str, expected: str
+) -> None:
+ cfg = tmp_path / "cfg.yaml"
+ cfg.write_text(
+ "model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"
+ "stage: sft\nfinetuning_type: lora\n"
+ f"quantization_bit: {yaml_value}\ndataset: alpaca\n",
+ encoding="utf-8",
+ )
+ assert isinstance(yaml.safe_load(cfg.read_text(encoding="utf-8"))["quantization_bit"], str)
+ loaded = load_config_from_string(config_to_yaml(migrate_llamafactory(cfg)))
+ assert loaded.training.quantization == expected
+
+
+def test_llamafactory_bnb_bit_width_other_than_4_or_8_is_refused(tmp_path: Path) -> None:
+ cfg = tmp_path / "cfg.yaml"
+ cfg.write_text(
+ "model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"
+ "stage: sft\nfinetuning_type: lora\nquantization_bit: 2\ndataset: alpaca\n",
+ encoding="utf-8",
+ )
+ with pytest.raises(ValueError, match="quantization_bit=2"):
+ migrate_llamafactory(cfg)
+
+
+def test_unsloth_full_finetuning_on_dpo_is_refused(tmp_path: Path) -> None:
+ cells = [{"cell_type": "code", "source": [
+ "from unsloth import FastLanguageModel\n",
+ "model, tok = FastLanguageModel.from_pretrained('m', full_finetuning=True)\n",
+ "from trl import DPOTrainer\n",
+ "trainer = DPOTrainer(model=model)\n",
+ ]}]
+ nb = tmp_path / "nb.ipynb"
+ nb.write_text(json.dumps({"cells": cells}), encoding="utf-8")
+ with pytest.raises(ValueError, match="task 'dpo'"):
+ migrate_unsloth(nb)
+
+
+def test_axolotl_non_lora_adapter_warns_and_falls_back_to_lora(tmp_path: Path) -> None:
+ cfg = tmp_path / "cfg.yaml"
+ cfg.write_text(
+ "base_model: meta-llama/Llama-3.1-8B-Instruct\n"
+ "adapter: llama-adapter\n"
+ "datasets:\n"
+ " - path: ./data/train.jsonl\n"
+ " type: alpaca\n",
+ encoding="utf-8",
+ )
+ res = migrate_axolotl(cfg)
+ assert any("llama-adapter" in w and "Using LoRA instead" in w for w in res["_warnings"])
+ loaded = load_config_from_string(config_to_yaml(res))
+ assert loaded.training.lora.r != 0
+
+
[email protected]("bits", [5, 6])
+def test_llamafactory_hqq_5_and_6_bit(tmp_path: Path, bits: int) -> None:
+ cfg = tmp_path / "cfg.yaml"
+ cfg.write_text(
+ "model_name_or_path: meta-llama/Llama-3.1-8B-Instruct\n"
+ "stage: sft\nfinetuning_type: lora\n"
+ f"quantization_bit: {bits}\nquantization_method: hqq\ndataset: alpaca\n",
+ encoding="utf-8",
+ )
+ res = migrate_llamafactory(cfg)
+ loaded = load_config_from_string(config_to_yaml(res))
+ assert loaded.training.quantization == f"hqq:{bits}bit"
+
+
+def test_unsloth_variable_in_helper_function_ignored(tmp_path: Path) -> None:
+ cells = [{"cell_type": "code", "source": [
+ "load_in_4bit = False\n",
+ "def helper():\n",
+ " load_in_4bit = True\n",
+ "from unsloth import FastLanguageModel\n",
+ "model, tok = FastLanguageModel.from_pretrained('m', load_in_4bit=load_in_4bit)\n",
+ ]}]
+ nb = tmp_path / "nb.ipynb"
+ nb.write_text(json.dumps({"cells": cells}), encoding="utf-8")
+ res = migrate_unsloth(nb)
+ loaded = load_config_from_string(config_to_yaml(res))
+ assert loaded.training.quantization == "none"
+
+
+def test_unsloth_conflicting_variable_assignments_warns(tmp_path: Path) -> None:
+ cells = [{"cell_type": "code", "source": [
+ "load_in_4bit = False\n",
+ "from unsloth import FastLanguageModel\n",
+ "model, tok = FastLanguageModel.from_pretrained('m', load_in_4bit=load_in_4bit)\n",
+ "load_in_4bit = True\n",
+ ]}]
+ nb = tmp_path / "nb.ipynb"
+ nb.write_text(json.dumps({"cells": cells}), encoding="utf-8")
+ res = migrate_unsloth(nb)
+ assert any("load_in_4bit" in w for w in res["_warnings"])
diff --git a/tests/test_issue748_config_fields_reach_a_consumer.py b/tests/test_issue748_config_fields_reach_a_consumer.py
index 5a5074ad..535f11bd 100644
--- a/tests/test_issue748_config_fields_reach_a_consumer.py
+++ b/tests/test_issue748_config_fields_reach_a_consumer.py
@@ -292,9 +292,17 @@ def _consumer_modules():
return [p for p in SRC.rglob("*.py") if p.name != SCHEMA]
+# Fields whose name collides with an unrelated read elsewhere in src/, so only
+# a read through a `*.training` receiver counts as consumption.
+_RECEIVER_QUALIFIED = frozenset({
+ "training.forgetting_threshold", # ship.py has a local of the same name
+ "training.load_in_16bit", # migrate/unsloth.py reads an Unsloth kwarg of that name
+})
+
+
def field_reaches_a_consumer(key: str, attr: str, consumed: set) -> bool:
"""Apply receiver-qualified checks where the global namespace collides."""
- if key == "training.forgetting_threshold":
+ if key in _RECEIVER_QUALIFIED:
return training_receiver_reads(_consumer_modules(), attr)
return attr in consumed
diff --git a/tests/test_migrate.py b/tests/test_migrate.py
index 9db4dbeb..c4fcc0aa 100644
--- a/tests/test_migrate.py
+++ b/tests/test_migrate.py
@@ -663,7 +663,9 @@ class TestLlamaFactoryMigration:
migrate_llamafactory(cfg_file)
def test_full_finetuning_no_lora(self, tmp_path):
- """finetuning_type: full → no lora section."""
+ """finetuning_type: full → lora.r: 0 and quantization: none on loaded config."""
+ 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
cfg_file = tmp_path / "config.yaml"
@@ -677,7 +679,12 @@ class TestLlamaFactoryMigration:
encoding="utf-8",
)
result = migrate_llamafactory(cfg_file)
- assert "lora" not in result.get("training", {})
+ assert result["training"]["lora"]["r"] == 0
+ assert result["training"]["quantization"] == "none"
+
+ loaded = load_config_from_string(config_to_yaml(result))
+ assert loaded.training.lora.r == 0
+ assert loaded.training.quantization == "none"
def test_quantization_8bit(self, tmp_path):
"""quantization_bit: 8 → quantization: 8bit."""