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.

feat(recipes): add Qwen3.5 2B DPO recipe (#2160)

Nurkhan Esenbekd2e9a0749622
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 9f523657..b3fd2779 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -124,7 +124,7 @@ src/soup_cli/
eval/ - Eval platform (custom tasks, LLM judge, human eval, leaderboard)
bench/ - Benchmark instruments behind `soup bench train` (collector, train_report, train_run) (#836)
migrate/ - Config migration (LLaMA-Factory, Axolotl, Unsloth)
- recipes/ - Ready-made configs for popular models (170 recipes)
+ recipes/ - Ready-made configs for popular models (171 recipes)
autopilot/ - Zero-config decision engine (v0.25.0)
registry/ - Model Registry (hashing, store, diff, attach) (v0.26.0 + v0.33.0)
cans/ - Shareable .can artifact format + run/publish orchestrator (v0.26.0 + v0.33.0)
diff --git a/changelog.d/0.76.0/2160.added.md b/changelog.d/0.76.0/2160.added.md
new file mode 100644
index 00000000..7583c287
--- /dev/null
+++ b/changelog.d/0.76.0/2160.added.md
@@ -0,0 +1,5 @@
+- Add `qwen3.5-2b-dpo`, a text preference-training recipe for `Qwen/Qwen3.5-2B`,
+ with independent metadata/YAML identity tests, language-tower and preference-pair
+ checks, and CPU/meta architecture qualification. Settings inherit the existing
+ Qwen3.5 DPO siblings; full-2B training and NF4 performance remain unmeasured
+ (#2160; tracking issue #275; by @kok-o).
diff --git a/docs/commands.md b/docs/commands.md
index 7ef2983b..2463141e 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -184,7 +184,7 @@ soup migrate --from llamafactory config.yaml Import config from LLaMA-Factory
soup migrate --from axolotl config.yml Import config from Axolotl
soup migrate --from unsloth notebook.ipynb Import config from Unsloth notebook
soup migrate --from llamafactory c.yaml --dry-run Preview without writing
-soup recipes list List all 170 ready-made recipes
+soup recipes list List all 171 ready-made recipes
soup recipes show llama3.1-8b-sft Print recipe YAML
soup recipes use llama3.1-8b-sft Copy recipe to soup.yaml
soup recipes search "reasoning" Search by keyword/task/size
diff --git a/docs/models.md b/docs/models.md
index 0c480897..9f3e7a8c 100644
--- a/docs/models.md
+++ b/docs/models.md
@@ -71,12 +71,16 @@ whose `scatter` operator still requires `int64` indices, Soup widens only the
QSA indexer's local index tensors before LoRA injection; Torch and the upstream
Transformers class remain unchanged.
-`soup recipes use qwen3.5-4b-dpo` selects the 4B language decoder for text
-preference pairs (`prompt`, `chosen`, `rejected`). It inherits the shipped
+`soup recipes use qwen3.5-2b-dpo` and `soup recipes use qwen3.5-4b-dpo` select
+the 2B and 4B language decoders for text preference pairs (`prompt`, `chosen`,
+`rejected`). Both inherit the shipped
Qwen3.5-9B DPO settings: `lr: 5e-6`, three epochs, LoRA rank 16 / alpha 32,
4-bit quantization and a 4096-token limit. These are inherited starting values,
-not a measured 4B tuning recommendation. The model's visual tower is excluded;
-image preference data is not supported by this recipe.
+not measured 2B or 4B tuning recommendations. The model's visual tower is excluded;
+image preference data is not supported by these recipes. The 2B config's native
+text architecture and LoRA attachment have been checked on the meta device, with
+a tiny random decoder's forward/backward pass checked on CPU. This does not
+establish full-checkpoint 2B training quality, NF4 execution, or GPU memory use.
With `training.stream_layers: true`, the Qwen4-Exp text decoder is admitted by
its own parity-tested path. Its very large frozen PLE N-gram table is excluded
diff --git a/docs/serving-and-export.md b/docs/serving-and-export.md
index fe59751c..356b80d9 100644
--- a/docs/serving-and-export.md
+++ b/docs/serving-and-export.md
@@ -781,7 +781,7 @@ still records the URL it was given.
**Pages:**
- **Dashboard** — view all experiment runs, loss charts, system info, multi-run comparison
-- **New Training** — create configs from templates or 170 ready-made recipes, validate, start training with live SSE log streaming and progress bar
+- **New Training** — create configs from templates or 171 ready-made recipes, validate, start training with live SSE log streaming and progress bar
- **Data Explorer** — browse and inspect datasets (JSONL, JSON, CSV, Parquet)
- **Model Chat** — chat with streaming responses, configurable temperature/top_p/max_tokens, system prompt, adapter selection, markdown rendering, chat export
@@ -790,7 +790,7 @@ still records the URL it was given.
- **Enhanced Metrics** — 2x2 chart grid (loss, LR, grad_norm, throughput) + GPU memory chart, eval results table
- **Multi-Run Compare** — overlay loss curves from up to 5 runs side-by-side
- **Chat Upgrade** — SSE streaming via proxy, typing indicator, cancel button, markdown renderer (bold, italic, code blocks), chat export as JSON
-- **Config Builder** — recipe dropdown (170 recipes), config schema API for dynamic form generation
+- **Config Builder** — recipe dropdown (171 recipes), config schema API for dynamic form generation
Gradient norm is nullable: backends or steps that do not report it store and
stream `null`, and the Web UI chart leaves a gap instead of drawing a false
diff --git a/src/soup_cli/recipes/catalog.py b/src/soup_cli/recipes/catalog.py
index 441c7485..5ee2163e 100644
--- a/src/soup_cli/recipes/catalog.py
+++ b/src/soup_cli/recipes/catalog.py
@@ -51,7 +51,7 @@ def search_recipes(
# ---------------------------------------------------------------------------
-# Recipe catalog (170 recipes)
+# Recipe catalog (171 recipes)
# ---------------------------------------------------------------------------
RECIPES: Dict[str, RecipeMeta] = {
@@ -3715,6 +3715,36 @@ training:
target_modules: auto
quantization: 4bit
+output: ./output
+""",
+ ),
+ "qwen3.5-2b-dpo": RecipeMeta(
+ model="Qwen/Qwen3.5-2B",
+ task="dpo",
+ size="2B",
+ tags=("qwen", "qwen3.5", "dpo", "alignment", "preference", "small", "edge"),
+ description="Qwen 3.5 2B text DPO alignment (Apache-2.0, small / edge)",
+ yaml_str="""\
+base: Qwen/Qwen3.5-2B
+task: dpo
+modality: text
+
+data:
+ train: ./data/preference_train.jsonl
+ format: dpo
+ max_length: 4096
+
+training:
+ epochs: 3
+ lr: 5e-6
+ batch_size: auto
+ lora:
+ r: 16
+ alpha: 32
+ target_modules: auto
+ quantization: 4bit
+ dpo_beta: 0.1
+
output: ./output
""",
),
diff --git a/tests/fixtures/recipe_config_snapshots.json b/tests/fixtures/recipe_config_snapshots.json
index d9131305..d4c07b08 100644
--- a/tests/fixtures/recipe_config_snapshots.json
+++ b/tests/fixtures/recipe_config_snapshots.json
@@ -1747,6 +1747,16 @@
"training.lora.r": 16,
"training.lr": 1e-05
},
+ "qwen3.5-2b-dpo": {
+ "base": "Qwen/Qwen3.5-2B",
+ "data.format": "dpo",
+ "data.max_length": 4096,
+ "data.train": "./data/preference_train.jsonl",
+ "task": "dpo",
+ "training.lora.alpha": 32,
+ "training.lora.r": 16,
+ "training.lr": 5e-06
+ },
"qwen3.5-2b-grpo": {
"base": "Qwen/Qwen3.5-2B",
"data.format": "auto",
diff --git a/tests/recipe_count.py b/tests/recipe_count.py
index 13603236..97825baa 100644
--- a/tests/recipe_count.py
+++ b/tests/recipe_count.py
@@ -9,7 +9,7 @@ the catalog, in ``tests/test_recipe_count_is_synced.py``.
from __future__ import annotations
-EXPECTED_RECIPE_COUNT = 170
+EXPECTED_RECIPE_COUNT = 171
def recipe_count_hint(actual: int) -> str:
diff --git a/tests/test_issue427_qwen35_text_modality.py b/tests/test_issue427_qwen35_text_modality.py
index 3f0192cf..2b1b29a3 100644
--- a/tests/test_issue427_qwen35_text_modality.py
+++ b/tests/test_issue427_qwen35_text_modality.py
@@ -12,6 +12,7 @@ EXPECTED_QWEN35_TEXT_RECIPES = {
"qwen3.5-0.8b-sft",
"qwen3.5-0.8b-grpo",
"qwen3.5-2b-sft",
+ "qwen3.5-2b-dpo",
"qwen3.5-2b-grpo",
"qwen3.5-4b-sft",
"qwen3.5-4b-dpo",
diff --git a/tests/test_qwen35_2b_dpo_recipe.py b/tests/test_qwen35_2b_dpo_recipe.py
new file mode 100644
index 00000000..a315408f
--- /dev/null
+++ b/tests/test_qwen35_2b_dpo_recipe.py
@@ -0,0 +1,133 @@
+"""The 2B recipe's independent IDs and real text-preference consumers."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+import yaml
+from typer.testing import CliRunner
+
+from soup_cli.config.loader import load_config_from_string
+from soup_cli.data.loader import load_dataset
+from soup_cli.recipes.catalog import RECIPES, get_recipe, search_recipes
+from tests.conftest import strip_ansi
+
+NAME = "qwen3.5-2b-dpo"
+BASE = "Qwen/Qwen3.5-2B"
+
+
+def test_metadata_selects_the_2b_preference_model_independently() -> None:
+ recipe = get_recipe(NAME)
+ assert recipe is not None
+ assert recipe.model == BASE
+ assert recipe.task == "dpo"
+ assert recipe.size == "2B"
+ assert {"qwen", "qwen3.5", "dpo", "preference", "small", "edge"} <= set(recipe.tags)
+ assert recipe in search_recipes(query="qwen3.5", task="dpo", size="2b")
+
+
+def test_yaml_selects_the_2b_text_decoder_and_inherited_dpo_settings() -> None:
+ raw = yaml.safe_load(RECIPES[NAME].yaml_str)
+ assert raw["base"] == BASE
+ assert raw["task"] == "dpo"
+ assert raw["modality"] == "text"
+ assert raw["data"]["format"] == "dpo"
+
+ cfg = load_config_from_string(RECIPES[NAME].yaml_str)
+ assert cfg.base == BASE
+ assert cfg.task == "dpo"
+ assert cfg.modality == "text"
+ assert cfg.data.train == "./data/preference_train.jsonl"
+ assert cfg.data.max_length == 4096
+ assert cfg.training.lr == 5e-6
+ assert cfg.training.epochs == 3
+ assert cfg.training.dpo_beta == 0.1
+ assert cfg.training.batch_size == "auto"
+ assert cfg.training.quantization == "4bit"
+ assert cfg.training.lora.r == 16
+ assert cfg.training.lora.alpha == 32
+ assert cfg.training.lora.target_modules == "auto"
+ assert cfg.output == "./output"
+
+
+def test_preference_loader_preserves_both_completions(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+ data_dir = tmp_path / "data"
+ data_dir.mkdir()
+ rows = [
+ {"prompt": "Name a prime", "chosen": "Three", "rejected": "Four"},
+ {"prompt": "Add one and two", "chosen": "Three", "rejected": "Two"},
+ ]
+ (data_dir / "preference_train.jsonl").write_text(
+ "\n".join(json.dumps(row) for row in rows) + "\n", encoding="utf-8"
+ )
+ cfg = load_config_from_string(RECIPES[NAME].yaml_str)
+ cfg.data.val_split = 0
+ assert load_dataset(cfg.data)["train"] == rows
+
+
+def test_show_and_use_write_the_same_loadable_text_dpo_config(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from soup_cli.cli import app
+
+ monkeypatch.chdir(tmp_path)
+ runner = CliRunner()
+ shown = runner.invoke(app, ["recipes", "show", NAME])
+ assert shown.exit_code == 0, (strip_ansi(shown.output), repr(shown.exception))
+ assert BASE in strip_ansi(shown.output)
+ used = runner.invoke(app, ["recipes", "use", NAME, "--yes"])
+ assert used.exit_code == 0, (strip_ansi(used.output), repr(used.exception))
+ text = (tmp_path / "soup.yaml").read_text(encoding="utf-8")
+ assert yaml.safe_load(text) == yaml.safe_load(RECIPES[NAME].yaml_str)
+ cfg = load_config_from_string(text)
+ assert cfg.base == BASE
+ assert cfg.task == "dpo"
+ assert cfg.modality == "text"
+ assert cfg.data.format == "dpo"
+
+
+def test_native_text_decoder_attaches_recipe_lora_and_backpropagates_on_cpu() -> None:
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("peft")
+ from peft import get_peft_model
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ from soup_cli.utils.attach_preflight import loader_for, trainer_lora_config
+
+ cfg = load_config_from_string(RECIPES[NAME].yaml_str)
+ assert loader_for(cfg) == ("AutoModelForCausalLM",)
+ # The public 2B decoder mixes linear and full attention. Keep both native
+ # block kinds, with tiny random weights and the pure-PyTorch CPU fallback.
+ # This qualifies the text/LoRA consumer, not public 2B weights or NF4.
+ with torch.random.fork_rng(devices=[]):
+ torch.manual_seed(0)
+ config = AutoConfig.for_model("qwen3_5", text_config={
+ "vocab_size": 32, "hidden_size": 32, "intermediate_size": 64,
+ "num_hidden_layers": 2, "num_attention_heads": 2, "num_key_value_heads": 2,
+ "head_dim": 16, "max_position_embeddings": 64, "full_attention_interval": 2,
+ "layer_types": ["linear_attention", "full_attention"],
+ "linear_conv_kernel_dim": 4, "linear_key_head_dim": 8,
+ "linear_num_key_heads": 2, "linear_num_value_heads": 2,
+ "linear_value_head_dim": 8, "tie_word_embeddings": False,
+ })
+ model = AutoModelForCausalLM.from_config(config).to("cpu")
+ lora_config, _targets = trainer_lora_config(model, cfg, None)
+ model = get_peft_model(model, lora_config)
+ assert not any("visual" in name for name, _ in model.named_parameters())
+ tokens = torch.tensor([[1, 2, 3, 4]])
+ result = model(input_ids=tokens, labels=tokens)
+ assert result.logits.shape == (1, 4, 32)
+ assert torch.isfinite(result.loss)
+ result.loss.backward()
+ for projection in ("q_proj", "v_proj", "in_proj_qkv", "out_proj"):
+ grads = [
+ param.grad for name, param in model.named_parameters()
+ if f".{projection}.lora_B." in name
+ ]
+ assert len(grads) == 1, projection
+ assert grads[0] is not None and grads[0].abs().sum() > 0, projection
diff --git a/tests/test_recipes.py b/tests/test_recipes.py
index e9629e47..ae485390 100644
--- a/tests/test_recipes.py
+++ b/tests/test_recipes.py
@@ -1830,6 +1830,7 @@ class TestV025NewRecipes:
Issue #1145 removed 3 (mistral-large-3-sft, mistral-large-3-dpo, minimax-m3-dpo) -> 170.
Issue #1867 retires the unsupported vision-preference recipe -> 169.
Task-variant for #275 added 1 (qwen3.5-4b-dpo) -> 170.
+ Task-variant for #275 added 1 (qwen3.5-2b-dpo) -> 171.
"""
from soup_cli.recipes.catalog import RECIPES
from tests.recipe_count import EXPECTED_RECIPE_COUNT, recipe_count_hint