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(sglang): bound runtime LoRA benchmark KV pools

svonava24f265b98aea
diff --git a/tools/benchmarks/runtime_lora/README.md b/tools/benchmarks/runtime_lora/README.md
index 574ff62c4..c70b77e3b 100644
--- a/tools/benchmarks/runtime_lora/README.md
+++ b/tools/benchmarks/runtime_lora/README.md
@@ -5,6 +5,14 @@ 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`.
+Both engines receive an explicit `--max-total-tokens 4096` KV pool upper bound. The
+fraction remains the production admission/static-memory setting; it does not
+imply a 4096-token cap when explicitly overridden. Generation uses its supported
+`extra_launch_args` option. Embedding has no such option, so a benchmark-only
+subclass appends the same fixed flag to its memory arguments while preserving
+the production launch and inference paths. CPU tests capture both real launch
+commands and check that only the KV cap differs from the uncapped profile.
+
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
diff --git a/tools/benchmarks/runtime_lora/adapters.py b/tools/benchmarks/runtime_lora/adapters.py
index b5396994e..6519e9f17 100644
--- a/tools/benchmarks/runtime_lora/adapters.py
+++ b/tools/benchmarks/runtime_lora/adapters.py
@@ -1,9 +1,28 @@
-"""Benchmark-owned observation hook; inference uses the production adapter."""
+"""Benchmark observation and fixed KV limits around production inference."""
+from dataclasses import asdict
from pathlib import Path
+from sie_server.adapters.sglang._memory import SGLangMemoryBudget
+from sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapter
from sie_server.adapters.sglang.generation import SGLangGenerationAdapter
+KV_CAPACITY = 4096
+STATIC_MEMORY_FRACTION = 0.5
+
+
+class CappedEmbeddingMemoryBudget(SGLangMemoryBudget):
+ def launch_args(self, device_index: int) -> list[str]:
+ if self.mem_fraction_static != STATIC_MEMORY_FRACTION or self.kv_budget_tokens != KV_CAPACITY:
+ raise ValueError("The benchmark requires fraction 0.5 and a 4096-token KV limit")
+ return [*super().launch_args(device_index), "--max-total-tokens", str(KV_CAPACITY)]
+
+
+class CappedEmbeddingAdapter(SGLangEmbeddingAdapter):
+ def load(self, device: str) -> None:
+ self._memory_budget = CappedEmbeddingMemoryBudget(**asdict(self._memory_budget))
+ super().load(device)
+
class ObservedGenerationAdapter(SGLangGenerationAdapter):
def _compat_pythonpath_entries(self) -> tuple[str, ...]:
diff --git a/tools/benchmarks/runtime_lora/probe.py b/tools/benchmarks/runtime_lora/probe.py
index 945c4bb3e..89a0ce570 100644
--- a/tools/benchmarks/runtime_lora/probe.py
+++ b/tools/benchmarks/runtime_lora/probe.py
@@ -33,6 +33,7 @@ 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.adapters import KV_CAPACITY, STATIC_MEMORY_FRACTION
from tools.benchmarks.runtime_lora.fixtures import ALIASES, MODELS, RANK, digest, prepare
from tools.benchmarks.runtime_lora.observer import TRACE_ENV
@@ -393,17 +394,23 @@ def configs(directory: Path, fixtures: Path) -> dict[str, Any]:
profile["adapter_path"] = (
f"{Path(__file__).with_name('adapters.py')}:ObservedGenerationAdapter"
if kind == "generation"
- else "sie_server.adapters.sglang.embedding:SGLangEmbeddingAdapter"
+ else f"{Path(__file__).with_name('adapters.py')}:CappedEmbeddingAdapter"
)
profile["max_batch_tokens"] = 4096
- profile["kv_budget_tokens"] = 4096
+ profile["kv_budget_tokens"] = KV_CAPACITY
loadtime = profile.setdefault("adapter_options", {}).setdefault("loadtime", {})
if kind == "embedding":
# The catalog's original PyTorch adapter owns the causal option.
loadtime.pop("causal", None)
+ else:
+ loadtime["extra_launch_args"] = [
+ *loadtime.get("extra_launch_args", []),
+ "--max-total-tokens",
+ str(KV_CAPACITY),
+ ]
loadtime.update(
{
- "mem_fraction_static": 0.5,
+ "mem_fraction_static": STATIC_MEMORY_FRACTION,
"max_seq_length": 4096,
"lora_paths": {alias: str((fixtures / kind / alias).resolve()) for alias in ALIASES},
"preload_loras": ["pin"],
diff --git a/tools/benchmarks/runtime_lora/tests/test_probe.py b/tools/benchmarks/runtime_lora/tests/test_probe.py
index 706bf9df7..3fef1f93f 100644
--- a/tools/benchmarks/runtime_lora/tests/test_probe.py
+++ b/tools/benchmarks/runtime_lora/tests/test_probe.py
@@ -7,6 +7,7 @@ import math
import os
import subprocess
import sys
+from copy import deepcopy
from pathlib import Path
from types import ModuleType, SimpleNamespace
@@ -18,6 +19,7 @@ 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_server.adapters.sglang import _server
from sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapter
from sie_server.adapters.sglang.generation import SGLangGenerationAdapter
from sie_server.config.model import ModelConfig
@@ -122,6 +124,62 @@ def test_generated_config_resolves_validates_and_constructs_without_engine_launc
adapter._lora.close()
[email protected]("kind", ["generation", "embedding"])
+def test_generated_profiles_only_add_one_kv_cap_to_actual_engine_argv(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, kind: str
+) -> None:
+ commands = []
+
+ class LaunchCapturedError(Exception):
+ pass
+
+ def capture_command(cmd, **kwargs):
+ commands.append(list(cmd))
+ raise LaunchCapturedError
+
+ monkeypatch.setattr(_server, "find_free_port", lambda *args: 30000)
+ monkeypatch.setattr(_server, "launch_sglang_server", capture_command)
+ directory = tmp_path / "models"
+ generated = configs(directory, tmp_path / "fixtures")[kind]
+ for capped in (False, True):
+ data = deepcopy(generated)
+ profile = data["profiles"]["default"]
+ if not capped:
+ if kind == "generation":
+ extra = profile["adapter_options"]["loadtime"]["extra_launch_args"]
+ assert extra[-2:] == ["--max-total-tokens", "4096"]
+ del extra[-2:]
+ else:
+ profile["adapter_path"] = "sie_server.adapters.sglang.embedding:SGLangEmbeddingAdapter"
+ config = ModelConfig.model_validate(data)
+ validate_loadtime_options(config, directory)
+ adapter = load_adapter(config, directory, device="cuda:0")
+ # Source materialization is separately tested; use the declared path so
+ # temporary snapshot names do not obscure the launch-argv comparison.
+ monkeypatch.setattr(adapter._lora, "fetch", lambda name: name)
+ expected_reservation = adapter._memory_budget.required_bytes(
+ device_type="cuda", device_total_bytes=80 * 1024**3
+ )
+ try:
+ with pytest.raises(LaunchCapturedError):
+ adapter.load("cuda:0")
+ assert adapter._process is None
+ assert (
+ adapter._memory_budget.required_bytes(device_type="cuda", device_total_bytes=80 * 1024**3)
+ == expected_reservation
+ )
+ finally:
+ adapter._lora.close()
+ uncapped, capped = commands
+ assert "--max-total-tokens" not in uncapped
+ assert capped.count("--max-total-tokens") == 1
+ index = capped.index("--max-total-tokens")
+ assert capped[index + 1] == "4096"
+ del capped[index : index + 2]
+ assert capped == uncapped
+ assert capped[capped.index("--mem-fraction-static") + 1] == "0.5"
+
+
def test_sdk_observer_captures_cold_503_and_native_retry(tmp_path: Path) -> None:
calls = []