Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(adapters): make CrossEncoder runtime LoRA explicitly opt in

svonavafc7eeac318d4
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__.py
index 9b5c96ba1..4104fffe2 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 TYPE_CHECKING, Any
+from typing import Any
import torch
from sentence_transformers import CrossEncoder
@@ -28,10 +28,6 @@ from sie_server.adapters._types import ERR_NOT_LOADED, ERR_REQUIRES_TEXT, AttnIm
from sie_server.core.inference_output import ScoreOutput
from 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.
@@ -44,15 +40,6 @@ 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_attention
which can dispatch to flash attention when available
@@ -74,9 +61,6 @@ 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.
@@ -92,12 +76,6 @@ class CrossEncoderAdapter(BaseAdapter):
revision: Optional HuggingFace revision/branch/commit SHA to pin when
loading the model. If None, the default branch is used. Forwarded
to ``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
@@ -110,12 +88,6 @@ class CrossEncoderAdapter(BaseAdapter):
self._model: CrossEncoder | None = None
self._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.
@@ -162,50 +134,6 @@ 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/runtime_lora.py b/packages/sie_server/src/sie_server/adapters/cross_encoder/runtime_lora.py
new file mode 100644
index 000000000..f042d478e
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/cross_encoder/runtime_lora.py
@@ -0,0 +1,88 @@
+"""Explicit runtime-LoRA adapter; ordinary CrossEncoder profiles stay unchanged."""
+
+from pathlib import Path
+from typing import Any
+
+from sie_server.adapters._types import AttnImplementation, ComputePrecision
+from sie_server.adapters.cross_encoder import CrossEncoderAdapter
+from sie_server.adapters.cross_encoder._lora import CrossEncoderLora
+from sie_server.adapters.lora import LoraRuntimeConfig
+
+
+class CrossEncoderLoraAdapter(CrossEncoderAdapter):
+ """Opt-in runtime LoRA for a standard, unquantized BERT cross-encoder.
+
+ Select ``sie_server.adapters.cross_encoder.runtime_lora:CrossEncoderLoraAdapter``
+ explicitly and declare ``lora_paths={served_name: source}``. Only ordinary
+ A/B matrices targeting BERT encoder Linear modules are accepted. The outer
+ CrossEncoder, classifier, activation and scoring methods are inherited;
+ trained replacement heads and custom/causal reranker classes are rejected.
+
+ ``options.lora=None`` restores the original base modules while adapters stay
+ resident off-tree. Loading, selection and eviction use the worker's existing
+ mutation guard. This lifecycle contract does not establish zero overhead or
+ retrieval quality. Ordinary ``CrossEncoderAdapter`` profiles do not import
+ this module or construct any of its state.
+ """
+
+ def __init__(
+ self,
+ model_name_or_path: str | Path,
+ *,
+ trust_remote_code: bool = False,
+ max_length: int | None = None,
+ 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,
+ ) -> None:
+ if not lora_paths:
+ raise ValueError("CrossEncoderLoraAdapter requires nonempty lora_paths declarations")
+ super().__init__(
+ model_name_or_path,
+ trust_remote_code=trust_remote_code,
+ max_length=max_length,
+ compute_precision=compute_precision,
+ attn_implementation=attn_implementation,
+ revision=revision,
+ **kwargs,
+ )
+ self._lora = CrossEncoderLora(lora_paths, lora_revisions, max_loaded_loras)
+
+ def load(self, device: str) -> None:
+ super().load(device)
+ assert self._model is not None
+ self._lora.bind(self._model)
+
+ def unload(self) -> None:
+ try:
+ self._lora.close()
+ finally:
+ super().unload()
+
+ def supports_lora(self) -> bool:
+ return True
+
+ def supports_hot_lora_reload(self) -> bool:
+ return True
+
+ def lora_runtime_config(self) -> LoraRuntimeConfig:
+ return self._lora.runtime_config()
+
+ def fetch_lora(self, lora_path: str, revision: str | None = None) -> str:
+ return self._lora.fetch(lora_path, revision)
+
+ def discard_lora_source(self, lora_path: str) -> None:
+ self._lora.discard(lora_path)
+
+ def load_lora(self, lora_path: str, revision: str | None = None, *, source: str | None = None) -> int:
+ return self._lora.load(lora_path, revision, source=source)
+
+ def unload_lora(self, lora_name: str) -> None:
+ self._lora.unload(lora_name)
+
+ def set_active_lora(self, lora_name: str | None) -> None:
+ self._lora.select(lora_name)
diff --git a/packages/sie_server/tests/adapters/test_cross_encoder_lora.py b/packages/sie_server/tests/adapters/test_cross_encoder_lora.py
index 26bd47253..6defe57df 100644
--- a/packages/sie_server/tests/adapters/test_cross_encoder_lora.py
+++ b/packages/sie_server/tests/adapters/test_cross_encoder_lora.py
@@ -5,6 +5,8 @@ from __future__ import annotations
import builtins
import gc
import json
+import subprocess
+import sys
import time
import weakref
from concurrent.futures import ThreadPoolExecutor
@@ -18,10 +20,14 @@ 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._base_adapter import BaseAdapter
from sie_server.adapters.cross_encoder import CrossEncoderAdapter
+from sie_server.adapters.cross_encoder.runtime_lora import CrossEncoderLoraAdapter
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.config.model import ModelConfig
+from sie_server.core.loader import load_adapter
from sie_server.core.registry import ModelRegistry
from transformers import BertConfig, BertForSequenceClassification, BertTokenizerFast
@@ -92,7 +98,7 @@ def save_adapter(path, seed=1, *, targets=("query", "value"), **overrides):
@pytest.fixture
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 = CrossEncoderLoraAdapter(checkpoint, lora_paths=paths, max_loaded_loras=2)
adapter.load("cpu")
yield adapter
adapter.unload()
@@ -149,12 +155,12 @@ 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"
+ assert name not in {"sie_server.adapters.cross_encoder._lora", "sie_server.adapters.cross_encoder.runtime_lora"}
return original(name, *args, **kwargs)
monkeypatch.setattr(builtins, "__import__", guarded_import)
adapter = CrossEncoderAdapter(checkpoint)
- assert adapter._lora is None
+ assert not hasattr(adapter, "_lora")
assert not adapter.supports_lora()
assert adapter.lora_capability() is None
assert not adapter.supports_hot_lora_reload()
@@ -165,11 +171,94 @@ def test_never_lora_has_no_manager_or_optional_imports(checkpoint, monkeypatch):
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")
+ # Preserve the original base hook contract; registry capability checks
+ # reject adapter requests before any model mutation.
+ adapter.set_active_lora("a")
+ np.testing.assert_array_equal(scores(adapter), baseline)
adapter.unload()
+def test_ordinary_module_import_and_hooks_stay_independent_of_runtime_lora(tmp_path):
+ script = """
+import builtins, sys
+original = builtins.__import__
+def guarded(name, *args, **kwargs):
+ assert name not in {
+ 'sie_server.adapters.cross_encoder.runtime_lora',
+ 'sie_server.adapters.cross_encoder._lora',
+ }, name
+ return original(name, *args, **kwargs)
+builtins.__import__ = guarded
+from sie_server.adapters._base_adapter import BaseAdapter
+from sie_server.adapters.cross_encoder import CrossEncoderAdapter
+adapter = CrossEncoderAdapter('unused-local-construction-only', lora_paths={'a': 'unused'})
+assert not hasattr(adapter, '_lora')
+for name in ('unload', 'supports_lora', 'supports_hot_lora_reload', 'lora_runtime_config',
+ 'fetch_lora', 'discard_lora_source', 'load_lora', 'unload_lora', 'set_active_lora'):
+ assert getattr(CrossEncoderAdapter, name) is getattr(BaseAdapter, name), name
+assert not adapter.supports_lora()
+assert 'sie_server.adapters.cross_encoder.runtime_lora' not in sys.modules
+assert 'sie_server.adapters.cross_encoder._lora' not in sys.modules
+"""
+ result = subprocess.run( # noqa: S603 -- fixed local import-only check, no model or network
+ [sys.executable, "-c", script], cwd=tmp_path, capture_output=True, text=True, timeout=45, check=False
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+
+
[email protected]("declarations", [None, {}, []])
+def test_explicit_runtime_class_requires_declarations(checkpoint, declarations):
+ with pytest.raises(ValueError, match="requires nonempty lora_paths"):
+ CrossEncoderLoraAdapter(checkpoint, lora_paths=declarations, lora_revisions={"org/other": "a" * 40})
+
+
[email protected]("runtime", [False, True])
+def test_real_loader_routes_only_the_explicit_profile_and_preserves_base_options(checkpoint, runtime):
+ adapter_type = CrossEncoderLoraAdapter if runtime else CrossEncoderAdapter
+ loadtime = {"max_length": 24, "trust_remote_code": True}
+ if runtime:
+ loadtime["lora_paths"] = {"a": {"id": "org/declared", "revision": "b" * 40}}
+ config = ModelConfig.model_validate(
+ {
+ "sie_id": "test/explicit-cross-encoder",
+ "weights_path": str(checkpoint),
+ "hf_revision": "a" * 40,
+ "inputs": {"text": True},
+ "tasks": {"score": {}},
+ "profiles": {
+ "default": {
+ "adapter_path": f"{adapter_type.__module__}:{adapter_type.__name__}",
+ "max_batch_tokens": 8192,
+ "adapter_options": {"loadtime": loadtime},
+ }
+ },
+ }
+ )
+ adapter = load_adapter(config, checkpoint, device="cpu", attention_backend="eager", max_loras_per_model=2)
+ assert type(adapter) is adapter_type
+ assert adapter._model_name_or_path == str(checkpoint)
+ assert adapter._max_length == 24
+ assert adapter._trust_remote_code
+ assert adapter._compute_precision == "float32"
+ assert adapter._attn_implementation == "eager"
+ assert adapter._revision == "a" * 40
+ assert adapter_type.score is CrossEncoderAdapter.score
+ assert adapter_type.score_pairs is CrossEncoderAdapter.score_pairs
+ if runtime:
+ assert adapter._lora._revisions == {"org/declared": "b" * 40}
+ assert adapter.lora_runtime_config().max_loaded == 2
+ assert adapter.lora_runtime_config().aliases == {"a": "org/declared"}
+ else:
+ assert not hasattr(adapter, "_lora")
+ assert adapter.set_active_lora.__func__ is BaseAdapter.set_active_lora
+ # Profile resolution is cached. Construct a distinct invalid config,
+ # rather than mutating the already-resolved instance behind its cache.
+ invalid = config.model_dump()
+ invalid["profiles"]["default"]["adapter_options"]["loadtime"]["lora_paths"] = {"a": "org/declared"}
+ with pytest.raises(ValueError, match=r"does not accept.*lora_paths"):
+ load_adapter(ModelConfig.model_validate(invalid), checkpoint, device="cpu")
+
+
def test_actual_effect_restoration_head_and_final_module_identity(adapter):
snapshot = base_snapshot(adapter)
baseline = scores(adapter)
@@ -216,6 +305,7 @@ def test_resident_adapters_leave_the_exact_base_tree_and_preserve_layer_hooks(ad
snapshot = base_snapshot(adapter)
baseline = scores(adapter)
original_query = snapshot[1].bert.encoder.layer[0].attention.self.query
+ original_storage = [(parameter, parameter.data_ptr()) for parameter in snapshot[1].parameters()]
original_calls, wrapper_calls = [], []
base_hook = original_query.register_forward_hook(lambda *_: original_calls.append(True))
adapter.load_lora("a")
@@ -246,18 +336,53 @@ def test_resident_adapters_leave_the_exact_base_tree_and_preserve_layer_hooks(ad
np.testing.assert_array_equal(actual, expected[selection])
expected[selection] = actual
assert_base_preserved(adapter, snapshot)
+ assert all(parameter.data_ptr() == pointer for parameter, pointer in original_storage)
assert {name: id(layer) for name, layer in manager._resident_layers.items()} == identities
assert np.max(np.abs(expected["a"] - expected["b"])) > 1e-6
base_hook.remove()
wrapper_hook.remove()
+def test_repeated_disabled_selection_checks_readiness_without_tree_or_peft_work(adapter, monkeypatch):
+ adapter.load_lora("a")
+ adapter.load_lora("b")
+ adapter.set_active_lora(None)
+ baseline = scores(adapter)
+ snapshot = base_snapshot(adapter)
+ manager = adapter._lora
+ original_ready = manager._ready
+ checks = []
+
+ def ready():
+ checks.append(True)
+ original_ready()
+
+ def unexpected(*_args, **_kwargs):
+ pytest.fail("disabled selection traversed or changed adapter layers")
+
+ with monkeypatch.context() as context:
+ context.setattr(manager, "_ready", ready)
+ for name in ("_attach_layers", "_detach_layers", "_restore_grad_flags"):
+ context.setattr(manager, name, unexpected)
+ for name in ("set_adapter", "enable_adapters", "disable_adapters"):
+ context.setattr(adapter._model, name, unexpected)
+ for _ in range(100):
+ adapter.set_active_lora(None)
+ assert len(checks) == 100
+ np.testing.assert_array_equal(scores(adapter), baseline)
+ assert dict(snapshot[1].named_modules()) == snapshot[5]
+ manager._uncertain = True
+ with pytest.raises(LoraStateUncertainError):
+ adapter.set_active_lora(None)
+ manager._uncertain = False
+
+
def test_disjoint_targets_evict_only_their_wrappers_and_final_unload_releases_weights(checkpoint, tmp_path):
paths = {
"a": save_adapter(tmp_path / "a", 1, targets=("query",)),
"b": save_adapter(tmp_path / "b", 2, targets=("value",)),
}
- adapter = CrossEncoderAdapter(checkpoint, lora_paths=paths, max_loaded_loras=2)
+ adapter = CrossEncoderLoraAdapter(checkpoint, lora_paths=paths, max_loaded_loras=2)
adapter.load("cpu")
try:
snapshot, baseline = base_snapshot(adapter), scores(adapter)
@@ -522,8 +647,8 @@ def test_discard_and_model_unload_release_owned_sources(adapter):
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})
+ CrossEncoderLoraAdapter(checkpoint, lora_paths={"a": path}, max_loaded_loras=0)
+ adapter = CrossEncoderLoraAdapter(checkpoint, lora_paths={"a": path}, lora_revisions={path: "a" * 40})
adapter.load("cpu")
try:
with pytest.raises(ValueError, match="differs"):
@@ -536,14 +661,14 @@ def test_revision_and_capacity_validation(checkpoint, tmp_path):
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 not hasattr(adapter, "_lora")
assert adapter.lora_capability() is None
@pytest.mark.parametrize("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)
+ CrossEncoderLoraAdapter(checkpoint, lora_paths=paths)
def test_fetch_rechecks_model_generation_before_publishing_source(adapter, monkeypatch):
@@ -669,7 +794,7 @@ def test_real_score_routes_authorize_aliases_isolate_batches_and_evict(
"max_sequence_length": 64,
"profiles": {
"default": {
- "adapter_path": "sie_server.adapters.cross_encoder:CrossEncoderAdapter",
+ "adapter_path": "sie_server.adapters.cross_encoder.runtime_lora:CrossEncoderLoraAdapter",
"max_batch_tokens": 8192,
"adapter_options": {"loadtime": {"lora_paths": {name: paths[name] for name in ("a", "b", "c")}}},
},
diff --git a/tools/benchmarks/cross_encoder_lora/README.md b/tools/benchmarks/cross_encoder_lora/README.md
index 1482be0e5..17dd57c01 100644
--- a/tools/benchmarks/cross_encoder_lora/README.md
+++ b/tools/benchmarks/cross_encoder_lora/README.md
@@ -1,7 +1,8 @@
# CrossEncoder runtime LoRA qualification
-This probe measures the ordinary `CrossEncoderAdapter` using the real SIE loader,
-worker, loopback HTTP API and `sie_sdk.SIEClient`. It does not provision compute,
+This probe measures the ordinary `CrossEncoderAdapter` and the explicit opt-in
+`CrossEncoderLoraAdapter` using the real SIE loader, worker, loopback HTTP API
+and `sie_sdk.SIEClient`. It does not provision compute,
install dependencies, change precision, or change the production catalog. The
catalog model is overridden locally to use the ordinary adapter rather than the
catalog's BertFlash implementation.
@@ -14,6 +15,46 @@ every BERT encoder query/value projection. They establish reversible numerical
effects and lifecycle behavior, **not retrieval quality**. Source seeds, model
files and adapter files are hashed in the fixture manifest.
+## Explicit opt-in adapter
+
+Ordinary profiles keep `sie_server.adapters.cross_encoder:CrossEncoderAdapter`.
+That module is restored exactly to the pinned baseline source, including its
+constructor, load/unload and inherited LoRA hooks. It does not import the
+runtime-LoRA module or construct a manager. The public catalog and fallback
+paths are unchanged.
+
+Experimental runtime profiles must select the separate class explicitly:
+
+```yaml
+profiles:
+ default:
+ adapter_path: sie_server.adapters.cross_encoder.runtime_lora:CrossEncoderLoraAdapter
+ max_batch_tokens: 8192
+ adapter_options:
+ loadtime:
+ lora_paths:
+ task_adapter:
+ id: example/bert-encoder-lora
+ revision: 0123456789abcdef0123456789abcdef01234567
+```
+
+The repository and revision above are placeholders. Use declared, compatible
+adapter weights. The explicit class requires nonempty declarations; revisions
+alone do not enable it. Older experimental PR775 configurations that added
+`lora_paths` to the ordinary class must change their `adapter_path`; the existing
+loader rejects those options on the ordinary class. Dependent architecture
+extensions must likewise opt into the separate class and retain their own
+qualification requirements; this change does not add XLM-R support.
+
+The opt-in class inherits the ordinary scoring methods. With base selected, its
+manager restores the original module objects and retains LoRA layers in a plain
+off-tree dictionary, without copying the base weights. Repeated base selection
+still checks manager readiness and active state; declared profiles retain their
+existing admission, reservation and mutation controls. These structural facts
+do not prove equal end-to-end latency or throughput for enabled profiles. All
+previous failed measurements and performance gates remain in force; the
+baseline-only pilot is not candidate qualification.
+
## Prepare immutable sources and fixtures
From a clean public checkout with the candidate committed:
@@ -66,7 +107,8 @@ drop failed trials to obtain a pass, or retry the same failed protocol unchanged
There are six fresh-process blocks, in order `BNR`, `NRB`, `RBN`, `BRN`, `RNB`,
`NBR` (18 fresh servers). B uses the pinned baseline with no declared LoRA.
-N uses the candidate with no declared LoRA. R uses the candidate after A/B
+N uses the candidate's ordinary class with no declared LoRA. R uses its explicit
+runtime-LoRA class after A/B
activity, with base selected and two adapters resident but disabled.
Every arm uses the same password-reset query and four documents in `protocol.py`.
diff --git a/tools/benchmarks/cross_encoder_lora/adapter.py b/tools/benchmarks/cross_encoder_lora/adapter.py
index a9c6ce828..68c80c6c1 100644
--- a/tools/benchmarks/cross_encoder_lora/adapter.py
+++ b/tools/benchmarks/cross_encoder_lora/adapter.py
@@ -14,6 +14,16 @@ from tools.benchmarks.cross_encoder_lora.protocol import require
INPUT_DIMENSIONS = 2
+def production_class(arm: str) -> type[CrossEncoderAdapter]:
+ require(arm in {"B", "N", "R"}, "unknown benchmark arm")
+ if arm == "R":
+ # Optional production adapter does not exist in the archived B source.
+ from sie_server.adapters.cross_encoder.runtime_lora import CrossEncoderLoraAdapter # noqa: PLC0415
+
+ return CrossEncoderLoraAdapter
+ return CrossEncoderAdapter
+
+
def require_forward_coverage(batch: dict[str, Any]) -> None:
"""An outer score batch alone does not prove the model forward was observed."""
forwards = batch["forwards"]
@@ -47,6 +57,8 @@ def require_forward_selection(batch: dict[str, Any], expected_adapter: str | Non
class ObservedCrossEncoder(CrossEncoderAdapter):
+ production_adapter_class = CrossEncoderAdapter
+
def load(self, device: str) -> None:
self.batch_observations = []
self.selection_observations = []
diff --git a/tools/benchmarks/cross_encoder_lora/runtime_adapter.py b/tools/benchmarks/cross_encoder_lora/runtime_adapter.py
new file mode 100644
index 000000000..1146de478
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/runtime_adapter.py
@@ -0,0 +1,9 @@
+"""Untimed observation of the explicitly selected runtime-LoRA production class."""
+
+from sie_server.adapters.cross_encoder.runtime_lora import CrossEncoderLoraAdapter
+
+from tools.benchmarks.cross_encoder_lora.adapter import ObservedCrossEncoder
+
+
+class ObservedRuntimeCrossEncoder(ObservedCrossEncoder, CrossEncoderLoraAdapter):
+ production_adapter_class = CrossEncoderLoraAdapter
diff --git a/tools/benchmarks/cross_encoder_lora/stability.py b/tools/benchmarks/cross_encoder_lora/stability.py
index 479900b66..beac02760 100644
--- a/tools/benchmarks/cross_encoder_lora/stability.py
+++ b/tools/benchmarks/cross_encoder_lora/stability.py
@@ -414,7 +414,7 @@ async def child(args: argparse.Namespace) -> dict[str, Any]:
torch.set_num_interop_threads(1)
try:
summary["required_telemetry_preflight"] = snapshot()
- environment = worker.preflight(args, evidence)
+ environment = worker.preflight(args, evidence, actual_arm="B")
environment["hardware_preflight_only"] = environment.pop("qualification")
environment["qualification"] = False
environment["source_imports"] = {}
diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_forward_observer.py b/tools/benchmarks/cross_encoder_lora/tests/test_forward_observer.py
index 46c4d0f25..ec9b01812 100644
--- a/tools/benchmarks/cross_encoder_lora/tests/test_forward_observer.py
+++ b/tools/benchmarks/cross_encoder_lora/tests/test_forward_observer.py
@@ -9,6 +9,8 @@ from pathlib import Path
import pytest
from sie_server.adapters.cross_encoder import CrossEncoderAdapter
+from sie_server.adapters.cross_encoder.runtime_lora import CrossEncoderLoraAdapter
+from sie_server.adapters.lora import LoraStateUncertainError
from sie_server.types.inputs import Item
from tools.benchmarks.cross_encoder_lora.adapter import (
@@ -16,6 +18,8 @@ from tools.benchmarks.cross_encoder_lora.adapter import (
require_forward_coverage,
require_forward_selection,
)
+from tools.benchmarks.cross_encoder_lora.fixtures import prepare
+from tools.benchmarks.cross_encoder_lora.runtime_adapter import ObservedRuntimeCrossEncoder
from tools.benchmarks.cross_encoder_lora.tests.test_probe import tiny_snapshot
from tools.benchmarks.cross_encoder_lora.worker import unobserved
@@ -137,6 +141,33 @@ def observed_batch() -> dict:
}
+def test_runtime_timing_uses_actual_opt_in_selection_and_preserves_poison_refusal(tmp_path: Path) -> None:
+ snapshot = tiny_snapshot(tmp_path / "model")
+ fixtures = tmp_path / "fixtures"
+ prepare(fixtures, snapshot, smoke=True)
+ adapter = ObservedRuntimeCrossEncoder(snapshot, lora_paths={"a": str(fixtures / "a")})
+ adapter.load("cpu")
+ try:
+ adapter.load_lora("a")
+ before = len(adapter.selection_observations)
+ with unobserved(adapter):
+ assert adapter.production_adapter_class is CrossEncoderLoraAdapter
+ assert adapter.score_pairs.__func__ is CrossEncoderAdapter.score_pairs
+ assert adapter.set_active_lora.__func__ is CrossEncoderLoraAdapter.set_active_lora
+ adapter.set_active_lora("a")
+ assert adapter._lora._active == str(fixtures / "a")
+ adapter.set_active_lora(None)
+ assert adapter._lora._active is None
+ adapter.score_pairs(*pairs())
+ assert len(adapter.selection_observations) == before
+ adapter._lora._uncertain = True
+ with pytest.raises(LoraStateUncertainError), unobserved(adapter):
+ adapter.set_active_lora(None)
+ assert adapter._observer_wrapper is not None
+ finally:
+ adapter.unload()
+
+
@pytest.mark.parametrize("failure", ["empty", "rows", "logits", "nonfinite", "wrong_adapter", "enabled_base"])
def test_missing_partial_or_wrong_tuner_observation_cannot_qualify(failure: str) -> None:
batch = copy.deepcopy(observed_batch())
diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_stability.py b/tools/benchmarks/cross_encoder_lora/tests/test_stability.py
index f0973a6e8..044c00657 100644
--- a/tools/benchmarks/cross_encoder_lora/tests/test_stability.py
+++ b/tools/benchmarks/cross_encoder_lora/tests/test_stability.py
@@ -349,7 +349,7 @@ def test_negative_raw_latency_cannot_hide_in_positive_aggregates() -> None:
probe.metrics(phase)
-def test_serving_observer_and_gc_are_unmodified() -> None:
+def test_memory_and_observer_flow_preserved_with_explicit_production_class() -> None:
baseline = subprocess.run(
["git", "show", "a2932d81:tools/benchmarks/cross_encoder_lora/worker.py"], # noqa: S607
cwd=ROOT,
@@ -361,13 +361,28 @@ def test_serving_observer_and_gc_are_unmodified() -> None:
pytest.skip("invariant control requires its documented parent commit in git history")
def code(text: str) -> dict[str, str]:
+ class ClassBinding(ast.NodeTransformer):
+ def visit_Name(self, node):
+ if node.id == "production":
+ node.id = "CrossEncoderAdapter"
+ return node
+
+ tree = ast.parse(text)
+ for node in tree.body:
+ if isinstance(node, ast.FunctionDef) and node.name == "unobserved":
+ binding = ast.parse("production = adapter.production_adapter_class").body[0]
+ node.body = [entry for entry in node.body if ast.dump(entry) != ast.dump(binding)]
+ ClassBinding().visit(node)
return {
node.name: ast.dump(node)
- for node in ast.parse(text).body
+ for node in tree.body
if isinstance(node, ast.FunctionDef) and node.name in {"unobserved", "memory"}
}
assert code(Path(worker.__file__).read_text()) == code(baseline.stdout)
+ # The explicit opt-in subclass now supplies selection; all timing/restore
+ # control flow and memory semantics stay the same. Real R forwarding is
+ # checked separately, including refusal of a poisoned resident manager.
# Historical diagnostic timing still uses the in-process wrapper and does
# not force GC. The new qualification load loop has its own extraction and
# clock-boundary tests; exact historical replay remains pinned to 482b.
diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_storage.py b/tools/benchmarks/cross_encoder_lora/tests/test_storage.py
index 976d953a7..0be591cf1 100644
--- a/tools/benchmarks/cross_encoder_lora/tests/test_storage.py
+++ b/tools/benchmarks/cross_encoder_lora/tests/test_storage.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import pytest
import torch
-from sie_server.adapters.cross_encoder import CrossEncoderAdapter
+from sie_server.adapters.cross_encoder.runtime_lora import CrossEncoderLoraAdapter
from tools.benchmarks.cross_encoder_lora.fixtures import prepare
from tools.benchmarks.cross_encoder_lora.tests.test_probe import tiny_snapshot
@@ -16,7 +16,7 @@ def resident(tmp_path):
snapshot = tiny_snapshot(tmp_path / "model")
fixtures = tmp_path / "fixtures"
prepare(fixtures, snapshot, smoke=True)
- adapter = CrossEncoderAdapter(snapshot, lora_paths={name: str(fixtures / name) for name in ("a", "b")})
+ adapter = CrossEncoderLoraAdapter(snapshot, lora_paths={name: str(fixtures / name) for name in ("a", "b")})
adapter.load("cpu")
adapter.load_lora("a")
adapter.load_lora("b")
diff --git a/tools/benchmarks/cross_encoder_lora/worker.py b/tools/benchmarks/cross_encoder_lora/worker.py
index 8c4d21bf4..db7910e27 100644
--- a/tools/benchmarks/cross_encoder_lora/worker.py
+++ b/tools/benchmarks/cross_encoder_lora/worker.py
@@ -28,14 +28,13 @@ import torch
import uvicorn
import yaml
from sie_sdk.client.errors import RequestError
-from sie_server.adapters.cross_encoder import CrossEncoderAdapter
from sie_server.adapters.peft_lora_mixin import PEFTLoRAMixin
from sie_server.app.app_factory import AppFactory
from sie_server.app.app_state_config import AppStateConfig
from sie_server.types.inputs import Item
from tools.benchmarks.cross_encoder_lora import client as client_workload
-from tools.benchmarks.cross_encoder_lora.adapter import require_forward_selection
+from tools.benchmarks.cross_encoder_lora.adapter import production_class, require_forward_selection
from tools.benchmarks.cross_encoder_lora.client import (
REQUEST_ITEMS,
Client,
@@ -208,15 +207,14 @@ def adapter_storage(adapter: Any) -> dict[str, int]:
def unobserved(adapter: Any) -> Iterator[None]:
"""Time production methods with the original forward attribute lookup restored."""
score_pairs, select = adapter.score_pairs, adapter.set_active_lora
+ production = adapter.production_adapter_class
before = (len(adapter.batch_observations), len(adapter.forward_observations), len(adapter.selection_observations))
adapter.remove_forward_observer()
- adapter.score_pairs = CrossEncoderAdapter.score_pairs.__get__(adapter)
- adapter.set_active_lora = CrossEncoderAdapter.set_active_lora.__get__(adapter)
+ adapter.score_pairs = production.score_pairs.__get__(adapter)
+ adapter.set_active_lora = production.set_active_lora.__get__(adapter)
try:
- require(adapter.score_pairs.__func__ is CrossEncoderAdapter.score_pairs, "timed scoring is instrumented")
- require(
- adapter.set_active_lora.__func__ is CrossEncoderAdapter.set_active_lora, "timed selection is instrumented"
- )
+ require(adapter.score_pairs.__func__ is production.score_pairs, "timed scoring is instrumented")
+ require(adapter.set_active_lora.__func__ is production.set_active_lora, "timed selection is instrumented")
adapter.assert_original_forward()
yield
adapter.assert_original_forward()
@@ -330,19 +328,21 @@ def configs(directory: Path, source: Path, fixtures: Path, arm: str, snapshot: P
profile = config["profiles"]["default"]
profile["adapter_path"] = f"{HERE / 'adapter.py'}:ObservedCrossEncoder"
if arm == "R":
+ profile["adapter_path"] = f"{HERE / 'runtime_adapter.py'}:ObservedRuntimeCrossEncoder"
profile["adapter_options"]["loadtime"] = {
"lora_paths": {name: str(fixtures / name) for name in ("a", "b", "c")}
}
(directory / "model.yaml").write_text(yaml.safe_dump(config))
-def preflight(args: argparse.Namespace, evidence: Evidence) -> dict[str, Any]:
+def preflight(args: argparse.Namespace, evidence: Evidence, *, actual_arm: str) -> dict[str, Any]:
versions = {name: importlib.metadata.version(name) for name in EXPECTED_VERSIONS}
try:
torchao = importlib.metadata.version("torchao")
except importlib.metadata.PackageNotFoundError:
torchao = None
- module_path = sys.modules[CrossEncoderAdapter.__module__].__file__
+ production = production_class(actual_arm)
+ module_path = sys.modules[production.__module__].__file__
assert module_path is not None
actual_source = Path(module_path).resolve()
require(actual_source.is_relative_to(args.source.resolve()), "adapter was imported from a different source tree")
@@ -351,6 +351,7 @@ def preflight(args: argparse.Namespace, evidence: Evidence) -> dict[str, Any]:
"torchao": torchao,
"adapter_source": str(actual_source),
"adapter_sha256": digest(actual_source),
+ "adapter_class": f"{production.__module__}:{production.__name__}",
"python": sys.version,
"threads": torch.get_num_threads(),
"device": str(torch.cuda.get_device_name(0)) if torch.cuda.is_available() else "cpu",
@@ -424,6 +425,7 @@ async def experiment(args: argparse.Namespace, evidence: Evidence, summary: dict
summary["loaded_before_forward_memory"] = memory()
summary["manager_present"] = getattr(adapter, "_lora", None) is not None
require(summary["manager_present"] == (args.arm == "R"), "unexpected manager activation")
+ require(adapter.production_adapter_class is production_class(args.arm), "wrong production adapter class")
async def call(selection: str | None, label: str, *, cold: bool = False) -> dict[str, Any]:
row = await asyncio.to_thread(client.score, selection, label, cold=cold)
@@ -754,7 +756,7 @@ async def run(args: argparse.Namespace) -> dict[str, Any]:
if group is not None:
await group.grant("prepare")
validate_source(group.binding, args.source, args.arm, args.pair)
- summary["environment"] = preflight(args, evidence)
+ summary["environment"] = preflight(args, evidence, actual_arm=args.arm)
timeout = max(0, group.binding["work_deadline"] - time.monotonic()) if group is not None else args.deadline_s
async with asyncio.timeout(timeout):
await experiment(args, evidence, summary)