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.

feat(peft): training.fast_lora switches the Fast-LoRA kernels on (#792) (#1973)

Yang Bai15dd4d9c7b5b
diff --git a/changelog.d/0.76.0/1973.added.md b/changelog.d/0.76.0/1973.added.md
new file mode 100644
index 00000000..fb4e33a8
--- /dev/null
+++ b/changelog.d/0.76.0/1973.added.md
@@ -0,0 +1 @@
+- **`training.fast_lora: true` runs a LoRA's projections through Soup's own Fast-LoRA autograd functions** (q/k/v with one shared input, gate/up/down as one SwiGLU block, every other adapted Linear as a single projection) instead of peft's modules, on the resident and the layer-streamed SFT paths. Setup prints what each kernel took over and refuses the run when none did. Off by default; `task: sft`, `transformers`, text, quantization `none` or `4bit`, and `lora.dropout: 0` (Soup's default is 0.05); refused with the reason beside `use_liger`, DoRA, VeRA, `target_parameters`, Spectrum (`unfrozen_parameters`), LISA and `quantization_aware: fp8`. Verified on CPU in float32 and float64 against peft's modules; the bf16/fp16, NF4 and streamed-CUDA checks have not been run, and no speedup is claimed. Try: `soup train --config soup.yaml` with `training.fast_lora: true` and `training.lora.dropout: 0` (#792 by @ybai08 in #1973).
diff --git a/docs/config-reference.md b/docs/config-reference.md
index f6fefba4..63fb4206 100644
--- a/docs/config-reference.md
+++ b/docs/config-reference.md
@@ -256,6 +256,7 @@ Sections:
| `training.moe_lora` | `bool` | `false` | | Enable MoE-aware LoRA (ScatterMoE) — applies LoRA to expert FFN layers |
| `training.moe_aux_loss_coeff` | `float` | `0.01` | `>= 0` | Auxiliary load-balancing loss coefficient for MoE models |
| `training.use_liger` | `bool` | `false` | | Enable Liger Kernel fused operations (20-60% memory savings, 20-40% speedup) |
+| `training.fast_lora` | `bool` | `false` | | Run LoRA's q/k/v, MLP and other projections through Soup's hand-written Fast-LoRA autograd functions instead of peft's modules. Same math; no speedup is claimed. task='sft' on the transformers backend with text, quantization none or 4bit, and lora.dropout 0; refused beside use_liger, DoRA, VeRA, target_parameters, Spectrum, LISA and FP8 training. |
| `training.use_flash_attn` | `bool` | `false` | | Enable FlashAttention (auto-detects v2/v3/v4 for faster attention) |
| `training.use_ring_attention` | `bool` | `false` | | Enable Ring FlashAttention for sequence parallelism across GPUs |
| `training.rope_scaling_type` | `str \| null` | `null` | one of `"linear"`, `"dynamic"`, `"yarn"`, `"llama3"` | RoPE scaling method for long-context: linear, dynamic, yarn or llama3 (v0.49.0). 'longrope' is refused at config load (#1239). Applied by task sft, tts and pretrain on backend: transformers (sft: the text path without layer streaming); refused at config load anywhere else (#1697). |
diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.md
index 45ecd727..b2bacef1 100644
--- a/docs/peft-and-efficiency.md
+++ b/docs/peft-and-efficiency.md
@@ -444,6 +444,50 @@ training:
- **Compatibility:** Supported on the `transformers` backend for `sft`, `pretrain`, and `embedding` tasks. Mutually exclusive with `loraplus_lr_ratio` (which differentiates $A$ and $B$ rates), `use_galore`, `lora.use_vera` (VeRA trains scaling vectors, so `create_lorafa_optimizer` finds no $B$ matrices), non-AdamW optimizers, and the `mlx` backend. Requires explicit `lora.r` and `lora.alpha`. LoRA-FA has not been validated under `stream_layers: true` (layer streaming); combining them is not recommended.
+## Fast-LoRA kernels (`training.fast_lora`)
+
+Runs a LoRA's projections through Soup's own autograd functions instead of
+peft's modules: q/k/v with one shared input and one accumulated input gradient,
+gate/up/down around SwiGLU as one block, and every other adapted Linear (such as
+`o_proj`) as a single projection. The math is LoRA's; the kernels change the
+order of the work and what is kept for the backward pass.
+
+```yaml
+training:
+ fast_lora: true
+ lora:
+ dropout: 0 # required: Soup's default is 0.05
+ target_modules: [q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj]
+```
+
+Setup prints how many modules each kernel took over, and refuses the run if the
+flag is on and none was. Off by default.
+
+- **Scope:** `task: sft` on the `transformers` backend, `modality: text`,
+ `quantization: none` or `4bit`, resident or with `stream_layers`. Refused, with
+ the reason: any other task, backend, modality or quantization; `lora.r: 0`;
+ `lora.use_dora`, `lora.use_vera`, `lora.target_parameters`; `lora.dropout`
+ other than 0 (peft gives every projection its own dropout, so q/k/v and
+ gate/up would no longer share one input); `training.use_liger`, which
+ replaces the MLP's forward too; `unfrozen_parameters` (Spectrum) and
+ `lisa_enabled`, which train the model's own weights and skip the LoRA setup;
+ and `quantization_aware: fp8`, whose converted projections the kernels would
+ read around. A model whose adapters the kernels cannot run (GPT-2's Conv1D
+ layout) is refused at setup, as if nothing had been patched.
+- **What is verified, on CPU:** float64 `gradcheck` of each kernel through the
+ switch; float32 forward and backward parity with peft's modules; the same
+ gradients with and without non-reentrant checkpointing; the base model's
+ output with the adapter disabled; fifty training steps whose losses stay
+ within 1e-3 of peft's; and a streamed model with more layers than
+ `stream_buffers`, whose LoRA gradients on every layer equal those without the
+ flag.
+- **Not verified:** bf16, fp16 and NF4 parity, and streaming on a GPU. Those
+ tests exist (`pytest -m gpu`) and need a CUDA card with bitsandbytes.
+- **No speedup is claimed.** Nothing here measures end-to-end throughput or
+ peak VRAM. Under gradient checkpointing, which layer streaming always uses, a
+ block's saved tensors exist only during its recompute, so any saving lowers a
+ per-layer transient, not the stored total.
+
## rsLoRA (Rank-Stabilized Scaling)
Use rank-stabilized LoRA scaling for better performance at high ranks:
diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.py
index 7ae86426..8c139ee5 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -3053,6 +3053,18 @@ class TrainingConfig(BaseModel):
default=False,
description="Enable Liger Kernel fused operations (20-60% memory savings, 20-40% speedup)",
)
+ # #792 — the Fast-LoRA kernels (utils/fast_lora*.py) behind one switch
+ fast_lora: bool = Field(
+ default=False,
+ description=(
+ "Run LoRA's q/k/v, MLP and other projections through Soup's "
+ "hand-written Fast-LoRA autograd functions instead of peft's "
+ "modules. Same math; no speedup is claimed. task='sft' on the "
+ "transformers backend with text, quantization none or 4bit, and "
+ "lora.dropout 0; refused beside use_liger, DoRA, VeRA, "
+ "target_parameters, Spectrum, LISA and FP8 training."
+ ),
+ )
# Performance — FlashAttention
use_flash_attn: bool = Field(
default=False,
@@ -6101,6 +6113,75 @@ class SoupConfig(BaseModel):
)
return self
+ @model_validator(mode="after")
+ def _validate_fast_lora_supported(self) -> "SoupConfig":
+ """#792 — the first slice of ``training.fast_lora``. The kernels patch
+ peft's LoRA modules on a text model trained by the SFT wrapper; every
+ other setting is refused with its reason rather than left unpatched."""
+ tcfg = self.training
+ if not tcfg.fast_lora:
+ return self
+ lora = tcfg.lora
+ reason = None
+ if self.backend != "transformers":
+ reason = (
+ f"needs backend='transformers'; got backend={self.backend!r}. The "
+ f"kernels replace peft's LoRA modules, which that backend does not use."
+ )
+ elif self.modality != "text":
+ reason = f"supports modality='text' only; got modality={self.modality!r}."
+ elif self.task != "sft":
+ reason = (
+ f"supports task='sft' only; got task={self.task!r}. Other trainers "
+ f"are not tested with the kernels yet."
+ )
+ elif lora.r == 0:
+ reason = "needs a LoRA; lora.r=0 trains the full model, with no LoRA to patch."
+ elif tcfg.unfrozen_parameters or tcfg.lisa_enabled:
+ name = "unfrozen_parameters" if tcfg.unfrozen_parameters else "lisa_enabled"
+ reason = (
+ f"cannot be combined with training.{name}: that mode trains the "
+ f"model's own weights and skips the LoRA setup the kernels hook into."
+ )
+ elif tcfg.quantization_aware == "fp8":
+ # (QuEST needs lora.r=0, refused above.)
+ reason = (
+ "cannot be combined with training.quantization_aware='fp8': FP8 "
+ "training converts the projections, and the kernels read their "
+ "weights directly, around the conversion."
+ )
+ elif lora.use_dora or lora.use_vera:
+ name = "use_dora" if lora.use_dora else "use_vera"
+ reason = (
+ f"cannot be combined with lora.{name}: the kernels compute plain "
+ f"LoRA, not that adapter's update."
+ )
+ elif lora.target_parameters:
+ reason = (
+ "cannot be combined with lora.target_parameters: those adapters "
+ "wrap parameters, not the Linear modules the kernels patch."
+ )
+ elif tcfg.quantization not in ("none", "4bit"):
+ reason = (
+ f"supports quantization 'none' or '4bit'; got "
+ f"quantization={tcfg.quantization!r}."
+ )
+ elif lora.dropout != 0:
+ reason = (
+ f"needs lora.dropout: 0; got {lora.dropout} (Soup's default is 0.05). "
+ f"peft gives every projection its own dropout, so q/k/v and gate/up "
+ f"would no longer share the one input the kernels read."
+ )
+ elif tcfg.use_liger:
+ reason = (
+ "cannot be combined with training.use_liger: Liger already replaces "
+ "the MLP's forward, and fast_lora would replace it again. Keep one "
+ "of them."
+ )
+ if reason is not None:
+ raise ValueError(f"training.fast_lora {reason}")
+ return self
+
@model_validator(mode="after")
def _validate_kernel_flags_task_gate(self) -> "SoupConfig":
"""#806: use_flash_attn / use_liger are read only by the SFT-family
diff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.py
index 6c2fa108..086ae2b2 100644
--- a/src/soup_cli/trainer/sft.py
+++ b/src/soup_cli/trainer/sft.py
@@ -1863,12 +1863,18 @@ class SFTTrainerWrapper(StreamingSetupMixin):
)
# v0.39.0 Part D / v0.40.6 #67 — surgical PEFT patches via shared helpers.
from soup_cli.utils.peft_wiring import (
+ apply_fast_lora_patches,
apply_post_lora_patches,
apply_pre_lora_patches,
+ fast_lora_summary,
)
apply_pre_lora_patches(self.model, cfg.base)
self.model = get_peft_model(self.model, lora_config)
apply_post_lora_patches(self.model)
+ # #792 — after every other LoRA patch, so the kernels see the final modules.
+ fast_lora_counts = apply_fast_lora_patches(self.model, tcfg)
+ if fast_lora_counts is not None:
+ console.print(f"[green]{fast_lora_summary(fast_lora_counts)}[/]")
# v0.71.12 #84 — Mixture-of-Depths selective-token routing. Applied
# AFTER get_peft_model so the freshly-added routers are trainable.
diff --git a/src/soup_cli/trainer/stream_setup.py b/src/soup_cli/trainer/stream_setup.py
index 7066d915..1ff5eaa9 100644
--- a/src/soup_cli/trainer/stream_setup.py
+++ b/src/soup_cli/trainer/stream_setup.py
@@ -1243,6 +1243,18 @@ class StreamingSetupMixin:
)
self.model = model
self._stream_runtime = runtime
+ # #792 — on the materialised adapters, before the probe measures a step.
+ from soup_cli.utils.peft_wiring import apply_fast_lora_patches, fast_lora_summary
+
+ try:
+ fast_lora_counts = apply_fast_lora_patches(model, tcfg)
+ except Exception:
+ # Training's cleanup context has not started yet: release the
+ # runtime here, as the probe below does on its own failure.
+ self._close_stream_runtime()
+ raise
+ if fast_lora_counts is not None:
+ console.print(f"[green]{fast_lora_summary(fast_lora_counts)}[/]")
if probe_plan is not None:
self._run_stream_vram_probe(model, probe_plan)
stats = runtime.stats()
diff --git a/src/soup_cli/utils/fast_lora.py b/src/soup_cli/utils/fast_lora.py
index 9e793d24..bb10702d 100644
--- a/src/soup_cli/utils/fast_lora.py
+++ b/src/soup_cli/utils/fast_lora.py
@@ -528,6 +528,19 @@ def patch_fast_lora_single_projection(model: Any, *, allow_dropout: bool = False
return len(targets)
+def eligible_single_projections(model: Any) -> int:
+ """Patched single projections the kernel can run (#792).
+
+ A ``fan_in_fan_out`` LoRA (GPT-2's Conv1D layout) is patched like any other
+ but delegates to peft on every call, so it is not counted.
+ """
+ return sum(
+ 1
+ for child in model.modules()
+ if getattr(child, _PATCH_MARKER, False) and not getattr(child, "fan_in_fan_out", False)
+ )
+
+
def _release_single_projection(child: Any) -> bool:
"""Give ``child`` back the forward it had before this kernel; ``True`` if it had it.
diff --git a/src/soup_cli/utils/peft_wiring.py b/src/soup_cli/utils/peft_wiring.py
index b55d6fb3..0925b457 100644
--- a/src/soup_cli/utils/peft_wiring.py
+++ b/src/soup_cli/utils/peft_wiring.py
@@ -570,6 +570,54 @@ def apply_post_lora_patches(model: Any) -> None:
logger.debug("strip_lora_dropout_for_3d_experts skipped: %s", exc)
+def apply_fast_lora_patches(model: Any, tcfg: Any) -> dict[str, int] | None:
+ """Switch the Fast-LoRA kernels on for ``training.fast_lora`` (#792).
+
+ The two group kernels first, then the single projection for every adapted
+ Linear they did not take (#1165: the order does not change the result).
+ Returns how many modules each kernel can run on, or None when the flag is
+ off. With the flag on and none it can run on, it takes the patches off and
+ raises, since the run would train through peft's own modules while the
+ config says otherwise.
+ """
+ if not getattr(tcfg, "fast_lora", False):
+ return None
+ from soup_cli.utils.fast_lora import (
+ eligible_single_projections,
+ patch_fast_lora_single_projection,
+ unpatch_fast_lora_single_projection,
+ )
+ from soup_cli.utils.fast_lora_mlp import patch_fast_lora_mlp, unpatch_fast_lora_mlp
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv, unpatch_fast_lora_qkv
+
+ counts = {
+ "q/k/v": patch_fast_lora_qkv(model),
+ "MLP": patch_fast_lora_mlp(model),
+ "single projection": patch_fast_lora_single_projection(model),
+ }
+ counts["single projection"] = eligible_single_projections(model)
+ if not any(counts.values()):
+ for unpatch in (
+ unpatch_fast_lora_single_projection,
+ unpatch_fast_lora_mlp,
+ unpatch_fast_lora_qkv,
+ ):
+ unpatch(model)
+ raise ValueError(
+ "training.fast_lora is on, but no LoRA module was patched: the model "
+ "has no adapted Linear the kernels support. Remove training.fast_lora "
+ "or check lora.target_modules."
+ )
+ return counts
+
+
+def fast_lora_summary(counts: dict[str, int]) -> str:
+ """The setup line that says what the kernels took over."""
+ return "Fast-LoRA kernels on: " + ", ".join(
+ f"{count} {name}" for name, count in counts.items()
+ )
+
+
def _relora_merge_target(trainer: Any) -> tuple[Any, Any, str | None, Any]:
"""Return the save owner, model holder, optional policy attr, and PEFT model."""
owner = getattr(trainer, "__dict__", {}).get("_trainer", trainer)
diff --git a/tests/fixtures/recipe_config_snapshots.json b/tests/fixtures/recipe_config_snapshots.json
index 7ecf4fb8..0b809ce6 100644
--- a/tests/fixtures/recipe_config_snapshots.json
+++ b/tests/fixtures/recipe_config_snapshots.json
@@ -105,6 +105,7 @@
"training.eval_gate": null,
"training.eval_steps": null,
"training.expand_layers": null,
+ "training.fast_lora": false,
"training.forgetting_benchmark": "mini_mmlu",
"training.forgetting_detection": false,
"training.forgetting_eval_steps": 100,
diff --git a/tests/test_fast_lora_flag.py b/tests/test_fast_lora_flag.py
new file mode 100644
index 00000000..56bcbaca
--- /dev/null
+++ b/tests/test_fast_lora_flag.py
@@ -0,0 +1,644 @@
+"""#792 — ``training.fast_lora``: the switch that puts the Fast-LoRA kernels
+(``utils/fast_lora.py``, ``fast_lora_mlp.py``, ``fast_lora_qkv.py``) on a run.
+
+What is checked here runs on CPU in float32 and float64: the settings the flag
+refuses, the wiring on the resident and the streamed SFT paths, and parity with
+peft's own modules through the switch. The bf16 / fp16, NF4 and streamed-CUDA
+rows of the issue are ``gpu`` tests at the end of the file.
+"""
+
+from __future__ import annotations
+
+import json
+import types
+
+import pytest
+from rich.console import Console
+
+torch = pytest.importorskip("torch")
+pytest.importorskip("peft")
+pytest.importorskip("transformers")
+
+CONSOLE = Console()
+TARGETS = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
+ON = types.SimpleNamespace(fast_lora=True)
+OFF = types.SimpleNamespace(fast_lora=False)
+
+
+def _cfg(task="sft", data=None, backend="transformers", modality="text", **training):
+ from soup_cli.config.schema import SoupConfig
+
+ lora = {"dropout": 0.0, **training.pop("lora", {})}
+ return SoupConfig(
+ base="test/model",
+ task=task,
+ backend=backend,
+ modality=modality,
+ data={"train": "tests/fixtures/sample_train.jsonl", **(data or {})},
+ training={"fast_lora": True, "lora": lora, **training},
+ )
+
+
+def _refusal(**kwargs) -> str:
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError) as excinfo:
+ _cfg(**kwargs)
+ return str(excinfo.value)
+
+
+# ─── The flag and what it refuses ────────────────────────────────────────────
+
+
+class TestTheFlag:
+ def test_it_is_off_unless_asked_for(self):
+ from soup_cli.config.schema import TrainingConfig
+
+ assert TrainingConfig().fast_lora is False
+
+ @pytest.mark.parametrize("quantization", ["none", "4bit"])
+ def test_the_first_slice_loads(self, quantization):
+ assert _cfg(quantization=quantization).training.fast_lora is True
+
+ def test_the_default_lora_dropout_is_refused_with_the_way_out(self):
+ from pydantic import ValidationError
+
+ from soup_cli.config.schema import SoupConfig
+
+ with pytest.raises(ValidationError) as excinfo:
+ SoupConfig(
+ base="test/model",
+ data={"train": "tests/fixtures/sample_train.jsonl"},
+ training={"fast_lora": True},
+ )
+ message = str(excinfo.value)
+ assert "training.fast_lora needs lora.dropout: 0" in message
+ assert "Soup's default is 0.05" in message
+
+ def test_another_backend_is_refused(self):
+ assert "training.fast_lora needs backend='transformers'" in _refusal(backend="unsloth")
+
+ def test_another_modality_is_refused(self):
+ assert "training.fast_lora supports modality='text' only" in _refusal(
+ modality="vision", data={"format": "llava"}
+ )
+
+ @pytest.mark.parametrize("task", ["dpo", "orpo", "kto"])
+ def test_another_task_is_refused(self, task):
+ data = {"format": "kto" if task == "kto" else "dpo"}
+ assert "training.fast_lora supports task='sft' only" in _refusal(task=task, data=data)
+
+ def test_no_lora_is_refused(self):
+ assert "training.fast_lora needs a LoRA; lora.r=0" in _refusal(
+ quantization="none", lora={"r": 0}
+ )
+
+ @pytest.mark.parametrize("adapter", ["use_dora", "use_vera"])
+ def test_another_adapter_is_refused(self, adapter):
+ assert f"training.fast_lora cannot be combined with lora.{adapter}" in _refusal(
+ quantization="none", lora={adapter: True}
+ )
+
+ def test_target_parameters_are_refused(self):
+ assert "cannot be combined with lora.target_parameters" in _refusal(
+ quantization="none", lora={"target_parameters": ["mlp.experts.gate_up_proj"]}
+ )
+
+ @pytest.mark.parametrize("quantization", ["8bit", "gptq"])
+ def test_another_quantization_is_refused(self, quantization):
+ assert "training.fast_lora supports quantization 'none' or '4bit'" in _refusal(
+ quantization=quantization
+ )
+
+ def test_use_liger_is_refused(self):
+ assert "training.fast_lora cannot be combined with training.use_liger" in _refusal(
+ use_liger=True
+ )
+
+ @pytest.mark.parametrize(
+ ("field", "value"),
+ [("unfrozen_parameters", ["model.layers.0.mlp"]), ("lisa_enabled", True)],
+ ids=["spectrum", "lisa"],
+ )
+ def test_a_full_fine_tuning_mode_is_refused(self, field, value):
+ """They train the model's own weights and skip the LoRA setup the
+ kernels hook into, so the flag would be ignored. The default rank 64,
+ as a user who sets only these would have it."""
+ from pydantic import ValidationError
+
+ from soup_cli.config.schema import SoupConfig
+
+ kwargs = {
+ "base": "test/model",
+ "data": {"train": "tests/fixtures/sample_train.jsonl"},
+ }
+ training = {"quantization": "none", "lora": {"dropout": 0.0}, field: value}
+ SoupConfig(**kwargs, training=training) # the premise: it loads without the flag
+ with pytest.raises(ValidationError) as excinfo:
+ SoupConfig(**kwargs, training={**training, "fast_lora": True})
+ assert f"training.fast_lora cannot be combined with training.{field}" in str(excinfo.value)
+
+ def test_fp8_training_is_refused(self):
+ assert (
+ "training.fast_lora cannot be combined with training.quantization_aware='fp8'"
+ in _refusal(quantization="none", quantization_aware="fp8")
+ )
+
+
+# ─── The switch on a model ───────────────────────────────────────────────────
+
+
+def _model(seed=0, dtype=None, hidden=32):
+ from peft import LoraConfig, get_peft_model
+ from transformers import LlamaConfig, LlamaForCausalLM
+
+ torch.manual_seed(seed)
+ config = LlamaConfig(
+ vocab_size=64,
+ hidden_size=hidden,
+ intermediate_size=2 * hidden,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ num_key_value_heads=4,
+ max_position_embeddings=64,
+ )
+ lora = LoraConfig(r=4, lora_alpha=8, lora_dropout=0.0, bias="none", target_modules=TARGETS)
+ model = get_peft_model(LlamaForCausalLM(config), lora)
+ with torch.no_grad(): # a trained adapter: lora_B at zero would hide a wrong path
+ for name, param in model.named_parameters():
+ if "lora_B" in name:
+ param.normal_(std=0.1)
+ return model.to(dtype) if dtype is not None else model
+
+
+def _pair(**kwargs):
+ """The same model twice; the second has the switch on."""
+ from soup_cli.utils.peft_wiring import apply_fast_lora_patches
+
+ plain, fast = _model(**kwargs), _model(**kwargs)
+ counts = apply_fast_lora_patches(fast, ON)
+ return plain, fast, counts
+
+
+def _ids(seed=1):
+ torch.manual_seed(seed)
+ return torch.randint(0, 64, (2, 7))
+
+
+def _lora_grads(model):
+ return {n: p.grad.detach().clone() for n, p in model.named_parameters() if "lora_" in n}
+
+
+class TestTheSwitch:
+ def test_off_leaves_peft_alone(self):
+ from soup_cli.utils.peft_wiring import apply_fast_lora_patches
+
+ model = _model()
+ assert apply_fast_lora_patches(model, OFF) is None
+ assert not any("forward" in vars(m) for m in model.modules())
+
+ def test_on_puts_every_kernel_on_its_modules(self):
+ _, fast, counts = _pair()
+
+ # Two layers: q/k/v and the MLP are each one group per layer, and o_proj
+ # is the only projection left for the single-projection kernel.
+ assert counts == {"q/k/v": 2, "MLP": 2, "single projection": 2}
+ layer = fast.base_model.model.model.layers[0]
+ x = torch.randn(1, 3, 32, requires_grad=True)
+ assert "Fast" in type(layer.self_attn.o_proj(x).grad_fn).__name__
+ assert "Fast" in type(layer.mlp(x).grad_fn).__name__
+
+ def test_on_with_nothing_to_patch_is_refused(self):
+ from soup_cli.utils.peft_wiring import apply_fast_lora_patches
+
+ with pytest.raises(ValueError, match="no LoRA module was patched"):
+ apply_fast_lora_patches(torch.nn.Sequential(torch.nn.Linear(4, 4)), ON)
+
+ def test_a_conv1d_only_model_is_refused(self):
+ """GPT-2's Conv1D LoRA (``fan_in_fan_out``) is patched but delegates to
+ peft on every call: nothing the kernels can run, so the switch refuses
+ and takes its patches off."""
+ from peft import LoraConfig, get_peft_model
+ from transformers import GPT2Config, GPT2LMHeadModel
+
+ from soup_cli.utils.peft_wiring import apply_fast_lora_patches
+
+ torch.manual_seed(0)
+ config = GPT2Config(vocab_size=64, n_positions=32, n_embd=16, n_layer=2, n_head=2)
+ lora = LoraConfig(r=4, lora_alpha=8, lora_dropout=0.0, target_modules=["c_attn"])
+ model = get_peft_model(GPT2LMHeadModel(config), lora)
+
+ with pytest.raises(ValueError, match="no LoRA module was patched"):
+ apply_fast_lora_patches(model, ON)
+ assert not any("forward" in vars(m) for m in model.modules())
+
+ def test_the_setup_line_names_each_kernel(self):
+ from soup_cli.utils.peft_wiring import fast_lora_summary
+
+ line = fast_lora_summary({"q/k/v": 2, "MLP": 2, "single projection": 2})
+ assert line == "Fast-LoRA kernels on: 2 q/k/v, 2 MLP, 2 single projection"
+
+
+class TestParityThroughTheSwitch:
+ """fp32 against peft's own modules; forward and backward reported apart."""
+
+ def test_forward(self):
+ plain, fast, _ = _pair()
+ ids = _ids()
+
+ torch.testing.assert_close(fast(input_ids=ids).logits, plain(input_ids=ids).logits)
+
+ def test_backward(self):
+ plain, fast, _ = _pair()
+ ids = _ids()
+ for model in (plain, fast):
+ model(input_ids=ids, labels=ids).loss.backward()
+
+ plain_grads, fast_grads = _lora_grads(plain), _lora_grads(fast)
+ assert plain_grads.keys() == fast_grads.keys() and len(plain_grads) == 28
+ for name in plain_grads:
+ torch.testing.assert_close(fast_grads[name], plain_grads[name], msg=name)
+
+ def test_gradients_are_the_same_with_non_reentrant_checkpointing(self):
+ _, fast, _ = _pair()
+ _, checkpointed, _ = _pair()
+ checkpointed.base_model.model.gradient_checkpointing_enable(
+ gradient_checkpointing_kwargs={"use_reentrant": False}
+ )
+ checkpointed.train()
+ fast.train()
+ ids = _ids()
+ for model in (fast, checkpointed):
+ model(input_ids=ids, labels=ids).loss.backward()
+
+ for name, grad in _lora_grads(fast).items():
+ torch.testing.assert_close(_lora_grads(checkpointed)[name], grad, msg=name)
+
+ def test_with_the_adapter_disabled_the_output_is_the_base_models(self):
+ plain, fast, _ = _pair()
+ ids = _ids()
+ with fast.disable_adapter():
+ fast_base = fast(input_ids=ids).logits
+ with plain.disable_adapter():
+ plain_base = plain(input_ids=ids).logits
+
+ torch.testing.assert_close(fast_base, plain_base)
+ assert not torch.allclose(fast(input_ids=ids).logits, fast_base) # the premise
+
+ @pytest.mark.parametrize("path", ["o_proj", "mlp", "self_attn"])
+ def test_gradcheck_in_float64(self, path):
+ """Per kernel, w.r.t. its input and its LoRA A and B, with the base
+ weight frozen. (Not through the whole model: Llama's RMSNorm runs in
+ float32 whatever the model's dtype, so peft fails that check too.)"""
+ from torch.func import functional_call
+
+ _, fast, _ = _pair(dtype=torch.float64, hidden=16)
+ decoder = fast.base_model.model.model
+ layer = decoder.layers[0]
+ module = layer.self_attn.o_proj if path == "o_proj" else getattr(layer, path)
+ lora = {
+ n: p.detach().clone().requires_grad_(True)
+ for n, p in module.named_parameters()
+ if "lora_" in n
+ }
+ names = list(lora)
+ torch.manual_seed(2)
+ x = torch.randn(1, 3, 16, dtype=torch.float64, requires_grad=True)
+ kwargs = {}
+ if path == "self_attn":
+ positions = torch.arange(3).unsqueeze(0)
+ kwargs = {
+ "position_embeddings": decoder.rotary_emb(x, positions),
+ "attention_mask": None,
+ }
+
+ def run(inputs, *params):
+ out = functional_call(module, dict(zip(names, params)), (inputs,), kwargs)
+ return out[0] if isinstance(out, tuple) else out
+
+ assert len(names) >= 2
+ assert torch.autograd.gradcheck(run, (x, *lora.values()), eps=1e-6, atol=1e-5)
+
+ def test_fifty_steps_lose_the_same_to_three_decimals(self):
+ """One batch, fifty AdamW steps at lr 1e-3. (At lr 1e-2 the two runs
+ stay bit-identical for 33 steps and then part, as any two float32 runs
+ whose last bits differ do under AdamW at that rate.)"""
+ plain, fast, _ = _pair()
+ torch.manual_seed(3)
+ ids = torch.randint(0, 64, (2, 9))
+ losses = {}
+ for name, model in (("plain", plain), ("fast", fast)):
+ params = [p for p in model.parameters() if p.requires_grad]
+ optimizer = torch.optim.AdamW(params, lr=1e-3)
+ losses[name] = []
+ for _ in range(50):
+ loss = model(input_ids=ids, labels=ids).loss
+ optimizer.zero_grad()
+ loss.backward()
+ optimizer.step()
+ losses[name].append(loss.item())
+
+ # Equal to 3 decimals: never 1e-3 apart (rounding each to 3 places would
+ # call 4.1935 and 4.1934 different).
+ gap = max(abs(f - p) for f, p in zip(losses["fast"], losses["plain"]))
+ CONSOLE.print(json.dumps({"fifty_step_max_loss_gap": gap}))
+ assert gap < 1e-3
+ assert losses["plain"][-1] < losses["plain"][0] - 0.1 # it trained
+
+
+# ─── Through the real SFT setup ──────────────────────────────────────────────
+
+
+def _sft_rows(n=4):
+ return [
+ {
+ "messages": [
+ {"role": "user", "content": "hello"},
+ {"role": "assistant", "content": "world"},
+ ]
+ }
+ ] * n
+
+
+def _resident_wrapper(tmp_path, monkeypatch, *, fast_lora):
+ import yaml
+
+ from soup_cli.config.loader import load_config_from_string
+ from soup_cli.trainer.sft import SFTTrainerWrapper
+ from tests._tiny_hf_models import tiny_model_dir
+
+ monkeypatch.chdir(tmp_path)
+ cfg = load_config_from_string(
+ yaml.safe_dump(
+ {
+ "base": tiny_model_dir("llama"),
+ "task": "sft",
+ "backend": "transformers",
+ "data": {"train": "unused.jsonl", "max_length": 64, "chat_template": "chatml"},
+ "training": {
+ "epochs": 1,
+ "batch_size": 2,
+ "quantization": "none",
+ "fast_lora": fast_lora,
+ "lora": {"r": 4, "alpha": 8, "dropout": 0.0, "target_modules": TARGETS},
+ },
+ "output": str(tmp_path / "out"),
+ }
+ )
+ )
+ wrapper = SFTTrainerWrapper(cfg, device="cpu")
+ wrapper.setup({"train": _sft_rows()})
+ return wrapper
+
+
+def _kernel_nodes(model):
+ return {type(m).__name__ for m in model.modules() if "forward" in vars(m)}
+
+
+class TestTheResidentSetup:
+ def test_the_switch_reaches_the_model_the_trainer_trains(self, tmp_path, monkeypatch, capsys):
+ wrapper = _resident_wrapper(tmp_path, monkeypatch, fast_lora=True)
+
+ modules = dict(wrapper.trainer.model.named_modules())
+ patched = [n for n, m in modules.items() if "forward" in vars(m)]
+ assert any(
+ hasattr(m, "_soup_fast_lora_qkv") for n, m in modules.items() if n.endswith("self_attn")
+ )
+ assert any(n.endswith("mlp") for n in patched)
+ assert any(n.endswith("o_proj") for n in patched)
+ assert "Fast-LoRA kernels on:" in capsys.readouterr().out
+
+ def test_without_the_switch_nothing_is_patched(self, tmp_path, monkeypatch):
+ wrapper = _resident_wrapper(tmp_path, monkeypatch, fast_lora=False)
+
+ assert not any("forward" in vars(m) for m in wrapper.trainer.model.modules())
+
+
+class TestAFailedPatchReleasesTheStreamedRuntime:
+ """The switch runs after the runtime is built and before training's
+ cleanup context starts: a failure there closes the runtime itself."""
+
+ def _setup(self, tmp_path, monkeypatch):
+ """The real streamed setup; returns, for each close, whether a runtime
+ was there to close."""
+ from soup_cli.trainer.stream_setup import StreamingSetupMixin
+ from tests.test_v07204 import _build_streamed_wrapper
+
+ closes = []
+ real_close = StreamingSetupMixin._close_stream_runtime
+
+ def counting_close(self):
+ closes.append(getattr(self, "_stream_runtime", None) is not None)
+ return real_close(self)
+
+ monkeypatch.setattr(StreamingSetupMixin, "_close_stream_runtime", counting_close)
+ with pytest.raises(Exception) as excinfo:
+ _build_streamed_wrapper(
+ tmp_path,
+ monkeypatch,
+ task="sft",
+ n_layers=2,
+ device="cpu",
+ tie=False,
+ fast_lora=True,
+ lora={"r": 4, "alpha": 8, "dropout": 0.0, "target_modules": TARGETS},
+ )
+ return closes, excinfo.value
+
+ def test_nothing_patched(self, tmp_path, monkeypatch):
+ from soup_cli.utils import fast_lora, fast_lora_mlp, fast_lora_qkv
+
+ monkeypatch.setattr(fast_lora_qkv, "patch_fast_lora_qkv", lambda model: 0)
+ monkeypatch.setattr(fast_lora_mlp, "patch_fast_lora_mlp", lambda model: 0)
+ monkeypatch.setattr(fast_lora, "patch_fast_lora_single_projection", lambda model: 0)
+ monkeypatch.setattr(fast_lora, "eligible_single_projections", lambda model: 0)
+
+ closes, error = self._setup(tmp_path, monkeypatch)
+
+ assert "no LoRA module was patched" in str(error)
+ assert closes == [True]
+
+ def test_a_patcher_that_raises(self, tmp_path, monkeypatch):
+ from soup_cli.utils import fast_lora_qkv
+
+ def boom(model):
+ raise RuntimeError("patcher failed")
+
+ monkeypatch.setattr(fast_lora_qkv, "patch_fast_lora_qkv", boom)
+
+ closes, error = self._setup(tmp_path, monkeypatch)
+
+ assert str(error) == "patcher failed"
+ assert closes == [True]
+
+
+class TestTheStreamedSetup:
+ """A streamed tiny Llama with more layers than ``stream_buffers``: the LoRA
+ gradients on every layer equal those of the same run without the switch."""
+
+ def _grads(self, tmp_path, monkeypatch, fast_lora):
+ from tests.test_v07204 import _build_streamed_wrapper
+
+ wrapper, _, _ = _build_streamed_wrapper(
+ tmp_path,
+ monkeypatch,
+ task="sft",
+ n_layers=4,
+ device="cpu",
+ tie=False,
+ stream_buffers=2,
+ fast_lora=fast_lora,
+ lora={"r": 4, "alpha": 8, "dropout": 0.0, "target_modules": TARGETS},
+ )
+ try:
+ with torch.no_grad():
+ for name, param in wrapper.model.named_parameters():
+ if "lora_B" in name:
+ torch.manual_seed(abs(hash(name)) % 2**31)
+ param.normal_(std=0.1)
+ ids = torch.tensor([[1, 5, 9, 13, 2, 7, 11]])
+ out = wrapper.model(input_ids=ids, labels=ids)
+ out.loss.backward()
+ patched = sum("forward" in vars(m) for m in wrapper.model.modules())
+ return _lora_grads(wrapper.model), patched
+ finally:
+ wrapper._close_stream_runtime()
+
+ def test_every_layers_gradients_match_without_the_switch(self, tmp_path, monkeypatch):
+ plain, plain_patched = self._grads(tmp_path / "plain", monkeypatch, False)
+ fast, fast_patched = self._grads(tmp_path / "fast", monkeypatch, True)
+
+ assert plain_patched < fast_patched # the premise: the kernels are on
+ layers = {name.split(".layers.")[1].split(".")[0] for name in fast if ".layers." in name}
+ assert layers == {"0", "1", "2", "3"}
+ assert plain.keys() == fast.keys()
+ for name in plain:
+ assert torch.count_nonzero(plain[name]) > 0, name
+ torch.testing.assert_close(fast[name], plain[name], msg=name)
+
+
+# ─── Rows that need CUDA (not run on CPU CI) ─────────────────────────────────
+
+
+def _half_error(dtype):
+ """Max-abs error of the fast and the peft path against float64, per output."""
+ plain, fast, _ = _pair()
+ reference = _model().double()
+ ids = _ids().cuda()
+ plain, fast, reference = plain.cuda().to(dtype), fast.cuda().to(dtype), reference.cuda()
+ want = reference(input_ids=ids).logits
+ plain_err = (plain(input_ids=ids).logits.double() - want).abs().max().item()
+ fast_err = (fast(input_ids=ids).logits.double() - want).abs().max().item()
+ return plain_err, fast_err
+
+
[email protected]("dtype", ["bfloat16", "float16"])
+def test_half_precision_forward_error_is_within_twice_peft(dtype):
+ plain_err, fast_err = _half_error(getattr(torch, dtype))
+ CONSOLE.print(json.dumps({"dtype": dtype, "peft_max_abs": plain_err, "fast_max_abs": fast_err}))
+ assert fast_err <= 2 * plain_err
+
+
[email protected]("dtype", ["bfloat16", "float16"])
+def test_half_precision_backward_error_is_within_twice_peft(dtype):
+ dtype = getattr(torch, dtype)
+ plain, fast, _ = _pair()
+ reference = _model().double().cuda()
+ ids = _ids().cuda()
+ reference(input_ids=ids, labels=ids).loss.backward()
+ want = _lora_grads(reference)
+ errors = {}
+ for name, model in (("peft", plain), ("fast", fast)):
+ model = model.cuda().to(dtype)
+ model(input_ids=ids, labels=ids).loss.backward()
+ got = _lora_grads(model)
+ errors[name] = max((got[n].double() - want[n]).abs().max().item() for n in want)
+ CONSOLE.print(json.dumps({"dtype": str(dtype), **errors}))
+ assert errors["fast"] <= 2 * errors["peft"]
+
+
+def test_nf4_matches_peft_over_the_same_linear4bit(tmp_path, monkeypatch):
+ """Reference: unpatched peft over the same NF4 model, never bf16."""
+ plain = _resident_wrapper_4bit(tmp_path / "plain", monkeypatch, fast_lora=False)
+ fast = _resident_wrapper_4bit(tmp_path / "fast", monkeypatch, fast_lora=True)
+ ids = torch.tensor([[1, 5, 9, 13, 2, 7, 11]], device="cuda")
+ for model in (plain, fast):
+ model(input_ids=ids, labels=ids).loss.backward()
+ torch.testing.assert_close(fast(input_ids=ids).logits, plain(input_ids=ids).logits)
+ for name, grad in _lora_grads(plain).items():
+ torch.testing.assert_close(_lora_grads(fast)[name], grad, msg=name)
+
+
+def _resident_wrapper_4bit(tmp_path, monkeypatch, *, fast_lora):
+ import yaml
+
+ from soup_cli.config.loader import load_config_from_string
+ from soup_cli.trainer.sft import SFTTrainerWrapper
+ from tests._tiny_hf_models import tiny_model_dir
+
+ tmp_path.mkdir(parents=True, exist_ok=True)
+ monkeypatch.chdir(tmp_path)
+ cfg = load_config_from_string(
+ yaml.safe_dump(
+ {
+ "base": tiny_model_dir("llama"),
+ "task": "sft",
+ "data": {"train": "unused.jsonl", "max_length": 64, "chat_template": "chatml"},
+ "training": {
+ "epochs": 1,
+ "batch_size": 2,
+ "quantization": "4bit",
+ "fast_lora": fast_lora,
+ "lora": {"r": 4, "alpha": 8, "dropout": 0.0, "target_modules": TARGETS},
+ },
+ "output": str(tmp_path / "out"),
+ }
+ )
+ )
+ wrapper = SFTTrainerWrapper(cfg, device="cuda")
+ wrapper.setup({"train": _sft_rows()})
+ torch.manual_seed(4)
+ with torch.no_grad():
+ for name, param in wrapper.model.named_parameters():
+ if "lora_B" in name:
+ param.normal_(std=0.1)
+ return wrapper.model
+
+
[email protected]("quantization", ["none", "4bit"])
+def test_streamed_on_cuda_every_layer_matches(tmp_path, monkeypatch, quantization):
+ """bf16 and NF4 on the GPU, streamed on both sides (#776: streamed NF4 and
+ resident NF4 are not bit-exact on sm_120)."""
+ from tests.test_v07204 import _build_streamed_wrapper
+
+ grads = {}
+ for name, flag in (("plain", False), ("fast", True)):
+ wrapper, _, _ = _build_streamed_wrapper(
+ tmp_path / name,
+ monkeypatch,
+ task="sft",
+ n_layers=4,
+ device="cuda",
+ tie=False,
+ stream_buffers=2,
+ quantization=quantization,
+ fast_lora=flag,
+ lora={"r": 4, "alpha": 8, "dropout": 0.0, "target_modules": TARGETS},
+ )
+ try:
+ torch.manual_seed(5)
+ with torch.no_grad():
+ for pname, param in wrapper.model.named_parameters():
+ if "lora_B" in pname:
+ param.normal_(std=0.1)
+ ids = torch.tensor([[1, 5, 9, 13, 2, 7, 11]], device="cuda")
+ wrapper.model(input_ids=ids, labels=ids).loss.backward()
+ grads[name] = _lora_grads(wrapper.model)
+ finally:
+ wrapper._close_stream_runtime()
+ for pname, grad in grads["plain"].items():
+ torch.testing.assert_close(grads["fast"][pname], grad, msg=pname)