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 4B text DPO variant (#2129)

Nurkhan Esenbeka82528c77a0d
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ee54b967..9f523657 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 (169 recipes)
+ recipes/ - Ready-made configs for popular models (170 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/2129.added.md b/changelog.d/0.76.0/2129.added.md
new file mode 100644
index 00000000..dfb9da10
--- /dev/null
+++ b/changelog.d/0.76.0/2129.added.md
@@ -0,0 +1,4 @@
+- Add `qwen3.5-4b-dpo`, a text preference-training recipe for `Qwen/Qwen3.5-4B`,
+ with independently tested metadata/YAML identities and the explicit language-tower
+ contract. Settings inherit the existing 9B DPO sibling; no full-4B training or
+ performance result is claimed (#2129; tracking issue #275).
diff --git a/docs/commands.md b/docs/commands.md
index a37a1285..1f590dfb 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -183,7 +183,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 169 ready-made recipes
+soup recipes list List all 170 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 048b036b..be572683 100644
--- a/docs/models.md
+++ b/docs/models.md
@@ -40,13 +40,20 @@ Qwen3.5, Qwen3.6, and Qwen3.8 checkpoints advertise a multimodal conditional-gen
architecture on the Hub, but Soup's catalog recipes are deliberately text-only.
Their explicit `modality: text` selects `AutoModelForCausalLM`, which instantiates the
language decoder without the visual tower. This is appropriate for text-only SFT,
-pre-training, and GRPO data; it is not a full multimodal fine-tune. The Transformers
+pre-training, DPO and GRPO data; it is not a full multimodal fine-tune. The Transformers
backend requires Transformers 5.16.1 or newer, which also supplies the
`qwen4_exp` text decoder used by Qwen3.8-Flash-Next (#571). On Torch runtimes
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
+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.
+
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
from the decoder-layer shard and can be served from the original safetensors
diff --git a/docs/serving-and-export.md b/docs/serving-and-export.md
index 20709e10..818db8af 100644
--- a/docs/serving-and-export.md
+++ b/docs/serving-and-export.md
@@ -748,7 +748,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 169 ready-made recipes, validate, start training with live SSE log streaming and progress bar
+- **New Training** — create configs from templates or 170 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
@@ -757,7 +757,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 (169 recipes), config schema API for dynamic form generation
+- **Config Builder** — recipe dropdown (170 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 413195e1..d0dfb7fc 100644
--- a/src/soup_cli/recipes/catalog.py
+++ b/src/soup_cli/recipes/catalog.py
@@ -48,7 +48,7 @@ def search_recipes(
# ---------------------------------------------------------------------------
-# Recipe catalog (169 recipes)
+# Recipe catalog (170 recipes)
# ---------------------------------------------------------------------------
RECIPES: Dict[str, RecipeMeta] = {
@@ -3773,6 +3773,36 @@ training:
target_modules: auto
quantization: 4bit
+output: ./output
+""",
+ ),
+ "qwen3.5-4b-dpo": RecipeMeta(
+ model="Qwen/Qwen3.5-4B",
+ task="dpo",
+ size="4B",
+ tags=("qwen", "qwen3.5", "dpo", "alignment", "preference", "small"),
+ description="Qwen 3.5 4B text DPO alignment (Apache-2.0)",
+ yaml_str="""\
+base: Qwen/Qwen3.5-4B
+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 e8433f21..915e24fa 100644
--- a/tests/fixtures/recipe_config_snapshots.json
+++ b/tests/fixtures/recipe_config_snapshots.json
@@ -1837,6 +1837,16 @@
"training.lr": 5e-06,
"training.moe_lora": true
},
+ "qwen3.5-4b-dpo": {
+ "base": "Qwen/Qwen3.5-4B",
+ "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-4b-pretrain": {
"base": "Qwen/Qwen3.5-4B-Base",
"data.format": "plaintext",
diff --git a/tests/recipe_count.py b/tests/recipe_count.py
index fcecb72e..13603236 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 = 169
+EXPECTED_RECIPE_COUNT = 170
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 00689a48..3f0192cf 100644
--- a/tests/test_issue427_qwen35_text_modality.py
+++ b/tests/test_issue427_qwen35_text_modality.py
@@ -14,6 +14,7 @@ EXPECTED_QWEN35_TEXT_RECIPES = {
"qwen3.5-2b-sft",
"qwen3.5-2b-grpo",
"qwen3.5-4b-sft",
+ "qwen3.5-4b-dpo",
"qwen3.5-4b-pretrain",
"qwen3.5-9b-sft",
"qwen3.5-9b-grpo",
diff --git a/tests/test_qwen35_4b_dpo_recipe.py b/tests/test_qwen35_4b_dpo_recipe.py
new file mode 100644
index 00000000..04dc2462
--- /dev/null
+++ b/tests/test_qwen35_4b_dpo_recipe.py
@@ -0,0 +1,95 @@
+"""Independent recipe metadata, YAML, preference-loader and CLI contracts."""
+
+import json
+
+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
+from tests.conftest import strip_ansi
+
+NAME = "qwen3.5-4b-dpo"
+BASE = "Qwen/Qwen3.5-4B"
+
+
+def test_metadata_names_the_4b_dpo_model_independently():
+ recipe = get_recipe(NAME)
+ assert recipe is not None
+ assert recipe.model == BASE
+ assert recipe.task == "dpo"
+ assert recipe.size == "4B"
+ assert {"qwen", "qwen3.5", "dpo", "preference"} <= set(recipe.tags)
+ assert recipe.model == RECIPES["qwen3.5-4b-sft"].model
+
+
+def test_yaml_names_the_base_and_selects_text_preference_training():
+ 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 and cfg.task == "dpo" and 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
+
+
+def test_recipe_loader_keeps_chosen_and_rejected(tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ data_dir = tmp_path / "data"
+ data_dir.mkdir()
+ row = {"prompt": "Q", "chosen": "good", "rejected": "bad"}
+ (data_dir / "preference_train.jsonl").write_text(json.dumps(row) + "\n", encoding="utf-8")
+ cfg = load_config_from_string(RECIPES[NAME].yaml_str)
+ cfg.data.val_split = 0
+ assert load_dataset(cfg.data)["train"] == [row]
+
+
+def test_show_and_use_write_a_loadable_text_dpo_config(tmp_path, monkeypatch):
+ 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)
+ assert BASE in strip_ansi(shown.output)
+ used = runner.invoke(app, ["recipes", "use", NAME, "--yes"])
+ assert used.exit_code == 0, strip_ansi(used.output)
+ text = (tmp_path / "soup.yaml").read_text(encoding="utf-8")
+ cfg = load_config_from_string(text)
+ assert cfg.base == BASE and cfg.task == "dpo" and cfg.modality == "text"
+ assert cfg.data.format == "dpo"
+
+
+def test_native_qwen35_text_decoder_loads_and_backpropagates_on_cpu():
+ torch = pytest.importorskip("torch")
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ # Same native model family as the public 4B config, deliberately tiny random
+ # weights: this tests the text consumer, not the full 4B checkpoint or NF4.
+ config = AutoConfig.for_model("qwen3_5", text_config={
+ "vocab_size": 32, "hidden_size": 32, "intermediate_size": 64,
+ "num_hidden_layers": 1, "num_attention_heads": 2, "num_key_value_heads": 2,
+ "head_dim": 16, "max_position_embeddings": 64, "full_attention_interval": 1,
+ "layer_types": ["full_attention"], "tie_word_embeddings": False,
+ })
+ model = AutoModelForCausalLM.from_config(config).to("cpu")
+ 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()
+ assert any(
+ param.grad is not None and param.grad.abs().sum() > 0 for param in model.parameters()
+ )
diff --git a/tests/test_recipes.py b/tests/test_recipes.py
index 78279e66..bf46f048 100644
--- a/tests/test_recipes.py
+++ b/tests/test_recipes.py
@@ -1827,6 +1827,7 @@ class TestV025NewRecipes:
PR #1113 removes spark-tts -> 173.
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.
"""
from soup_cli.recipes.catalog import RECIPES
from tests.recipe_count import EXPECTED_RECIPE_COUNT, recipe_count_hint