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
test(sglang): add runtime LoRA acceptance probe
svonava611c16f28e5c
diff --git a/tools/benchmarks/runtime_lora/README.md b/tools/benchmarks/runtime_lora/README.mdnew file mode 100644index 000000000..ec72bbef1--- /dev/null+++ b/tools/benchmarks/runtime_lora/README.md@@ -0,0 +1,61 @@+# Runtime LoRA acceptance probe++This standalone probe tests SGLang runtime LoRA through `sie_sdk.SIEClient` on+one CUDA device. It runs pinned Qwen3-0.6B generation and Qwen3-Embedding-0.6B+embedding engines sequentially, each with `mem_fraction_static: 0.5`.+It requires the runtime LoRA implementation and SGLang `0.5.10.post1`.++The local fixtures are **untrained correctness fixtures**, not useful task+adapters. Fixed-seed, nonzero rank-4 `q_proj`/`v_proj` weights make incorrect+selection observable without depending on a mutable Hub adapter. No quality+or performance conclusions follow from their outputs.++From a public checkout with its dependencies installed:++```sh+mise run test -- tools/benchmarks/runtime_lora+mise exec -- uv run --no-sync python -m tools.benchmarks.runtime_lora.fixtures \+ --output /tmp/runtime-lora-fixtures --download-weights+mise exec -- uv run --no-sync python -m tools.benchmarks.runtime_lora.probe \+ --fixtures /tmp/runtime-lora-fixtures --output /tmp/runtime-lora-evidence+```++For an installed CUDA bundle, run the same Python modules in that bundle's+environment; do not overlay an incompatible dependency environment. The CPU+tests verify fixture loading with PEFT, base restoration, SDK retry observation,+configuration, and observer behavior. **CPU tests are not GPU acceptance.**++The acceptance run checks:++- Actual `503 LORA_LOADING` followed by another successful SDK request, with no+ direct engine calls substituted for native generation, chat, or embeddings.+ Encode retries automatically. The current generation SDK surfaces this+ 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 chat token log probabilities and embedding vectors; base+ restoration after switching and after eviction. Pairwise effects must exceed+ the fixed minimum and five times measured base-repeat drift. These untrained+ fixtures provide selection evidence, not model-quality evidence.+- Stable engine PID, rejection of undeclared adapters, ready-name listing,+ preservation of one pinned adapter, and churn across four dynamic adapters.+- Overlapping A/B streams **and a successful engine forward containing both**.+ A benchmark-only subclass prepends an observer to the generation child's+ startup hooks, preserving SIE's normal compatibility hooks. The observer+ records request IDs, adapter UUIDs and aliases, and actual GPU pool slot+ assignments after `Scheduler.run_batch`. The A/B request UUIDs must occupy+ distinct valid slots, with consistent inverse mappings. Completed SDK streams+ establish completion; the hook timestamp is not a GPU timing measurement.+ It also requires SIE's slot-release compatibility hook to be present.+ Observation does not alter scheduling or model tensors.++`evidence.json` contains the final verdict. `events.jsonl`, `batches.jsonl`,+fixture hashes, generated model configurations, and `source-manifest.json`+provide the supporting record. Use a fresh output directory. The run has a+780-second default deadline and unloads each owned engine before starting the+next; any external compute allocation must have its own finite lifetime and+be stopped and verified separately by its owner.++Pinned primary sources: [generation config](https://huggingface.co/Qwen/Qwen3-0.6B/blob/c1899de289a04d12100db370d81485cdf75e47ca/config.json),+[embedding config](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B/blob/97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3/config.json),+[SGLang scheduler](https://github.com/sgl-project/sglang/blob/v0.5.10.post1/python/sglang/srt/managers/scheduler.py),+and [LoRA GPU pool](https://github.com/sgl-project/sglang/blob/v0.5.10.post1/python/sglang/srt/lora/mem_pool.py).diff --git a/tools/benchmarks/runtime_lora/__init__.py b/tools/benchmarks/runtime_lora/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tools/benchmarks/runtime_lora/_hooks/__init__.py b/tools/benchmarks/runtime_lora/_hooks/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tools/benchmarks/runtime_lora/_hooks/sitecustomize.py b/tools/benchmarks/runtime_lora/_hooks/sitecustomize.pynew file mode 100644index 000000000..6ee37fc19--- /dev/null+++ b/tools/benchmarks/runtime_lora/_hooks/sitecustomize.py@@ -0,0 +1,6 @@+"""Chain SIE's production child hooks before the benchmark-only observer."""++import importlib++importlib.import_module("sie_server.adapters.sglang._compat.sitecustomize")+importlib.import_module("tools.benchmarks.runtime_lora.observer").install()diff --git a/tools/benchmarks/runtime_lora/adapters.py b/tools/benchmarks/runtime_lora/adapters.pynew file mode 100644index 000000000..302d2fec1--- /dev/null+++ b/tools/benchmarks/runtime_lora/adapters.py@@ -0,0 +1,10 @@+"""Benchmark-owned observation hook; inference uses the production adapter."""++from pathlib import Path++from sie_server.adapters.sglang.generation import SGLangGenerationAdapter+++class ObservedGenerationAdapter(SGLangGenerationAdapter):+ def _compat_pythonpath_entries(self) -> tuple[str, ...]:+ return (str(Path(__file__).parent / "_hooks"), *super()._compat_pythonpath_entries())diff --git a/tools/benchmarks/runtime_lora/fixtures.py b/tools/benchmarks/runtime_lora/fixtures.pynew file mode 100644index 000000000..381ae4ab5--- /dev/null+++ b/tools/benchmarks/runtime_lora/fixtures.py@@ -0,0 +1,114 @@+"""Deterministic, deliberately untrained LoRAs for runtime correctness checks."""++from __future__ import annotations++import argparse+import hashlib+import json+from pathlib import Path+from typing import Any++import torch+from huggingface_hub import hf_hub_download, snapshot_download+from safetensors.torch import save_file++MODELS = {+ "generation": ("Qwen/Qwen3-0.6B", "c1899de289a04d12100db370d81485cdf75e47ca"),+ "embedding": ("Qwen/Qwen3-Embedding-0.6B", "97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3"),+}+ALIASES = ("pin", "a", "b", "c", "d")+RANK = 4+SEED = 20261016+++def digest(path: Path) -> str:+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def write_adapter(directory: Path, config: dict[str, Any], model: str, revision: str, seed: int) -> dict[str, Any]:+ directory.mkdir(parents=True, exist_ok=True)+ generator = torch.Generator(device="cpu").manual_seed(seed)+ hidden = config["hidden_size"]+ head = config["head_dim"]+ widths = {"q_proj": config["num_attention_heads"] * head, "v_proj": config["num_key_value_heads"] * head}+ tensors = {}+ for layer in range(config["num_hidden_layers"]):+ for module, width in widths.items():+ prefix = f"base_model.model.model.layers.{layer}.self_attn.{module}"+ tensors[f"{prefix}.lora_A.weight"] = torch.randn(RANK, hidden, generator=generator) * 0.04+ tensors[f"{prefix}.lora_B.weight"] = torch.randn(width, RANK, generator=generator) * 0.04+ adapter_config = {+ "base_model_name_or_path": model,+ "revision": revision,+ "peft_type": "LORA",+ "task_type": "CAUSAL_LM",+ "r": RANK,+ "lora_alpha": 8,+ "lora_dropout": 0.0,+ "bias": "none",+ "target_modules": list(widths),+ "inference_mode": True,+ }+ (directory / "adapter_config.json").write_text(json.dumps(adapter_config, indent=2) + "\n")+ save_file(tensors, str(directory / "adapter_model.safetensors"))+ return {+ "seed": seed,+ "rank": RANK,+ "target_modules": list(widths),+ "tensor_count": len(tensors),+ "files": {name: digest(directory / name) for name in ("adapter_config.json", "adapter_model.safetensors")},+ }+++def prepare(output: Path, *, download_weights: bool = False, cache_dir: str | None = None) -> dict[str, Any]:+ manifest = {}+ for kind, (model, revision) in MODELS.items():+ config_path = Path(hf_hub_download(model, "config.json", revision=revision, cache_dir=cache_dir))+ config = json.loads(config_path.read_text())+ if config["model_type"] != "qwen3":+ raise ValueError("This fixture generator requires the pinned Qwen3 architecture")+ if download_weights:+ snapshot_download(+ model,+ revision=revision,+ cache_dir=cache_dir,+ allow_patterns=["*.safetensors", "*.safetensors.index.json", "*.json", "*.txt"],+ )+ manifest[kind] = {+ "model": model,+ "revision": revision,+ "config_sha256": digest(config_path),+ "shape": {+ key: config[key]+ for key in (+ "hidden_size",+ "head_dim",+ "num_attention_heads",+ "num_key_value_heads",+ "num_hidden_layers",+ )+ },+ "adapters": {+ alias: write_adapter(output / kind / alias, config, model, revision, SEED + index)+ for index, alias in enumerate(ALIASES)+ },+ }+ (output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")+ return manifest+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--output", type=Path, required=True)+ parser.add_argument("--cache-dir")+ parser.add_argument("--download-weights", action="store_true")+ args = parser.parse_args()+ print(+ json.dumps(+ prepare(args.output.resolve(), download_weights=args.download_weights, cache_dir=args.cache_dir), indent=2+ )+ )+++if __name__ == "__main__":+ main()diff --git a/tools/benchmarks/runtime_lora/observer.py b/tools/benchmarks/runtime_lora/observer.pynew file mode 100644index 000000000..3591a4093--- /dev/null+++ b/tools/benchmarks/runtime_lora/observer.py@@ -0,0 +1,112 @@+"""Observe successful SGLang forwards without changing scheduling or tensors."""++from __future__ import annotations++import builtins+import hashlib+import importlib.metadata+import json+import os+import sys+import time+from collections.abc import Mapping, Sequence+from functools import wraps+from pathlib import Path+from types import ModuleType+from typing import Any++MODULE = "sglang.srt.managers.scheduler"+LORA_MODULE = "sglang.srt.lora.lora_manager"+COMPAT_MARKER = "_sie_lora_slot_release_compat"+MARKER = "_sie_runtime_lora_benchmark"+TRACE_ENV = "SIE_RUNTIME_LORA_BATCH_TRACE"+++def append(path: str, row: dict[str, Any]) -> None:+ data = (json.dumps(row, sort_keys=True) + "\n").encode()+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)+ try:+ os.write(fd, data)+ finally:+ os.close(fd)+++def patch_scheduler(module: ModuleType, path: str) -> None:+ scheduler = module.Scheduler+ if getattr(scheduler, MARKER, False):+ return+ original = scheduler.run_batch++ @wraps(original)+ def observed(self: Any, batch: Any, *args: Any, **kwargs: Any) -> Any:+ manager = self.tp_worker.model_runner.lora_manager++ def alias(uid: str | None) -> str | None:+ return manager.lora_refs[uid].lora_name if uid is not None else None++ row = {+ "event": "forward",+ "pid": os.getpid(),+ "start_ns": time.time_ns(),+ "mode": str(batch.forward_mode),+ "requests": [{"rid": req.rid, "uid": req.lora_id, "lora": alias(req.lora_id)} for req in batch.reqs],+ }+ result = original(self, batch, *args, **kwargs)+ row["end_ns"] = time.time_ns()+ pool = manager.memory_pool+ row["gpu_slot_count"] = len(pool.buffer_id_to_uid)+ row["gpu_slot_uids"] = list(pool.buffer_id_to_uid)+ row["gpu_slots"] = [+ {"uid": uid, "lora": alias(uid), "slot": slot} for uid, slot in pool.uid_to_buffer_id.items()+ ]+ append(path, row)+ return result++ scheduler.run_batch = observed+ setattr(scheduler, MARKER, True)+++def install() -> None:+ path = os.environ.get(TRACE_ENV)+ if not path:+ return+ version = importlib.metadata.version("sglang")+ if version != "0.5.10.post1":+ raise RuntimeError(f"The benchmark observer is qualified only for SGLang 0.5.10.post1; found {version}")+ previous = builtins.__import__+ installed = False++ def imported(+ name: str,+ globals: Mapping[str, object] | None = None,+ locals: Mapping[str, object] | None = None,+ fromlist: Sequence[str] | None = (),+ level: int = 0,+ ) -> ModuleType:+ nonlocal installed+ result = previous(name, globals, locals, fromlist, level)+ module = sys.modules.get(MODULE)+ if not installed and isinstance(module, ModuleType) and hasattr(module, "Scheduler"):+ if module.__file__ is None:+ raise RuntimeError("The scheduler source file is unavailable for provenance")+ manager = getattr(sys.modules.get(LORA_MODULE), "LoRAManager", None)+ slot_release_compat = bool(getattr(manager, COMPAT_MARKER, False))+ if not slot_release_compat:+ raise RuntimeError("The production LoRA slot-release compatibility hook is absent")+ installed = True+ patch_scheduler(module, path)+ append(+ path,+ {+ "event": "observer_installed",+ "pid": os.getpid(),+ "version": version,+ "slot_release_compat": slot_release_compat,+ "scheduler_sha256": hashlib.sha256(Path(module.__file__).read_bytes()).hexdigest(),+ },+ )+ if builtins.__import__ is imported:+ setattr(builtins, "__import__", previous) # noqa: B010+ return result++ setattr(builtins, "__import__", imported) # noqa: B010diff --git a/tools/benchmarks/runtime_lora/probe.py b/tools/benchmarks/runtime_lora/probe.pynew file mode 100644index 000000000..18149716a--- /dev/null+++ b/tools/benchmarks/runtime_lora/probe.py@@ -0,0 +1,536 @@+"""Exercise runtime LoRA through public SIE SDK routes on one CUDA device."""++from __future__ import annotations++import argparse+import asyncio+import hashlib+import importlib.metadata+import inspect+import json+import math+import os+import socket+import threading+import time+from http import HTTPStatus+from pathlib import Path+from typing import Any, cast++import httpx+import numpy as np+import torch+import uvicorn+import yaml+from msgpack.exceptions import UnpackException+from sie_sdk import SIEClient+from sie_sdk._msgpack import unpackb as unpack_msgpack+from sie_sdk.client.errors import RequestError, ServerError+from sie_sdk.types import ChatMessage+from sie_server.adapters.sglang.generation import SGLangGenerationAdapter+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 tools.benchmarks.runtime_lora.fixtures import ALIASES, MODELS, RANK, digest, prepare+from tools.benchmarks.runtime_lora.observer import TRACE_ENV++ROOT = Path(__file__).resolve().parents[3]+MESSAGES: list[ChatMessage] = [{"role": "user", "content": "Explain why the sky is blue in two short sentences."}]+PROMPT = "The sky appears blue because"+TEXTS = ["A red fox walks through the forest.", "Neural networks encode text as vectors."]+MAX_RESIDENT = 3+MIN_EMBEDDING_EFFECT = 1e-5+MAX_EMBEDDING_RESET_ERROR = 5e-5+MIN_PROBABILITY_EFFECT = 1e-4+MAX_PROBABILITY_RESET_ERROR = 1e-3+MAX_GENERATION_RETRIES = 10+MAX_RETRY_DELAY_S = 5+EFFECT_DRIFT_MULTIPLIER = 5+++def require(condition: Any, message: str) -> None:+ if not condition:+ raise AssertionError(message)+++def wire_object(message: httpx.Request | httpx.Response) -> dict[str, Any]:+ try:+ if message.headers.get("content-type", "").split(";", 1)[0] == "application/msgpack":+ value = unpack_msgpack(message.content, numeric_arrays=False)+ else:+ value = json.loads(message.content)+ except (ValueError, UnpackException, httpx.RequestNotRead):+ return {}+ return value if isinstance(value, dict) else {}+++class Evidence:+ def __init__(self, directory: Path) -> None:+ self.directory = directory+ directory.mkdir(parents=True, exist_ok=True)+ self._lock = threading.Lock()++ def emit(self, event: str, **fields: Any) -> dict[str, Any]:+ row = {"event": event, "time_ns": time.time_ns(), **fields}+ encoded = json.dumps(row, sort_keys=True)+ with self._lock, (self.directory / "events.jsonl").open("a") as file:+ file.write(encoded + "\n")+ print("RUNTIME_LORA " + encoded, flush=True)+ return row+++class Client:+ def __init__(self, url: str, evidence: Evidence, *, transport: httpx.BaseTransport | None = None) -> None:+ self.evidence = evidence+ self.responses: list[dict[str, Any]] = []+ http = httpx.Client(base_url=url, timeout=180, transport=transport, event_hooks={"response": [self.observe]})+ self.sdk = SIEClient(url, timeout_s=180, http_client=http)++ def observe(self, response: httpx.Response) -> None:+ code = None+ if response.status_code >= HTTPStatus.BAD_REQUEST:+ response.read()+ body = wire_object(response)+ error = body.get("error", body.get("detail", body))+ code = error.get("code") if isinstance(error, dict) else None+ request = wire_object(response.request)+ options = (request.get("params") or {}).get("options") or request.get("options") or {}+ row = {+ "path": response.request.url.path,+ "status": response.status_code,+ "code": code,+ "selection": request.get("lora_adapter", options.get("lora")),+ }+ self.responses.append(row)+ self.evidence.emit("http_response", **row)++ def call(self, kind: str, model: str, selection: str | None, route: str = "chat") -> dict[str, Any]:+ for attempt in range(MAX_GENERATION_RETRIES + 1):+ try:+ return self._call(kind, model, selection, route)+ except ServerError as error:+ if (+ kind != "generation"+ or error.status_code != HTTPStatus.SERVICE_UNAVAILABLE+ or error.code != "LORA_LOADING"+ or attempt == MAX_GENERATION_RETRIES+ ):+ raise+ delay = error.retry_after if error.retry_after is not None else 0.2+ require(0 <= delay <= MAX_RETRY_DELAY_S, "LoRA retry delay is outside this bounded probe")+ self.evidence.emit(+ "fresh_sdk_generation_retry", selection=selection, route=route, attempt=attempt + 1, delay_s=delay+ )+ time.sleep(delay)+ raise AssertionError("unreachable retry state")++ def _call(self, kind: str, model: str, selection: str | None, route: str) -> dict[str, Any]:+ if kind == "embedding":+ result = self.sdk.encode(+ model,+ [{"text": text} for text in TEXTS],+ output_types=["dense"],+ options={"lora": selection},+ max_oom_retries=0,+ )+ return {"vectors": np.stack([item["dense"] for item in result]).tolist()}+ if route == "generate":+ result = self.sdk.generate(+ model,+ PROMPT,+ max_new_tokens=24,+ temperature=0.0,+ seed=17,+ lora_adapter=selection,+ max_oom_retries=0,+ )+ return {"text": result["text"]}+ result = self.sdk.chat_completions(+ model,+ MESSAGES,+ max_tokens=24,+ temperature=0.0,+ seed=17,+ logprobs=True,+ top_logprobs=5,+ lora_adapter=selection,+ max_oom_retries=0,+ )+ choice = result["choices"][0]+ return {"text": choice["message"].get("content") or "", "logprobs": choice.get("logprobs")}++ def stream(self, model: str, selection: str, barrier: threading.Barrier) -> dict[str, Any]:+ barrier.wait(timeout=10)+ start = time.time_ns()+ chunks = list(+ self.sdk.stream_chat_completions(+ model,+ [{"role": "user", "content": "Count from 1 to 200, separated by commas. Do not explain."}],+ max_tokens=128,+ temperature=0.0,+ seed=17,+ lora_adapter=selection,+ extra_body={"min_tokens": 96},+ max_oom_retries=0,+ )+ )+ end = time.time_ns()+ text = "".join(+ choice.get("delta", {}).get("content") or "" for chunk in chunks for choice in chunk.get("choices", [])+ )+ require(chunks and text, "stream returned no content")+ return {"selection": selection, "start_ns": start, "end_ns": end, "chunk_count": len(chunks), "text": text}++ def close(self) -> None:+ self.sdk.close()+++def first_distribution(result: dict[str, Any]) -> dict[str, float]:+ content = (result.get("logprobs") or {}).get("content") or []+ require(content, "chat must return token logprobs")+ first = content[0]+ return {item["token"]: float(item["logprob"]) for item in first.get("top_logprobs", [first])}+++def distribution_delta(left: dict[str, Any], right: dict[str, Any]) -> float:+ a, b = first_distribution(left), first_distribution(right)+ probabilities_a = {token: math.exp(value) for token, value in a.items()}+ probabilities_b = {token: math.exp(value) for token, value in b.items()}+ return max(abs(probabilities_a.get(token, 0.0) - probabilities_b.get(token, 0.0)) for token in a.keys() | b.keys())+++def check_effect(+ kind: str, base: dict[str, Any], a: dict[str, Any], b: dict[str, Any], restored: dict[str, Any]+) -> dict[str, Any]:+ 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])))+ require(reset < MAX_EMBEDDING_RESET_ERROR, "base embeddings were not restored")+ minimum = max(MIN_EMBEDDING_EFFECT, EFFECT_DRIFT_MULTIPLIER * reset)+ 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,+ "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)+ minimum = max(MIN_PROBABILITY_EFFECT, EFFECT_DRIFT_MULTIPLIER * reset)+ require(+ base["text"] == restored["text"] and reset < MAX_PROBABILITY_RESET_ERROR,+ "base generation was not restored",+ )+ require(min(aa, bb, ab) > minimum, "LoRA generation had no observable effect beyond base drift")+ return {+ "a_vs_base_first_token_probability_delta": aa,+ "b_vs_base_first_token_probability_delta": bb,+ "a_vs_b_first_token_probability_delta": ab,+ "base_reset_first_token_probability_delta": reset,+ "required_effect_minimum": minimum,+ "base_text_restored": True,+ }+++def configs(directory: Path, fixtures: Path) -> dict[str, Any]:+ directory.mkdir(parents=True, exist_ok=True)+ result = {}+ for kind, (model, revision) in MODELS.items():+ data = yaml.safe_load((ROOT / "packages/sie_server/models" / f"{model.replace('/', '__')}.yaml").read_text())+ require(data["hf_revision"] == revision, "catalog model revision differs from benchmark pin")+ profile = data["profiles"]["default"]+ profile["adapter_path"] = (+ "tools.benchmarks.runtime_lora.adapters:ObservedGenerationAdapter"+ if kind == "generation"+ else "sie_server.adapters.sglang.embedding:SGLangEmbeddingAdapter"+ )+ profile["max_batch_tokens"] = 4096+ profile["kv_budget_tokens"] = 4096+ loadtime = profile.setdefault("adapter_options", {}).setdefault("loadtime", {})+ loadtime.update(+ {+ "mem_fraction_static": 0.5,+ "max_seq_length": 4096,+ "lora_paths": {alias: str((fixtures / kind / alias).resolve()) for alias in ALIASES},+ "preload_loras": ["pin"],+ "max_lora_rank": RANK,+ "lora_target_modules": ["q_proj", "v_proj"],+ "max_loras_per_batch": 2,+ "max_loaded_loras": 3,+ }+ )+ data["profiles"] = {"default": profile}+ data["max_sequence_length"] = 4096+ ModelConfig.model_validate(data)+ (directory / f"{kind}.yaml").write_text(yaml.safe_dump(data, sort_keys=False))+ result[kind] = data+ return result+++def source_manifest() -> dict[str, Any]:+ roots = [ROOT / "packages/sie_server/src", ROOT / "packages/sie_sdk/src", Path(__file__).parent]+ files = [path for root in roots for path in root.rglob("*.py") if "__pycache__" not in path.parts]+ files.extend(ROOT / name for name in ("pyproject.toml", "uv.lock"))+ files.extend(+ ROOT / "packages/sie_server/models" / f"{model.replace('/', '__')}.yaml" for model, _ in MODELS.values()+ )+ files.sort()+ hashes = {str(path.relative_to(ROOT)): digest(path) for path in files}+ return {"sha256": hashlib.sha256(json.dumps(hashes, sort_keys=True).encode()).hexdigest(), "files": hashes}+++def batch_rows(path: Path) -> list[dict[str, Any]]:+ return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else []+++def mixed_batches(rows: list[dict[str, Any]], start: int, end: int) -> list[dict[str, Any]]:+ result = []+ for row in rows:+ if row.get("event") != "forward" or not start <= row["start_ns"] <= end:+ continue+ selected = {req["uid"]: req["lora"] for req in row["requests"] if req["lora"] in {"a", "b"}}+ if not {"a", "b"}.issubset(selected.values()):+ continue+ slots = {entry["uid"]: entry for entry in row["gpu_slots"]}+ if not all(+ uid in slots+ and slots[uid]["lora"] == alias+ and 0 <= slots[uid]["slot"] < row["gpu_slot_count"]+ and row["gpu_slot_uids"][slots[uid]["slot"]] == uid+ for uid, alias in selected.items()+ ):+ continue+ if len({slots[uid]["slot"] for uid in selected}) == len(selected):+ result.append(row)+ return result+++async def run_model(kind: str, registry: Any, url: str, evidence: Evidence, trace: Path) -> dict[str, Any]:+ model = MODELS[kind][0]+ client = Client(url, evidence)+ others = []+ pid = None++ async def call(selection: str | None, phase: str, route: str = "chat") -> dict[str, Any]:+ start = time.time_ns()+ value = await asyncio.to_thread(client.call, kind, model, selection, route)+ end = time.time_ns()+ evidence.emit(+ "result", kind=kind, phase=phase, route=route, selection=selection, start_ns=start, end_ns=end, result=value+ )+ if kind == "generation":+ matching = [+ row+ for row in batch_rows(trace)+ if row.get("event") == "forward"+ and start <= row["start_ns"] <= end+ and any(req["lora"] == selection for req in row["requests"])+ ]+ require(matching, f"{route} did not forward with its selected LoRA")+ if pid is not None:+ require(registry.get(model)._process.pid == pid, "engine PID changed during LoRA lifecycle")+ return value++ async def listing(phase: str) -> set[str]:+ models = await asyncio.to_thread(client.sdk.list_models)+ current = cast("dict[str, Any]", next(item for item in models if item["name"] == model))+ require("lora_adapters" in current, "local listing did not expose ready LoRAs")+ names = set(current["lora_adapters"])+ require("pin" in names and len(names) <= MAX_RESIDENT, "pinned adapter or residency bound violated")+ evidence.emit("residency", kind=kind, phase=phase, names=sorted(names), pid=registry.get(model)._process.pid)+ return names++ try:+ base = await call(None, "base_before")+ process = registry.get(model)._process+ pid = process.pid+ require(await listing("initial") == {"pin"}, "dynamic adapters must start unloaded")+ try:+ await call("undeclared", "undeclared")+ except RequestError as error:+ require(error.status_code == HTTPStatus.BAD_REQUEST, "undeclared adapter was not rejected as invalid input")+ evidence.emit("undeclared_denied", kind=kind, status=error.status_code, code=error.code)+ else:+ raise AssertionError("undeclared adapter was accepted")+ native_base = None+ if kind == "generation":+ native_base = await call(None, "native_base", "generate")+ await call("a", "native_cold_a", "generate")+ a = await call("a", "a")+ b = await call("b", "cold_b")+ require(await listing("a_b_ready") == {"pin", "a", "b"}, "ready listing omitted a selected adapter")+ reset = await call(None, "base_after_a_b")+ effects = check_effect(kind, base, a, b, reset)+ evidence.emit("effect_pass", kind=kind, **effects)++ if kind == "generation":+ await call("b", "native_b", "generate")+ native_reset = await call(None, "native_reset", "generate")+ require(native_base == native_reset, "native generation base did not restore")+ barrier = threading.Barrier(2)+ others = [Client(url, evidence), Client(url, evidence)]+ streams = await asyncio.gather(+ *(+ asyncio.to_thread(item.stream, model, alias, barrier)+ for item, alias in zip(others, ("a", "b"), strict=True)+ )+ )+ start, end = max(item["start_ns"] for item in streams), min(item["end_ns"] for item in streams)+ require(start < end, "A/B client streams did not overlap")+ batches = mixed_batches(batch_rows(trace), start, end)+ require(batches, "no successful SGLang forward contained both A and B")+ evidence.emit(+ "mixed_engine_batch_pass", streams=streams, forward_count=len(batches), first_batch=batches[0]+ )++ previous = await listing("before_churn")+ evicted = set()+ for index, selection in enumerate(("c", "d", "a", "b", "c", "d", "pin")):+ await call(selection, f"churn_{index}")+ ready = await listing(f"churn_{index}")+ require(selection in ready, "successful request missing from ready listing")+ evicted.update(previous - ready)+ previous = ready+ require(evicted and "pin" not in evicted, "churn did not evict dynamic adapters while preserving pin")+ restored = await call(None, "base_after_churn")+ post_churn_effects = check_effect(kind, base, a, b, restored)+ evidence.emit("post_churn_effect_pass", kind=kind, **post_churn_effects)+ cold = {+ row["selection"]+ for row in client.responses+ if row["status"] == HTTPStatus.SERVICE_UNAVAILABLE and row["code"] == "LORA_LOADING"+ }+ require(+ {"a", "b", "c", "d"}.issubset(cold),+ "cold adapter requests did not expose 503 LORA_LOADING before SDK retry",+ )+ result = {+ "model": model,+ "pid": pid,+ "effects": effects,+ "post_churn_effects": post_churn_effects,+ "cold_retried": sorted(cold),+ "evicted": sorted(evicted),+ "pin_preserved": True,+ }+ if kind == "generation":+ forwards = [row for row in batch_rows(trace) if row.get("event") == "forward"]+ capacity = max(row["gpu_slot_count"] for row in forwards)+ seen = {req["lora"] for row in forwards for req in row["requests"]} - {None}+ require(+ set(ALIASES).issubset(seen) and len(seen) > capacity,+ "successful churn did not exceed actual GPU slot count",+ )+ result.update({"gpu_slot_count": capacity, "distinct_forward_adapters": sorted(seen)})+ evidence.emit("model_pass", kind=kind, **result)+ await registry.unload_async(model)+ require(process.poll() is not None, "owned engine still running after sequential unload")+ evidence.emit("engine_stopped", kind=kind, pid=pid, returncode=process.poll())+ return result+ finally:+ client.close()+ for item in others:+ item.close()+++async def run(args: argparse.Namespace) -> None:+ output = args.output.resolve()+ evidence = Evidence(output)+ os.environ.update(+ {+ "SIE_TELEMETRY_DISABLED": "1",+ "SIE_DISK_CACHE_ENABLED": "false",+ "SIE_MAX_LORAS_PER_MODEL": "3",+ "SIE_MODEL_LOAD_TIMEOUT_S": "360",+ "SIE_SGLANG_STARTUP_TIMEOUT_S": "330",+ TRACE_ENV: str(output / "batches.jsonl"),+ }+ )+ require(+ "preload_loras" in inspect.signature(SGLangGenerationAdapter).parameters,+ "runtime LoRA implementation is absent from this source tree",+ )+ versions = {name: importlib.metadata.version(name) for name in ("torch", "transformers", "sglang", "peft")}+ require(versions["sglang"] == "0.5.10.post1", "unexpected SGLang version")+ require(torch.cuda.is_available(), "CUDA is required for acceptance; run test_probe.py for CPU smoke")+ evidence.emit(+ "environment",+ versions=versions,+ device=torch.cuda.get_device_name(0),+ total_memory=torch.cuda.get_device_properties(0).total_memory,+ )+ manifest = source_manifest()+ (output / "source-manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")+ evidence.emit("source", sha256=manifest["sha256"])+ fixtures = args.fixtures.resolve() if args.fixtures else output / "fixtures"+ if not (fixtures / "manifest.json").is_file():+ prepare(fixtures, cache_dir=args.cache_dir)+ fixture_manifest = json.loads((fixtures / "manifest.json").read_text())+ for kind in MODELS:+ for alias, metadata in fixture_manifest[kind]["adapters"].items():+ require(+ all(digest(fixtures / kind / alias / name) == sha for name, sha in metadata["files"].items()),+ "fixture hash mismatch",+ )+ (output / "fixtures-manifest.json").write_text(json.dumps(fixture_manifest, indent=2) + "\n")+ configs(output / "models", fixtures)+ app = AppFactory.create_app(+ AppStateConfig(models_dir=output / "models", device="cuda:0", remote_serving=False, bind_host="127.0.0.1")+ )+ sock = socket.socket()+ sock.bind(("127.0.0.1", 0))+ url = f"http://127.0.0.1:{sock.getsockname()[1]}"+ server = uvicorn.Server(uvicorn.Config(app, log_level="info", timeout_graceful_shutdown=30))+ task = asyncio.create_task(server.serve(sockets=[sock]))+ summary: dict[str, Any] = {"passed": False, "versions": versions, "source_sha256": manifest["sha256"], "models": {}}+ try:+ async with asyncio.timeout(args.deadline_s):+ while not server.started:+ if task.done():+ await task+ raise RuntimeError("SIE stopped before readiness")+ await asyncio.sleep(0.1)+ for kind in MODELS:+ summary["models"][kind] = await run_model(+ kind, app.state.registry, url, evidence, output / "batches.jsonl"+ )+ summary["passed"] = True+ except BaseException as error:+ summary["error"] = {"type": type(error).__name__, "message": str(error)}+ raise+ finally:+ summary["shutdown_complete"] = False+ (output / "evidence.json").write_text(json.dumps(summary, indent=2) + "\n")+ server.should_exit = True+ try:+ async with asyncio.timeout(40):+ await task+ summary["shutdown_complete"] = True+ except BaseException as error:+ summary["shutdown_error"] = {"type": type(error).__name__, "message": str(error)}+ raise+ finally:+ (output / "evidence.json").write_text(json.dumps(summary, indent=2) + "\n")+ evidence.emit("finished", passed=summary["passed"], shutdown_complete=summary["shutdown_complete"])+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--output", type=Path, required=True)+ parser.add_argument("--fixtures", type=Path)+ parser.add_argument("--cache-dir")+ parser.add_argument("--deadline-s", type=float, default=780)+ args = parser.parse_args()+ require(not args.output.exists() or not any(args.output.iterdir()), "use a fresh evidence directory")+ asyncio.run(run(args))+++if __name__ == "__main__":+ main()diff --git a/tools/benchmarks/runtime_lora/tests/test_probe.py b/tools/benchmarks/runtime_lora/tests/test_probe.pynew file mode 100644index 000000000..18e23ff5b--- /dev/null+++ b/tools/benchmarks/runtime_lora/tests/test_probe.py@@ -0,0 +1,257 @@+"""CPU contract smoke; these checks do not establish CUDA acceptance."""++from __future__ import annotations++import json+import math+import os+import subprocess+import sys+from pathlib import Path+from types import ModuleType, SimpleNamespace++import httpx+import numpy as np+import pytest+import torch+from peft import PeftModel+from safetensors.torch import load_file+from sie_sdk._msgpack import packb as pack_msgpack+from transformers import Qwen3Config, Qwen3ForCausalLM++from tools.benchmarks.runtime_lora.fixtures import MODELS, digest, write_adapter+from tools.benchmarks.runtime_lora.observer import patch_scheduler+from tools.benchmarks.runtime_lora.probe import ROOT, Client, Evidence, batch_rows, check_effect, configs, mixed_batches+++def tiny_config() -> Qwen3Config:+ return Qwen3Config(+ vocab_size=32,+ hidden_size=16,+ intermediate_size=32,+ num_hidden_layers=2,+ num_attention_heads=2,+ num_key_value_heads=1,+ head_dim=8,+ )+++def test_fixture_weights_load_in_peft_change_logits_and_restore_base(tmp_path: Path) -> None:+ config = tiny_config()+ first = write_adapter(tmp_path / "a", config.to_dict(), "tiny-qwen", "test", 17)+ write_adapter(tmp_path / "same", config.to_dict(), "tiny-qwen", "test", 17)+ write_adapter(tmp_path / "b", config.to_dict(), "tiny-qwen", "test", 18)+ assert first["files"]["adapter_model.safetensors"] == digest(tmp_path / "same/adapter_model.safetensors")+ tensors = load_file(tmp_path / "a/adapter_model.safetensors")+ assert len(tensors) == 8+ assert all(torch.count_nonzero(value) == value.numel() for value in tensors.values())+ torch.manual_seed(1)+ model = Qwen3ForCausalLM(config).eval()+ inputs = torch.tensor([[1, 2, 3, 4]])+ with torch.no_grad():+ base = model(inputs).logits.clone()+ model = PeftModel.from_pretrained(model, tmp_path / "a", adapter_name="a")+ model.load_adapter(tmp_path / "b", adapter_name="b")+ with torch.no_grad():+ model.set_adapter("a")+ a = model(inputs).logits.clone()+ model.set_adapter("b")+ b = model(inputs).logits.clone()+ with model.disable_adapter():+ restored = model(inputs).logits+ assert torch.max(torch.abs(base - a)) > 1e-5+ assert torch.max(torch.abs(base - b)) > 1e-5+ assert torch.max(torch.abs(a - b)) > 1e-5+ torch.testing.assert_close(restored, base, rtol=0, atol=1e-6)+++def test_catalog_pins_and_declared_fixture_config(tmp_path: Path) -> None:+ generated = configs(tmp_path / "models", tmp_path / "fixtures")+ for kind, (name, revision) in MODELS.items():+ data = generated[kind]+ assert data["hf_id"] == name+ assert data["hf_revision"] == revision+ options = data["profiles"]["default"]["adapter_options"]["loadtime"]+ assert options["preload_loras"] == ["pin"]+ assert set(options["lora_paths"]) == {"pin", "a", "b", "c", "d"}+ assert options["max_loras_per_batch"] == 2+ assert options["max_loaded_loras"] == 3+ assert options["mem_fraction_static"] == 0.5+++def test_sdk_observer_captures_cold_503_and_native_retry(tmp_path: Path) -> None:+ calls = []++ def respond(request: httpx.Request) -> httpx.Response:+ calls.append(json.loads(request.content))+ if len(calls) == 1:+ return httpx.Response(+ 503, json={"error": {"code": "LORA_LOADING", "message": "loading"}}, headers={"Retry-After": "0"}+ )+ return httpx.Response(200, json={"model": MODELS["generation"][0], "text": "ok"})++ client = Client("http://localhost", Evidence(tmp_path), transport=httpx.MockTransport(respond))+ try:+ assert client.call("generation", MODELS["generation"][0], "a", "generate") == {"text": "ok"}+ assert [row["status"] for row in client.responses] == [503, 200]+ assert all(request["lora_adapter"] == "a" for request in calls)+ assert client.responses[0]["code"] == "LORA_LOADING"+ finally:+ client.close()++[email protected]("error_content_type", ["application/json", "application/msgpack"])+def test_sdk_observer_captures_msgpack_selection_and_automatic_encode_retry(+ tmp_path: Path, error_content_type: str+) -> None:+ calls = []++ def respond(request: httpx.Request) -> httpx.Response:+ calls.append(request)+ if len(calls) == 1:+ error = {"error": {"code": "LORA_LOADING", "message": "loading"}}+ content = pack_msgpack(error) if error_content_type == "application/msgpack" else json.dumps(error).encode()+ return httpx.Response(+ 503, content=content, headers={"Content-Type": error_content_type, "Retry-After": "0"}+ )+ return httpx.Response(+ 200,+ content=pack_msgpack({"items": [{"dense": {"dims": 2, "values": np.array([0.5, 0.25])}}] * 2}),+ headers={"Content-Type": "application/msgpack"},+ )++ client = Client("http://localhost", Evidence(tmp_path), transport=httpx.MockTransport(respond))+ try:+ assert client.call("embedding", MODELS["embedding"][0], "a") == {"vectors": [[0.5, 0.25]] * 2}+ assert [row["status"] for row in client.responses] == [503, 200]+ assert all(row["selection"] == "a" for row in client.responses)+ assert client.responses[0]["code"] == "LORA_LOADING"+ assert all(request.headers["content-type"] == "application/msgpack" for request in calls)+ assert "fresh_sdk_generation_retry" not in (tmp_path / "events.jsonl").read_text()+ finally:+ client.close()+++def test_observer_records_actual_successful_batch_and_does_not_change_result(tmp_path: Path) -> None:+ trace = tmp_path / "batches.jsonl"+ result = object()+ seen = []++ class Scheduler:+ def run_batch(self, batch, extra=None):+ seen.append((batch, extra))+ if extra == "fail":+ raise ValueError("forward failed")+ return result++ module = ModuleType("fake_scheduler")+ module.Scheduler = Scheduler+ patch_scheduler(module, str(trace))+ scheduler = Scheduler()+ uid_a, uid_b = "62f6770ac6ac4f718ff17fe577616e01", "ad52764f1b98498595d08d1243932632"+ scheduler.tp_worker = SimpleNamespace(+ model_runner=SimpleNamespace(+ lora_manager=SimpleNamespace(+ lora_refs={uid_a: SimpleNamespace(lora_name="a"), uid_b: SimpleNamespace(lora_name="b")},+ memory_pool=SimpleNamespace(buffer_id_to_uid=[uid_a, uid_b], uid_to_buffer_id={uid_a: 0, uid_b: 1}),+ )+ )+ )+ batch = SimpleNamespace(+ forward_mode="DECODE", reqs=[SimpleNamespace(rid="1", lora_id=uid_a), SimpleNamespace(rid="2", lora_id=uid_b)]+ )+ assert scheduler.run_batch(batch, extra=3) is result+ assert seen == [(batch, 3)]+ with pytest.raises(ValueError, match="forward failed"):+ scheduler.run_batch(batch, extra="fail")+ rows = batch_rows(trace)+ assert len(rows) == 1+ assert rows[0]["gpu_slot_count"] == 2+ assert rows[0]["requests"][0] == {"rid": "1", "uid": uid_a, "lora": "a"}+ assert rows[0]["gpu_slots"] == [{"uid": uid_a, "lora": "a", "slot": 0}, {"uid": uid_b, "lora": "b", "slot": 1}]+ assert mixed_batches(rows, 0, 2**64) == rows+ rows[0]["gpu_slot_uids"][1] = uid_a+ assert mixed_batches(rows, 0, 2**64) == []+ rows[0]["gpu_slot_uids"][1] = uid_b+ rows[0]["gpu_slots"][1]["slot"] = 0+ assert mixed_batches(rows, 0, 2**64) == []+ rows[0]["gpu_slots"][1]["slot"] = 1+ rows[0]["requests"][1]["lora"] = "a"+ assert mixed_batches(rows, 0, 2**64) == []+++def test_child_observer_defers_import_and_preserves_production_hook(tmp_path: Path) -> None:+ """A synthetic upstream package checks startup composition without CUDA."""+ for package in ("sglang", "sglang/srt", "sglang/srt/managers", "sglang/srt/lora"):+ directory = tmp_path / package+ directory.mkdir(parents=True, exist_ok=True)+ (directory / "__init__.py").touch()+ metadata = tmp_path / "sglang-0.5.10.post1.dist-info"+ metadata.mkdir()+ (metadata / "METADATA").write_text("Metadata-Version: 2.1\nName: sglang\nVersion: 0.5.10.post1\n")+ # The real slot-release implementation has its own production tests. This+ # sentinel exercises the observer's explicit prerequisite and evidence.+ (tmp_path / "sglang/srt/lora/lora_manager.py").write_text(+ "class LoRAManager:\n _sie_lora_slot_release_compat = True\n"+ )+ (tmp_path / "sglang/srt/managers/scheduler.py").write_text(+ "from sglang.srt.lora.lora_manager import LoRAManager\n"+ "class Scheduler:\n def run_batch(self, batch):\n return 47\n"+ )+ trace = tmp_path / "child-batches.jsonl"+ environment = {+ **os.environ,+ "PYTHONPATH": os.pathsep.join(+ map(str, (ROOT / "tools/benchmarks/runtime_lora/_hooks", tmp_path, ROOT, ROOT / "packages/sie_server/src"))+ ),+ "SIE_RUNTIME_LORA_BATCH_TRACE": str(trace),+ "SIE_SGLANG_MM_PROCESS_CONFIG_COMPAT": "1",+ "SIE_SGLANG_LORA_COMPAT": "",+ }+ script = (+ "import sys\nassert 'sglang' not in sys.modules\n"+ "from sglang.srt.managers.scheduler import Scheduler\n"+ "import builtins\nfrom types import SimpleNamespace as S\n"+ "assert getattr(builtins.__import__, '_sie_mm_process_config_deferred_compat', False)\n"+ "scheduler = Scheduler()\n"+ "scheduler.tp_worker = S(model_runner=S(lora_manager=S(lora_refs={}, "+ "memory_pool=S(buffer_id_to_uid=[None], uid_to_buffer_id={None: 0}))))\n"+ "assert scheduler.run_batch(S(forward_mode='DECODE', reqs=[S(rid='r', lora_id=None)])) == 47\n"+ )+ result = subprocess.run( # noqa: S603 — fixed synthetic package and script, no external input+ [sys.executable, "-c", script], env=environment, capture_output=True, text=True, check=False+ )+ assert result.returncode == 0, result.stderr+ rows = batch_rows(trace)+ assert [row["event"] for row in rows] == ["observer_installed", "forward"]+ assert rows[0]["slot_release_compat"] is True+ assert rows[1]["requests"] == [{"rid": "r", "uid": None, "lora": None}]+++def test_effect_checks_fail_for_ignored_adapters_and_contaminated_base() -> None:+ base = {"vectors": [[0.1, 0.2]]}+ a = {"vectors": [[0.2, 0.3]]}+ b = {"vectors": [[0.3, 0.4]]}+ assert check_effect("embedding", base, a, b, base)["base_reset_max_abs"] == 0+ with pytest.raises(AssertionError, match="did not differ"):+ check_effect("embedding", base, base, b, base)+ with pytest.raises(AssertionError, match="not restored"):+ check_effect("embedding", base, a, b, a)+ assert np.isfinite(check_effect("embedding", base, a, b, base)["a_vs_b_max_abs"])+++def test_effect_checks_require_delta_beyond_observed_numeric_drift() -> None:+ def embedding(value: float) -> dict:+ return {"vectors": [[value]]}++ def generation(value: float) -> dict:+ return {"text": "same", "logprobs": {"content": [{"token": "same", "logprob": math.log(value)}]}}++ for kind, build, a, b, reset in (+ ("embedding", embedding, 0.0001, 0.0003, 0.00004),+ ("generation", generation, 0.0002, 0.0004, 0.00005),+ ):+ base = build(0.5)+ assert check_effect(kind, base, build(0.5 + a), build(0.5 + b), base)+ with pytest.raises(AssertionError, match="beyond base drift"):+ check_effect(kind, base, build(0.5 + a), build(0.5 + b), build(0.5 + reset))