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): shared-X Fast-LoRA QKV autograd (#838) (#1108)

AmixDigital1f0ad43fbd9e
diff --git a/src/soup_cli/utils/fast_lora.py b/src/soup_cli/utils/fast_lora.py
index 53f70bec..6f50eb72 100644
--- a/src/soup_cli/utils/fast_lora.py
+++ b/src/soup_cli/utils/fast_lora.py
@@ -39,6 +39,8 @@ logger = logging.getLogger(__name__)
_PATCH_MARKER = "_soup_fast_lora_single_projection"
_ORIGINAL_FORWARD_MARKER = "_soup_fast_lora_original_forward"
+_GROUP_PATCH_OWNER_MARKER = "_soup_fast_lora_group_owner"
+_FORWARD_OWNER_MARKER = "_soup_fast_lora_forward_owner"
__all__ = [
"patch_fast_lora_single_projection",
@@ -420,6 +422,8 @@ def patch_fast_lora_single_projection(model: Any) -> int:
for child in model.modules():
if getattr(child, _PATCH_MARKER, False):
continue
+ if getattr(child, _GROUP_PATCH_OWNER_MARKER, None) is not None:
+ continue
if isinstance(child, types_to_match):
targets.append(child)
diff --git a/src/soup_cli/utils/fast_lora_qkv.py b/src/soup_cli/utils/fast_lora_qkv.py
new file mode 100644
index 00000000..33b72c0b
--- /dev/null
+++ b/src/soup_cli/utils/fast_lora_qkv.py
@@ -0,0 +1,349 @@
+"""Fast-LoRA shared-X Q/K/V autograd path for issue #838.
+
+The q projection computes Q/K/V together and caches K/V only until the next
+two projection calls with the identical input object. Cross-attention calls
+that use a different key/value tensor delegate to PEFT; the speculative K/V
+computed by q_proj are then discarded. This avoids copying architecture-
+specific attention forwards while still sharing one X@A_cat.T GEMM.
+
+A lone q_proj call intentionally retains one {x, k, v} graph until the next q
+call or unpatch. That is bounded to one attention module rather than a leak,
+but callers doing projection-only probes should unpatch or issue the normal
+k/v calls so the short-lived cache is drained.
+"""
+
+from __future__ import annotations
+
+import types
+from typing import Any
+
+from soup_cli.utils.fast_lora import (
+ _FORWARD_OWNER_MARKER,
+ _GROUP_PATCH_OWNER_MARKER,
+ _as_dtype,
+ _dense_weight,
+ _flatten,
+ _is_supported_lora_projection,
+ _projection_state,
+ _scaled_lora_add,
+)
+
+_PATCH_MARKER = "_soup_fast_lora_qkv"
+_SINGLE_PROJECTION_PATCH_MARKER = "_soup_fast_lora_single_projection"
+_CACHE_MARKER = "_soup_fast_lora_qkv_cache"
+_CACHE_HIT_MARKER = "_soup_fast_lora_qkv_last_cache_hits"
+_RESTORE_MARKER = "_soup_fast_lora_qkv_restore"
+_OWNER = "qkv"
+_FUNCTION: Any = None
+
+__all__ = ["patch_fast_lora_qkv", "unpatch_fast_lora_qkv"]
+
+
+def _qkv_function() -> Any:
+ global _FUNCTION
+ if _FUNCTION is not None:
+ return _FUNCTION
+
+ import torch
+ import torch.nn.functional as functional
+
+ class _FastLoraQKV(torch.autograd.Function):
+ @staticmethod
+ def forward(
+ ctx, x, wq, bq, wk, bk, wv, bv,
+ aq, bql, ak, bkl, av, bvl,
+ sq, sk, sv, qq_meta, qk_meta, qv_meta, *qparts,
+ ):
+ metas = (qq_meta, qk_meta, qv_meta)
+ counts = [0 if meta is None else int(meta["_count"]) for meta in metas]
+ starts = (0, counts[0], counts[0] + counts[1])
+ qlists = [
+ list(qparts[starts[i] : starts[i] + counts[i]]) for i in range(3)
+ ]
+ weights = (wq, wk, wv)
+ biases = (bq, bk, bv)
+ outs = []
+ for weight, bias, meta, parts in zip(weights, biases, metas, qlists):
+ dense = _dense_weight(weight, meta, parts, x.dtype)
+ outs.append(
+ functional.linear(
+ x, dense, _as_dtype(bias, x.dtype) if bias is not None else None
+ )
+ )
+ del dense
+
+ adapters = ((aq, bql, sq), (ak, bkl, sk), (av, bvl, sv))
+ ranks = [a.shape[0] if a.numel() else 0 for a, _b, _s in adapters]
+ present = [i for i, rank in enumerate(ranks) if rank]
+ if present:
+ a_cat = torch.cat([adapters[i][0] for i in present], dim=0)
+ h = functional.linear(_as_dtype(x, a_cat.dtype), a_cat)
+ cursor = 0
+ for i in present:
+ a, b, scaling = adapters[i]
+ rank = a.shape[0]
+ hi = h[..., cursor : cursor + rank]
+ outs[i] = _scaled_lora_add(outs[i], hi, b, scaling)
+ cursor += rank
+ else:
+ h = x.new_empty((*x.shape[:-1], 0))
+
+ ctx.ranks = ranks
+ ctx.present = present
+ ctx.scalings = (float(sq), float(sk), float(sv))
+ ctx.qmetas = metas
+ ctx.qcounts = counts
+ ctx.qparts_len = len(qparts)
+
+ ctx.save_for_backward(
+ x, wq, wk, wv, aq, bql, ak, bkl, av, bvl, h, *qparts
+ )
+ return tuple(outs)
+
+ @staticmethod
+ @torch.autograd.function.once_differentiable
+ def backward(ctx, grad_q, grad_k, grad_v):
+ saved = ctx.saved_tensors
+ x, wq, wk, wv, aq, bql, ak, bkl, av, bvl, h = saved[:11]
+ qparts = list(saved[11:])
+ grads_out = (grad_q, grad_k, grad_v)
+ weights = (wq, wk, wv)
+ adapters = ((aq, bql), (ak, bkl), (av, bvl))
+ sq, sk, sv = ctx.scalings
+ scalings = (sq, sk, sv)
+ cq, ck, cv = ctx.qcounts
+ qlists = (
+ qparts[:cq],
+ qparts[cq : cq + ck],
+ qparts[cq + ck : cq + ck + cv],
+ )
+
+ grad_x = None
+ for grad, weight, meta, parts in zip(
+ grads_out, weights, ctx.qmetas, qlists
+ ):
+ dense = _dense_weight(weight, meta, parts, grad.dtype)
+ term = torch.matmul(grad, dense)
+
+ grad_x = term if grad_x is None else torch.add(grad_x, term)
+ del dense
+
+ grad_as = [None, None, None]
+ grad_bs = [None, None, None]
+ if ctx.present:
+ dh_parts = []
+ cursor = 0
+ for i in ctx.present:
+ a, b = adapters[i]
+ grad = grads_out[i]
+ rank = ctx.ranks[i]
+ hi = h[..., cursor : cursor + rank]
+ grad_bs[i] = (
+ _flatten(_as_dtype(grad, hi.dtype)).t() @ _flatten(hi)
+ * scalings[i]
+ )
+ dhi = torch.matmul(_as_dtype(grad, b.dtype), b) * scalings[i]
+ dh_parts.append(dhi)
+ cursor += rank
+
+ dh = torch.cat(dh_parts, dim=-1)
+ a_cat = torch.cat([adapters[i][0] for i in ctx.present], dim=0)
+ grad_a_cat = _flatten(dh).t() @ _as_dtype(_flatten(x), dh.dtype)
+ grad_x = torch.add(
+ grad_x,
+ torch.matmul(_as_dtype(dh, grad_x.dtype), _as_dtype(a_cat, grad_x.dtype)),
+ )
+ cursor = 0
+
+ for i in ctx.present:
+ rank = ctx.ranks[i]
+ grad_as[i] = grad_a_cat[cursor : cursor + rank]
+ cursor += rank
+
+ result = [
+ grad_x,
+ None, None, None, None, None, None,
+ grad_as[0], grad_bs[0],
+ grad_as[1], grad_bs[1],
+ grad_as[2], grad_bs[2],
+ None, None, None, None, None, None,
+ ]
+ result.extend([None] * ctx.qparts_len)
+ return tuple(result)
+
+ _FUNCTION = _FastLoraQKV
+ return _FUNCTION
+
+
+def _install_attention_patch(attn: Any) -> None:
+ fast = _qkv_function()
+ projections = {name: getattr(attn, name) for name in ("q_proj", "k_proj", "v_proj")}
+ originals = {name: proj.forward for name, proj in projections.items()}
+ restore = {
+ name: ("forward" in proj.__dict__, proj.__dict__.get("forward"))
+ for name, proj in projections.items()
+ }
+
+ def q_forward(_proj, x, *args, **kwargs):
+ setattr(attn, _CACHE_MARKER, None)
+ setattr(attn, _CACHE_HIT_MARKER, (0, ()))
+ if args or kwargs:
+ return originals["q_proj"](x, *args, **kwargs)
+ states = [
+ _projection_state(getattr(attn, name), x, allow_unadapted=True)
+ for name in ("q_proj", "k_proj", "v_proj")
+ ]
+ if any(state is None for state in states):
+ return originals["q_proj"](x)
+ q, k, v = states
+ compute_dtypes = {
+ state.compute_dtype for state in states if state.compute_dtype is not None
+ }
+ if len(compute_dtypes) > 1:
+ return originals["q_proj"](x)
+
+ input_dtype = x.dtype
+ work_x = x
+ if compute_dtypes:
+ compute_dtype = next(iter(compute_dtypes))
+ if work_x.dtype != compute_dtype:
+ work_x = work_x.to(compute_dtype)
+
+ qparts = [*q.qparts, *k.qparts, *v.qparts]
+ q_out, k_out, v_out = fast.apply(
+ work_x,
+ q.weight, q.bias, k.weight, k.bias, v.weight, v.bias,
+ q.lora_a, q.lora_b, k.lora_a, k.lora_b, v.lora_a, v.lora_b,
+ q.scaling, k.scaling, v.scaling,
+ q.qmeta, k.qmeta, v.qmeta,
+ *qparts,
+ )
+ if work_x is not x:
+ q_out = q_out.to(input_dtype)
+ k_out = k_out.to(input_dtype)
+ v_out = v_out.to(input_dtype)
+
+ setattr(
+ attn,
+ _CACHE_MARKER,
+ {
+ "x": x,
+ "k": k_out,
+ "v": v_out,
+ "hits": 0,
+ "grad_fns": [type(q_out.grad_fn).__name__],
+ },
+ )
+ return q_out
+
+ def k_forward(_proj, x, *args, **kwargs):
+ cache = getattr(attn, _CACHE_MARKER, None)
+ if not args and not kwargs and cache is not None and cache.get("x") is x and "k" in cache:
+ out = cache.pop("k")
+ cache["hits"] += 1
+ cache["grad_fns"].append(type(out.grad_fn).__name__)
+ return out
+ setattr(attn, _CACHE_MARKER, None)
+ setattr(attn, _CACHE_HIT_MARKER, (0, ()))
+ return originals["k_proj"](x, *args, **kwargs)
+
+ def v_forward(_proj, x, *args, **kwargs):
+ cache = getattr(attn, _CACHE_MARKER, None)
+ if not args and not kwargs and cache is not None and cache.get("x") is x and "v" in cache:
+ out = cache.pop("v")
+ cache["hits"] += 1
+ cache["grad_fns"].append(type(out.grad_fn).__name__)
+ setattr(attn, _CACHE_HIT_MARKER, (cache["hits"], tuple(cache["grad_fns"])))
+ setattr(attn, _CACHE_MARKER, None)
+ return out
+ setattr(attn, _CACHE_MARKER, None)
+ setattr(attn, _CACHE_HIT_MARKER, (0, ()))
+ return originals["v_proj"](x, *args, **kwargs)
+
+ for forward in (q_forward, k_forward, v_forward):
+ setattr(forward, _FORWARD_OWNER_MARKER, _OWNER)
+ for name, forward in (
+ ("q_proj", q_forward),
+ ("k_proj", k_forward),
+ ("v_proj", v_forward),
+ ):
+ projection = projections[name]
+ setattr(projection, _GROUP_PATCH_OWNER_MARKER, _OWNER)
+ projection.forward = types.MethodType(forward, projection)
+ setattr(attn, "_soup_fast_lora_qkv_originals", originals)
+ setattr(attn, _RESTORE_MARKER, restore)
+ setattr(attn, _PATCH_MARKER, True)
+
+
+def patch_fast_lora_qkv(model: Any) -> int:
+ """Patch structural q_proj/k_proj/v_proj attention modules."""
+ count = 0
+ for module in model.modules():
+ if getattr(module, _PATCH_MARKER, False):
+ continue
+ if not all(hasattr(module, name) for name in ("q_proj", "k_proj", "v_proj")):
+ continue
+ if not any(
+ hasattr(getattr(module, name), "lora_A")
+ for name in ("q_proj", "k_proj", "v_proj")
+ ):
+ continue
+ projections = [
+ getattr(module, name) for name in ("q_proj", "k_proj", "v_proj")
+ ]
+ # Shared-X fusion is only valid when Q, K and V consume the same-width
+ # tensor. Cross-attention modules such as TrOCR use a narrower memory
+ # input for K/V; patching them would make q_proj speculatively apply the
+ # K/V weights to the query and fail before delegation can occur.
+ widths = {getattr(proj, "in_features", None) for proj in projections}
+ if len(widths) != 1 or None in widths:
+ continue
+ if any(hasattr(proj, "modules_to_save") for proj in projections):
+ continue
+ if any(
+ hasattr(proj, "lora_A") and not _is_supported_lora_projection(proj)
+ for proj in projections
+ ):
+ continue
+ if any(
+ getattr(proj, _GROUP_PATCH_OWNER_MARKER, None) is not None
+ for proj in projections
+ ):
+ continue
+ if any(
+ getattr(proj, _SINGLE_PROJECTION_PATCH_MARKER, False)
+ for proj in projections
+ ):
+ continue
+ _install_attention_patch(module)
+ count += 1
+ return count
+
+
+def unpatch_fast_lora_qkv(model: Any) -> int:
+ restored = 0
+ for module in model.modules():
+ originals = getattr(module, "_soup_fast_lora_qkv_originals", None)
+ restore = getattr(module, _RESTORE_MARKER, None)
+ if originals is None or restore is None or not getattr(module, _PATCH_MARKER, False):
+ continue
+ for name, (had_instance_forward, instance_forward) in restore.items():
+ proj = getattr(module, name)
+ if getattr(proj.forward, _FORWARD_OWNER_MARKER, None) == _OWNER:
+ if had_instance_forward:
+ proj.forward = instance_forward
+ elif "forward" in proj.__dict__:
+ delattr(proj, "forward")
+ if getattr(proj, _GROUP_PATCH_OWNER_MARKER, None) == _OWNER:
+ delattr(proj, _GROUP_PATCH_OWNER_MARKER)
+ for attr in (
+ _CACHE_MARKER,
+ _CACHE_HIT_MARKER,
+ "_soup_fast_lora_qkv_originals",
+ _RESTORE_MARKER,
+ _PATCH_MARKER,
+ ):
+ if hasattr(module, attr):
+ delattr(module, attr)
+ restored += 1
+ return restored
diff --git a/tests/test_issue838_fast_lora_qkv.py b/tests/test_issue838_fast_lora_qkv.py
new file mode 100644
index 00000000..dbba0a97
--- /dev/null
+++ b/tests/test_issue838_fast_lora_qkv.py
@@ -0,0 +1,887 @@
+"""#838: shared-X Fast-LoRA Q/K/V correctness tests."""
+
+from __future__ import annotations
+
+import copy
+import types
+
+import pytest
+
+pytestmark = pytest.mark.filterwarnings("ignore::DeprecationWarning")
+
+
+def _deps():
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("peft")
+ return torch
+
+
+def _randomise_b(model):
+ torch = _deps()
+ with torch.no_grad():
+ for name, param in model.named_parameters():
+ if "lora_B" in name:
+ torch.nn.init.normal_(param, std=0.2)
+
+
+def _make_model(targets, *, ranks=None, bias=True, modules_to_save=None, dropout=0.0):
+ _deps()
+ import torch.nn as nn
+ from peft import LoraConfig, inject_adapter_in_model
+
+ class TinyAttention(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.q_proj = nn.Linear(8, 8, bias=bias)
+ self.k_proj = nn.Linear(8, 4, bias=bias)
+ self.v_proj = nn.Linear(8, 4, bias=bias)
+
+ def forward(self, x):
+ return self.q_proj(x), self.k_proj(x), self.v_proj(x)
+
+ class Model(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.attn = TinyAttention()
+
+ def forward(self, x):
+ return self.attn(x)
+
+ model = Model()
+ inject_adapter_in_model(
+ LoraConfig(
+ r=2,
+ lora_alpha=4,
+ lora_dropout=dropout,
+ bias="none",
+ target_modules=list(targets),
+ rank_pattern=ranks or {},
+ modules_to_save=modules_to_save,
+ ),
+ model,
+ )
+ _randomise_b(model)
+ return model
+
+
+def _adapter_grads(model):
+ return {
+ name: param.grad.detach().clone()
+ for name, param in model.named_parameters()
+ if "lora_" in name and param.grad is not None
+ }
+
+
+class TestMath:
+ @pytest.mark.parametrize(
+ "ranks",
+ [
+ (2, 0, 3),
+ (2, 2, 2),
+ ],
+ )
+ def test_float64_gradcheck_gqa_shapes(self, ranks):
+ torch = _deps()
+ from soup_cli.utils.fast_lora_qkv import _qkv_function
+
+ torch.manual_seed(3)
+ x = torch.randn(5, 8, dtype=torch.float64, requires_grad=True)
+ wq = torch.randn(8, 8, dtype=torch.float64)
+ wk = torch.randn(4, 8, dtype=torch.float64)
+ wv = torch.randn(4, 8, dtype=torch.float64)
+ bq = torch.randn(8, dtype=torch.float64)
+ bk = torch.randn(4, dtype=torch.float64)
+ bv = torch.randn(4, dtype=torch.float64)
+
+ def pair(rank, out):
+ if rank == 0:
+ return x.new_empty(0), x.new_empty(0)
+ return (
+ torch.randn(rank, 8, dtype=torch.float64, requires_grad=True),
+ torch.randn(out, rank, dtype=torch.float64, requires_grad=True),
+ )
+
+ aq, bql = pair(ranks[0], 8)
+ ak, bkl = pair(ranks[1], 4)
+ av, bvl = pair(ranks[2], 4)
+ fn = _qkv_function()
+
+ variables = [x]
+ for a, b in ((aq, bql), (ak, bkl), (av, bvl)):
+ if a.numel():
+ variables += [a, b]
+
+ def call(*vals):
+ it = iter(vals)
+ x_ = next(it)
+ pairs = []
+ for a, b in ((aq, bql), (ak, bkl), (av, bvl)):
+ if a.numel():
+ pairs.append((next(it), next(it)))
+ else:
+ pairs.append((a, b))
+ (aq_, bq_), (ak_, bk_), (av_, bv_) = pairs
+ q, k, v = fn.apply(
+ x_, wq, bq, wk, bk, wv, bv,
+ aq_, bq_, ak_, bk_, av_, bv_,
+ 1.2, 0.8, 1.7, None, None, None,
+ )
+ return torch.cat((q, k, v), dim=-1)
+
+ assert torch.autograd.gradcheck(
+ call, tuple(variables), eps=1e-6, atol=1e-5, rtol=1e-4
+ )
+
+ @pytest.mark.parametrize(
+ "targets",
+ [
+ ("q_proj", "v_proj"),
+ ("q_proj", "k_proj", "v_proj"),
+ ("q_proj",),
+ ("v_proj",),
+ ],
+ )
+ def test_fp32_forward_and_backward_match_peft(self, targets):
+ torch = _deps()
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ torch.manual_seed(11)
+ model = _make_model(targets, bias=True)
+ x0 = torch.randn(2, 5, 8, requires_grad=True)
+ ref = model(x0)
+ ref_loss = sum(part.square().mean() for part in ref)
+ ref_loss.backward()
+ ref_x = x0.grad.detach().clone()
+ ref_grads = _adapter_grads(model)
+ for param in model.parameters():
+ param.grad = None
+
+ x1 = x0.detach().clone().requires_grad_(True)
+ assert patch_fast_lora_qkv(model) == 1
+ got = model(x1)
+ sum(part.square().mean() for part in got).backward()
+
+ for got_part, ref_part in zip(got, ref):
+ torch.testing.assert_close(got_part, ref_part)
+
+ torch.testing.assert_close(x1.grad, ref_x)
+ got_grads = _adapter_grads(model)
+ assert got_grads.keys() == ref_grads.keys()
+ for name, grad in got_grads.items():
+ torch.testing.assert_close(grad, ref_grads[name], msg=name)
+
+ def test_unequal_ranks_and_gqa_match_peft(self):
+ torch = _deps()
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ torch.manual_seed(19)
+ model = _make_model(
+ ("q_proj", "k_proj", "v_proj"),
+ ranks={"q_proj": 2, "k_proj": 3, "v_proj": 4},
+ )
+ actual = tuple(
+ model.attn.__getattr__(name).lora_A["default"].weight.shape[0]
+ for name in ("q_proj", "k_proj", "v_proj")
+ )
+ assert actual == (2, 3, 4)
+
+ x0 = torch.randn(9, 8, requires_grad=True)
+ ref = model(x0)
+ sum(part.sum() for part in ref).backward()
+ ref_x = x0.grad.detach().clone()
+ ref_grads = _adapter_grads(model)
+
+ for param in model.parameters():
+ param.grad = None
+
+ x1 = x0.detach().clone().requires_grad_(True)
+ assert patch_fast_lora_qkv(model) == 1
+ got = model(x1)
+ sum(part.sum() for part in got).backward()
+ for a, b in zip(got, ref):
+ torch.testing.assert_close(a, b)
+ torch.testing.assert_close(x1.grad, ref_x)
+ for name, grad in _adapter_grads(model).items():
+ torch.testing.assert_close(grad, ref_grads[name], msg=name)
+
+
+class TestCoordinator:
+ def test_patch_is_idempotent_reversible_and_cache_is_drained(self):
+ _deps()
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv, unpatch_fast_lora_qkv
+
+ model = _make_model(("q_proj", "v_proj"))
+ had_instance = {
+ name: "forward" in getattr(model.attn, name).__dict__
+ for name in ("q_proj", "k_proj", "v_proj")
+ }
+ assert patch_fast_lora_qkv(model) == 1
+ assert patch_fast_lora_qkv(model) == 0
+ model(_deps().randn(2, 8))
+ assert getattr(model.attn, "_soup_fast_lora_qkv_cache", None) is None
+ hits, grad_fns = getattr(model.attn, "_soup_fast_lora_qkv_last_cache_hits")
+ assert hits == 2
+ assert grad_fns == ("_FastLoraQKVBackward",) * 3
+ assert unpatch_fast_lora_qkv(model) == 1
+ assert unpatch_fast_lora_qkv(model) == 0
+ for name in ("q_proj", "k_proj", "v_proj"):
+ assert ("forward" in getattr(model.attn, name).__dict__) is had_instance[name]
+
+ def test_checkpoint_non_reentrant_matches_plain(self):
+ torch = _deps()
+ from torch.utils.checkpoint import checkpoint
+
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ torch.manual_seed(23)
+ model = _make_model(("q_proj", "v_proj"))
+ x0 = torch.randn(3, 8, requires_grad=True)
+
+ def objective(x):
+ q, k, v = model(x)
+ return q.square().mean() + k.square().mean() + v.square().mean()
+
+ ref = checkpoint(objective, x0, use_reentrant=False)
+ ref.backward()
+ ref_x = x0.grad.detach().clone()
+ ref_grads = _adapter_grads(model)
+ for param in model.parameters():
+ param.grad = None
+
+ x1 = x0.detach().clone().requires_grad_(True)
+ assert patch_fast_lora_qkv(model) == 1
+ got = checkpoint(objective, x1, use_reentrant=False)
+ got.backward()
+
+ torch.testing.assert_close(got, ref)
+ torch.testing.assert_close(x1.grad, ref_x)
+ for name, grad in _adapter_grads(model).items():
+ torch.testing.assert_close(grad, ref_grads[name], msg=name)
+
+ def test_mps_bfloat16_qv_default_is_finite(self):
+ torch = _deps()
+ if not torch.backends.mps.is_available():
+ pytest.skip("Apple MPS is required")
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ model = _make_model(("q_proj", "v_proj")).to(
+ device="mps", dtype=torch.bfloat16
+ )
+ assert patch_fast_lora_qkv(model) == 1
+ x = torch.randn(4, 8, device="mps", dtype=torch.bfloat16, requires_grad=True)
+ q, k, v = model(x)
+ (q.float().sum() + k.float().sum() + v.float().sum()).backward()
+ assert all(torch.isfinite(part).all() for part in (q, k, v))
+ assert torch.isfinite(x.grad).all()
+
+ def test_cross_attention_different_kv_tensor_delegates_without_stale_cache(self):
+ torch = _deps()
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ model = _make_model(("q_proj", "k_proj", "v_proj"))
+ query = torch.randn(2, 3, 8, requires_grad=True)
+ memory = torch.randn(2, 3, 8, requires_grad=True)
+ reference_q = model.attn.q_proj(query)
+ reference_k = model.attn.k_proj(memory)
+ reference_v = model.attn.v_proj(memory)
+
+ assert patch_fast_lora_qkv(model) == 1
+ q = model.attn.q_proj(query)
+ k = model.attn.k_proj(memory)
+ v = model.attn.v_proj(memory)
+
+ torch.testing.assert_close(q, reference_q)
+ torch.testing.assert_close(k, reference_k)
+ torch.testing.assert_close(v, reference_v)
+ assert type(q.grad_fn).__name__ == "_FastLoraQKVBackward"
+ assert type(k.grad_fn).__name__ != "_FastLoraQKVBackward"
+ assert type(v.grad_fn).__name__ != "_FastLoraQKVBackward"
+ assert getattr(model.attn, "_soup_fast_lora_qkv_cache", None) is None
+ assert getattr(model.attn, "_soup_fast_lora_qkv_last_cache_hits") == (0, ())
+
+ def test_cross_attention_with_a_different_key_width_is_not_patched(self):
+ torch = _deps()
+ import torch.nn as nn
+ from peft import LoraConfig, inject_adapter_in_model
+
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ class CrossAttention(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.q_proj = nn.Linear(8, 8)
+ self.k_proj = nn.Linear(6, 8)
+ self.v_proj = nn.Linear(6, 8)
+
+ def forward(self, x, memory):
+ return self.q_proj(x), self.k_proj(memory), self.v_proj(memory)
+
+ class Model(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.attn = CrossAttention()
+
+ def forward(self, x, memory):
+ return self.attn(x, memory)
+
+ model = Model()
+ inject_adapter_in_model(
+ LoraConfig(
+ r=2,
+ lora_alpha=4,
+ lora_dropout=0.0,
+ target_modules=["q_proj", "k_proj", "v_proj"],
+ ),
+ model,
+ )
+ x = torch.randn(2, 3, 8)
+ memory = torch.randn(2, 5, 6)
+ reference = model(x, memory)
+ assert patch_fast_lora_qkv(model) == 0
+ for got, want in zip(model(x, memory), reference):
+ torch.testing.assert_close(got, want)
+
+ def test_modules_to_save_projection_keeps_peft_ownership(self):
+ _deps()
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ model = _make_model(
+ ("q_proj", "v_proj"), modules_to_save=["k_proj"]
+ )
+ assert hasattr(model.attn.k_proj, "modules_to_save")
+ assert patch_fast_lora_qkv(model) == 0
+
+ def test_nonzero_dropout_delegates_to_peft(self):
+ torch = _deps()
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ model = _make_model(("q_proj", "k_proj", "v_proj"), dropout=0.25)
+ model.train()
+ assert patch_fast_lora_qkv(model) == 1
+ output = model(torch.randn(2, 3, 8, requires_grad=True))
+ assert all(
+ type(part.grad_fn).__name__ != "_FastLoraQKVBackward"
+ for part in output
+ )
+
+ def test_qkv_owns_projections_until_unpatched(self):
+ torch = _deps()
+ from soup_cli.utils.fast_lora import patch_fast_lora_single_projection
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv, unpatch_fast_lora_qkv
+
+ model = _make_model(("q_proj", "k_proj", "v_proj"))
+ assert patch_fast_lora_qkv(model) == 1
+ assert patch_fast_lora_single_projection(model) == 0
+
+ replacement = lambda _self, x: torch.zeros_like(x) # noqa: E731
+ model.attn.q_proj.forward = types.MethodType(replacement, model.attn.q_proj)
+ assert unpatch_fast_lora_qkv(model) == 1
+ assert model.attn.q_proj.forward.__func__ is replacement
+
+ def test_qkv_refuses_projections_already_owned_by_single_projection(self):
+ _deps()
+ from soup_cli.utils.fast_lora import (
+ patch_fast_lora_single_projection,
+ unpatch_fast_lora_single_projection,
+ )
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ model = _make_model(("q_proj", "k_proj", "v_proj"))
+ assert patch_fast_lora_single_projection(model) == 3
+ assert patch_fast_lora_qkv(model) == 0
+ assert unpatch_fast_lora_single_projection(model) == 3
+
+ def test_real_peft_8bit_layers_are_not_patched(self):
+ _deps()
+ bnb = pytest.importorskip("bitsandbytes")
+ import torch.nn as nn
+ from peft import LoraConfig, inject_adapter_in_model
+
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ class Attention(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.q_proj = bnb.nn.Linear8bitLt(8, 8, bias=False)
+ self.k_proj = bnb.nn.Linear8bitLt(
+ 8, 4, bias=False, has_fp16_weights=False
+ )
+ self.v_proj = bnb.nn.Linear8bitLt(8, 4, bias=False)
+
+ class Model(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.is_loaded_in_8bit = True
+ self.attn = Attention()
+
+ model = Model()
+ inject_adapter_in_model(
+ LoraConfig(
+ r=2,
+ lora_alpha=4,
+ target_modules=["q_proj", "k_proj", "v_proj"],
+ ),
+ model,
+ )
+ assert all(
+ type(getattr(model.attn, name)).__name__ == "Linear8bitLt"
+ for name in ("q_proj", "k_proj", "v_proj")
+ )
+ assert patch_fast_lora_qkv(model) == 0
+
+ def test_unadapted_int8_sibling_refuses_the_whole_qkv_fast_path(self):
+ torch = _deps()
+ bnb = pytest.importorskip("bitsandbytes")
+ import torch.nn as nn
+ from peft import LoraConfig, inject_adapter_in_model
+
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ class Attention(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.q_proj = nn.Linear(8, 8, bias=False)
+ self.k_proj = bnb.nn.Linear8bitLt(
+ 8, 4, bias=False, has_fp16_weights=False
+ )
+ self.v_proj = nn.Linear(8, 4, bias=False)
+
+ def forward(self, x):
+ return self.q_proj(x), self.k_proj(x), self.v_proj(x)
+
+ class Model(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.attn = Attention()
+
+ def forward(self, x):
+ return self.attn(x)
+
+ model = Model().to("cpu")
+ inject_adapter_in_model(
+ LoraConfig(
+ r=2,
+ lora_alpha=4,
+ lora_dropout=0.0,
+ target_modules=["q_proj", "v_proj"],
+ ),
+ model,
+ )
+ x = torch.randn(2, 3, 8, requires_grad=True)
+ reference = model(x)
+ assert not model.attn.k_proj.weight.is_floating_point()
+ assert patch_fast_lora_qkv(model) == 1
+ output = model(x)
+ assert all(
+ type(part.grad_fn).__name__ != "_FastLoraQKVBackward"
+ for part in output
+ )
+ for got, want in zip(output, reference):
+ torch.testing.assert_close(got, want)
+
+
+class TestFastPathIsActuallyTaken:
+ @pytest.mark.parametrize(
+ ("targets", "ranks"),
+ [
+ pytest.param(("q_proj",), None, id="q"),
+ pytest.param(("k_proj",), None, id="k"),
+ pytest.param(("v_proj",), None, id="v"),
+ pytest.param(("q_proj", "v_proj"), None, id="qv"),
+ pytest.param(("q_proj", "k_proj", "v_proj"), None, id="qkv-equal"),
+ pytest.param(
+ ("q_proj", "k_proj", "v_proj"),
+ {"q_proj": 2, "k_proj": 3, "v_proj": 4},
+ id="qkv-unequal",
+ ),
+ ],
+ )
+ @pytest.mark.parametrize("bias", [True, False], ids=["bias", "no-bias"])
+ @pytest.mark.parametrize("shape", [(4, 8), (2, 3, 8)], ids=["2d", "3d"])
+ @pytest.mark.parametrize("dtype_name", ["float32", "bfloat16"], ids=["fp32", "bf16"])
+ def test_all_three_outputs_come_from_the_fused_kernel(
+ self, targets, ranks, bias, shape, dtype_name
+ ):
+ torch = _deps()
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ dtype = getattr(torch, dtype_name)
+ model = _make_model(targets, ranks=ranks, bias=bias).to(dtype=dtype)
+ x = torch.randn(*shape, dtype=dtype, requires_grad=True)
+
+ before = model(x)
+ assert all(type(part.grad_fn).__name__ != "_FastLoraQKVBackward" for part in before)
+
+ assert patch_fast_lora_qkv(model) == 1
+ out = model(x)
+ assert [type(part.grad_fn).__name__ for part in out] == [
+ "_FastLoraQKVBackward",
+ "_FastLoraQKVBackward",
+ "_FastLoraQKVBackward",
+ ]
+ hits, grad_fns = getattr(model.attn, "_soup_fast_lora_qkv_last_cache_hits")
+ assert hits == 2
+ assert grad_fns == ("_FastLoraQKVBackward",) * 3
+
+ def test_cpu_autocast_preserves_pefts_bfloat16_outputs(self):
+ torch = _deps()
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ torch.manual_seed(31)
+ model = _make_model(("q_proj", "k_proj", "v_proj"))
+ x = torch.randn(2, 5, 8, requires_grad=True)
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ reference = model(x)
+ assert all(part.dtype == torch.bfloat16 for part in reference)
+
+ assert patch_fast_lora_qkv(model) == 1
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ output = model(x)
+ assert all(part.dtype == torch.bfloat16 for part in output)
+ assert all(
+ type(part.grad_fn).__name__ == "_FastLoraQKVBackward" for part in output
+ )
+
+ def test_non_contiguous_three_dimensional_input_stays_on_fast_path(self):
+ torch = _deps()
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ model = _make_model(("q_proj", "v_proj"), bias=False)
+ base = torch.randn(3, 2, 8, requires_grad=True)
+ x = base.transpose(0, 1)
+ assert not x.is_contiguous()
+ ref = model(x)
+ assert patch_fast_lora_qkv(model) == 1
+ got = model(x)
+ for actual, expected in zip(got, ref):
+ torch.testing.assert_close(actual, expected)
+ assert all(type(part.grad_fn).__name__ == "_FastLoraQKVBackward" for part in got)
+
+ @pytest.mark.parametrize(
+ "device", ["cpu", pytest.param("cuda", marks=pytest.mark.gpu)]
+ )
+ @pytest.mark.parametrize("seed", [3, 7, 11])
+ def test_nf4_qkv_forward_backward_matches_unpatched_peft(self, seed, device):
+ torch = _deps()
+ bnb = pytest.importorskip("bitsandbytes")
+ import torch.nn as nn
+ from peft import LoraConfig, inject_adapter_in_model
+
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ class Attention(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.q_proj = bnb.nn.Linear4bit(
+ 8, 8, bias=False, compute_dtype=torch.bfloat16, quant_type="nf4"
+ )
+ self.k_proj = bnb.nn.Linear4bit(
+ 8, 4, bias=False, compute_dtype=torch.bfloat16, quant_type="nf4"
+ )
+ self.v_proj = bnb.nn.Linear4bit(
+ 8, 4, bias=False, compute_dtype=torch.bfloat16, quant_type="nf4"
+ )
+
+ def forward(self, x):
+ return self.q_proj(x), self.k_proj(x), self.v_proj(x)
+
+ class Model(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.attn = Attention()
+
+ def forward(self, x):
+ return self.attn(x)
+
+ torch.manual_seed(seed)
+ model = Model()
+ with torch.no_grad():
+ model.attn.v_proj.weight.mul_(4)
+ model = model.to(device)
+ inject_adapter_in_model(
+ LoraConfig(
+ r=2,
+ lora_alpha=4,
+ lora_dropout=0.0,
+ bias="none",
+ target_modules=["q_proj", "k_proj", "v_proj"],
+ ),
+ model,
+ )
+ _randomise_b(model)
+ assert all(
+ getattr(model.attn, name).get_base_layer().weight.quant_state is not None
+ for name in ("q_proj", "k_proj", "v_proj")
+ )
+ reference = copy.deepcopy(model)
+ x_ref = torch.randn(
+ 2, 3, 8, device=device, dtype=torch.bfloat16, requires_grad=True
+ )
+ expected = reference(x_ref)
+ sum(part.float().square().mean() for part in expected).backward()
+ expected_x_grad = x_ref.grad.detach().clone()
+ expected_grads = _adapter_grads(reference)
+
+ x = x_ref.detach().clone().requires_grad_(True)
+ assert patch_fast_lora_qkv(model) == 1
+ out = model(x)
+ assert all(type(part.grad_fn).__name__ == "_FastLoraQKVBackward" for part in out)
+ sum(part.float().square().mean() for part in out).backward()
+ hits, _ = getattr(model.attn, "_soup_fast_lora_qkv_last_cache_hits")
+ assert hits == 2
+ for actual, wanted in zip(out, expected):
+ torch.testing.assert_close(actual, wanted, rtol=1e-2, atol=1e-2)
+ torch.testing.assert_close(x.grad, expected_x_grad, rtol=1e-2, atol=1e-2)
+ got_grads = _adapter_grads(model)
+ assert got_grads.keys() == expected_grads.keys()
+ for name, grad in got_grads.items():
+ torch.testing.assert_close(
+ grad, expected_grads[name], rtol=1e-2, atol=1e-2, msg=name
+ )
+
+
[email protected]("seed", range(12))
+def test_bf16_qkv_stays_within_twice_pefts_error_against_float64(
+ seed, aten_half_matmuls
+):
+ torch = _deps()
+ import torch.nn as nn
+ from peft import LoraConfig, inject_adapter_in_model
+
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ class Attention(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.q_proj = nn.Linear(32, 32, bias=False)
+ self.k_proj = nn.Linear(32, 16, bias=False)
+ self.v_proj = nn.Linear(32, 16, bias=False)
+
+ def forward(self, x):
+ return self.q_proj(x), self.k_proj(x), self.v_proj(x)
+
+ class Model(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.attn = Attention()
+
+ def forward(self, x):
+ return self.attn(x)
+
+ torch.manual_seed(seed)
+ model = Model()
+ with torch.no_grad():
+ model.attn.v_proj.weight.mul_(4)
+ inject_adapter_in_model(
+ LoraConfig(
+ r=4,
+ lora_alpha=8,
+ lora_dropout=0.0,
+ target_modules=["q_proj", "k_proj", "v_proj"],
+ ),
+ model,
+ )
+ _randomise_b(model)
+ for name, param in model.named_parameters():
+ # Soup's layout since #429: frozen base in bf16, trainable LoRA in fp32.
+ param.data = param.data.float() if "lora_" in name else param.data.to(torch.bfloat16)
+ x0 = torch.randn(2, 5, 32, dtype=torch.bfloat16)
+
+ def run(module, x):
+ x = x.clone().requires_grad_(True)
+ outputs = module(x)
+ sum(output.double().square().mean() for output in outputs).backward()
+ grads = [
+ param.grad
+ for name, param in sorted(module.named_parameters())
+ if "lora_" in name
+ ]
+ result = [
+ tensor.detach().double().clone()
+ for tensor in (*outputs, x.grad, *grads)
+ ]
+ module.zero_grad(set_to_none=True)
+ return result
+
+ oracle = run(copy.deepcopy(model).double(), x0.double())
+ reference = run(model, x0)
+ assert patch_fast_lora_qkv(model) == 1
+ fast = run(model, x0)
+ for got, ref, exact in zip(fast, reference, oracle):
+ assert (got - exact).abs().max() <= 2 * (ref - exact).abs().max() + 1e-8
+
+
+class TestStreamedModel:
+ def test_qkv_kernel_matches_resident_peft_across_reused_stream_buffers(
+ self, tmp_path
+ ):
+ torch = _deps()
+ pytest.importorskip("transformers")
+ pytest.importorskip("safetensors")
+ from peft import LoraConfig, TaskType, get_peft_model
+ from safetensors.torch import save_file
+ from transformers import AutoModelForCausalLM, LlamaConfig, LlamaForCausalLM
+
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+ from soup_cli.utils.layer_shard import shard_checkpoint
+ from soup_cli.utils.layer_stream_runtime import build_streamed_model
+
+ def lora_config():
+ return LoraConfig(
+ r=2,
+ lora_alpha=4,
+ lora_dropout=0.0,
+ bias="none",
+ target_modules=["q_proj", "k_proj", "v_proj"],
+ task_type=TaskType.CAUSAL_LM,
+ )
+
+ torch.manual_seed(43)
+ config = LlamaConfig(
+ vocab_size=64,
+ hidden_size=16,
+ intermediate_size=32,
+ num_hidden_layers=4,
+ num_attention_heads=2,
+ num_key_value_heads=2,
+ tie_word_embeddings=False,
+ max_position_embeddings=64,
+ )
+ weights = tmp_path / "model"
+ weights.mkdir(parents=True, exist_ok=True)
+ save_file(
+ {
+ key: value.contiguous()
+ for key, value in LlamaForCausalLM(config).state_dict().items()
+ },
+ str(weights / "model.safetensors"),
+ )
+ config.save_pretrained(str(weights))
+
+ shards = str(tmp_path / "shards")
+ index = shard_checkpoint(str(weights), shards, dtype="float32", arch="llama")
+ streamed, _runtime = build_streamed_model(
+ model_id=str(weights),
+ shard_dir=shards,
+ index=index,
+ lora_config=lora_config(),
+ device="cpu",
+ dtype="float32",
+ buffers=2,
+ pin=False,
+ seed=5,
+ )
+ assert patch_fast_lora_qkv(streamed) == 4
+ _randomise_b(streamed)
+
+ resident = get_peft_model(
+ AutoModelForCausalLM.from_pretrained(str(weights), dtype=torch.float32),
+ lora_config(),
+ )
+ resident_params = dict(resident.named_parameters())
+ copied = 0
+ for name, parameter in streamed.named_parameters():
+ if "lora_" not in name or parameter.is_meta:
+ continue
+ target = next(
+ (
+ candidate
+ for candidate_name, candidate in resident_params.items()
+ if candidate_name.endswith(name)
+ ),
+ None,
+ )
+ assert target is not None, f"resident model has no parameter ending in {name!r}"
+ with torch.no_grad():
+ target.copy_(parameter)
+ copied += 1
+ assert copied == 24
+
+ input_ids = torch.randint(0, 64, (1, 8))
+ labels = torch.randint(0, 64, (1, 8))
+ streamed_loss = streamed(input_ids=input_ids, labels=labels).loss
+ hits = [
+ getattr(module, "_soup_fast_lora_qkv_last_cache_hits", None)
+ for module in streamed.modules()
+ if getattr(module, "_soup_fast_lora_qkv", False)
+ ]
+ assert hits == [(2, ("_FastLoraQKVBackward",) * 3)] * 4, hits
+ streamed_loss.backward()
+ resident_loss = resident(input_ids=input_ids, labels=labels).loss
+ resident_loss.backward()
+
+ torch.testing.assert_close(streamed_loss, resident_loss, rtol=1e-5, atol=1e-5)
+ streamed_grads = {
+ name: parameter.grad
+ for name, parameter in streamed.named_parameters()
+ if "lora_" in name and parameter.grad is not None
+ }
+ resident_grads = {
+ name: parameter.grad
+ for name, parameter in resident.named_parameters()
+ if "lora_" in name and parameter.grad is not None
+ }
+ assert len(streamed_grads) == len(resident_grads) == 24
+ for name, grad in streamed_grads.items():
+ target = next(
+ (
+ candidate
+ for candidate_name, candidate in resident_grads.items()
+ if candidate_name.endswith(name)
+ ),
+ None,
+ )
+ assert target is not None, f"no resident gradient for {name!r}"
+ torch.testing.assert_close(grad, target, rtol=1e-4, atol=1e-5, msg=name)
+
+
+class TestRealLlamaAttention:
+ def test_real_llama_gqa_forward_backward_and_cache_hits(self):
+ torch = _deps()
+ from peft import LoraConfig, inject_adapter_in_model
+ from transformers import LlamaConfig, LlamaForCausalLM
+
+ from soup_cli.utils.fast_lora_qkv import patch_fast_lora_qkv
+
+ config = LlamaConfig(
+ vocab_size=32,
+ hidden_size=16,
+ intermediate_size=32,
+ num_hidden_layers=1,
+ num_attention_heads=4,
+ num_key_value_heads=2,
+ attention_bias=False,
+ )
+ config._attn_implementation = "eager"
+ model = LlamaForCausalLM(config)
+ inject_adapter_in_model(
+ LoraConfig(
+ r=2,
+ lora_alpha=4,
+ lora_dropout=0.0,
+ bias="none",
+ target_modules=["q_proj", "v_proj"],
+ ),
+ model,
+ )
+ _randomise_b(model)
+
+ input_ids = torch.tensor([[1, 2, 3, 4], [4, 3, 2, 1]])
+ ref = model(input_ids=input_ids, use_cache=False).logits
+ ref.square().mean().backward()
+ ref_grads = _adapter_grads(model)
+ for param in model.parameters():
+ param.grad = None
+
+ assert patch_fast_lora_qkv(model) == 1
+ got = model(input_ids=input_ids, use_cache=False).logits
+ got.square().mean().backward()
+ torch.testing.assert_close(got, ref, rtol=1e-5, atol=1e-6)
+ for name, grad in _adapter_grads(model).items():
+ torch.testing.assert_close(grad, ref_grads[name], rtol=1e-5, atol=1e-6, msg=name)
+
+ attn = model.model.layers[0].self_attn
+ assert getattr(attn, "_soup_fast_lora_qkv_cache", None) is None
+ hits, grad_fns = getattr(attn, "_soup_fast_lora_qkv_last_cache_hits")
+ assert hits == 2
+ assert grad_fns == ("_FastLoraQKVBackward",) * 3