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(layer-stream): refuse a LoRA on the streamed embedding or head at build, not by name at parse (#2082)

Yang Bai1a3388191dda
diff --git a/changelog.d/0.76.0/2082.fixed.md b/changelog.d/0.76.0/2082.fixed.md
new file mode 100644
index 00000000..28dff6be
--- /dev/null
+++ b/changelog.d/0.76.0/2082.fixed.md
@@ -0,0 +1,14 @@
+- **Under `training.stream_layers`, a LoRA target on the streamed embedding or head is refused
+ while the streamed model is built, whatever `target_modules` spelling matched it, and a tied
+ checkpoint is no longer refused (#1048 by @ybai08 in #2082).** The old check ran when the
+ config was read and matched only the literal names `lm_head` and `embed_tokens`. On an untied
+ checkpoint a regex such as `'.*(q_proj|lm_head)'` or a dotted name such as
+ `model.embed_tokens` loaded; the regex then failed at its first default save
+ (`Cannot copy out of meta tensor`), and under `task: dpo` it failed in peft during setup
+ (`Target module StreamedLargeLayer(...) is not supported`). A tied checkpoint streams neither
+ module, and its adapter saves and loads back unchanged, but it was refused anyway. The check
+ now runs after the adapter is attached and before any streaming buffer is allocated. On an
+ untied checkpoint it names the module or modules and the current `target_modules`, and says to
+ change them or train without `stream_layers`. A tied checkpoint trains and saves with the
+ defaults. Saving or resuming an adapter on an untied checkpoint's streamed embedding or head
+ is still not supported.
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index 6d849509..2280763d 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -781,6 +781,7 @@ prints this advice when it sees you accumulating.
- `task: kto` with `batch_size: 1` → TRL's KL term is degenerate at batch 1; refused when the config is read (this applies to every KTO run, not only to streaming) rather than minutes later after sharding
- `lora.use_dora` / `lora.use_vera` / `lora.init_strategy` other than `random` → these initialise from the real base weight, which is on the meta device under streaming
- `moe_expert_quant` → expert quantization runs only in the resident model-construction path and would otherwise be silently ignored
+- a LoRA target on the streamed `embed_tokens` or `lm_head` of an untied checkpoint, however `target_modules` spells it (a name, a regex, a dotted path) → refused while the streamed model is built, after the adapter is attached and before any streaming buffer is allocated, not at config load: only then is it known whether the checkpoint streams them and which modules the spelling matched. Saving or resuming that adapter is not supported yet (#1048). The dotted `[q_proj, model.embed_tokens]` is refused like the other spellings until item 1 of #1048 (save and resume) lands. A tied checkpoint streams neither weight, so a target there trains, saves with the defaults and loads back unchanged, as it does without streaming
- `unfrozen_parameters`, `lisa_enabled`, `packing`, `multipack`, `use_fsdp2_compile`, `train_router_only`, `expand_layers` → each independently rewrites or re-freezes the same layers
- `use_cut_ce` is refused with `stream_layers` (#1206): streamed setup does not install the resident CCE patch. Disable CCE to stream with the conservative full-logits budget, or disable streaming to use resident CCE. A tiny local streamed Llama was exercised through sharding, forward/loss and backward on CPU; this is no CUDA memory measurement.
- `use_liger` / `use_flash_attn` → **not reached at all** under streaming (#1692). Both are read by the *resident* setup: Liger patches the MLP forward there, and flash-attn is handed to `from_pretrained` as `attn_implementation`. A streamed model is built by `from_config` with no attention argument and no Liger patch, and `_liger_applied` is never set, so `use_liger_kernel` misses `TrainingArguments` too. These are the switches you reach for when a streamed run will not fit, so they are refused rather than dropped; each is offered again once it is wired and shown to engage on a streamed model. On every task outside `{sft, tts}` they are already refused at config load (#806)
diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.py
index 5b5694f0..1d7de5b7 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -7046,26 +7046,10 @@ class SoupConfig(BaseModel):
"VeRA's shared projections are built from the materialised "
"base weights, which streaming keeps on the meta device."
)
- # #1012 follow-up: the forward pass for a LoRA target on the streamed
- # large-layer boundary modules (lm_head / embed_tokens) is correct
- # (#1019), and a save -> load_adapter round trip now preserves the
- # adapter's tensors (#1048), but save_pretrained() still raises
- # trying to copy a meta tensor. Refuse by name at parse time rather
- # than let a run train for hours and die at its first save_steps.
- target_modules = tcfg.lora.target_modules
- named_targets = (
- {target_modules} if isinstance(target_modules, str) else set(target_modules)
- )
- head_targets = sorted(named_targets & {"lm_head", "embed_tokens"})
- if head_targets:
- raise ValueError(
- "training.stream_layers does not yet support a LoRA target on "
- f"{', '.join(head_targets)}: the forward pass is correct, but "
- "saving or resuming an adapter that targets the streamed "
- "head/embedding boundary is not supported yet. Drop "
- f"{', '.join(head_targets)} from training.lora.target_modules, "
- "or train without stream_layers."
- )
+ # A LoRA target on the streamed embedding or head (#1012) is refused by
+ # build_streamed_model() after get_peft_model() (#1048): whether the
+ # checkpoint streams them (untied) and which modules a target_modules
+ # spelling matches are not known here.
if tcfg.moe_expert_quant is not None:
raise ValueError(
"training.stream_layers is incompatible with "
diff --git a/src/soup_cli/utils/layer_stream_runtime.py b/src/soup_cli/utils/layer_stream_runtime.py
index 6f5d5608..2ce8422a 100644
--- a/src/soup_cli/utils/layer_stream_runtime.py
+++ b/src/soup_cli/utils/layer_stream_runtime.py
@@ -1838,6 +1838,38 @@ def _unwrap_tuner_base(module: Any) -> Any:
return module
+def _refuse_lora_on_streamed_boundary(model: Any, index: Any, lora_config: Any) -> None:
+ """Refuse a LoRA target on the streamed embedding or head (#1048).
+
+ Saving or resuming that adapter is not supported yet. Checked after
+ get_peft_model(), so it covers every spelling of ``target_modules`` that
+ matched the module, and only when the checkpoint streams those weights: a
+ tied one has no large-layer keys and keeps both modules resident.
+ """
+ if not tuple(getattr(index, "large_keys", ()) or ()):
+ return
+ from peft.tuners.tuners_utils import BaseTunerLayer
+
+ wrapped = [
+ role
+ for role, module in (
+ ("embed_tokens", model.get_input_embeddings()),
+ ("lm_head", model.get_output_embeddings()),
+ )
+ if isinstance(module, BaseTunerLayer)
+ ]
+ if wrapped:
+ names = ", ".join(wrapped)
+ raise ValueError(
+ f"training.stream_layers does not yet support a LoRA target on the "
+ f"streamed {names} of an untied checkpoint: the forward pass is "
+ f"correct, but saving or resuming that adapter is not supported yet. "
+ f"Change training.lora.target_modules (now "
+ f"{lora_config.target_modules!r}) so it does not match {names}, or "
+ f"train without stream_layers."
+ )
+
+
def _build_streamed_large_layer_class():
import torch
import torch.nn as nn
@@ -3792,6 +3824,7 @@ def build_streamed_model(
apply_pre_lora_patches(model, model_id)
model = get_peft_model(model, lora_config)
+ _refuse_lora_on_streamed_boundary(model, index, lora_config)
materialize_meta_adapters(model, seed=seed, device=device)
assert_trainable_adapters_materialized(model)
runtime = install_streaming(
diff --git a/tests/test_issue1012_lora_head_streamed_large_layer.py b/tests/test_issue1012_lora_head_streamed_large_layer.py
index 0a95dae1..02da35f3 100644
--- a/tests/test_issue1012_lora_head_streamed_large_layer.py
+++ b/tests/test_issue1012_lora_head_streamed_large_layer.py
@@ -26,6 +26,8 @@ entry and both modules stay resident (untouched by this fix; pinned below).
from __future__ import annotations
+from unittest import mock
+
import pytest
pytestmark = pytest.mark.filterwarnings("ignore::DeprecationWarning")
@@ -79,23 +81,28 @@ def _lora(target_modules):
def _build_streamed(tmp_path, *, tie, target_modules, seed=3):
+ from soup_cli.utils import layer_stream_runtime
from soup_cli.utils.layer_shard import shard_checkpoint
from soup_cli.utils.layer_stream_runtime import build_streamed_model
weights = _tiny_llama_dir(tmp_path, tie=tie)
shards = str(tmp_path / "shards")
index = shard_checkpoint(weights, shards, dtype="float32", arch="llama")
- model, runtime = build_streamed_model(
- model_id=weights,
- shard_dir=shards,
- index=index,
- lora_config=_lora(target_modules),
- device="cpu",
- dtype="float32",
- buffers=2,
- pin=False,
- seed=seed,
- )
+ # #1048: build_streamed_model refuses these targets until saving and
+ # resuming them works. This file pins the part that already does, so it
+ # builds past that refusal.
+ with mock.patch.object(layer_stream_runtime, "_refuse_lora_on_streamed_boundary"):
+ model, runtime = build_streamed_model(
+ model_id=weights,
+ shard_dir=shards,
+ index=index,
+ lora_config=_lora(target_modules),
+ device="cpu",
+ dtype="float32",
+ buffers=2,
+ pin=False,
+ seed=seed,
+ )
return model, runtime, weights
diff --git a/tests/test_issue1048_lora_head_save_resume.py b/tests/test_issue1048_lora_head_save_resume.py
index 5f2770c5..a38c019e 100644
--- a/tests/test_issue1048_lora_head_save_resume.py
+++ b/tests/test_issue1048_lora_head_save_resume.py
@@ -21,6 +21,8 @@ success).
from __future__ import annotations
+from unittest import mock
+
import pytest
pytestmark = pytest.mark.filterwarnings("ignore::DeprecationWarning")
@@ -74,23 +76,28 @@ def _lora(target_modules):
def _build_streamed(tmp_path, *, tie, target_modules, seed):
+ from soup_cli.utils import layer_stream_runtime
from soup_cli.utils.layer_shard import shard_checkpoint
from soup_cli.utils.layer_stream_runtime import build_streamed_model
weights = _tiny_llama_dir(tmp_path, tie=tie)
shards = str(tmp_path / "shards")
index = shard_checkpoint(weights, shards, dtype="float32", arch="llama")
- model, runtime = build_streamed_model(
- model_id=weights,
- shard_dir=shards,
- index=index,
- lora_config=_lora(target_modules),
- device="cpu",
- dtype="float32",
- buffers=2,
- pin=False,
- seed=seed,
- )
+ # #1048: build_streamed_model refuses these targets until saving and
+ # resuming them works. This file pins the part that already does, so it
+ # builds past that refusal.
+ with mock.patch.object(layer_stream_runtime, "_refuse_lora_on_streamed_boundary"):
+ model, runtime = build_streamed_model(
+ model_id=weights,
+ shard_dir=shards,
+ index=index,
+ lora_config=_lora(target_modules),
+ device="cpu",
+ dtype="float32",
+ buffers=2,
+ pin=False,
+ seed=seed,
+ )
return model, runtime
diff --git a/tests/test_layer_stream_boundary_lora.py b/tests/test_layer_stream_boundary_lora.py
new file mode 100644
index 00000000..7188202b
--- /dev/null
+++ b/tests/test_layer_stream_boundary_lora.py
@@ -0,0 +1,211 @@
+"""#1048 item 2: a LoRA target on the streamed embedding or head is refused at
+build time, where the model says whether the checkpoint streams them.
+
+The parse-time refusal matched the literal names ``lm_head`` and
+``embed_tokens`` only. A regex or dotted spelling of the same target loaded and
+then crashed at the first save, and a tied checkpoint, which streams neither
+weight and round-trips cleanly, was refused.
+"""
+
+from __future__ import annotations
+
+import pytest
+import yaml
+
+from soup_cli.config.loader import load_config_from_string
+
+pytestmark = pytest.mark.filterwarnings("ignore::DeprecationWarning")
+
+pytest.importorskip("torch")
+pytest.importorskip("transformers")
+pytest.importorskip("peft")
+
+
+def _config(target_modules, task="sft"):
+ return load_config_from_string(
+ yaml.safe_dump(
+ {
+ "base": "meta-llama/Llama-3.1-8B",
+ "task": task,
+ "data": {"train": "data.jsonl"},
+ "training": {
+ "batch_size": 2,
+ "stream_layers": True,
+ "lora": {"target_modules": target_modules},
+ },
+ }
+ )
+ )
+
+
+class TestTheConfigNoLongerDecides:
+ @pytest.mark.parametrize(
+ "target_modules",
+ [["q_proj", "v_proj", "lm_head"], ["q_proj", "embed_tokens"], "lm_head"],
+ )
+ def test_a_boundary_target_loads(self, target_modules):
+ cfg = _config(target_modules)
+
+ assert cfg.training.lora.target_modules == target_modules
+
+
+# The real streamed setup on a tiny Llama, as in test_v07204.
+
+
+def _setup(tmp_path, monkeypatch, *, tie, target_modules, task="sft", device="cpu", **training):
+ from tests.test_v07204 import _build_streamed_wrapper
+
+ wrapper, _, _ = _build_streamed_wrapper(
+ tmp_path,
+ monkeypatch,
+ task=task,
+ n_layers=2,
+ device=device,
+ tie=tie,
+ lora={"r": 4, "alpha": 8, "dropout": 0.0, "target_modules": target_modules},
+ **training,
+ )
+ return wrapper
+
+
+def _counted_installs(monkeypatch):
+ """Each call to install_streaming, which allocates the streaming buffers."""
+ from soup_cli.utils import layer_stream_runtime
+
+ installs = []
+ real_install = layer_stream_runtime.install_streaming
+
+ def counting_install(*args, **kwargs):
+ installs.append(True)
+ return real_install(*args, **kwargs)
+
+ monkeypatch.setattr(layer_stream_runtime, "install_streaming", counting_install)
+ return installs
+
+
+class TestAnUntiedBoundaryTargetIsRefusedAtBuild:
+ @pytest.mark.parametrize(
+ ("target_modules", "named"),
+ [
+ (["q_proj", "v_proj", "lm_head"], "lm_head"),
+ (["q_proj", "embed_tokens"], "embed_tokens"),
+ (".*(q_proj|lm_head)", "lm_head"),
+ (["q_proj", "embed_tokens", "lm_head"], "embed_tokens, lm_head"),
+ ],
+ )
+ def test_every_spelling(self, tmp_path, monkeypatch, target_modules, named):
+ installs = _counted_installs(monkeypatch)
+
+ with pytest.raises(ValueError) as excinfo:
+ _setup(tmp_path, monkeypatch, tie=False, target_modules=target_modules)
+
+ message = str(excinfo.value)
+ assert f"LoRA target on the streamed {named} of an untied checkpoint" in message
+ assert "training.lora.target_modules" in message
+ assert installs == [] # refused before any buffer is allocated
+
+ def test_the_dotted_embedding_path_on_purpose(self, tmp_path, monkeypatch):
+ # Per the maintainer's answer on #1048: refused like every other adapted
+ # boundary module until saving and resuming it (item 1) lands.
+ installs = _counted_installs(monkeypatch)
+
+ with pytest.raises(ValueError) as excinfo:
+ _setup(
+ tmp_path, monkeypatch, tie=False, target_modules=["q_proj", "model.embed_tokens"]
+ )
+
+ message = str(excinfo.value)
+ assert "LoRA target on the streamed embed_tokens of an untied checkpoint" in message
+ assert "'model.embed_tokens'" in message # the spelling it was given
+ assert "lm_head" not in message
+ assert installs == [] # refused before any buffer is allocated
+
+ def test_a_preference_task_too(self, tmp_path, monkeypatch):
+ installs = _counted_installs(monkeypatch)
+
+ with pytest.raises(ValueError, match="streamed lm_head of an untied checkpoint"):
+ _setup(
+ tmp_path, monkeypatch, tie=False, target_modules=".*(q_proj|lm_head)", task="dpo"
+ )
+
+ assert installs == [] # refused before any buffer is allocated
+
+ def test_without_a_boundary_target_it_builds(self, tmp_path, monkeypatch):
+ installs = _counted_installs(monkeypatch)
+
+ wrapper = _setup(tmp_path, monkeypatch, tie=False, target_modules=["q_proj", "v_proj"])
+
+ wrapper._close_stream_runtime()
+ assert installs == [True]
+
+
+def _lora_parameters(model):
+ return {
+ name: param.detach().cpu().clone()
+ for name, param in model.named_parameters()
+ if "lora_" in name
+ }
+
+
+class TestATiedBoundaryTargetTrainsAndSaves:
+ """A tied checkpoint streams neither weight, so nothing refuses it: a step
+ with a save writes every adapter tensor through the Trainer's default
+ save, and a fresh build loads each of them unchanged."""
+
+ @pytest.mark.parametrize("target", ["lm_head", "embed_tokens"])
+ def test_one_step_a_checkpoint_and_a_reload(self, tmp_path, monkeypatch, target):
+ import torch
+ from peft import get_peft_model_state_dict, load_peft_weights, set_peft_model_state_dict
+ from safetensors.torch import load_file
+
+ targets = ["q_proj", "v_proj", target]
+ wrapper = _setup(
+ tmp_path / "run",
+ monkeypatch,
+ tie=True,
+ target_modules=targets,
+ # The accelerator, as test_v07204's training tests do: the Trainer
+ # picks it whatever the wrapper was given.
+ device=None,
+ save_steps=1,
+ )
+ wrapper.trainer.args.max_steps = 1
+ try:
+ wrapper.trainer.train()
+ trained_state = {
+ k: v.detach().cpu() for k, v in get_peft_model_state_dict(wrapper.model).items()
+ }
+ trained = _lora_parameters(wrapper.model)
+ finally:
+ wrapper._close_stream_runtime()
+
+ checkpoint = tmp_path / "run" / "out" / "checkpoint-1"
+ saved = load_file(str(checkpoint / "adapter_model.safetensors"))
+ assert sorted(saved) == sorted(trained_state)
+ for key, value in saved.items():
+ assert torch.equal(trained_state[key], value), key
+ boundary = [k for k in saved if target in k and "lora_" in k]
+ assert len(boundary) == 2, sorted(saved)
+ # Two decoder layers x (q_proj, v_proj) x (A, B), plus the boundary's A and B.
+ assert len(trained) == 10, sorted(trained)
+
+ fresh = _setup(
+ tmp_path / "fresh", monkeypatch, tie=True, target_modules=targets, device="cpu"
+ )
+ try:
+ # Off every value a dropped tensor could keep: lora_B starts at
+ # zero and lora_A from the same seed, so either could match the
+ # trained one without being loaded.
+ torch.manual_seed(1234)
+ with torch.no_grad():
+ for name, param in fresh.model.named_parameters():
+ if "lora_" in name:
+ param.copy_(torch.randn_like(param) + 5.0)
+ set_peft_model_state_dict(fresh.model, load_peft_weights(str(checkpoint)))
+ loaded = _lora_parameters(fresh.model)
+ finally:
+ fresh._close_stream_runtime()
+
+ assert sorted(loaded) == sorted(trained)
+ for name, value in trained.items():
+ assert torch.equal(loaded[name], value), f"{name!r} did not load unchanged"
diff --git a/tests/test_v07200.py b/tests/test_v07200.py
index 0ea0be4d..ff2c22ba 100644
--- a/tests/test_v07200.py
+++ b/tests/test_v07200.py
@@ -2164,47 +2164,11 @@ class TestStreamLoraVariantGates:
class TestStreamLoraHeadTargetGate:
"""#1012 follow-up (#1019 review): the forward pass for a LoRA target on
lm_head/embed_tokens under streaming is correct, but saving and resuming
- that adapter is not implemented yet (save_pretrained() raises copying a
- meta tensor; a save -> load_adapter round trip silently drops most of the
- adapter's tensors). Refuse at parse time, before any shard I/O runs, the
- same way lora.use_dora / lora.use_vera are refused above."""
-
- def test_lm_head_target_rejected(self):
- with pytest.raises(ValueError, match="lm_head"):
- _load(
- _stream_yaml(
- training={"lora": {"r": 4, "target_modules": ["q_proj", "lm_head"]}}
- )
- )
-
- def test_embed_tokens_target_rejected(self):
- with pytest.raises(ValueError, match="embed_tokens"):
- _load(
- _stream_yaml(
- training={
- "lora": {"r": 4, "target_modules": ["q_proj", "embed_tokens"]}
- }
- )
- )
-
- def test_both_boundary_modules_named_together(self):
- with pytest.raises(ValueError, match="embed_tokens.*lm_head|lm_head.*embed_tokens"):
- _load(
- _stream_yaml(
- training={
- "lora": {
- "r": 4,
- "target_modules": ["embed_tokens", "q_proj", "lm_head"],
- }
- }
- )
- )
-
- def test_bare_string_target_is_checked_too(self):
- """target_modules accepts a bare string (Union[str, List[str]]), not
- only a list: the guard must not assume a list."""
- with pytest.raises(ValueError, match="lm_head"):
- _load(_stream_yaml(training={"lora": {"r": 4, "target_modules": "lm_head"}}))
+ that adapter is not implemented yet. The refusal moved from parse time to
+ the streamed setup (#1048), which knows whether the checkpoint streams
+ those modules and which ones a target spelling matched; it is tested in
+ tests/test_layer_stream_boundary_lora.py. What stays here is that ordinary
+ targets load."""
def test_non_boundary_targets_still_accepted(self):
"""Negative control: q_proj/v_proj/o_proj/k_proj are unaffected. This