Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,19 @@ class BGEM3FlashAdapter(BGEM3ScoreMixin, PEFTLoRAMixin, FlashBaseAdapter):

fallback_adapter_path: ClassVar[str | None] = "bge_m3:BGEM3Adapter"

lora_called_module_names: ClassVar[frozenset[str] | None] = frozenset(
{
"word_embeddings",
"position_embeddings",
"token_type_embeddings",
"query",
"key",
"value",
"output.dense",
"intermediate.dense",
}
)

spec = AdapterSpec(
inputs=("text",),
outputs=("dense", "sparse", "multivector", "score"),
Expand Down
120 changes: 110 additions & 10 deletions packages/sie_server/src/sie_server/adapters/peft_lora_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,10 @@ def validate_lora_target_modules(
list/set of module-name suffixes (``"query"``, ``"q_proj"``,
possibly dotted like ``"encoder.layer.0.attention.self.query"``)
or a regex string matched against full module paths.
called_module_names: Leaf module names the adapter's serving forward
actually invokes (e.g. ``{"query", "key", "value", "dense"}``).
called_module_names: Names of the modules the adapter's serving
forward actually invokes, as leaf names (e.g. ``{"query", "key",
"value", "dense"}``) or dotted name suffixes (e.g.
``"intermediate.dense"``). This check compares leaf names.
Raises:
ValueError: If ``target_modules`` is a collection and none of its
Expand All @@ -105,6 +107,7 @@ def validate_lora_target_modules(
return

called = set(called_module_names)
called_leaves = {name.rsplit(".", 1)[-1] for name in called}

if isinstance(target_modules, str):
# PEFT regex form (fullmatched against full module paths). Leaf names
Expand All @@ -123,7 +126,7 @@ def validate_lora_target_modules(
targets = [str(t) for t in target_modules]
# Compare by leaf component: PEFT matches suffixes, and dotted targets
# ("encoder.layer.0.attention.self.query") end in the module's leaf name.
if any(t.rsplit(".", 1)[-1] in called for t in targets):
if any(t.rsplit(".", 1)[-1] in called_leaves for t in targets):
return

msg = (
Expand All @@ -135,6 +138,95 @@ def validate_lora_target_modules(
raise ValueError(msg)


def _is_called_module(module_path: str, called_module_names: Collection[str]) -> bool:
return any(module_path == name or module_path.endswith(f".{name}") for name in called_module_names)


_PRODUCT_CHUNK_ELEMENTS = 1 << 24


def _product_is_nonzero(up: Any, down: Any) -> bool:
# In exact arithmetic ``up @ down`` is zero exactly when
# ``up @ (down @ down.T)`` is. Rounding can zero the Gram form for a
# nonzero update, so only its nonzero answer is trusted; a zero answer is
# confirmed on the update itself, in float64 and in bounded chunks.
up, down = up.flatten(1), down.flatten(1)
if bool((up.float() @ (down.float() @ down.float().T)).any()):
return True
up = up.double()
step = max(1, _PRODUCT_CHUNK_ELEMENTS // max(1, up.shape[0]))
return any(bool((up @ down[:, start : start + step].double()).any()) for start in range(0, down.shape[1], step))


def _lora_layer_changes_output(layer: Any, adapter_name: str) -> bool:
if adapter_name in layer.lora_variant:
return True
if layer.scaling[adapter_name] == 0:
return False
if adapter_name in layer.lora_B:
down, up = layer.lora_A[adapter_name], layer.lora_B[adapter_name]
if up.bias is not None and bool(up.bias.any()):
return True
return _product_is_nonzero(up.weight, down.weight)
return _product_is_nonzero(layer.lora_embedding_B[adapter_name], layer.lora_embedding_A[adapter_name])


def validate_lora_has_effect(
lora_path: str,
model: Any,
adapter_name: str,
called_module_names: Collection[str] | None,
) -> None:
"""Reject a LoRA whose attached weights cannot change any module the serving forward calls.
A LoRA module adds ``B @ A`` (plus ``B``'s bias, if it has one), scaled
by ``lora_alpha / r``, to its base module's output, so it changes nothing
when that product or the scaling is zero. PEFT initializes ``lora_B`` to zero, so an adapter exported before
training is a no-op, and so is one trained only on modules the serving
forward never calls, such as ``pooler.dense`` under a manual flash
forward. Both can pass :func:`validate_lora_target_modules`, which reads
only names, and then serve base weights. This check reads the weights
PEFT attached under ``adapter_name``. DoRA and other LoRA variants count
as changing their module.
Args:
lora_path: Public LoRA id (HF/local path), for error messages.
model: The ``PeftModel`` the LoRA is attached to.
adapter_name: The PEFT adapter name the LoRA is attached under.
called_module_names: Module names or dotted name suffixes the serving
forward calls (see :func:`validate_lora_target_modules`), matched
against module paths the way PEFT matches ``target_modules``.
``None`` or empty counts every module as called.
Raises:
ValueError: If no LoRA module the serving forward calls can change
its output.
"""
from peft.tuners.lora import LoraLayer

layers = {
name: module
for name, module in model.named_modules()
if isinstance(module, LoraLayer) and (adapter_name in module.lora_A or adapter_name in module.lora_embedding_A)
}
if not layers:
return
called = {name for name in layers if not called_module_names or _is_called_module(name, called_module_names)}
if any(_lora_layer_changes_output(layers[name], adapter_name) for name in called):
return

uncalled = sorted(
name.removeprefix("base_model.model.")
for name, layer in layers.items()
if name not in called and _lora_layer_changes_output(layer, adapter_name)
)
msg = f"LoRA '{lora_path}' cannot change any output: its update is zero on every module the serving forward calls"
if uncalled:
msg += f", and only {uncalled!r}, which the serving forward never calls, carry non-zero weights"
msg += ". Export the LoRA after training it on the called projections."
raise ValueError(msg)


class PEFTLoRAMixin:
"""Mixin providing PEFT-based LoRA support for PyTorch adapters.
Expand Down Expand Up @@ -281,7 +373,9 @@ def load_lora(self, lora_path: str, revision: str | None = None, *, source: str
Raises:
RuntimeError: If model not loaded or PEFT import fails.
ValueError: If :meth:`fetch_lora` or :meth:`_check_lora_config`
refuses the LoRA.
refuses the LoRA, or its attached weights cannot change any
module the serving forward calls (see
:func:`validate_lora_has_effect`).
"""
self._ensure_lora_tracking()

Expand Down Expand Up @@ -314,22 +408,27 @@ def load_lora(self, lora_path: str, revision: str | None = None, *, source: str
if self._peft_model is None:
# First LoRA - wrap the base model
logger.debug("Creating PeftModel from base model")
self._peft_model = PeftModel.from_pretrained(
peft_model = PeftModel.from_pretrained(
base_model,
source,
adapter_name=peft_adapter_name,
)
# Update self._model to point to the PEFT-wrapped model
# This ensures encode() uses the LoRA-enhanced model
self._model = self._peft_model
else:
# Additional LoRA - add to existing PeftModel
logger.debug("Adding adapter to existing PeftModel")
self._peft_model.load_adapter(source, adapter_name=peft_adapter_name)
peft_model = self._peft_model
peft_model.load_adapter(source, adapter_name=peft_adapter_name)
validate_lora_has_effect(lora_path, peft_model, peft_adapter_name, self.lora_called_module_names)
Comment thread
krisztian-gajdar marked this conversation as resolved.
Resolved
except Exception:
self._detach_failed_lora(base_model, peft_adapter_name)
raise

if self._peft_model is None:
# Update self._model to point to the PEFT-wrapped model
# This ensures encode() uses the LoRA-enhanced model
self._peft_model = peft_model
self._model = peft_model

self._loaded_loras.add(lora_path)
self._lora_adapter_names[lora_path] = peft_adapter_name

Expand All @@ -350,7 +449,8 @@ def _detach_failed_lora(self, base_model: Any, peft_adapter_name: str) -> None:
"""Remove what PEFT attached for a LoRA whose load raised, so no request runs through it.
PEFT injects a LoRA's layers into the model before it loads the
adapter's weights, so a load that fails on the weights leaves them in
adapter's weights, so a load that fails on the weights, or whose
weights :func:`validate_lora_has_effect` refuses, leaves them in
place. A first LoRA's layers wrap the shared base model's own modules,
which are restored here; a later LoRA's adapter is deleted from the
existing PeftModel.
Expand Down
83 changes: 83 additions & 0 deletions packages/sie_server/tests/adapters/test_bge_m3_flash.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

import sys
from pathlib import Path
from types import ModuleType
from typing import Any
from unittest.mock import MagicMock

Expand All @@ -9,12 +11,15 @@
import torch
import transformers
import yaml
from peft import LoraConfig, get_peft_model
from sie_server.adapters._types import ComputePrecision
from sie_server.adapters.bge_m3_flash import BGEM3FlashAdapter
from sie_server.adapters.peft_lora_mixin import _is_called_module
from sie_server.config.model import ModelConfig
from sie_server.core.inference_output import EncodeOutput, SparseVector
from sie_server.core.loader import _build_adapter_kwargs
from sie_server.types.inputs import Item
from torch import nn
from transformers import XLMRobertaConfig
from transformers.models.xlm_roberta.modeling_xlm_roberta import XLMRobertaEmbeddings

Expand Down Expand Up @@ -192,6 +197,84 @@ def test_packed_embeddings_match_native_addition_order(self, dtype: torch.dtype)
torch.testing.assert_close(actual, expected, rtol=0, atol=0)


def _tiny_xlm_roberta() -> transformers.XLMRobertaModel:
torch.manual_seed(0)
config = XLMRobertaConfig(
vocab_size=8,
hidden_size=4,
num_hidden_layers=2,
num_attention_heads=2,
intermediate_size=8,
max_position_embeddings=8,
type_vocab_size=1,
hidden_dropout_prob=0.0,
pad_token_id=1,
)
return transformers.XLMRobertaModel(config).eval()


def _save_lora(path: Path, *, trained: set[str]) -> str:
"""Save a LoRA on every projection whose ``lora_B`` is zero except on the ``trained`` modules."""
lora = get_peft_model(
_tiny_xlm_roberta(),
LoraConfig(r=2, target_modules=["query", "key", "value", "dense"], bias="none", init_lora_weights=False),
)
with torch.no_grad():
for name, parameter in lora.named_parameters():
if ".lora_B." in name and not any(f".{module}.lora_B." in name for module in trained):
parameter.zero_()
lora.save_pretrained(str(path))
return str(path)


class TestBGEM3LoraCalledModules:
"""The declared LoRA modules are the ones the flash forward calls, so a pooler-only LoRA is refused."""

def test_declared_modules_are_exactly_the_modules_the_flash_forward_calls(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
flash_attn = ModuleType("flash_attn")
flash_attn.flash_attn_varlen_func = lambda query, key, value, **_: value # type: ignore[attr-defined]
monkeypatch.setitem(sys.modules, "flash_attn", flash_attn)
model = _tiny_xlm_roberta()
adaptable = [name for name, module in model.named_modules() if isinstance(module, (nn.Linear, nn.Embedding))]
called: set[str] = set()
for name in adaptable:
model.get_submodule(name).register_forward_hook(lambda *_, name=name: called.add(name))
adapter = BGEM3FlashAdapter()
adapter._model = model

with torch.no_grad():
hidden = adapter._run_embeddings(torch.tensor([0, 4, 2, 0, 2]), torch.tensor([2, 3, 4, 2, 3]))
adapter._run_transformer_flash(hidden, torch.tensor([0, 3, 5], dtype=torch.int32), 3, 5)

declared = BGEM3FlashAdapter.lora_called_module_names
assert declared is not None
assert {name for name in adaptable if _is_called_module(name, declared)} == called
assert "pooler.dense" in adaptable
assert "pooler.dense" not in called

def test_lora_trained_only_on_the_pooler_is_refused(self, tmp_path: Path) -> None:
lora = _save_lora(tmp_path, trained={"pooler.dense"})
adapter = BGEM3FlashAdapter()
adapter._model = _tiny_xlm_roberta()

with pytest.raises(ValueError, match=r"cannot change any output.*\['pooler\.dense'\]"):
adapter.load_lora(lora)

assert adapter._peft_model is None
assert not adapter._loaded_loras

def test_lora_trained_on_a_called_projection_loads(self, tmp_path: Path) -> None:
lora = _save_lora(tmp_path, trained={"pooler.dense", "value"})
adapter = BGEM3FlashAdapter()
adapter._model = _tiny_xlm_roberta()

adapter.load_lora(lora)

assert adapter._loaded_loras == {lora}


class TestBGEM3Packing:
"""CPU-only equivalence guards for BGE-M3's Flash varlen input packing."""

Expand Down
Loading
Loading