Skip to content

armgit / sie

Public Imported from GitHub
0

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

test: establish warm embedding LoRA baselines

svonava924305db7924
diff --git a/tools/benchmarks/runtime_lora/README.md b/tools/benchmarks/runtime_lora/README.md
index c70b77e3b..d2d7dbfe4 100644
--- a/tools/benchmarks/runtime_lora/README.md
+++ b/tools/benchmarks/runtime_lora/README.md
@@ -41,17 +41,20 @@ The acceptance run checks:
refusal, so the probe records and makes bounded fresh SDK calls only for
pre-execution `503 LORA_LOADING`; it never retries a failed open stream.
- Adapter effects in native/chat token log probabilities and embedding vectors;
- base restoration after switching and after eviction. Generation records a
+ base restoration after switching and after eviction. Both engines record a
first response and two warm baseline repeats before any runtime selection.
- Restored warm text must match exactly. At every matching token context, chosen
- and shared top-token probability drift must stay below the fixed `1e-3` bound.
+ For generation, restored warm text must match exactly. At every matching token
+ context, chosen and shared top-token probability drift must stay below the fixed `1e-3` bound.
Top-k support changes are recorded: absent tokens have probability bounded by
the other top-k cutoff, and conservative difference lower bounds also must stay
below `1e-3`. Unreported tail probabilities remain unmeasured; small lower bounds
do not establish upper bounds on their drift. First-token
pairwise selection effects must exceed `1e-4` and five times baseline/reset
- first-token drift. Embeddings retain fixed `1e-5` effect and `5e-5` reset bounds.
- All full text and token probabilities are retained, including cold/warm
+ first-token drift. Embeddings compare raw SDK vectors without extra
+ normalization: warm-repeat and reset maximum absolute error must stay below
+ `5e-5`, while all pairwise selection effects must exceed `1e-5` and five times
+ the larger warm-repeat/reset error. Non-finite vectors and shape changes fail.
+ All full text, vectors, and token probabilities are retained, including cold/warm
differences. Native streaming also probes one token after a fixed common
prefix where an earlier run diverged; this holds context constant when
comparing base/A/B/reset. These fixtures establish selection, not quality.
diff --git a/tools/benchmarks/runtime_lora/probe.py b/tools/benchmarks/runtime_lora/probe.py
index 89a0ce570..b40b7be3d 100644
--- a/tools/benchmarks/runtime_lora/probe.py
+++ b/tools/benchmarks/runtime_lora/probe.py
@@ -43,6 +43,7 @@ PROMPT = "The sky appears blue because"
BOUNDARY_PROMPT = PROMPT + " of the reflection of light. This is an example of"
TEXTS = ["A red fox walks through the forest.", "Neural networks encode text as vectors."]
MAX_RESIDENT = 3
+EMBEDDING_ARRAY_NDIM = 2
MIN_EMBEDDING_EFFECT = 1e-5
MAX_EMBEDDING_RESET_ERROR = 5e-5
MIN_PROBABILITY_EFFECT = 1e-4
@@ -298,6 +299,17 @@ def sequence_comparison(left: dict[str, Any], right: dict[str, Any]) -> dict[str
}
+def embedding_delta(left: dict[str, Any], right: dict[str, Any]) -> float:
+ """Compare raw SDK vectors without normalizing away output differences."""
+ a, b = (np.asarray(value["vectors"], dtype=np.float64) for value in (left, right))
+ require(
+ a.ndim == b.ndim == EMBEDDING_ARRAY_NDIM and a.shape == b.shape and a.size > 0,
+ "embedding shapes differ or are empty",
+ )
+ require(np.isfinite(a).all() and np.isfinite(b).all(), "non-finite embedding")
+ return float(np.max(np.abs(a - b)))
+
+
def check_effect(
kind: str,
base: dict[str, Any],
@@ -306,27 +318,25 @@ def check_effect(
restored: dict[str, Any],
baseline_repeat: dict[str, Any] | None = None,
) -> dict[str, Any]:
+ baseline = baseline_repeat if baseline_repeat is not None else base
if kind == "embedding":
- vectors = [np.asarray(value["vectors"], dtype=np.float64) for value in (base, a, b, restored)]
- require(all(np.isfinite(value).all() for value in vectors), "non-finite embedding")
- ab, aa, bb = (
- float(np.max(np.abs(x - y)))
- for x, y in ((vectors[1], vectors[2]), (vectors[0], vectors[1]), (vectors[0], vectors[2]))
- )
- reset = float(np.max(np.abs(vectors[0] - vectors[3])))
+ ab, aa, bb = (embedding_delta(x, y) for x, y in ((a, b), (base, a), (base, b)))
+ baseline_drift = embedding_delta(base, baseline)
+ reset = embedding_delta(base, restored)
+ require(baseline_drift < MAX_EMBEDDING_RESET_ERROR, "warm embedding baseline was not stable")
require(reset < MAX_EMBEDDING_RESET_ERROR, "base embeddings were not restored")
- minimum = max(MIN_EMBEDDING_EFFECT, EFFECT_DRIFT_MULTIPLIER * reset)
+ minimum = max(MIN_EMBEDDING_EFFECT, EFFECT_DRIFT_MULTIPLIER * max(reset, baseline_drift))
require(min(ab, aa, bb) > minimum, "LoRA embeddings did not differ beyond base drift from base and each other")
return {
"a_vs_b_max_abs": ab,
"a_vs_base_max_abs": aa,
"b_vs_base_max_abs": bb,
"base_reset_max_abs": reset,
+ "baseline_max_abs": baseline_drift,
"required_effect_minimum": minimum,
}
aa, bb, ab = (distribution_delta(x, y) for x, y in ((base, a), (base, b), (a, b)))
reset = distribution_delta(base, restored)
- baseline = baseline_repeat if baseline_repeat is not None else base
baseline_drift = distribution_delta(base, baseline)
repeat_comparison = sequence_comparison(base, baseline)
reset_comparison = sequence_comparison(base, restored)
@@ -516,7 +526,17 @@ async def run_model(kind: str, registry: Any, url: str, evidence: Evidence, trac
raise AssertionError("undeclared adapter was accepted")
native: dict[str, dict[str, dict[str, Any]]] = {}
baseline_repeat = None
- if kind == "generation":
+ if kind == "embedding":
+ baseline_repeat = await call(None, "embedding_base_warm_1")
+ warm = await call(None, "embedding_base_warm_2")
+ evidence.emit(
+ "baseline_comparison",
+ route="embedding",
+ first_vs_warm_max_abs=embedding_delta(base, warm),
+ warm_repeat_max_abs=embedding_delta(baseline_repeat, warm),
+ )
+ base = warm
+ else:
baseline_repeat = await call(None, "chat_base_warm_1")
warm = await call(None, "chat_base_warm_2")
evidence.emit(
diff --git a/tools/benchmarks/runtime_lora/tests/test_probe.py b/tools/benchmarks/runtime_lora/tests/test_probe.py
index 3fef1f93f..68b72e806 100644
--- a/tools/benchmarks/runtime_lora/tests/test_probe.py
+++ b/tools/benchmarks/runtime_lora/tests/test_probe.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
import json
import math
import os
@@ -18,7 +19,7 @@ import torch
from peft import PeftModel
from safetensors.torch import load_file
from sie_sdk._msgpack import packb as pack_msgpack
-from sie_sdk.client.errors import ServerError
+from sie_sdk.client.errors import RequestError, ServerError
from sie_server.adapters.sglang import _server
from sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapter
from sie_server.adapters.sglang.generation import SGLangGenerationAdapter
@@ -26,6 +27,7 @@ from sie_server.config.model import ModelConfig
from sie_server.core.loader import load_adapter, resolve_adapter_class, validate_loadtime_options
from transformers import Qwen3Config, Qwen3ForCausalLM
+from tools.benchmarks.runtime_lora import probe
from tools.benchmarks.runtime_lora.adapters import ObservedGenerationAdapter
from tools.benchmarks.runtime_lora.fixtures import MODELS, digest, write_adapter
from tools.benchmarks.runtime_lora.observer import patch_scheduler
@@ -37,6 +39,7 @@ from tools.benchmarks.runtime_lora.probe import (
check_buffered_native,
check_effect,
configs,
+ embedding_delta,
mixed_batches,
probability,
record_check,
@@ -450,6 +453,94 @@ def test_effect_checks_fail_for_ignored_adapters_and_contaminated_base() -> None
assert np.isfinite(check_effect("embedding", base, a, b, base)["a_vs_b_max_abs"])
+def test_embedding_warm_baseline_is_stable_and_sets_effect_floor() -> None:
+ def result(value: float) -> dict:
+ return {"vectors": [[0.1, value]]}
+
+ base, a, b = result(0.5), result(0.6), result(0.7)
+ effects = check_effect("embedding", base, a, b, base, result(0.50001))
+ assert effects["baseline_max_abs"] == pytest.approx(1e-5)
+ assert effects["required_effect_minimum"] == pytest.approx(5e-5)
+ with pytest.raises(AssertionError, match="baseline was not stable"):
+ check_effect("embedding", base, a, b, base, result(0.5001))
+ with pytest.raises(AssertionError, match="not restored"):
+ check_effect("embedding", base, a, b, result(0.5001), base)
+ with pytest.raises(AssertionError, match="beyond base drift"):
+ check_effect("embedding", base, result(0.5001), result(0.5003), base, result(0.50004))
+
+
[email protected]("invalid", [math.nan, math.inf, -math.inf])
+def test_embedding_comparison_rejects_nonfinite_baseline_or_output(invalid: float) -> None:
+ base = {"vectors": [[0.1, 0.5]]}
+ a, b = {"vectors": [[0.1, 0.6]]}, {"vectors": [[0.1, 0.7]]}
+ invalid_result = {"vectors": [[0.1, invalid]]}
+ with pytest.raises(AssertionError, match="non-finite"):
+ embedding_delta(base, invalid_result)
+ with pytest.raises(AssertionError, match="non-finite"):
+ check_effect("embedding", base, a, b, base, invalid_result)
+ with pytest.raises(AssertionError, match="non-finite"):
+ check_effect("embedding", base, a, b, invalid_result, base)
+
+
[email protected]("vectors", [[], [[0.1]], [[0.1, 0.5], [0.1, 0.5]]])
+def test_embedding_comparison_rejects_empty_or_broadcastable_shape_mismatch(vectors: list) -> None:
+ with pytest.raises(AssertionError, match="shapes differ or are empty"):
+ embedding_delta({"vectors": [[0.1, 0.5]]}, {"vectors": vectors})
+
+
+def test_embedding_probe_chooses_warm_reference_before_adapter_selection(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ selections = []
+ ready = ["pin"]
+ model = MODELS["embedding"][0]
+ process = SimpleNamespace(pid=123, returncode=None)
+ process.poll = lambda: process.returncode
+
+ class FakeClient:
+ def __init__(self, *args):
+ self.sdk = self
+ self.responses = []
+
+ def call(self, kind, name, selection, route):
+ assert kind == "embedding"
+ assert name == model
+ if selection == "undeclared":
+ raise RequestError("undeclared", "INVALID_INPUT", 400)
+ selections.append(selection)
+ if selection is None:
+ return {"vectors": [[0.48 if len(selections) == 1 else 0.5]]}
+ if selection not in ready:
+ self.responses.append({"selection": selection, "status": 503, "code": "LORA_LOADING"})
+ ready.append(selection)
+ if len(ready) > 3:
+ del ready[1]
+ return {"vectors": [[0.6 if selection == "a" else 0.7]]}
+
+ def list_models(self):
+ return [{"name": model, "lora_adapters": list(ready)}]
+
+ def close(self):
+ pass
+
+ async def unload(name):
+ assert name == model
+ process.returncode = 0
+
+ monkeypatch.setattr(probe, "Client", FakeClient)
+ registry = SimpleNamespace(get=lambda name: SimpleNamespace(_process=process), unload_async=unload)
+ result = asyncio.run(
+ probe.run_model("embedding", registry, "http://unused", Evidence(tmp_path), tmp_path / "trace")
+ )
+ assert selections[:5] == [None, None, None, "a", "b"]
+ assert result["passed"] is True
+ assert result["effects"]["baseline_max_abs"] == result["effects"]["base_reset_max_abs"] == 0
+ rows = [json.loads(line) for line in (tmp_path / "events.jsonl").read_text().splitlines()]
+ baseline = next(row for row in rows if row["event"] == "baseline_comparison")
+ assert baseline["first_vs_warm_max_abs"] == pytest.approx(0.02)
+ assert baseline["warm_repeat_max_abs"] == 0
+
+
def test_effect_checks_require_delta_beyond_observed_numeric_drift() -> None:
def embedding(value: float) -> dict:
return {"vectors": [[value]]}