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): refuse expand_layers on a quantized base (#1237) (#1308)
Vladimir Babin81a7f2ac2e2a
diff --git a/changelog.d/0.75.1/1308.fixed.md b/changelog.d/0.75.1/1308.fixed.mdnew file mode 100644index 00000000..9f1e1817--- /dev/null+++ b/changelog.d/0.75.1/1308.fixed.md@@ -0,0 +1 @@+- **`training.expand_layers` is refused at config load unless `training.quantization` is `none` (#1237 by @chiliec in #1308).** Under the default `4bit`, the "zeroed" residual projections of the appended LLaMA Pro blocks decoded to `-absmax` instead of 0 (NF4 code 0 is `-1.0`), so the new blocks were not identity, and a positive `freeze_trainable_layers` crashed at setup on `4bit` and `8bit` because torch cannot set `requires_grad` on integer weights. The error now names both fields and asks for `quantization: none`.diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.mdindex fd4e76fa..07b73f08 100644--- a/docs/peft-and-efficiency.md+++ b/docs/peft-and-efficiency.md@@ -175,6 +175,7 @@ task: sftdata:train: ./domain.jsonltraining:+ quantization: none # block expansion needs an unquantized baseexpand_layers: 4 # append 4 zero-init decoder blocksfreeze_trainable_layers: 4 # train only the appended blocks (requires expand_layers)lr: 5e-5@@ -183,7 +184,7 @@ training:**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.-**Scope.** Works on `task: sft` and `task: pretrain` with `backend: transformers` and `modality: text`; any other task, backend or modality is refused at config load, because no other trainer applies the expansion. 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` 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.## Optimizer & PEFT Zoodiff --git a/docs/training.md b/docs/training.mdindex d056ee1b..101993fa 100644--- a/docs/training.md+++ b/docs/training.md@@ -1942,7 +1942,7 @@ 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).+ # ones (freeze_trainable_layers 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 be147304..30290965 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -4145,6 +4145,11 @@ class TrainingConfig(BaseModel):"nothing reads it, so the run trains as if it were unset. ""Remove it, or set expand_layers: <int> to append new blocks.")+ # The expand_layers + quantization rule is enforced by+ # SoupConfig._validate_expand_layers_quantization, which runs after+ # _resolve_quantization_for_unhonouring_tasks so it reads the resolved+ # value (an unset quantization on a #795 task has resolved to none by+ # then and must not be refused here on its unresolved 4bit default).return self@model_validator(mode="after")@@ -4892,6 +4897,27 @@ class SoupConfig(BaseModel):)return self+ @model_validator(mode="after")+ def _validate_expand_layers_quantization(self) -> "SoupConfig":+ """v0.41.0 Part C — expand_layers requires an unquantized base.++ Runs after ``_resolve_quantization_for_unhonouring_tasks`` so it reads the+ RESOLVED quantization. For the #795 unhonoured tasks an unset+ ``quantization`` has resolved to ``none`` by now, so a minimal config for+ those tasks (which defaults the field to ``4bit``) is not wrongly refused;+ the check fires only when the base actually trains quantised.+ """+ tcfg = self.training+ if tcfg.expand_layers is not None and tcfg.quantization != "none":+ raise ValueError(+ "training.expand_layers (LLaMA Pro block expansion) requires "+ f"training.quantization: none, but it is {tcfg.quantization!r}. "+ "The appended blocks are zero-initialised and trained, which the "+ "block-expansion path only supports on an unquantized base. "+ "Set quantization: none."+ )+ return self+@model_validator(mode="after")def _validate_quest_first_slice(self) -> "SoupConfig":"""Keep #674 on the one route supported by the measured prototype."""diff --git a/tests/test_v0410_part_c.py b/tests/test_v0410_part_c.pyindex f9acc174..4b56cb88 100644--- a/tests/test_v0410_part_c.py+++ b/tests/test_v0410_part_c.py@@ -2,6 +2,8 @@from __future__ import annotations+import typing+import pytestfrom pydantic import ValidationError@@ -23,6 +25,19 @@ def _base_data():return {"train": "/tmp/x.jsonl"}+# Every quantization value except "none", read from the schema, so a new Quant+# Menu format is refused -- and tested -- without editing a list here.+_QUANTIZED = tuple(+ value+ for value in typing.get_args(TrainingConfig.model_fields["quantization"].annotation)+ if value != "none"+)+++def _sft(**training):+ return SoupConfig(base="fake-org/fake-model", task="sft", data=_base_data(), training=training)++# ---------- LoftQ ----------class TestLoftqValidators:@@ -131,7 +146,9 @@ class TestSchemaBlockExpansion:TrainingConfig(expand_layers=4)def test_expand_layers_with_freeze_accepted(self):- cfg = TrainingConfig(expand_layers=4, freeze_trainable_layers=4)+ cfg = TrainingConfig(+ expand_layers=4, freeze_trainable_layers=4, quantization="none"+ )assert cfg.expand_layers == 4assert cfg.freeze_trainable_layers == 4@@ -161,6 +178,74 @@ class TestSchemaBlockExpansion:"training:\n freeze_trainable_layers: 2\n")+ @pytest.mark.parametrize("quantization", _QUANTIZED)+ @pytest.mark.parametrize("freeze", [4, -4, 0])+ 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"):+ _sft(+ expand_layers=4,+ freeze_trainable_layers=freeze,+ quantization=quantization,+ )++ def test_expand_layers_refused_on_default_quantization(self):+ with pytest.raises(ValidationError, match="requires training.quantization: none"):+ _sft(expand_layers=2, freeze_trainable_layers=2)++ 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)+ assert cfg.training.quantization == "none"+ assert cfg.training.expand_layers == 2++ def test_load_in_8bit_alias_is_refused(self):+ with pytest.raises(ValidationError, match="requires training.quantization: none"):+ _sft(expand_layers=2, freeze_trainable_layers=2, load_in_8bit=True)++ @pytest.mark.parametrize("task", ["sft", "pretrain"])+ def test_default_quantization_refused_through_the_loader(self, task):+ # #1237's acceptance box: task sft AND pretrain, through the loader `soup train` uses.+ from soup_cli.config.loader import load_config_from_string++ with pytest.raises(ValueError, match="requires training.quantization: none"):+ load_config_from_string(+ "base: org/model\n"+ f"task: {task}\n"+ "data:\n train: ./data.jsonl\n"+ "training:\n expand_layers: 2\n freeze_trainable_layers: 2\n"+ )++ @pytest.mark.parametrize(+ "task,backend", [("dpo", "transformers"), ("sft", "mlx"), ("sft", "unsloth")]+ )+ def test_scope_refusal_precedes_the_quantization_refusal(self, task, backend):+ with pytest.raises(ValidationError, match="only wired for task sft/pretrain"):+ SoupConfig(+ base="fake-org/fake-model",+ task=task,+ backend=backend,+ data=_base_data(),+ training={"expand_layers": 2, "freeze_trainable_layers": 2},+ )++ def test_expand_layers_explicit_quant_still_refused_on_unhonoured_task(self):+ # A quant-menu value the resolver never rewrites (gptq) is still refused on an+ # unhonoured task, and with THAT task's reason: this check must not mask it.+ # (Fails if the check is defined above the resolver.)+ with pytest.raises(ValidationError, match="task='prm' does not apply"):+ SoupConfig(+ base="fake-org/fake-model",+ task="prm",+ data=_base_data(),+ training={+ "expand_layers": 2,+ "freeze_trainable_layers": 2,+ "quantization": "gptq",+ },+ )+def test_freeze_magnitude_oob(self):with pytest.raises(ValidationError, match="magnitude"):TrainingConfig(freeze_trainable_layers=1500)diff --git a/tests/test_v0534.py b/tests/test_v0534.pyindex 7792ccb4..60d3467c 100644--- a/tests/test_v0534.py+++ b/tests/test_v0534.py@@ -713,6 +713,7 @@ training:base: meta-llama/Llama-3.1-8Btask: sfttraining:+ quantization: noneexpand_layers: 4freeze_trainable_layers: 4"""