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(train): thread the freeze plan into the LoRA layer selection (#1432) (#2145)
Vansh Sharma9d2277627ba4
diff --git a/changelog.d/0.76.0/2145.fixed.md b/changelog.d/0.76.0/2145.fixed.mdnew file mode 100644index 00000000..300288fe--- /dev/null+++ b/changelog.d/0.76.0/2145.fixed.md@@ -0,0 +1,3 @@+- **`training.freeze_layers` / `training.freeze_ratio` did nothing on a LoRA run: the freeze was set before `get_peft_model`, which then attached a fresh trainable adapter to every targeted module in every layer, the frozen ones included (#1432 by @AmirF194 and @VanshSharmaPES in #2145).**+ The SFT trainer now passes the layers the freeze plan left trainable to peft as `layers_to_transform`, so a frozen layer gets no adapter. On a 2-layer Llama with LoRA on `q_proj` / `v_proj`, `freeze_layers: 1` (or `freeze_ratio: 0.5`) takes the trainable LoRA parameters from 1,024 to 512 and layer 0 no longer changes. A config that sets `freeze_layers` / `freeze_ratio` together with LoRA now trains fewer layers than it did before, which is what the option always documented.+ Shapes peft cannot restrict by layer are refused when the model is built rather than ignoring the freeze: a string `lora.target_modules` (a regex, or `all-linear`, including the value `auto` resolves to for some architectures), a list target that resolves only outside a numbered decoder layer (such as `embed_tokens`), `lora.target_parameters`, `lora.use_vera`, and a plan that freezes every layer. A top-level `lm_head` target is accepted and keeps its adapter. Full fine-tuning (`lora.r: 0`) is unchanged.diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.mdindex 87434f8f..05447220 100644--- a/docs/peft-and-efficiency.md+++ b/docs/peft-and-efficiency.md@@ -616,7 +616,22 @@ training:freeze_ratio: 0.75 # Freeze 75% of layers from the bottom```-Works with and without LoRA. When used with LoRA, LoRA is applied only to unfrozen layers.+Works with and without LoRA. When used with LoRA, the adapter is attached only to the unfrozen+layers, so a frozen layer stays frozen rather than training through a fresh adapter.++`freeze_layers`/`freeze_ratio` cannot currently be combined with LoRA when+`training.lora.target_modules` is a regex string (an explicit one, or an `auto`-resolved+architecture table entry such as Mistral 3.5's), when `training.lora.target_parameters` is+set (per-parameter LoRA, e.g. fused MoE experts), or with `training.lora.use_vera`. A+`target_modules` list entry that only matches modules outside a numbered decoder layer (such as+`embed_tokens`) and a freeze plan that freezes every layer refuse too. Each of these refuses when+the model is built rather than silently drop the freeze plan (#1432). A top-level `lm_head` target+is accepted and keeps its adapter.++Known limitation: a `target_modules` entry spelled as a full module path, such as+`model.layers.0.self_attn.q_proj`, keeps its adapter even when that layer is frozen, because peft+accepts an exact module name before it reads `layers_to_transform`. Use module-name suffixes such+as `q_proj` with `freeze_layers` / `freeze_ratio`.## LISA — Layerwise Importance Sampling (v0.71.34)diff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.pyindex 99335cae..6565f0a8 100644--- a/src/soup_cli/trainer/sft.py+++ b/src/soup_cli/trainer/sft.py@@ -1755,8 +1755,10 @@ class SFTTrainerWrapper(StreamingSetupMixin):)# Freeze training — freeze bottom layers before LoRA+ # #1432: cutoff re-read below to scope the LoRA adapter to it too.+ lora_layers_to_transform = Noneif tcfg.freeze_layers is not None or tcfg.freeze_ratio is not None:- from soup_cli.utils.freeze import freeze_model_layers+ from soup_cli.utils.freeze import freeze_layer_cutoff, freeze_model_layersfrozen = freeze_model_layers(self.model,@@ -1766,6 +1768,20 @@ class SFTTrainerWrapper(StreamingSetupMixin):console.print(f"[green]Freeze training:[/] {frozen} parameters frozen")+ plan = freeze_layer_cutoff(+ self.model,+ freeze_layers=tcfg.freeze_layers,+ freeze_ratio=tcfg.freeze_ratio,+ )+ if plan is not None:+ cutoff, total_layers = plan+ # #1432: a zero cutoff freezes nothing, but peft still reads+ # any layers_to_transform list as "restrict to these numbered+ # layers only", which silently drops a target outside a+ # numbered layer (embed_tokens) even though nothing was+ # frozen. Leave it unset rather than pass a no-op range.+ if cutoff:+ lora_layers_to_transform = list(range(cutoff, total_layers))# v0.53.4 #83 — LLaMA Pro block expansion. Run BEFORE LoRA so PEFT's# target-module matcher sees the new blocks. Centralised in@@ -1875,11 +1891,83 @@ class SFTTrainerWrapper(StreamingSetupMixin):self.model, tcfg, target_modules, console)+ # #1432: an empty range means every layer is frozen, refuse+ # rather than silently build an adapter matching nothing.+ if lora_layers_to_transform is not None and not lora_layers_to_transform:+ raise ValueError(+ "training.freeze_layers / training.freeze_ratio freezes "+ "every decoder layer, leaving no layer for the LoRA "+ "adapter to attach to. Reduce freeze_layers/freeze_ratio."+ )++ # #1432: peft only applies layers_to_transform when+ # target_modules is a list, never a string (a regex or+ # all-linear), so refuse rather than silently ship the same bug+ # for that shape.+ if lora_layers_to_transform is not None and isinstance(target_modules, str):+ raise ValueError(+ "training.freeze_layers / training.freeze_ratio cannot "+ "currently be combined with a string "+ f"training.lora.target_modules ({target_modules!r}, a regex "+ "or all-linear): peft only restricts layers_to_transform "+ "when target_modules is a list of module-name suffixes. "+ "Give an explicit training.lora.target_modules list (the "+ "module names are in model.named_modules()) instead, or "+ "drop freeze_layers/freeze_ratio."+ )++ # #1432: peft only applies layers_to_transform to a list target+ # that lives inside a numbered decoder layer, or to an exact+ # module name (a top-level lm_head keeps its adapter). embed_tokens,+ # or any other target outside the stack, silently gets no adapter+ # otherwise. Refuse by name rather than drop it.+ if lora_layers_to_transform is not None and isinstance(target_modules, list):+ from soup_cli.utils.peft_wiring import find_layer_unscoped_targets++ unscoped = find_layer_unscoped_targets(self.model, target_modules)+ if unscoped:+ raise ValueError(+ "training.freeze_layers / training.freeze_ratio cannot "+ "currently be combined with training.lora.target_modules "+ f"naming {unscoped!r}: peft's layers_to_transform only "+ "restricts targets that live inside a numbered decoder "+ f"layer, so {unscoped!r} would silently get no LoRA "+ "adapter. Drop freeze_layers/freeze_ratio, or remove "+ f"{unscoped!r} from training.lora.target_modules."+ )++ # #1432: target_parameters matching is a separate, layer-unaware+ # peft path with no layers_to_transform check, same refusal.+ if lora_layers_to_transform is not None and target_parameters:+ raise ValueError(+ "training.freeze_layers / training.freeze_ratio cannot "+ "currently be combined with training.lora.target_parameters "+ "(per-parameter LoRA, e.g. fused MoE experts): peft's "+ "target_parameters matching does not apply "+ "layers_to_transform. Drop freeze_layers/freeze_ratio, or "+ "drop target_parameters and use training.lora.target_modules "+ "instead."+ )++ # #1432: VeRA is a separate peft tuner (build_peft_config_spec's+ # own branch, not the LoraConfig path layers_to_transform is+ # wired into below), so refuse rather than silently reproduce+ # the same bug for it.+ if lora_layers_to_transform is not None and getattr(tcfg.lora, "use_vera", False):+ raise ValueError(+ "training.freeze_layers / training.freeze_ratio cannot "+ "currently be combined with training.lora.use_vera: the "+ "freeze plan is not wired into the VeRA config path. Drop "+ "freeze_layers/freeze_ratio, or drop use_vera and use "+ "ordinary LoRA instead."+ )+lora_config = build_lora_config(tcfg.lora,target_modules=target_modules,target_parameters=target_parameters,task_type=TaskType.CAUSAL_LM,+ layers_to_transform=lora_layers_to_transform,)# v0.39.0 Part D / v0.40.6 #67 — surgical PEFT patches via shared helpers.from soup_cli.utils.peft_wiring import (diff --git a/src/soup_cli/utils/freeze.py b/src/soup_cli/utils/freeze.pyindex f6bfbe28..0908e07d 100644--- a/src/soup_cli/utils/freeze.py+++ b/src/soup_cli/utils/freeze.py@@ -26,6 +26,33 @@ def _detect_num_layers(model: Any) -> int:return max_layer + 1 if max_layer >= 0 else 0+def freeze_layer_cutoff(+ model: Any,+ freeze_layers: Optional[int] = None,+ freeze_ratio: Optional[float] = None,+) -> Optional[tuple[int, int]]:+ """Resolve a freeze plan to ``(cutoff, total_layers)``, or ``None``.++ Shared by :func:`freeze_model_layers` (which acts on it) and callers that+ need the same boundary applied elsewhere in the model-build pipeline+ (#1432: threading it into the LoRA adapter's ``layers_to_transform`` so+ ``get_peft_model`` does not re-attach a trainable adapter to a layer this+ just froze). Layers ``< cutoff`` are the frozen ones. ``None`` means+ "no plan" or "no numbered layers detected", the caller's own no-op case,+ not a plan with an empty range.+ """+ if freeze_layers is None and freeze_ratio is None:+ return None+ total_layers = _detect_num_layers(model)+ if total_layers == 0:+ return None+ if freeze_layers is not None:+ cutoff = min(freeze_layers, total_layers)+ else:+ cutoff = int(total_layers * freeze_ratio)+ return cutoff, total_layers++def freeze_model_layers(model: Any,freeze_layers: Optional[int] = None,@@ -41,23 +68,16 @@ def freeze_model_layers(Returns:Number of parameters frozen."""- if freeze_layers is None and freeze_ratio is None:- return 0-- total_layers = _detect_num_layers(model)- if total_layers == 0:- logger.warning(- "freeze_model_layers: could not detect numbered layers in model "- "parameter names. Freezing has no effect. Check that your model "- "uses 'layers.N.' or 'h.N.' naming."- )+ plan = freeze_layer_cutoff(model, freeze_layers=freeze_layers, freeze_ratio=freeze_ratio)+ if plan is None:+ if freeze_layers is not None or freeze_ratio is not None:+ logger.warning(+ "freeze_model_layers: could not detect numbered layers in model "+ "parameter names. Freezing has no effect. Check that your model "+ "uses 'layers.N.' or 'h.N.' naming."+ )return 0-- # Determine cutoff- if freeze_layers is not None:- cutoff = min(freeze_layers, total_layers)- else:- cutoff = int(total_layers * freeze_ratio)+ cutoff, _total_layers = plan# Freeze parameters in layers below cutofffrozen_count = 0diff --git a/src/soup_cli/utils/peft_wiring.py b/src/soup_cli/utils/peft_wiring.pyindex 673528a7..722bca0d 100644--- a/src/soup_cli/utils/peft_wiring.py+++ b/src/soup_cli/utils/peft_wiring.py@@ -444,6 +444,45 @@ def _as_targets(entry: Any) -> Any:return entry if isinstance(entry, str) else list(entry)+_LAYER_INDEX = re.compile(r"(?:^|\.)(?:layers|h)\.\d+(?:\.|$)")+++def find_layer_unscoped_targets(model: Any, target_modules: Any) -> list[str]:+ """Names in a list ``target_modules`` that ``layers_to_transform`` drops.++ peft applies ``layers_to_transform`` only to a LIST ``target_modules``,+ and even then only to matches that sit inside a numbered decoder layer+ (``...layers.N....`` / ``...h.N....``): a name that matches nothing else+ just gets no adapter, with no error (#1432). ``embed_tokens`` is the+ common case. The exception is an EXACT module name such as a top-level+ ``lm_head``: peft returns on an exact match before it reads+ ``layers_to_transform``, so that target keeps its adapter and is not+ flagged here.++ Returns every target whose matches in ``model.named_modules()`` are all+ outside a numbered layer. A target that resolves to nothing in this+ model is left alone (nothing here to silently drop); a target with at+ least one in-layer match is left alone too. ``target_modules`` that is+ not a list (a PEFT regex string, or ``None``) has nothing to check and+ returns an empty list (the regex case is refused separately, because+ peft does not layer-scope a regex at all).+ """+ if not isinstance(target_modules, list):+ return []+ module_names = [name for name, _ in model.named_modules() if name]+ unscoped = []+ for target in target_modules:+ if target in module_names:+ continue # an exact module name: peft keeps it before reading layers_to_transform+ matches = [+ name for name in module_names+ if name == target or name.endswith(f".{target}")+ ]+ if matches and not any(_LAYER_INDEX.search(name) for name in matches):+ unscoped.append(target)+ return unscoped++def resolve_lora_target_parameters(model: Any, configured: Any) -> Any:"""Resolve opt-in raw-parameter LoRA targets for supported architectures.@@ -470,6 +509,7 @@ def build_lora_config_kwargs(target_modules: Any,target_parameters: Any,task_type: Any,+ layers_to_transform: Any = None,) -> dict[str, Any]:"""Build the shared PEFT LoRA kwargs used by every trainer path."""kwargs = {@@ -483,6 +523,10 @@ def build_lora_config_kwargs("use_dora": lora_cfg.use_dora,"use_rslora": lora_cfg.use_rslora,}+ if layers_to_transform is not None:+ # #1432: scopes the adapter to the layers freeze_model_layers left+ # trainable. No layers_pattern needed, peft's default covers 'layers'/'h'.+ kwargs["layers_to_transform"] = layers_to_transformrank_pattern = lora_cfg.rank_patternalpha_pattern = lora_cfg.alpha_patternif rank_pattern:@@ -515,12 +559,16 @@ def build_peft_config_spec(target_modules: Any,task_type: Any,target_parameters: Any = None,+ layers_to_transform: Any = None,) -> dict[str, Any]:"""Return the PEFT class name and kwargs for the configured adapter.VeRA is a distinct PEFT tuner, not a LoRA option. Keeping this branch nextto the shared LoRA kwargs is what makes every trainer consume the samemethod choice instead of silently constructing ordinary LoRA.+ ``VeraConfig`` does accept its own ``layers_to_transform``, but the caller+ (``sft.py``) refuses ``use_vera`` combined with a freeze plan rather than+ wiring it here, so ``layers_to_transform`` is LoRA-only in practice (#1432)."""if getattr(lora_cfg, "use_vera", False):return {@@ -540,6 +588,7 @@ def build_peft_config_spec(target_modules=target_modules,target_parameters=target_parameters,task_type=task_type,+ layers_to_transform=layers_to_transform,),}@@ -591,12 +640,17 @@ def build_lora_config(target_modules: Any,task_type: Any,target_parameters: Any = None,+ layers_to_transform: Any = None,) -> Any:"""Build the configured PEFT adapter through the single shared path.Keeping the PEFT import inside this function preserves Soup's lazy-importboundary while ensuring every trainer consumes new shared LoRA fields suchas ``rank_pattern`` and ``alpha_pattern`` automatically.++ ``layers_to_transform`` (#1432) restricts which decoder layers actually+ get a LoRA adapter. Callers pass the layer indices freeze_model_layers+ left trainable, so the adapter cannot silently re-train a frozen layer."""import peft@@ -614,6 +668,7 @@ def build_lora_config(target_modules=target_modules,target_parameters=target_parameters,task_type=task_type,+ layers_to_transform=layers_to_transform,)if exclude_modules:spec["init_kwargs"]["exclude_modules"] = exclude_modulesdiff --git a/tests/test_freeze_lora_layers.py b/tests/test_freeze_lora_layers.pynew file mode 100644index 00000000..a1d646a2--- /dev/null+++ b/tests/test_freeze_lora_layers.py@@ -0,0 +1,472 @@+"""#1432: freeze_layers / freeze_ratio did nothing under LoRA.++``_setup_transformers`` called ``freeze_model_layers()`` (sets+``requires_grad=False`` on the bottom layers) BEFORE ``get_peft_model()``+wraps the model, and the ``LoraConfig`` it built carried no+``layers_to_transform``, so ``get_peft_model`` re-attached a fresh, trainable+LoRA adapter to every targeted module in EVERY layer, including the ones just+frozen. The freeze plan was silently discarded: a "frozen" layer still+trained, through its adapter, exactly as if freeze_layers/freeze_ratio had+never been set.++The fix threads the same ``(cutoff, total_layers)`` pair+``freeze_model_layers`` already computes (now exposed as+``freeze.freeze_layer_cutoff``) into ``build_lora_config`` as+``layers_to_transform``, so ``get_peft_model`` only attaches an adapter to+the layers the freeze plan actually left trainable.++The controls are the point:++* the MECHANISM control (``TestLayersToTransformIsWhatFixesIt``) directly+ reproduces the reported bug by calling ``build_lora_config`` the OLD way+ (no ``layers_to_transform``) against the same frozen model, and shows the+ frozen layer's adapter comes back trainable. That proves the harness would+ have caught #1432 before the fix, not just that the new code happens to+ pass.+* the real-trainer half (``TestFreezeLayersRestrictsLoraAdapter``) drives+ the actual ``SFTTrainerWrapper._setup_transformers`` path end to end.++Import-light: the schema/helper half runs without the ``[train]`` extra; the+behavioural half skips (loudly) when torch / transformers / peft are absent,+matching ``tests/test_issue341_seed_and_fullft.py``'s own convention.+"""++from __future__ import annotations++import json+import os++import pytest+import yaml++from soup_cli.config.loader import load_config_from_string+++def _requires_train_extra():+ for mod in ("torch", "transformers", "peft"):+ pytest.importorskip(mod, reason=f"{mod} is only in the [train] extra")+++def _tiny_llama_dir(tmp_path, n_layers=2):+ """A real (tiny) 2-layer Llama checkpoint + offline tokenizer on disk.++ Mirrors test_issue341_seed_and_fullft.py's helper: a real from-scratch+ model, not a mock, so get_peft_model's actual module-name matching (the+ thing #1432 is about) runs for real.+ """+ import torch+ from safetensors.torch import save_file+ from transformers import LlamaConfig, LlamaForCausalLM++ torch.manual_seed(7)+ config = LlamaConfig(+ vocab_size=64,+ hidden_size=32,+ intermediate_size=64,+ num_hidden_layers=n_layers,+ num_attention_heads=4,+ num_key_value_heads=2,+ tie_word_embeddings=True,+ max_position_embeddings=128,+ architectures=["LlamaForCausalLM"],+ )+ model = LlamaForCausalLM(config).to(torch.float32).eval()+ weights = tmp_path / "model"+ weights.mkdir(parents=True, exist_ok=True)+ state = {k: v.contiguous() for k, v in model.state_dict().items()}+ state.pop("lm_head.weight", None) # tied+ save_file(state, str(weights / "model.safetensors"))+ config.save_pretrained(str(weights))+ _write_tiny_tokenizer(str(weights))+ return str(weights)+++def _write_tiny_tokenizer(directory):+ from tokenizers import Tokenizer, models, pre_tokenizers++ vocab = {"<unk>": 0, "<s>": 1, "</s>": 2, "<pad>": 3}+ for word in ("hello", "world", "hi", "yo", "the", "cat", "sat", "on", "mat"):+ vocab[word] = len(vocab)+ tokenizer = Tokenizer(models.WordLevel(vocab=vocab, unk_token="<unk>"))+ tokenizer.pre_tokenizer = pre_tokenizers.Whitespace()+ tokenizer.save(os.path.join(directory, "tokenizer.json"))+ with open(os.path.join(directory, "tokenizer_config.json"), "w", encoding="utf-8") as fh:+ json.dump(+ {+ "tokenizer_class": "PreTrainedTokenizerFast",+ "unk_token": "<unk>",+ "bos_token": "<s>",+ "eos_token": "</s>",+ "pad_token": "<pad>",+ "model_max_length": 128,+ "clean_up_tokenization_spaces": False,+ },+ fh,+ )+++def _dataset():+ rows = [("hi", "hello world"), ("yo", "the cat sat"), ("hello", "on the mat")]+ return {+ "train": [+ {+ "messages": [+ {"role": "user", "content": user},+ {"role": "assistant", "content": assistant},+ ]+ }+ for user, assistant in rows+ ]+ }+++def _wrapper(tmp_path, monkeypatch, n_layers=2, **training_over):+ """A real SFTTrainerWrapper over a real tiny checkpoint, LoRA on."""+ from soup_cli.trainer.sft import SFTTrainerWrapper++ base = _tiny_llama_dir(tmp_path, n_layers=n_layers)+ monkeypatch.chdir(tmp_path)+ training = {+ "batch_size": 1,+ "gradient_accumulation_steps": 1,+ "quantization": "none",+ "epochs": 1,+ "lr": 1e-3,+ "logging_steps": 100,+ "save_steps": 10_000,+ "lora": {"r": 4, "alpha": 8, "dropout": 0.0, "target_modules": ["q_proj", "v_proj"]},+ }+ lora_over = training_over.pop("lora", None)+ training.update(training_over)+ if lora_over is not None:+ training["lora"] = {**training["lora"], **lora_over}+ cfg = load_config_from_string(+ yaml.safe_dump(+ {+ "base": base,+ "task": "sft",+ "backend": "transformers",+ "modality": "text",+ "data": {"train": "train.jsonl", "max_length": 64, "chat_template": "chatml"},+ "training": training,+ "output": str(tmp_path / "out"),+ }+ )+ )+ return SFTTrainerWrapper(cfg, device="cpu"), _dataset()+++def _lora_param_names(model):+ return [name for name, _ in model.named_parameters() if "lora_" in name]+++class TestFreezeLayersRestrictsLoraAdapter:+ """The real _setup_transformers path, real tiny Llama, real get_peft_model."""++ def test_freeze_layers_excludes_frozen_layer_from_adapter(self, tmp_path, monkeypatch):+ """AmirF194's exact repro shape: freeze_layers=1 on a 2-layer model+ must leave layer 0 with no LoRA adapter at all, and layer 1 with a+ trainable one."""+ _requires_train_extra()+ wrapper, dataset = _wrapper(tmp_path, monkeypatch, freeze_layers=1)+ wrapper.setup(dataset)++ lora_names = _lora_param_names(wrapper.model)+ assert lora_names, "expected a LoRA adapter on the unfrozen layer"+ assert not any(".layers.0." in name for name in lora_names), (+ f"layer 0 is frozen but has a LoRA adapter: {lora_names}"+ )+ assert any(".layers.1." in name for name in lora_names)++ by_name = dict(wrapper.model.named_parameters())+ layer1_lora_a = next(n for n in by_name if ".layers.1." in n and "lora_A" in n)+ assert by_name[layer1_lora_a].requires_grad is True++ # The base weight itself is still frozen (freeze_model_layers' own+ # job, unaffected by this fix). Confirms the fix restricts the+ # ADAPTER without undoing the base freeze.+ base_q_proj = next(+ n+ for n in by_name+ if n.endswith("layers.0.self_attn.q_proj.base_layer.weight")+ or n.endswith("layers.0.self_attn.q_proj.weight")+ )+ assert by_name[base_q_proj].requires_grad is False++ def test_freeze_ratio_excludes_frozen_layers_from_adapter(self, tmp_path, monkeypatch):+ """freeze_ratio=0.5 on a 4-layer model freezes layers 0-1; only+ layers 2-3 may get a LoRA adapter."""+ _requires_train_extra()+ wrapper, dataset = _wrapper(tmp_path, monkeypatch, n_layers=4, freeze_ratio=0.5)+ wrapper.setup(dataset)++ lora_names = _lora_param_names(wrapper.model)+ frozen_layers_with_adapter = {+ idx for idx in (0, 1) if any(f".layers.{idx}." in n for n in lora_names)+ }+ assert not frozen_layers_with_adapter, (+ f"frozen layers still got a LoRA adapter: {frozen_layers_with_adapter}"+ )+ assert any(".layers.2." in n for n in lora_names)+ assert any(".layers.3." in n for n in lora_names)++ def test_no_freeze_still_adapts_every_layer(self, tmp_path, monkeypatch):+ """CONTROL: with no freeze_layers/freeze_ratio set, every layer+ still gets an adapter (this fix must not narrow the ordinary case)."""+ _requires_train_extra()+ wrapper, dataset = _wrapper(tmp_path, monkeypatch)+ wrapper.setup(dataset)++ lora_names = _lora_param_names(wrapper.model)+ assert any(".layers.0." in n for n in lora_names)+ assert any(".layers.1." in n for n in lora_names)++ def test_freeze_layers_with_default_auto_target_modules(self, tmp_path, monkeypatch):+ """training.lora.target_modules defaults to 'auto'. For a plain+ Llama-family model (no Soup table entry), resolve_lora_target_modules+ returns None and peft resolves its OWN default target list before+ matching. Confirm layers_to_transform still restricts the adapter+ on this, the path most configs actually take, not only the explicit+ target_modules list the other tests pin."""+ _requires_train_extra()+ wrapper, dataset = _wrapper(+ tmp_path, monkeypatch, freeze_layers=1, lora={"target_modules": "auto"}+ )+ wrapper.setup(dataset)++ lora_names = _lora_param_names(wrapper.model)+ assert lora_names+ assert not any(".layers.0." in n for n in lora_names)+ assert any(".layers.1." in n for n in lora_names)++ def test_freeze_everything_refuses_rather_than_silently_no_op(self, tmp_path, monkeypatch):+ """freeze_layers >= total layers leaves nothing for LoRA to attach+ to; must raise, not silently build a useless adapter."""+ _requires_train_extra()+ wrapper, dataset = _wrapper(tmp_path, monkeypatch, freeze_layers=99)+ with pytest.raises(ValueError, match="leaving no layer"):+ wrapper.setup(dataset)++ def test_freeze_layers_with_regex_target_modules_refuses(self, tmp_path, monkeypatch):+ """peft's layers_to_transform only filters a LIST of target module+ suffixes, never a regex target_modules string, so refuse loudly+ instead of silently shipping the same #1432 bug for this shape."""+ _requires_train_extra()+ wrapper, dataset = _wrapper(+ tmp_path,+ monkeypatch,+ freeze_layers=1,+ lora={"target_modules": r".*self_attn\.(q_proj|v_proj)"},+ )+ with pytest.raises(ValueError, match="regex"):+ wrapper.setup(dataset)++ def test_freeze_layers_with_target_parameters_refuses(self, tmp_path, monkeypatch):+ """peft's target_parameters (per-parameter LoRA) matching has no+ layers_to_transform check at all, so refuse loudly rather than+ silently ignore the freeze plan for this shape too. An explicit+ target_parameters list is returned unchanged by+ resolve_lora_target_parameters regardless of architecture, so this+ does not need a real MoE model to reach the guard."""+ _requires_train_extra()+ wrapper, dataset = _wrapper(+ tmp_path,+ monkeypatch,+ freeze_layers=1,+ lora={"target_parameters": ["mlp.gate_up_proj"]},+ )+ with pytest.raises(ValueError, match="target_parameters"):+ wrapper.setup(dataset)++ def test_freeze_layers_with_use_vera_refuses(self, tmp_path, monkeypatch):+ """VeRA is a separate peft tuner built by build_peft_config_spec's+ own branch, not the LoraConfig path layers_to_transform is wired+ into, so refuse loudly rather than silently reproduce #1432 for it+ too (VeraConfig does accept its own layers_to_transform, but nothing+ here passes it through)."""+ _requires_train_extra()+ wrapper, dataset = _wrapper(+ tmp_path, monkeypatch, freeze_layers=1, lora={"use_vera": True}+ )+ with pytest.raises(ValueError, match="use_vera"):+ wrapper.setup(dataset)++ def test_freeze_with_expand_layers_under_lora_is_refused_at_load(self, tmp_path, monkeypatch):+ """LLaMA Pro under LoRA is refused at config load (#1326), so the+ freeze plan never has to cover blocks that expand_layers appends."""+ _requires_train_extra()+ with pytest.raises(ValueError, match="cannot be combined with LoRA"):+ _wrapper(+ tmp_path, monkeypatch, n_layers=4,+ freeze_layers=1, expand_layers=2, freeze_trainable_layers=2,+ )++ def test_freeze_with_embed_tokens_target_is_not_silently_dropped(self, tmp_path, monkeypatch):+ """#1494 review: peft only restricts layers_to_transform to a list+ target that lives inside a numbered decoder layer, so embed_tokens+ (module path model.embed_tokens, no layer index) silently lost its+ adapter as soon as any freeze option was set."""+ _requires_train_extra()+ wrapper, dataset = _wrapper(+ tmp_path, monkeypatch, n_layers=4, freeze_layers=2,+ lora={"target_modules": ["q_proj", "v_proj", "embed_tokens"]},+ )+ try:+ wrapper.setup(dataset)+ except ValueError as exc:+ assert "embed_tokens" in str(exc)+ return+ names = _lora_param_names(wrapper.model)+ assert any("embed_tokens" in name for name in names), (+ "embed_tokens adapter silently dropped"+ )++ def test_freeze_ratio_cutoff_zero_does_not_restrict_layers(self, tmp_path, monkeypatch):+ """#1494 review: freeze_ratio=0.1 on a 4-layer model resolves to+ cutoff=0 (nothing frozen), but the pre-fix code still built a+ non-None layers_to_transform=[0..4), which silently drops a target+ outside a numbered layer even though nothing was frozen."""+ _requires_train_extra()+ wrapper, dataset = _wrapper(+ tmp_path, monkeypatch, n_layers=4, freeze_ratio=0.1,+ lora={"target_modules": ["q_proj", "v_proj", "embed_tokens"]},+ )+ wrapper.setup(dataset)+ names = _lora_param_names(wrapper.model)+ assert any(".layers.0." in name for name in names)+ assert any("embed_tokens" in name for name in names)++ def test_lm_head_target_with_freeze_is_accepted_and_adapted(self, tmp_path, monkeypatch):+ _requires_train_extra()+ wrapper, dataset = _wrapper(+ tmp_path, monkeypatch, n_layers=4, freeze_layers=2,+ lora={"target_modules": ["q_proj", "v_proj", "lm_head"]},+ )+ wrapper.setup(dataset)+ names = _lora_param_names(wrapper.model)+ assert any("lm_head" in name for name in names)+ assert not any(".layers.0." in name or ".layers.1." in name for name in names)++ def test_a_target_absent_from_the_model_does_not_trip_the_refusal(self, tmp_path, monkeypatch):+ _requires_train_extra()+ wrapper, dataset = _wrapper(+ tmp_path, monkeypatch, n_layers=4, freeze_layers=2,+ lora={"target_modules": ["q_proj", "v_proj", "no_such_proj"]},+ )+ wrapper.setup(dataset)+ names = _lora_param_names(wrapper.model)+ assert any(".layers.2." in name for name in names)+ assert not any(".layers.0." in name for name in names)++class TestLayersToTransformIsWhatFixesIt:+ """MECHANISM control: reproduces #1432 directly against peft, without+ going through sft.py at all, and shows layers_to_transform is what+ closes it. If this control could not be made to fail on the pre-fix+ call shape, the behavioural tests above would not be trustworthy."""++ def test_without_layers_to_transform_frozen_layer_gets_a_trainable_adapter(+ self, tmp_path+ ):+ """This is #1432 itself: the exact pre-fix call (no+ layers_to_transform) against a model with layer 0 already frozen."""+ _requires_train_extra()+ import torch+ from peft import LoraConfig, TaskType, get_peft_model+ from transformers import LlamaConfig, LlamaForCausalLM++ from soup_cli.utils.freeze import freeze_model_layers++ torch.manual_seed(0)+ model = LlamaForCausalLM(+ LlamaConfig(+ vocab_size=64, hidden_size=32, intermediate_size=64,+ num_hidden_layers=2, num_attention_heads=4, num_key_value_heads=2,+ )+ )+ freeze_model_layers(model, freeze_layers=1)++ old_config = LoraConfig(+ r=4, lora_alpha=8, target_modules=["q_proj", "v_proj"],+ task_type=TaskType.CAUSAL_LM,+ )+ peft_model = get_peft_model(model, old_config)+ by_name = dict(peft_model.named_parameters())+ layer0_lora_a = next(n for n in by_name if ".layers.0." in n and "lora_A" in n)+ # The bug: a fresh, trainable adapter on a layer that was frozen.+ assert by_name[layer0_lora_a].requires_grad is True++ def test_with_layers_to_transform_frozen_layer_gets_no_adapter(self, tmp_path):+ """Same setup, layers_to_transform=[1] (build_lora_config's #1432+ fix) added: layer 0 gets no adapter at all."""+ _requires_train_extra()+ import torch+ from peft import LoraConfig, TaskType, get_peft_model+ from transformers import LlamaConfig, LlamaForCausalLM++ from soup_cli.utils.freeze import freeze_model_layers++ torch.manual_seed(0)+ model = LlamaForCausalLM(+ LlamaConfig(+ vocab_size=64, hidden_size=32, intermediate_size=64,+ num_hidden_layers=2, num_attention_heads=4, num_key_value_heads=2,+ )+ )+ freeze_model_layers(model, freeze_layers=1)++ new_config = LoraConfig(+ r=4, lora_alpha=8, target_modules=["q_proj", "v_proj"],+ task_type=TaskType.CAUSAL_LM, layers_to_transform=[1],+ )+ peft_model = get_peft_model(model, new_config)+ lora_names = [n for n, _ in peft_model.named_parameters() if "lora_" in n]+ assert not any(".layers.0." in n for n in lora_names)+ assert any(".layers.1." in n for n in lora_names)+++def _tiny_model(model_type="llama"):+ _requires_train_extra()+ from transformers import GPT2Config, GPT2LMHeadModel, LlamaConfig, LlamaForCausalLM++ if model_type == "gpt2":+ return GPT2LMHeadModel(+ GPT2Config(vocab_size=64, n_embd=32, n_layer=4, n_head=4, n_positions=64)+ )+ return LlamaForCausalLM(LlamaConfig(+ vocab_size=64, hidden_size=32, intermediate_size=64, num_hidden_layers=4,+ num_attention_heads=4, num_key_value_heads=2,+ ))+++class TestFindLayerUnscopedTargets:+ def test_embed_tokens_is_unscoped_but_in_layer_targets_are_not(self):+ from soup_cli.utils.peft_wiring import find_layer_unscoped_targets++ assert find_layer_unscoped_targets(+ _tiny_model(), ["q_proj", "v_proj", "embed_tokens"]+ ) == ["embed_tokens"]++ def test_gpt2_h_n_layout_counts_as_a_numbered_layer(self):+ from soup_cli.utils.peft_wiring import find_layer_unscoped_targets++ model = _tiny_model("gpt2")+ assert find_layer_unscoped_targets(model, ["c_attn"]) == []+ assert find_layer_unscoped_targets(model, ["wte"]) == ["wte"]++ def test_a_target_the_model_does_not_have_is_left_alone(self):+ from soup_cli.utils.peft_wiring import find_layer_unscoped_targets++ assert find_layer_unscoped_targets(_tiny_model(), ["q_proj", "no_such_proj"]) == []++ def test_lm_head_keeps_its_adapter_under_layers_to_transform_so_is_not_flagged(self):+ """peft returns on an EXACT module-name match before it reads layers_to_transform."""+ from peft import LoraConfig, get_peft_model++ from soup_cli.utils.peft_wiring import find_layer_unscoped_targets++ peft_model = get_peft_model(+ _tiny_model(),+ LoraConfig(r=4, target_modules=["q_proj", "lm_head"], layers_to_transform=[2, 3]),+ )+ assert any("lm_head" in n and "lora_" in n for n, _ in peft_model.named_parameters())+ assert find_layer_unscoped_targets(_tiny_model(), ["q_proj", "lm_head"]) == []diff --git a/tests/test_freeze_training.py b/tests/test_freeze_training.pyindex 2fc12e35..70593f8c 100644--- a/tests/test_freeze_training.py+++ b/tests/test_freeze_training.py@@ -212,6 +212,18 @@ class TestFreezeModelLayers:frozen = freeze_model_layers(model, freeze_layers=None, freeze_ratio=None)assert frozen == 0+ def test_freeze_warns_when_no_numbered_layers_detected(self, caplog):+ """A freeze request against a model with no 'layers.N.'/'h.N.' naming+ is a no-op, and must say so rather than silently doing nothing."""+ from soup_cli.utils.freeze import freeze_model_layers++ model = MagicMock()+ model.named_parameters.return_value = [("embed.weight", MagicMock())]+ with caplog.at_level("WARNING"):+ frozen = freeze_model_layers(model, freeze_layers=4)+ assert frozen == 0+ assert "could not detect numbered layers" in caplog.text+def test_detect_num_layers(self):"""_detect_num_layers extracts layer count from model params."""from soup_cli.utils.freeze import _detect_num_layers@@ -247,6 +259,83 @@ class TestFreezeModelLayers:assert _detect_num_layers(model) == 12+# ---------------------------------------------------------------------------+# #1432: freeze_layer_cutoff (the range LoRA must respect too)+# ---------------------------------------------------------------------------+++class TestFreezeLayerCutoff:+ """freeze_layer_cutoff resolves the same (cutoff, total_layers) pair+ freeze_model_layers acts on, for a caller that needs the boundary+ without mutating requires_grad (#1432: the LoRA branch reads this to+ build ``layers_to_transform`` for the range freeze_model_layers left+ trainable)."""++ def _make_model(self, num_layers: int):+ model = MagicMock()+ model.named_parameters.return_value = [+ (f"model.layers.{idx}.self_attn.q_proj.weight", MagicMock())+ for idx in range(num_layers)+ ]+ return model++ def test_both_none_returns_none(self):+ from soup_cli.utils.freeze import freeze_layer_cutoff++ model = self._make_model(32)+ assert freeze_layer_cutoff(model, freeze_layers=None, freeze_ratio=None) is None++ def test_no_numbered_layers_returns_none(self):+ from soup_cli.utils.freeze import freeze_layer_cutoff++ model = MagicMock()+ model.named_parameters.return_value = [("embed.weight", MagicMock())]+ assert freeze_layer_cutoff(model, freeze_layers=4) is None++ def test_freeze_layers_cutoff(self):+ from soup_cli.utils.freeze import freeze_layer_cutoff++ model = self._make_model(32)+ assert freeze_layer_cutoff(model, freeze_layers=24) == (24, 32)++ def test_freeze_layers_clamped_to_total(self):+ """Mirrors freeze_model_layers' own clamp: freezing more layers than+ exist freezes all of them, cutoff == total_layers."""+ from soup_cli.utils.freeze import freeze_layer_cutoff++ model = self._make_model(8)+ assert freeze_layer_cutoff(model, freeze_layers=100) == (8, 8)++ def test_freeze_ratio_cutoff(self):+ from soup_cli.utils.freeze import freeze_layer_cutoff++ model = self._make_model(32)+ assert freeze_layer_cutoff(model, freeze_ratio=0.75) == (24, 32)++ def test_freeze_layers_takes_priority_over_ratio(self):+ from soup_cli.utils.freeze import freeze_layer_cutoff++ model = self._make_model(32)+ assert freeze_layer_cutoff(model, freeze_layers=10, freeze_ratio=0.75) == (10, 32)++ def test_matches_freeze_model_layers_frozen_set(self):+ """CONTROL: the boundary this returns must be the exact same one+ freeze_model_layers used to set requires_grad=False, or the two+ would silently drift apart the next time either is edited."""+ from soup_cli.utils.freeze import freeze_layer_cutoff, freeze_model_layers++ model = self._make_model(32)+ params = dict(model.named_parameters())+ for _name, param in params.items():+ param.requires_grad = True+ freeze_model_layers(model, freeze_layers=24)+ cutoff, total_layers = freeze_layer_cutoff(model, freeze_layers=24)+ assert total_layers == 32+ for name, param in params.items():+ layer_idx = int(name.split("layers.")[1].split(".")[0])+ assert param.requires_grad == (layer_idx >= cutoff)++# ---------------------------------------------------------------------------# Sweep integration# ---------------------------------------------------------------------------