Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(config): require freeze_trainable_layers to equal expand_layers (#1409) (#1586)
Dipak Chaudharie906e1374bfd
diff --git a/changelog.d/0.75.1/1586.fixed.md b/changelog.d/0.75.1/1586.fixed.mdnew file mode 100644index 00000000..21f426a7--- /dev/null+++ b/changelog.d/0.75.1/1586.fixed.md@@ -0,0 +1,11 @@+- **With `training.expand_layers` set, `training.freeze_trainable_layers` must now equal it, and any other value fails at load (#1409 by @dchaudhari7177 in #1586).**+ The field was read only for its sign: `1`, `2` and `4` all trained just the+ appended blocks, and `0` or a negative value silently trained the whole+ expanded model. It now has one meaning, freeze the original model and train+ only the appended blocks, so a config with `expand_layers: N` and a+ `freeze_trainable_layers` of `0`, a negative value or a different positive+ value is refused with both fields named and `Set freeze_trainable_layers: N.`+ Before, with `lora.r: 0`, `0` and negative values trained every layer and any+ positive value trained the appended blocks; under LoRA the value changed+ nothing (#1326). `expand_layers: N` with `freeze_trainable_layers: N` trains+ exactly what it did.diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.mdindex 6586dec7..391d0cda 100644--- a/docs/peft-and-efficiency.md+++ b/docs/peft-and-efficiency.md@@ -177,12 +177,12 @@ data:training:quantization: none # block expansion needs an unquantized baseexpand_layers: 4 # append 4 zero-init decoder blocks- freeze_trainable_layers: 4 # train only the appended blocks (requires expand_layers)+ freeze_trainable_layers: 4 # must equal expand_layers: freeze the original model, train only the appended blockslr: 5e-5epochs: 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`. When `freeze_trainable_layers > 0` is set, every parameter except the appended blocks is frozen — this is the canonical LLaMA Pro "train only new blocks" recipe.+**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.@@ -208,7 +208,7 @@ training:loftq_iter: 1loftq_bits: 4- # LLaMA Pro block expansion (schema only in v0.41.0; live wiring in v0.41.1)+ # LLaMA Pro block expansion (freeze_trainable_layers must equal expand_layers)expand_layers: 4freeze_trainable_layers: 4```diff --git a/docs/training.md b/docs/training.mdindex 4212b71f..365119de 100644--- a/docs/training.md+++ b/docs/training.md@@ -2036,7 +2036,8 @@ training:mod_capacity_factor: 0.125# LLaMA Pro: append zero-initialised identity decoder blocks and train only the new- # ones (freeze_trainable_layers freezes the originals). Needs quantization: none.+ # ones (freeze_trainable_layers must equal expand_layers and freezes the+ # originals). Needs quantization: none.expand_layers: 4freeze_trainable_layers: 4```diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex b05bfff1..43516e68 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -1287,9 +1287,10 @@ class TrainingConfig(BaseModel):freeze_trainable_layers: Optional[int] = Field(default=None,description=(- "LLaMA Pro: applies only together with expand_layers and is "- "refused without it. A positive value freezes every parameter "- "except the appended blocks. Magnitude capped at 1000. "+ "LLaMA Pro: applies only together with expand_layers, must equal "+ "it, and is refused otherwise. It freezes every parameter of the "+ "original model so only the appended blocks train; it does not "+ "select top-N or bottom-N layers. Magnitude capped at 1000. ""(v0.41.0)"),)@@ -4189,15 +4190,32 @@ class TrainingConfig(BaseModel):raise ValueError("expand_layers requires freeze_trainable_layers (LLaMA Pro ""freezes the original layers and trains only the new blocks). "- "Set freeze_trainable_layers: <signed int>."+ f"Set freeze_trainable_layers: {self.expand_layers}.")if self.expand_layers is None and self.freeze_trainable_layers is not None:raise ValueError("freeze_trainable_layers only applies together with "- "expand_layers (LLaMA Pro block expansion), where a positive "- "value trains only the appended blocks. Without expand_layers "- "nothing reads it, so the run trains as if it were unset. "- "Remove it, or set expand_layers: <int> to append new blocks."+ "expand_layers (LLaMA Pro block expansion), where it must equal "+ "expand_layers and trains only the appended blocks. Without "+ "expand_layers nothing reads it, so the run trains as if it were "+ "unset. Remove it, or set expand_layers: <int> to append new blocks."+ )+ if (+ self.expand_layers is not None+ and self.freeze_trainable_layers is not None+ and self.freeze_trainable_layers != self.expand_layers+ ):+ # #1409: the value was only ever read for its sign, so 1, 2 and 4+ # trained the same appended blocks and 0 or a negative value+ # silently trained the whole expanded model.+ raise ValueError(+ f"freeze_trainable_layers: {self.freeze_trainable_layers} does not "+ f"match expand_layers: {self.expand_layers}. With expand_layers "+ "set, freeze_trainable_layers freezes every parameter of the "+ "original model and trains only the appended blocks. It does not "+ "select the top-N or bottom-N layers, and 0 or a negative value "+ "does not switch the freeze off. "+ f"Set freeze_trainable_layers: {self.expand_layers}.")# The expand_layers + quantization rule is enforced by# SoupConfig._validate_expand_layers_quantization, which runs afterdiff --git a/src/soup_cli/utils/block_expansion.py b/src/soup_cli/utils/block_expansion.pyindex 41d82715..8f30c5d8 100644--- a/src/soup_cli/utils/block_expansion.py+++ b/src/soup_cli/utils/block_expansion.py@@ -14,14 +14,14 @@ v0.53.4 #83 lifts the stub with a real implementation:3. Append the clones to ``model.model.layers`` (HF causal-LM convention).4. Update ``model.config.num_hidden_layers`` so cached counts stay coherent.-The new-block-only freeze policy is owned by the caller via-``freeze_trainable_layers`` (positive = train top-N, negative = train-bottom-N); ``apply_llama_pro_freeze`` is provided for the canonical-"train only the appended blocks" case.+The freeze is driven by ``freeze_trainable_layers``, which the schema requires+to equal ``expand_layers`` (#1409): it freezes every parameter of the original+model so only the appended blocks train (``apply_llama_pro_freeze``). It does+not select top-N or bottom-N layers.References:-- LlamaFactory ``freeze_trainable_layers`` (positive = train top-N, negative- = train bottom-N) + ``expand_layers`` (block count).+- LlamaFactory's LLaMA Pro example, which sets ``freeze_trainable_layers``+ to the same value as ``num_expand``."""from __future__ import annotations@@ -76,7 +76,7 @@ def validate_expand_layers(value: object) -> int:def validate_freeze_trainable_layers(value: object) -> int:- """Signed int — positive = train top-N, negative = train bottom-N."""+ """Type and magnitude check; the schema then requires it to equal ``expand_layers`` (#1409)."""if value is None:return 0if isinstance(value, bool) or not isinstance(value, int):@@ -296,9 +296,9 @@ def apply_block_expansion_if_configured(f"(+{added} zero-init blocks)")freeze = getattr(tcfg, "freeze_trainable_layers", None)- # Project policy ``is None`` over falsy — but a value of 0 means "no- # positive freeze direction", so the canonical "train only new blocks"- # path runs iff the user opted in with a positive ``freeze_trainable_layers``.+ # The schema refuses any value other than ``expand_layers`` (#1409), so a+ # loaded config only gets here with a positive value; the check stays as a+ # guard for callers that build ``tcfg`` without the schema.if freeze is not None and freeze > 0 and added > 0:trainable = apply_llama_pro_freeze(model, added)if console is not None:diff --git a/tests/test_issue1409_freeze_equals_expand.py b/tests/test_issue1409_freeze_equals_expand.pynew file mode 100644index 00000000..2bb8f56c--- /dev/null+++ b/tests/test_issue1409_freeze_equals_expand.py@@ -0,0 +1,93 @@+"""Issue #1409: with ``expand_layers`` set, ``freeze_trainable_layers`` must equal it.++The value was read only for its sign: 1, 2 and 4 all trained just the appended+blocks, and 0 or a negative value silently trained the whole expanded model.+The ruling on #1409 gives the field one meaning (freeze the original model,+train only the appended blocks) and refuses every value other than+``expand_layers`` at config load.+"""++from __future__ import annotations++import pytest++from soup_cli.config.loader import load_config_from_string+++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")+ return load_config_from_string(+ "base: org/model\n"+ f"task: {task}\n"+ "data:\n train: ./data.jsonl\n"+ "training:\n" + "".join(lines)+ )++[email protected]("task", ["sft", "pretrain"])+def test_freeze_equal_to_expand_loads(task):+ cfg = _load(task, expand=4, freeze=4)+ assert cfg.training.expand_layers == 4+ assert cfg.training.freeze_trainable_layers == 4++[email protected]("task", ["sft", "pretrain"])+ "freeze", [0, -1, -4, 2, 8], ids=["zero", "minus_one", "minus_n", "smaller", "larger"]+)+def test_any_other_value_is_refused(task, freeze):+ with pytest.raises(ValueError) as excinfo:+ _load(task, expand=4, freeze=freeze)+ message = str(excinfo.value)+ assert f"freeze_trainable_layers: {freeze}" in message+ assert "expand_layers: 4" in message+ assert "trains only the appended blocks" in message+ assert "top-N or bottom-N" in message+ assert "Set freeze_trainable_layers: 4." in message++[email protected]("task", ["sft", "pretrain"])+def test_expand_without_freeze_names_the_expand_value(task):+ with pytest.raises(ValueError, match=r"Set freeze_trainable_layers: 3\."):+ _load(task, expand=3, freeze=None)+++def test_freeze_without_expand_keeps_the_1399_message():+ with pytest.raises(+ ValueError,+ match="only applies together with expand_layers.*must equal expand_layers.*Remove it",+ ):+ load_config_from_string(+ "base: org/model\n"+ "task: sft\n"+ "data:\n train: ./data.jsonl\n"+ "training:\n quantization: none\n freeze_trainable_layers: 2\n"+ )+++def test_setup_trains_exactly_the_appended_blocks(tmp_path, monkeypatch):+ """Through the real ``SFTTrainerWrapper.setup()`` on a tiny Llama (#341 fixture)."""+ from tests.test_issue341_seed_and_fullft import _requires_train_extra, _wrapper++ _requires_train_extra()+ wrapper, dataset = _wrapper(+ tmp_path,+ monkeypatch,+ expand_layers=2,+ freeze_trainable_layers=2,+ lora={"r": 0},+ )+ wrapper.setup(dataset)++ model = wrapper.trainer.model+ trainable = {name for name, param in model.named_parameters() if param.requires_grad}+ appended = {+ name+ for name, _ in model.named_parameters()+ if name.startswith(("model.layers.2.", "model.layers.3."))+ }+ assert len(model.model.layers) == 4+ assert appended+ assert trainable == appendeddiff --git a/tests/test_v0410_part_c.py b/tests/test_v0410_part_c.pyindex 4b56cb88..25d6f46b 100644--- a/tests/test_v0410_part_c.py+++ b/tests/test_v0410_part_c.py@@ -183,7 +183,14 @@ class TestSchemaBlockExpansion:def test_expand_layers_refused_on_quantized_base(self, quantization, freeze):# The refusal lives on SoupConfig now (it reads the resolved# quantization), so build a full config rather than a bare TrainingConfig.- with pytest.raises(ValidationError, match="requires training.quantization: none"):+ # #1409's equality check runs first (TrainingConfig before SoupConfig),+ # so -4 and 0 are refused for not matching expand_layers instead.+ match = (+ "requires training.quantization: none"+ if freeze == 4+ else r"freeze_trainable_layers: -?\d+ does not match expand_layers: 4"+ )+ with pytest.raises(ValidationError, match=match):_sft(expand_layers=4,freeze_trainable_layers=freeze,