Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(cross-encoder): add declared runtime LoRA lifecycle
svonava3bc2c41c9119
diff --git a/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.py b/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.pyindex 4104fffe2..9b5c96ba1 100644--- a/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.py@@ -17,7 +17,7 @@ Performance optimizations:"""from pathlib import Path-from typing import Any+from typing import TYPE_CHECKING, Anyimport torchfrom sentence_transformers import CrossEncoder@@ -28,6 +28,10 @@ from sie_server.adapters._types import ERR_NOT_LOADED, ERR_REQUIRES_TEXT, AttnImfrom sie_server.core.inference_output import ScoreOutputfrom sie_server.types.inputs import Item+if TYPE_CHECKING:+ from sie_server.adapters.cross_encoder._lora import CrossEncoderLora+ from sie_server.adapters.lora import LoraRuntimeConfig+class CrossEncoderAdapter(BaseAdapter):"""Adapter for cross-encoder reranker models.@@ -40,6 +44,15 @@ class CrossEncoderAdapter(BaseAdapter):These models take (query, document) pairs and output relevance scores.Higher scores indicate more relevant documents.+ Runtime LoRA is opt-in through ``lora_paths={served_name: source}``.+ Only ordinary A/B LoRA matrices targeting encoder Linear modules in a+ standard, unquantized ``BertForSequenceClassification`` are supported.+ The scoring head and activation stay those of the base checkpoint;+ trained replacement heads, causal rerankers and custom model classes+ are rejected when LoRA is enabled. Adapters load on demand under the+ registry's resident limit. ``options.lora=None`` selects the base model.+ Configurations without declarations use the original model and scoring path.+Performance optimizations:- SDPA attention (default): Uses PyTorch's scaled_dot_product_attentionwhich can dispatch to flash attention when available@@ -61,6 +74,9 @@ class CrossEncoderAdapter(BaseAdapter):compute_precision: ComputePrecision | None = None,attn_implementation: AttnImplementation = "sdpa",revision: str | None = None,+ lora_paths: dict[str, str] | None = None,+ lora_revisions: dict[str, str | None] | None = None,+ max_loaded_loras: int = 10,**kwargs: Any, # Accept extra args from loader (e.g., pooling)) -> None:"""Initialize the adapter.@@ -76,6 +92,12 @@ class CrossEncoderAdapter(BaseAdapter):revision: Optional HuggingFace revision/branch/commit SHA to pin whenloading the model. If None, the default branch is used. Forwardedto ``CrossEncoder(..., revision=...)``.+ lora_paths: Declared adapter aliases/sources. Enables deferred runtime+ loading for standard BERT encoder projections only. Served names+ use letters, digits, underscores, dots and hyphens; sources may+ be local directories or Hugging Face repositories.+ lora_revisions: Source revisions supplied by the model loader.+ max_loaded_loras: Resident adapter limit, enforced with registry LRU eviction.**kwargs: Additional arguments (ignored, for compatibility)."""_ = kwargs # Unused, but accepted for loader compatibility@@ -88,6 +110,12 @@ class CrossEncoderAdapter(BaseAdapter):self._model: CrossEncoder | None = Noneself._device: str | None = None+ self._lora: CrossEncoderLora | None = None+ if lora_paths:+ # Keep optional dependency imports and all LoRA state off the ordinary path.+ from sie_server.adapters.cross_encoder._lora import CrossEncoderLora as LoraManager++ self._lora = LoraManager(lora_paths, lora_revisions, max_loaded_loras)def load(self, device: str) -> None:"""Load the model onto the specified device.@@ -134,6 +162,50 @@ class CrossEncoderAdapter(BaseAdapter):if self._max_length is not None:self._model.max_length = self._max_length+ if self._lora is not None:+ self._lora.bind(self._model)++ def unload(self) -> None:+ try:+ if self._lora is not None:+ self._lora.close()+ finally:+ super().unload()++ def supports_lora(self) -> bool:+ return self._lora is not None++ def supports_hot_lora_reload(self) -> bool:+ return self._lora is not None++ def lora_runtime_config(self) -> "LoraRuntimeConfig | None":+ return self._lora.runtime_config() if self._lora is not None else None++ def fetch_lora(self, lora_path: str, revision: str | None = None) -> str:+ if self._lora is None:+ return super().fetch_lora(lora_path, revision)+ return self._lora.fetch(lora_path, revision)++ def discard_lora_source(self, lora_path: str) -> None:+ if self._lora is not None:+ self._lora.discard(lora_path)++ def load_lora(self, lora_path: str, revision: str | None = None, *, source: str | None = None) -> int:+ if self._lora is None:+ return super().load_lora(lora_path, revision, source=source)+ return self._lora.load(lora_path, revision, source=source)++ def unload_lora(self, lora_name: str) -> None:+ if self._lora is None:+ super().unload_lora(lora_name)+ else:+ self._lora.unload(lora_name)++ def set_active_lora(self, lora_name: str | None) -> None:+ if self._lora is not None:+ self._lora.select(lora_name)+ elif lora_name is not None:+ raise ValueError("No LoRA sources are declared for this cross-encoder")def score(self,diff --git a/packages/sie_server/src/sie_server/adapters/cross_encoder/_lora.py b/packages/sie_server/src/sie_server/adapters/cross_encoder/_lora.pynew file mode 100644index 000000000..e3d330407--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/cross_encoder/_lora.py@@ -0,0 +1,384 @@+"""Opt-in LoRA lifecycle for the ordinary sentence-transformers CrossEncoder.++The outer wrapper, tokenizer, classifier and activation are never replaced.+Transformers injects ordinary LoRA layers into declared BERT encoder Linear+modules. The worker owns selection/mutation exclusion; only background source+preparation needs a separate lock here. No scoring code calls into this module.+"""++from __future__ import annotations++import math+import re+import shutil+import tempfile+import threading+from dataclasses import dataclass+from pathlib import Path+from typing import Any++import torch+from huggingface_hub import snapshot_download+from peft import LoraConfig, PeftConfig+from peft.functional import delete_adapter+from safetensors.torch import load_file+from sentence_transformers import CrossEncoder+from transformers import BertForSequenceClassification++from sie_server.adapters.lora import LoraRuntimeConfig, LoraStateUncertainError, LoraUnavailableError+from sie_server.adapters.peft_lora_mixin import PEFTLoRAMixin++_FILES = ("adapter_config.json", "adapter_model.safetensors")+_UNSUPPORTED = (+ "use_dora",+ "use_rslora",+ "use_qalora",+ "use_bdlora",+ "lora_bias",+ "fan_in_fan_out",+ "rank_pattern",+ "alpha_pattern",+ "layers_to_transform",+ "layers_pattern",+ "exclude_modules",+ "target_parameters",+ "alora_invocation_tokens",+ "arrow_config",+ "ensure_weight_tying",+ "loftq_config",+ "eva_config",+ "corda_config",+ "lora_ga_config",+)+++@dataclass+class _Prepared:+ directory: tempfile.TemporaryDirectory[str]+ config: LoraConfig+ weights: dict[str, torch.Tensor]+++class CrossEncoderLora:+ """Declared, bounded inference adapters; lifecycle calls run under the worker guard."""++ def __init__(+ self,+ paths: dict[str, str],+ revisions: dict[str, str | None] | None,+ max_loaded: int,+ ) -> None:+ if isinstance(max_loaded, bool) or not isinstance(max_loaded, int) or max_loaded < 1:+ raise ValueError("max_loaded_loras must be a positive integer")+ if not isinstance(paths, dict):+ raise ValueError("CrossEncoder lora_paths must map served aliases to declared sources")+ aliases = dict(paths)+ if any(not isinstance(k, str) or not k or not isinstance(v, str) or not v for k, v in aliases.items()):+ raise ValueError("LoRA declarations must map nonempty names to nonempty sources")+ if any(not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]*", alias) for alias in aliases):+ raise ValueError("LoRA served aliases must contain only letters, numbers, underscores, dots and hyphens")+ self._sources = set(aliases.values())+ self._revisions = {source: (revisions or {}).get(source) for source in self._sources}+ for source in self._sources:+ if source in aliases and aliases[source] != source:+ raise ValueError(f"LoRA alias {source!r} shadows a different declared source")+ self._aliases = aliases+ self._max_loaded = max_loaded+ self._source_lock = threading.Lock()+ self._prepared: dict[str, _Prepared] = {}+ self._loaded: dict[str, int] = {}+ self._parameters: dict[str, list[torch.nn.Parameter]] = {}+ self._active: str | None = None+ self._outer: CrossEncoder | None = None+ self._model: Any = None+ self._originals: dict[str, torch.nn.Linear] = {}+ self._grad_flags: list[tuple[torch.nn.Parameter, bool]] = []+ self._closed = True+ self._uncertain = False+ self._generation = 0++ def runtime_config(self) -> LoraRuntimeConfig:+ return LoraRuntimeConfig(dict(self._aliases), frozenset(), frozenset(), self._max_loaded)++ def bind(self, outer: CrossEncoder) -> None:+ model = outer.model+ if type(model) is not BertForSequenceClassification or getattr(model, "is_quantized", False):+ raise ValueError(+ "CrossEncoder LoRA currently requires a standard, unquantized BertForSequenceClassification"+ )+ if getattr(model, "peft_config", None) or getattr(model, "_hf_peft_config_loaded", False):+ raise ValueError("The cross-encoder must start from a base checkpoint without attached adapters")+ self._outer, self._model = outer, model+ self._originals = {name: module for name, module in model.named_modules() if type(module) is torch.nn.Linear}+ self._grad_flags = [(parameter, parameter.requires_grad) for parameter in model.parameters()]+ self._active = None+ self._uncertain = False+ with self._source_lock:+ self._generation += 1+ self._closed = False++ def _source(self, name: str) -> str:+ source = self._aliases.get(name, name)+ if source not in self._sources:+ raise ValueError(f"LoRA {name!r} is not declared for this cross-encoder")+ return source++ def _ready(self) -> None:+ if self._uncertain:+ raise LoraStateUncertainError("CrossEncoder LoRA state is uncertain; reload the model")+ if self._closed or self._outer is None:+ raise RuntimeError("CrossEncoder is not loaded")++ def _check_config(self, source: str, config: PeftConfig) -> LoraConfig:+ PEFTLoRAMixin()._check_lora_config(source, config)+ if not isinstance(config, LoraConfig):+ raise ValueError("Only ordinary LoRA configurations are supported")+ for field in _UNSUPPORTED:+ if getattr(config, field, None):+ raise ValueError(f"CrossEncoder LoRA does not support {field}")+ if not isinstance(config.init_lora_weights, bool):+ raise ValueError("CrossEncoder LoRA requires a plain boolean init_lora_weights")+ if isinstance(config.r, bool) or not isinstance(config.r, int) or config.r < 1:+ raise ValueError("LoRA rank must be a positive integer")+ if not math.isfinite(config.lora_alpha) or config.lora_alpha <= 0:+ raise ValueError("LoRA alpha must be finite and positive")+ if not math.isfinite(config.lora_dropout) or not 0 <= config.lora_dropout < 1:+ raise ValueError("LoRA dropout must be finite and in [0, 1)")+ targets = config.target_modules+ if not isinstance(targets, (set, list)) or not targets or any(not isinstance(t, str) or not t for t in targets):+ raise ValueError("CrossEncoder LoRA requires an explicit list of target module names")+ config.inference_mode = True+ return config++ def _validate_weights(self, config: LoraConfig, weights: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:+ expected: dict[str, tuple[int, int]] = {}+ for target in config.target_modules or []:+ matches = [name for name in self._originals if name == target or name.endswith(f".{target}")]+ if not matches or any(not name.startswith("bert.encoder.") for name in matches):+ raise ValueError(f"LoRA target {target!r} must resolve only to BERT encoder Linear modules")+ for name in matches:+ module = self._originals[name]+ expected[f"{name}.lora_A.weight"] = (config.r, module.in_features)+ expected[f"{name}.lora_B.weight"] = (module.out_features, config.r)+ normalized: dict[str, torch.Tensor] = {}+ for key, tensor in weights.items():+ name = key.removeprefix("base_model.model.")+ if name in normalized:+ raise ValueError(f"Duplicate LoRA weight {name!r}")+ normalized[name] = tensor+ if set(normalized) != set(expected):+ raise ValueError("LoRA weights must exactly match every declared target's A/B matrices")+ for name, tensor in normalized.items():+ if (+ tuple(tensor.shape) != expected[name]+ or not tensor.is_floating_point()+ or not torch.isfinite(tensor).all()+ ):+ raise ValueError(f"Invalid shape, dtype or nonfinite values in LoRA weight {name!r}")+ module_name = name.rsplit(".", 2)[0]+ dtype = self._originals[module_name].weight.dtype+ if not torch.isfinite(tensor.to(dtype=dtype)).all():+ raise ValueError(f"LoRA weight {name!r} overflows the base model's compute dtype")+ return normalized++ def fetch(self, name: str, revision: str | None = None) -> str:+ self._ready()+ source = self._source(name)+ pinned = self._revisions[source]+ if revision is not None and revision != pinned:+ raise ValueError("LoRA revision differs from the declared source revision")+ with self._source_lock:+ generation = self._generation+ if source in self._prepared:+ return self._prepared[source].directory.name+ directory = Path(source)+ if directory.is_dir():+ if pinned is not None:+ raise ValueError("A local LoRA directory cannot honor a Hugging Face revision pin")+ else:+ directory = Path(snapshot_download(source, revision=pinned, allow_patterns=list(_FILES)))+ temporary = tempfile.TemporaryDirectory(prefix="sie-cross-encoder-lora-")+ try:+ # A private snapshot prevents later source edits or alternative pickle files+ # from changing the checkpoint after validation.+ for filename in _FILES:+ shutil.copyfile(directory / filename, Path(temporary.name) / filename)+ config = self._check_config(source, PeftConfig.from_pretrained(temporary.name, local_files_only=True))+ weights = self._validate_weights(config, load_file(str(Path(temporary.name) / _FILES[1])))+ with self._source_lock:+ self._ready()+ if generation != self._generation:+ raise RuntimeError("CrossEncoder reloaded while LoRA source was being fetched")+ existing = self._prepared.get(source)+ if existing is not None:+ temporary.cleanup()+ return existing.directory.name+ self._prepared[source] = _Prepared(temporary, config, weights)+ return temporary.name+ except BaseException:+ temporary.cleanup()+ raise++ def discard(self, name: str) -> None:+ source = self._source(name)+ with self._source_lock:+ prepared = self._prepared.pop(source, None)+ if prepared is not None:+ try:+ prepared.directory.cleanup()+ except OSError:+ # Keep ownership for model teardown to retry, rather than losing+ # the path when filesystem cleanup fails.+ with self._source_lock:+ self._prepared[source] = prepared+ raise++ def _restore_grad_flags(self) -> None:+ for parameter, requires_grad in self._grad_flags:+ parameter.requires_grad_(requires_grad)++ def _restore_tree(self) -> None:+ for name, original in self._originals.items():+ parent_name, _, child = name.rpartition(".")+ setattr(self._model.get_submodule(parent_name), child, original)+ if hasattr(self._model, "peft_config"):+ del self._model.peft_config+ self._model._hf_peft_config_loaded = False+ self._restore_grad_flags()+ self._active = None++ def _remove(self, adapter_name: str) -> None:+ # The low-level deletion also handles an injection that failed before+ # Transformers set its configuration-loaded flag.+ delete_adapter(self._model, adapter_name=adapter_name, prefix="lora_")+ getattr(self._model, "peft_config", {}).pop(adapter_name, None)++ def load(self, name: str, revision: str | None = None, *, source: str | None = None) -> int:+ self._ready()+ canonical = self._source(name)+ if canonical in self._loaded:+ return self._loaded[canonical]+ if len(self._loaded) >= self._max_loaded:+ raise ValueError("CrossEncoder resident LoRA capacity is exhausted; evict an adapter first")+ if source is None:+ source = self.fetch(canonical, revision)+ with self._source_lock:+ prepared = self._prepared.get(canonical)+ if prepared is None or prepared.directory.name != source:+ raise ValueError("LoRA source must be the validated snapshot fetched for this declaration")+ adapter_name = PEFTLoRAMixin._peft_adapter_name(canonical)+ try:+ assert self._outer is not None+ self._outer.load_adapter(+ adapter_name=adapter_name,+ peft_config=prepared.config,+ adapter_state_dict=prepared.weights,+ is_trainable=False,+ )+ memory = 0+ parameters = []+ for key, weight in prepared.weights.items():+ module_name, part, _ = key.rsplit(".", 2)+ parameter = getattr(self._model.get_submodule(module_name), part)[adapter_name].weight+ # Transformers only warns on missing/unexpected keys. Verify the+ # actual installed tensors before admitting the adapter.+ if not torch.isfinite(parameter).all() or not torch.equal(+ parameter.detach(), weight.to(device=parameter.device, dtype=parameter.dtype)+ ):+ raise ValueError(f"LoRA weight {key!r} was not installed exactly")+ parameter.requires_grad_(False)+ parameters.append(parameter)+ memory += parameter.numel() * parameter.element_size()+ self._outer.disable_adapters()+ self._restore_grad_flags()+ self._active = None+ self._loaded[canonical] = memory+ self._parameters[canonical] = parameters+ except BaseException:+ try:+ if self._loaded:+ self._remove(adapter_name)+ assert self._outer is not None+ self._outer.disable_adapters()+ self._restore_grad_flags()+ self._active = None+ else:+ self._restore_tree()+ except BaseException as rollback:+ self._uncertain = True+ raise LoraStateUncertainError("Failed to roll back CrossEncoder LoRA attachment") from rollback+ raise+ finally:+ try:+ self.discard(canonical)+ except OSError as exc:+ self._uncertain = True+ raise LoraStateUncertainError("LoRA source cleanup failed; retain capacity until model reload") from exc+ return memory++ def select(self, name: str | None) -> None:+ self._ready()+ canonical = self._source(name) if name is not None else None+ if canonical is not None and canonical not in self._loaded:+ raise LoraUnavailableError(f"Declared LoRA {name!r} is not resident")+ if canonical == self._active:+ return+ assert self._outer is not None+ try:+ if canonical is None:+ self._outer.disable_adapters()+ else:+ self._outer.set_adapter(PEFTLoRAMixin._peft_adapter_name(canonical))+ self._outer.enable_adapters()+ # Transformers' enable/set hooks default to trainable adapters.+ for parameter in self._parameters[canonical]:+ parameter.requires_grad_(False)+ self._restore_grad_flags()+ self._active = canonical+ except BaseException as exc:+ self._uncertain = True+ raise LoraStateUncertainError("Failed to select CrossEncoder LoRA; reload the model") from exc++ def unload(self, name: str) -> None:+ self._ready()+ canonical = self._source(name)+ if canonical not in self._loaded:+ raise LoraUnavailableError(f"LoRA {name!r} is not resident")+ try:+ self._remove(PEFTLoRAMixin._peft_adapter_name(canonical))+ if len(self._loaded) == 1:+ self._restore_tree()+ else:+ assert self._outer is not None+ self._outer.disable_adapters()+ self._restore_grad_flags()+ self._active = None+ except BaseException as exc:+ self._uncertain = True+ raise LoraStateUncertainError("Failed to unload CrossEncoder LoRA; reload the model") from exc+ del self._loaded[canonical]+ del self._parameters[canonical]+ self.discard(canonical)++ def close(self) -> None:+ with self._source_lock:+ self._closed = True+ prepared, self._prepared = self._prepared, {}+ errors = []+ try:+ for item in prepared.values():+ try:+ item.directory.cleanup()+ except OSError as exc:+ errors.append(exc)+ if self._model is not None:+ self._restore_tree()+ finally:+ self._loaded.clear()+ self._parameters.clear()+ self._originals.clear()+ self._grad_flags.clear()+ self._outer = self._model = None+ self._uncertain = False+ if errors:+ raise ExceptionGroup("Failed to remove owned LoRA source snapshots", errors)diff --git a/packages/sie_server/tests/adapters/test_cross_encoder_lora.py b/packages/sie_server/tests/adapters/test_cross_encoder_lora.pynew file mode 100644index 000000000..59c19fbdd--- /dev/null+++ b/packages/sie_server/tests/adapters/test_cross_encoder_lora.py@@ -0,0 +1,583 @@+"""Real BERT/Transformers/PEFT lifecycle checks without model downloads."""++from __future__ import annotations++import builtins+import json+import time+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++import httpx+import numpy as np+import pytest+import torch+import yaml+from peft import LoraConfig+from peft.tuners.tuners_utils import BaseTunerLayer+from safetensors.torch import load_file, save_file+from sie_server.adapters.cross_encoder import CrossEncoderAdapter+from sie_server.adapters.lora import LoraStateUncertainError, LoraUnavailableError+from sie_server.app.app_factory import AppFactory+from sie_server.app.app_state_config import AppStateConfig+from sie_server.core.registry import ModelRegistry+from transformers import BertConfig, BertForSequenceClassification, BertTokenizerFast++QUERY = {"text": "how do i reset my password"}+DOCS = [{"text": "reset your password by email"}, {"text": "the capital is paris"}]++[email protected](scope="module")+def checkpoint(tmp_path_factory):+ directory = tmp_path_factory.mktemp("cross-encoder-base")+ vocab = [+ "[PAD]",+ "[UNK]",+ "[CLS]",+ "[SEP]",+ "[MASK]",+ *["how", "do", "i", "reset", "my", "password", "your", "by", "email", "the", "capital", "is", "paris"],+ ]+ vocab = list(dict.fromkeys(vocab))+ vocab_path = directory / "vocab.txt"+ vocab_path.write_text("\n".join(vocab))+ BertTokenizerFast(vocab_file=str(vocab_path), model_max_length=64).save_pretrained(directory)+ config = BertConfig(+ vocab_size=len(vocab),+ hidden_size=16,+ num_hidden_layers=2,+ num_attention_heads=2,+ intermediate_size=32,+ max_position_embeddings=64,+ num_labels=1,+ hidden_dropout_prob=0,+ attention_probs_dropout_prob=0,+ )+ config.sbert_ce_default_activation_function = "torch.nn.modules.linear.Identity"+ with torch.random.fork_rng():+ torch.manual_seed(29)+ BertForSequenceClassification(config).save_pretrained(directory)+ return directory+++def save_adapter(path, seed=1, **overrides):+ path.mkdir()+ LoraConfig(+ task_type="SEQ_CLS",+ r=4,+ lora_alpha=8,+ target_modules=["query", "value"],+ bias="none",+ lora_dropout=0,+ inference_mode=True,+ ).save_pretrained(path)+ if overrides:+ config_path = path / "adapter_config.json"+ config = json.loads(config_path.read_text())+ config.update(overrides)+ config_path.write_text(json.dumps(config))+ generator = torch.Generator().manual_seed(seed)+ weights = {}+ for layer in range(2):+ for target in ("query", "value"):+ prefix = f"base_model.model.bert.encoder.layer.{layer}.attention.self.{target}"+ weights[f"{prefix}.lora_A.weight"] = torch.randn(4, 16, generator=generator) * 0.4+ weights[f"{prefix}.lora_B.weight"] = torch.randn(16, 4, generator=generator) * 0.4+ save_file(weights, path / "adapter_model.safetensors")+ return str(path)+++def adapter(checkpoint, tmp_path):+ paths = {name: save_adapter(tmp_path / name, seed) for seed, name in enumerate(("a", "b", "c"), 1)}+ adapter = CrossEncoderAdapter(checkpoint, lora_paths=paths, max_loaded_loras=2)+ adapter.load("cpu")+ yield adapter+ adapter.unload()+++def scores(adapter):+ from sie_server.types.inputs import Item++ query, docs = Item(**QUERY), [Item(**doc) for doc in DOCS]+ direct = np.asarray(adapter.score(query, docs))+ pairs = adapter.score_pairs([query] * len(docs), docs)+ assert np.isfinite(direct).all()+ np.testing.assert_allclose(pairs.scores, direct, atol=1e-7, rtol=0)+ assert pairs.input_token_counts+ assert all(count > 0 for count in pairs.input_token_counts)+ return direct+++def base_snapshot(adapter):+ outer = adapter._model+ return (+ outer,+ outer.model,+ outer.model.classifier,+ outer.tokenizer,+ outer.activation_fn,+ dict(outer.model.named_modules()),+ {name: value.detach().clone() for name, value in outer.model.state_dict().items()},+ [(parameter, parameter.requires_grad) for parameter in outer.model.parameters()],+ )+++def assert_base_preserved(adapter, snapshot, *, unwrapped=False):+ outer, model, head, tokenizer, activation, modules, weights, grad = snapshot+ assert adapter._model is outer+ assert outer.model is model+ assert model.classifier is head+ assert outer.tokenizer is tokenizer+ assert outer.activation_fn is activation+ for name, expected in weights.items():+ parent, _, leaf = name.rpartition(".")+ module = model.get_submodule(parent)+ if isinstance(module, BaseTunerLayer):+ module = module.get_base_layer()+ assert torch.equal(getattr(module, leaf), expected), name+ assert all(parameter.requires_grad == flag for parameter, flag in grad)+ if unwrapped:+ assert dict(model.named_modules()) == modules+ assert not hasattr(model, "peft_config")+ assert not model._hf_peft_config_loaded+++def test_never_lora_has_no_manager_or_optional_imports(checkpoint, monkeypatch):+ original = builtins.__import__++ def guarded_import(name, *args, **kwargs):+ assert name != "sie_server.adapters.cross_encoder._lora"+ return original(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", guarded_import)+ adapter = CrossEncoderAdapter(checkpoint)+ assert adapter._lora is None+ assert not adapter.supports_lora()+ assert adapter.lora_capability() is None+ assert not adapter.supports_hot_lora_reload()+ assert adapter.lora_runtime_config() is None+ adapter.load("cpu")+ before = base_snapshot(adapter)+ baseline = scores(adapter)+ adapter.set_active_lora(None)+ np.testing.assert_array_equal(scores(adapter), baseline)+ assert_base_preserved(adapter, before)+ with pytest.raises(ValueError, match="No LoRA sources"):+ adapter.set_active_lora("a")+ adapter.unload()+++def test_actual_effect_restoration_head_and_final_module_identity(adapter):+ snapshot = base_snapshot(adapter)+ baseline = scores(adapter)+ np.testing.assert_array_equal(scores(adapter), baseline)+ runtime = adapter.lora_runtime_config()+ assert runtime is not None+ assert runtime.max_loaded == 2+ assert set(runtime.aliases) == {"a", "b", "c"}+ assert not runtime.preloaded+ assert not runtime.pinned+ with pytest.raises(LoraUnavailableError):+ adapter.set_active_lora("a")+ assert adapter.load_lora("a") == 2048+ # Successful attachment must leave base selected, including SEQ_CLS configs.+ np.testing.assert_array_equal(scores(adapter), baseline)+ adapter.set_active_lora("a")+ a = scores(adapter)+ assert not any(parameter.requires_grad for parameter in adapter._lora._parameters[adapter._lora._aliases["a"]])+ assert np.max(np.abs(a - baseline)) > 1e-6+ assert_base_preserved(adapter, snapshot)+ adapter.load_lora("b")+ np.testing.assert_array_equal(scores(adapter), baseline)+ adapter.set_active_lora("b")+ b = scores(adapter)+ assert np.max(np.abs(b - a)) > 1e-6+ adapter.set_active_lora(None)+ np.testing.assert_array_equal(scores(adapter), baseline)+ with pytest.raises(ValueError, match="capacity"):+ adapter.load_lora("c")+ adapter.unload_lora("a")+ with pytest.raises(LoraUnavailableError):+ adapter.set_active_lora("a")+ adapter.set_active_lora("b")+ np.testing.assert_array_equal(scores(adapter), b)+ adapter.unload_lora("b")+ assert_base_preserved(adapter, snapshot, unwrapped=True)+ np.testing.assert_array_equal(scores(adapter), baseline)+ adapter.load_lora("a")+ adapter.set_active_lora("a")+ np.testing.assert_array_equal(scores(adapter), a)++[email protected]("existing", [False, True])+def test_failed_attachment_rolls_back_entire_base_or_only_failed_adapter(adapter, monkeypatch, existing):+ snapshot = base_snapshot(adapter)+ baseline = scores(adapter)+ if existing:+ adapter.load_lora("a")+ adapter.set_active_lora("a")+ a = scores(adapter)+ original = adapter._model.load_adapter++ def fail_after_injection(*args, **kwargs):+ original(*args, **kwargs)+ raise RuntimeError("injected post-load failure")++ with monkeypatch.context() as context:+ context.setattr(adapter._model, "load_adapter", fail_after_injection)+ with pytest.raises(RuntimeError, match="injected post-load"):+ adapter.load_lora("b")+ assert_base_preserved(adapter, snapshot, unwrapped=not existing)+ np.testing.assert_array_equal(scores(adapter), baseline)+ assert adapter._lora._prepared == {}+ with pytest.raises(LoraUnavailableError):+ adapter.set_active_lora("b")+ if existing:+ adapter.set_active_lora("a")+ np.testing.assert_array_equal(scores(adapter), a)+ adapter.load_lora("b")+ adapter.set_active_lora("b")+ assert np.max(np.abs(scores(adapter) - baseline)) > 1e-6++[email protected]("damage", ["missing", "empty", "foreign", "shape", "nan", "overflow", "duplicate"])+def test_bad_weights_rejected_before_model_mutation(adapter, damage):+ source = Path(adapter._lora._aliases["a"])+ weights_path = source / "adapter_model.safetensors"+ weights = load_file(weights_path)+ key = next(iter(weights))+ if damage == "missing":+ del weights[key]+ elif damage == "empty":+ weights.clear()+ elif damage == "foreign":+ weights["base_model.model.classifier.weight"] = torch.ones(1, 16)+ elif damage == "shape":+ weights[key] = torch.ones(3, 16)+ elif damage == "nan":+ weights[key][0, 0] = float("nan")+ elif damage == "overflow":+ weights[key] = torch.full(weights[key].shape, 1e300, dtype=torch.float64)+ else:+ weights[key.removeprefix("base_model.model.")] = weights[key].clone()+ save_file(weights, weights_path)+ snapshot = base_snapshot(adapter)+ with pytest.raises(ValueError, match="LoRA"):+ adapter.load_lora("a")+ assert_base_preserved(adapter, snapshot, unwrapped=True)+ assert adapter._lora._prepared == {}+ assert not adapter._lora._loaded+++ "change",+ [+ {"modules_to_save": ["classifier"]},+ {"bias": "all"},+ {"target_modules": ["classifier"]},+ {"target_modules": ["dense"]},+ {"target_modules": ["does_not_exist"]},+ {"target_modules": "query"},+ {"init_lora_weights": "pissa"},+ {"use_dora": True},+ {"rank_pattern": {"query": 2}},+ {"target_parameters": ["classifier.weight"]},+ {"lora_alpha": float("inf")},+ ],+)+def test_unsafe_or_unqualified_config_is_rejected(adapter, change):+ path = Path(adapter._lora._aliases["a"]) / "adapter_config.json"+ config = json.loads(path.read_text())+ config.update(change)+ path.write_text(json.dumps(config))+ snapshot = base_snapshot(adapter)+ with pytest.raises(ValueError, match="LoRA"):+ adapter.load_lora("a")+ assert_base_preserved(adapter, snapshot, unwrapped=True)+++def test_only_declared_private_snapshot_can_attach(adapter, tmp_path):+ unknown = save_adapter(tmp_path / "unknown")+ with pytest.raises(ValueError, match="not declared"):+ adapter.fetch_lora(unknown)+ with pytest.raises(ValueError, match="validated snapshot"):+ adapter.load_lora("a", source=unknown)+ prepared = Path(adapter.fetch_lora("a"))+ assert prepared.is_dir()+ assert prepared != Path(adapter._lora._aliases["a"])+ (Path(adapter._lora._aliases["a"]) / "adapter_model.safetensors").write_bytes(b"corrupted after validation")+ assert adapter.load_lora("a", source=str(prepared)) > 0+ assert not prepared.exists()+++def test_uncertain_mutation_refuses_even_base_until_whole_model_unload(adapter, monkeypatch):+ adapter.load_lora("a")+ snapshot = base_snapshot(adapter)++ def fail(*args, **kwargs):+ raise RuntimeError("injected rollback failure")++ with monkeypatch.context() as context:+ context.setattr(adapter._model, "load_adapter", fail)+ context.setattr(adapter._lora, "_remove", fail)+ with pytest.raises(LoraStateUncertainError):+ adapter.load_lora("b")+ with pytest.raises(LoraStateUncertainError):+ adapter.set_active_lora(None)+ adapter.unload()+ assert not any(isinstance(module, BaseTunerLayer) for module in snapshot[1].modules())+ assert adapter._lora._outer is None+ assert adapter._lora._originals == {}+ adapter.load("cpu")+ adapter.load_lora("a")+ adapter.set_active_lora("a")+ assert np.isfinite(scores(adapter)).all()+++def test_discard_and_model_unload_release_owned_sources(adapter):+ a = Path(adapter.fetch_lora("a"))+ adapter.discard_lora_source("a")+ assert not a.exists()+ b = Path(adapter.fetch_lora("b"))+ model = adapter._model.model+ adapter.unload()+ assert not b.exists()+ assert not adapter._lora._prepared+ assert not any(isinstance(module, BaseTunerLayer) for module in model.modules())+ with pytest.raises(RuntimeError, match="not loaded"):+ adapter.fetch_lora("a")+++def test_revision_and_capacity_validation(checkpoint, tmp_path):+ path = save_adapter(tmp_path / "a")+ with pytest.raises(ValueError, match="positive integer"):+ CrossEncoderAdapter(checkpoint, lora_paths={"a": path}, max_loaded_loras=0)+ adapter = CrossEncoderAdapter(checkpoint, lora_paths={"a": path}, lora_revisions={path: "a" * 40})+ adapter.load("cpu")+ try:+ with pytest.raises(ValueError, match="differs"):+ adapter.fetch_lora("a", revision="b" * 40)+ with pytest.raises(ValueError, match="local LoRA"):+ adapter.fetch_lora("a")+ finally:+ adapter.unload()+++def test_revisions_alone_do_not_enable_or_authorize_lora(checkpoint):+ adapter = CrossEncoderAdapter(checkpoint, lora_revisions={"other-profile/source": "a" * 40})+ assert adapter._lora is None+ assert adapter.lora_capability() is None++[email protected]("paths", [["org/source"], {"/private/source": "org/source"}, {"a": "b", "b": "c"}])+def test_aliases_are_public_names_and_cannot_shadow_sources(checkpoint, paths):+ with pytest.raises(ValueError, match=r"aliases|shadows"):+ CrossEncoderAdapter(checkpoint, lora_paths=paths)+++def test_fetch_rechecks_model_generation_before_publishing_source(adapter, monkeypatch):+ from sie_server.adapters.cross_encoder import _lora++ original = _lora.load_file++ def reload_during_fetch(path):+ weights = original(path)+ adapter.unload()+ adapter.load("cpu")+ return weights++ monkeypatch.setattr(_lora, "load_file", reload_during_fetch)+ with pytest.raises(RuntimeError, match="reloaded while"):+ adapter.fetch_lora("a")+ assert adapter._lora._prepared == {}++[email protected]("existing", [False, True])+def test_partial_injection_failure_preserves_old_adapters_and_base(adapter, monkeypatch, existing):+ from peft.tuners.lora.model import LoraModel++ snapshot = base_snapshot(adapter)+ baseline = scores(adapter)+ if existing:+ adapter.load_lora("a")+ adapter.set_active_lora("a")+ a = scores(adapter)+ original = LoraModel._create_and_replace+ calls = 0++ def fail_second_layer(self, *args, **kwargs):+ nonlocal calls+ calls += 1+ if calls == 2:+ raise RuntimeError("injected mid-attachment failure")+ return original(self, *args, **kwargs)++ with monkeypatch.context() as context:+ context.setattr(LoraModel, "_create_and_replace", fail_second_layer)+ with pytest.raises(RuntimeError, match="mid-attachment"):+ adapter.load_lora("b")+ assert calls == 2+ assert_base_preserved(adapter, snapshot, unwrapped=not existing)+ np.testing.assert_array_equal(scores(adapter), baseline)+ if existing:+ adapter.set_active_lora("a")+ np.testing.assert_array_equal(scores(adapter), a)+ adapter.load_lora("b")+++def test_source_cleanup_failure_retains_capacity_and_blocks_selection(adapter, monkeypatch):+ path = adapter.fetch_lora("a")+ canonical = adapter._lora._aliases["a"]+ temporary = adapter._lora._prepared[canonical].directory++ def fail_cleanup():+ raise OSError("injected cleanup failure")++ with monkeypatch.context() as context:+ context.setattr(temporary, "cleanup", fail_cleanup)+ with pytest.raises(LoraStateUncertainError, match="cleanup failed"):+ adapter.load_lora("a", source=path)+ assert canonical in adapter._lora._loaded+ assert canonical in adapter._lora._prepared+ with pytest.raises(LoraStateUncertainError):+ adapter.set_active_lora(None)+ adapter.unload()+ assert not Path(path).exists()+++def test_source_cleanup_failure_cannot_skip_whole_model_teardown(adapter, monkeypatch):+ adapter.load_lora("a")+ original_model = adapter._model.model+ path = adapter.fetch_lora("b")+ temporary = adapter._lora._prepared[adapter._lora._aliases["b"]].directory++ def fail_cleanup():+ raise OSError("injected cleanup failure")++ with monkeypatch.context() as context:+ context.setattr(temporary, "cleanup", fail_cleanup)+ with pytest.raises(ExceptionGroup, match="owned LoRA"):+ adapter.unload()+ assert adapter._model is None+ assert adapter._lora._model is None+ assert not adapter._lora._loaded+ assert not any(isinstance(module, BaseTunerLayer) for module in original_model.modules())+ assert Path(path).exists()+ temporary.cleanup()++[email protected]("_offline_apps")+def test_real_score_routes_authorize_aliases_isolate_batches_and_evict(+ checkpoint,+ tmp_path,+ monkeypatch,+ serve_on_loopback,+):+ from sie_server.adapters.cross_encoder._lora import CrossEncoderLora++ paths = {name: save_adapter(tmp_path / name, index) for index, name in enumerate(("a", "b", "c", "other"), 1)}+ models = tmp_path / "models"+ models.mkdir()+ config = {+ "sie_id": "test/cross-encoder-lora",+ "weights_path": str(checkpoint),+ "inputs": {"text": True},+ "tasks": {"score": {}},+ "max_sequence_length": 64,+ "profiles": {+ "default": {+ "adapter_path": "sie_server.adapters.cross_encoder:CrossEncoderAdapter",+ "max_batch_tokens": 8192,+ "adapter_options": {"loadtime": {"lora_paths": {name: paths[name] for name in ("a", "b", "c")}}},+ },+ "other": {"extends": "default", "adapter_options": {"loadtime": {"lora_paths": {"other": paths["other"]}}}},+ },+ }+ (models / "model.yaml").write_text(yaml.safe_dump(config))+ monkeypatch.setenv("SIE_MAX_LORAS_PER_MODEL", "2")+ monkeypatch.setenv("SIE_DISK_CACHE_ENABLED", "false")++ async def no_watcher(self):+ pass++ monkeypatch.setattr(ModelRegistry, "start_hot_reload", no_watcher)+ fetched = []+ original_fetch = CrossEncoderLora.fetch++ def observed_fetch(self, name, revision=None):+ fetched.append(name)+ return original_fetch(self, name, revision)++ monkeypatch.setattr(CrossEncoderLora, "fetch", observed_fetch)+ app = AppFactory.create_app(AppStateConfig(models_dir=str(models), device="cpu", remote_serving=False))+ model = config["sie_id"]+ with (+ serve_on_loopback(app) as url,+ httpx.Client(base_url=url, timeout=15, headers={"Accept": "application/json"}) as client,+ ):++ def request(selection=None, *, profile=None):+ options = {"lora": selection}+ if profile is not None:+ options["profile"] = profile+ return client.post(f"/v1/score/{model}", json={"query": QUERY, "items": DOCS, "options": options})++ def ready(selection=None):+ deadline = time.monotonic() + 20+ response = request(selection)+ statuses = [response.status_code]+ if selection is not None and response.status_code == 503:+ assert response.json()["detail"]["code"] == "LORA_LOADING"+ assert float(response.headers["Retry-After"]) > 0+ while response.status_code == 503 and time.monotonic() < deadline:+ time.sleep(0.02)+ response = request(selection)+ statuses.append(response.status_code)+ assert response.status_code == 200, response.text+ values = np.asarray(+ [entry["score"] for entry in sorted(response.json()["scores"], key=lambda row: row["item_id"])]+ )+ assert np.isfinite(values).all()+ return values, statuses++ baseline, _ = ready()+ assert fetched == []+ for rejected, profile in (+ ("https://example.invalid/adapter", None),+ (str(tmp_path / "not-declared"), None),+ ("other", None),+ (paths["other"], None),+ ("a", "other"),+ ):+ response = request(rejected, profile=profile)+ assert response.status_code == 400, response.text+ assert response.json()["detail"]["code"] == "INVALID_INPUT"+ assert fetched == []+ a, statuses = ready("a")+ assert statuses[0] == 503+ b, statuses = ready("b")+ assert statuses[0] == 503+ assert np.max(np.abs(a - baseline)) > 1e-6+ assert np.max(np.abs(b - a)) > 1e-6+ assert set(app.state.registry.loaded_lora_names(model)) == {"a", "b"}+ listed = client.get("/v1/models").json()["models"]+ metadata = next(item for item in listed if item["name"] == model)+ assert set(metadata["lora_adapters"]) == {"a", "b"}+ assert not any(source in json.dumps(metadata["lora_adapters"]) for source in paths.values())+ assert len(app.state.registry._loaded[model].loras) == 2+ assert all(value.memory_bytes == 2048 for value in app.state.registry._loaded[model].loras.values())+ expected = {None: baseline, "a": a, "b": b}+ selections = ["a", None, "b"] * 8+ with ThreadPoolExecutor(max_workers=6) as executor:+ futures = [(selection, executor.submit(ready, selection)) for selection in selections]+ for selection, future in futures:+ actual, statuses = future.result(timeout=20)+ assert statuses == [200]+ np.testing.assert_allclose(actual, expected[selection], atol=1e-6, rtol=0)+ ready("b") # A is now the least recently used resident.+ ready("c")+ assert set(app.state.registry.loaded_lora_names(model)) == {"b", "c"}+ assert not app.state.registry.is_lora_loaded(model, "a")+ np.testing.assert_allclose(ready()[0], baseline, atol=1e-6, rtol=0)+ assert fetched == [paths["a"], paths["b"], paths["c"]]