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(config): refuse LoRA with LLaMA Pro block expansion (#1326) (#1783)

Abdulwaarith Zakariyyab7c6ac2c9cc0
diff --git a/changelog.d/0.76.0/1783.fixed.md b/changelog.d/0.76.0/1783.fixed.md
new file mode 100644
index 00000000..98398cb1
--- /dev/null
+++ b/changelog.d/0.76.0/1783.fixed.md
@@ -0,0 +1,9 @@
+- **`training.expand_layers` (LLaMA Pro) is refused at config load together with a LoRA rank (#1326 by @abdulwaarith0 in #1783).**
+ The block expansion runs before `get_peft_model`, which froze the appended
+ blocks again, so only adapters on the original layers trained while the
+ appended blocks stayed the identity. The error names `expand_layers`,
+ `freeze_trainable_layers` and `lora.r` and points to `lora.r: 0` with
+ `quantization: none`; on `task: pretrain`, which has no `lora.r: 0`, it says
+ the recipe needs `task: sft`. The LLaMA Pro examples in
+ `docs/peft-and-efficiency.md` and `docs/training.md` now set `lora.r: 0`, and
+ `docs/training.md` now says the expansion runs before `get_peft_model`.
diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.md
index d6dde688..755463bf 100644
--- a/docs/peft-and-efficiency.md
+++ b/docs/peft-and-efficiency.md
@@ -178,13 +178,15 @@ training:
quantization: none # block expansion needs an unquantized base
expand_layers: 4 # append 4 zero-init decoder blocks
freeze_trainable_layers: 4 # must equal expand_layers: freeze the original model, train only the appended blocks
+ lora:
+ r: 0 # train the appended blocks directly; a LoRA rank is refused with expand_layers
lr: 5e-5
epochs: 1
```
**What happens at trainer start.** Soup deep-copies the last `expand_layers` decoder blocks, zero-inits each clone's residual projections (`mlp.down_proj` + `self_attn.o_proj`) so the appended block initially acts as identity, appends them to `model.model.layers`, and updates `config.num_hidden_layers`. `freeze_trainable_layers` must equal `expand_layers`: it freezes every parameter except the appended blocks, the canonical LLaMA Pro "train only new blocks" recipe. It does not select the top-N or bottom-N layers, and any other value, including `0` or a negative one, is refused at config load.
-**Scope.** Works on `task: sft` and `task: pretrain` with `backend: transformers`, `modality: text` and `quantization: none`; any other combination is refused at config load. No other trainer applies the expansion, and the appended blocks are only supported on an unquantized base. Bounds: `expand_layers ∈ [1, 64]`. Over-expansion (more new blocks than the base has layers) silently clamps to the base layer count. Non-Llama-shaped architectures (e.g. Falcon's `dense_4h_to_h`) emit a `warnings.warn` because the residual zero-init heuristic only matches the standard `down_proj` / `o_proj` names — the appended blocks are still appended + trainable, but lose the identity-init guarantee.
+**Scope.** Works on `task: sft` with `backend: transformers`, `modality: text`, `quantization: none` and `lora.r: 0`. A LoRA rank is refused together with `expand_layers` ([#1326](https://github.com/MakazhanAlpamys/Soup/issues/1326)): the expansion runs before `get_peft_model`, which freezes every non-adapter parameter again, appended blocks included, so only adapters on the original layers would train. `task: pretrain` has no `lora.r: 0` route: a rank is refused at config load, and `lora.r: 0` loads but then fails inside peft at trainer start ([#1813](https://github.com/MakazhanAlpamys/Soup/issues/1813)), so the recipe needs `task: sft`. Other tasks, backends and modalities, and a quantized base, are refused at config load. No other trainer applies the expansion, and the appended blocks are only supported on an unquantized base. Bounds: `expand_layers ∈ [1, 64]`. Over-expansion (more new blocks than the base has layers) silently clamps to the base layer count. Non-Llama-shaped architectures (e.g. Falcon's `dense_4h_to_h`) emit a `warnings.warn` because the residual zero-init heuristic only matches the standard `down_proj` / `o_proj` names — the appended blocks are still appended + trainable, but lose the identity-init guarantee.
## Optimizer & PEFT Zoo
@@ -211,9 +213,8 @@ training:
loftq_iter: 1
loftq_bits: 4
- # LLaMA Pro block expansion (freeze_trainable_layers must equal expand_layers)
- expand_layers: 4
- freeze_trainable_layers: 4
+ # LLaMA Pro block expansion needs lora.r: 0, so it cannot share a run with a
+ # LoRA init such as LoftQ; see LLaMA Pro Block Expansion above.
```
Catch-all friendly errors: typos in `optimizer:` are rejected at config-load with the v0.41.0 additions listed in the message; `load_in_8bit` mixed with `load_in_16bit` raises rather than picking one silently.
diff --git a/docs/training.md b/docs/training.md
index 9ca9cda6..d4af41cc 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -2107,16 +2107,25 @@ training:
# block. capacity_factor is the fraction of tokens that get the residual update.
use_mod: true
mod_capacity_factor: 0.125
+```
+```yaml
+training:
# LLaMA Pro: append zero-initialised identity decoder blocks and train only the new
# ones (freeze_trainable_layers must equal expand_layers and freezes the
- # originals). Needs quantization: none.
+ # originals). Needs quantization: none and lora.r: 0 (task: sft).
expand_layers: 4
freeze_trainable_layers: 4
+ quantization: none
+ lora:
+ r: 0
```
-`use_mod` / `expand_layers` attach AFTER `get_peft_model` so the new routers / blocks are
-trainable. Unsupported architectures warn + skip. Pick one of MoD / LLaMA Pro per run. (v0.71.12)
+`use_mod` attaches AFTER `get_peft_model`, so the new routers are trainable. `expand_layers`
+runs BEFORE it, and `get_peft_model` would freeze the appended blocks again, so a LoRA rank is
+refused with `expand_layers` and the blocks train with `lora.r: 0`
+([#1326](https://github.com/MakazhanAlpamys/Soup/issues/1326)). Unsupported architectures
+warn + skip. Pick one of MoD / LLaMA Pro per run. (v0.71.12)
LongLoRA S² (`use_longlora: true`) is refused at config load
([#1240](https://github.com/MakazhanAlpamys/Soup/issues/1240)). Its override rolled the
diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.py
index f7ddd272..995e5a99 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -1284,7 +1284,9 @@ class TrainingConfig(BaseModel):
default=None, ge=1, le=64,
description=(
"LLaMA Pro: append N zero-init transformer blocks and freeze "
- "the original ones before SFT or pre-training."
+ "the original ones, so only the new blocks train. A LoRA rank is "
+ "refused with it, since get_peft_model would freeze the new blocks "
+ "again (#1326): set lora.r: 0 and quantization: none on task: sft."
),
)
freeze_trainable_layers: Optional[int] = Field(
@@ -5058,6 +5060,51 @@ class SoupConfig(BaseModel):
)
return self
+ @model_validator(mode="after")
+ def _validate_expand_layers_lora(self) -> "SoupConfig":
+ """#1326 - LLaMA Pro under LoRA does not train the appended blocks.
+
+ The block expansion freezes everything but the new blocks, then
+ ``get_peft_model`` runs and freezes every non-adapter parameter again,
+ new blocks included, while adapters land on every targeted layer. With
+ the default ``q_proj``/``v_proj`` targets the new blocks also stay the
+ identity (their zero-initialised ``o_proj``/``down_proj`` are frozen), so
+ only the original layers learn. Route 1 of the ruling: refuse the
+ combination; ``lora.r: 0`` trains the new blocks directly, and is
+ available on ``task: sft`` only.
+ """
+ tcfg = self.training
+ if tcfg.expand_layers is None or tcfg.lora.r == 0:
+ return self
+ if (
+ tcfg.stream_layers
+ or tcfg.unfrozen_parameters
+ or tcfg.lisa_enabled
+ or tcfg.quantization_aware == "quest"
+ ):
+ # Streaming, Spectrum, LISA and QuEST refuse expand_layers outright in
+ # their own validators. Let that message speak: lora.r: 0 would not
+ # make such a config load.
+ return self
+ fields = (
+ f"training.expand_layers: {tcfg.expand_layers} with "
+ f"training.freeze_trainable_layers: {tcfg.freeze_trainable_layers} "
+ f"(LLaMA Pro) cannot be combined with LoRA (training.lora.r: "
+ f"{tcfg.lora.r}). get_peft_model runs after the block expansion and "
+ "freezes the appended blocks again, so only adapters on the original "
+ "layers would train. "
+ )
+ if self.task == "pretrain":
+ raise ValueError(
+ fields + "Training only the new blocks needs lora.r: 0, which "
+ "task: pretrain does not support, so this recipe needs task: sft "
+ "with lora.r: 0 and quantization: none."
+ )
+ raise ValueError(
+ fields + "To train only the new blocks, set lora.r: 0 with "
+ "quantization: none."
+ )
+
@model_validator(mode="after")
def _validate_v042_pre_tokenized_modality(self) -> "SoupConfig":
if self.data.format == "pre_tokenized" and self.modality != "text":
diff --git a/tests/test_issue1325_expand_layers_scope.py b/tests/test_issue1325_expand_layers_scope.py
index afa05e7f..9ec745de 100644
--- a/tests/test_issue1325_expand_layers_scope.py
+++ b/tests/test_issue1325_expand_layers_scope.py
@@ -93,6 +93,7 @@ def test_refused_off_text(task, modality):
@pytest.mark.parametrize("task", _SUPPORTED_TASKS)
def test_supported_routes_still_load(task):
- cfg = load_config_from_string(_yaml(task, modality="text"))
+ # #1326: a LoRA rank is refused with expand_layers, so the loading route is lora.r: 0.
+ cfg = load_config_from_string(_yaml(task, modality="text") + " lora:\n r: 0\n")
assert cfg.training.expand_layers == 2
assert cfg.training.freeze_trainable_layers == 2
diff --git a/tests/test_issue1326_llama_pro_lora_refused.py b/tests/test_issue1326_llama_pro_lora_refused.py
new file mode 100644
index 00000000..ce386447
--- /dev/null
+++ b/tests/test_issue1326_llama_pro_lora_refused.py
@@ -0,0 +1,126 @@
+"""Issue #1326: LLaMA Pro under LoRA does not train the appended blocks.
+
+``apply_block_expansion_if_configured`` freezes everything but the appended
+blocks, then ``get_peft_model`` freezes every non-adapter parameter again,
+appended blocks included, and puts adapters on the original layers. The ruling
+(route 1) refuses ``expand_layers`` together with a LoRA rank at config load and
+points to ``lora.r: 0``, which ``task: pretrain`` does not have.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+import pytest
+
+from soup_cli.config.loader import load_config_from_string
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+_DOCS = ("docs/peft-and-efficiency.md", "docs/training.md")
+_FENCE = re.compile(r"```ya?ml\n(.*?)```", re.DOTALL)
+_HEAD = "base: org/model\ntask: sft\ndata:\n train: ./data.jsonl\n"
+
+
+def _config(task: str, lora: str = "") -> str:
+ return (
+ "base: org/model\n"
+ f"task: {task}\n"
+ "data:\n train: ./data.jsonl\n"
+ "training:\n quantization: none\n expand_layers: 4\n freeze_trainable_layers: 4\n"
+ + lora
+ )
+
+
[email protected]("task", ["sft", "pretrain"])
+ ("lora", "rank"),
+ [("", 64), (" lora:\n r: 8\n", 8)],
+ ids=["default_rank", "explicit_rank"],
+)
+def test_a_lora_rank_with_llama_pro_is_refused(task, lora, rank):
+ with pytest.raises(ValueError) as excinfo:
+ load_config_from_string(_config(task, lora))
+ message = " ".join(str(excinfo.value).split())
+ assert "training.expand_layers: 4" in message
+ assert "training.freeze_trainable_layers: 4" in message
+ assert f"training.lora.r: {rank}" in message
+ assert "freezes the appended blocks again" in message
+ assert "lora.r: 0" in message
+ assert "quantization: none" in message
+ if task == "pretrain":
+ assert "needs task: sft" in message
+ else:
+ assert "needs task: sft" not in message
+
+
+ ("mode", "named"),
+ [
+ (" stream_layers: true\n batch_size: 1\n", "stream_layers"),
+ (" unfrozen_parameters:\n - 'model.layers.0.*'\n", "unfrozen_parameters"),
+ (" lisa_enabled: true\n", "lisa_enabled"),
+ (" quantization_aware: quest\n", "quantization_aware"),
+ ],
+ ids=["stream_layers", "spectrum", "lisa", "quest"],
+)
+def test_modes_that_refuse_expand_layers_outright_keep_their_own_message(mode, named):
+ # lora.r: 0 would not make these configs load, so the #1326 message must not win.
+ with pytest.raises(ValueError) as excinfo:
+ load_config_from_string(_config("sft", mode))
+ message = " ".join(str(excinfo.value).split())
+ assert named in message
+ assert "freezes the appended blocks again" not in message
+
+
[email protected]("freeze", [None, 0, 2], ids=["missing", "zero", "smaller"])
+def test_a_wrong_freeze_value_keeps_the_1409_message(freeze):
+ # The #1409 check runs first, so the #1326 message only ever shows matching values.
+ config = _config("sft").replace(" freeze_trainable_layers: 4\n", "")
+ if freeze is not None:
+ config += f" freeze_trainable_layers: {freeze}\n"
+ with pytest.raises(ValueError) as excinfo:
+ load_config_from_string(config)
+ message = " ".join(str(excinfo.value).split())
+ assert "Set freeze_trainable_layers: 4." in message
+ assert "freezes the appended blocks again" not in message
+
+
+def test_full_fine_tuning_of_the_new_blocks_loads_on_sft():
+ cfg = load_config_from_string(_config("sft", " lora:\n r: 0\n"))
+ assert cfg.training.expand_layers == 4
+ assert cfg.training.freeze_trainable_layers == 4
+ assert cfg.training.lora.r == 0
+
+
+def test_lora_without_llama_pro_still_loads():
+ cfg = load_config_from_string(_HEAD + "training:\n quantization: none\n")
+ assert cfg.training.expand_layers is None
+ assert cfg.training.lora.r == 64
+
+
+def _llama_pro_examples() -> list[tuple[str, str]]:
+ examples = []
+ for rel in _DOCS:
+ text = (REPO_ROOT / rel).read_text(encoding="utf-8")
+ for block in _FENCE.findall(text):
+ if re.search(r"^\s*expand_layers:", block, re.MULTILINE):
+ examples.append((rel, block))
+ return examples
+
+
+def test_every_llama_pro_example_in_the_docs_loads():
+ examples = _llama_pro_examples()
+ assert {rel for rel, _ in examples} == set(_DOCS), examples
+ for rel, block in examples:
+ text = block if re.search(r"^base:", block, re.MULTILINE) else _HEAD + block
+ cfg = load_config_from_string(text)
+ assert cfg.training.expand_layers is not None, rel
+ assert cfg.training.lora.r == 0, rel
+
+
+def test_the_training_docs_put_the_expansion_before_get_peft_model():
+ flat = " ".join((REPO_ROOT / "docs" / "training.md").read_text(encoding="utf-8").split())
+ assert "`use_mod` / `expand_layers` attach AFTER" not in flat
+ assert "`expand_layers` runs BEFORE it" in flat
+ assert "#1326" in flat
diff --git a/tests/test_issue1409_freeze_equals_expand.py b/tests/test_issue1409_freeze_equals_expand.py
index 2bb8f56c..c530a66d 100644
--- a/tests/test_issue1409_freeze_equals_expand.py
+++ b/tests/test_issue1409_freeze_equals_expand.py
@@ -18,6 +18,7 @@ def _load(task, expand, freeze):
lines = [" quantization: none\n", f" expand_layers: {expand}\n"]
if freeze is not None:
lines.append(f" freeze_trainable_layers: {freeze}\n")
+ lines.append(" lora:\n r: 0\n") # #1326: a LoRA rank is refused with expand_layers
return load_config_from_string(
"base: org/model\n"
f"task: {task}\n"
diff --git a/tests/test_v0410_part_c.py b/tests/test_v0410_part_c.py
index 6db3f446..d8ebda6d 100644
--- a/tests/test_v0410_part_c.py
+++ b/tests/test_v0410_part_c.py
@@ -203,7 +203,8 @@ class TestSchemaBlockExpansion:
def test_load_in_16bit_alias_satisfies_the_requirement(self):
# docs/peft-and-efficiency.md: load_in_16bit: true == quantization: none
- cfg = _sft(expand_layers=2, freeze_trainable_layers=2, load_in_16bit=True)
+ # #1326: a LoRA rank is refused with expand_layers.
+ cfg = _sft(expand_layers=2, freeze_trainable_layers=2, load_in_16bit=True, lora={"r": 0})
assert cfg.training.quantization == "none"
assert cfg.training.expand_layers == 2
diff --git a/tests/test_v0534.py b/tests/test_v0534.py
index 60d3467c..76075a3e 100644
--- a/tests/test_v0534.py
+++ b/tests/test_v0534.py
@@ -716,6 +716,8 @@ training:
quantization: none
expand_layers: 4
freeze_trainable_layers: 4
+ lora:
+ r: 0 # #1326: a LoRA rank is refused with expand_layers
"""
cfg = _load(yaml_in)
assert cfg.training.expand_layers == 4