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(examples): time one request at a time beside the website's times (#923)

Shai Shmuelf11ec14f8749
diff --git a/examples/evaluations/published-benchmarks/README.md b/examples/evaluations/published-benchmarks/README.md
index a21e9d3b7..857bd7bbd 100644
--- a/examples/evaluations/published-benchmarks/README.md
+++ b/examples/evaluations/published-benchmarks/README.md
@@ -5,7 +5,9 @@ repeats the method behind the benchmark numbers published on the SIE website,
six quality records and six fixed-rate performance records. And it measures a
model you are adding the same way, against an official number it looks up in
the public results repository or one you supply, before you open a pull
-request: see [Test a new model](#test-a-new-model).
+request: see [Test a new model](#test-a-new-model). It also times one request
+at a time against your own server, beside a per-request time the website
+shows: see [Check a time on the website](#check-a-time-on-the-website).
Each `references/<id>.json` is a projection of one published benchmark record:
the model and profile, the task key, the pinned dataset revision, the request
@@ -623,6 +625,85 @@ no official number, so they need it to get a verdict.
Some rows on the model pages are measured on our own GPUs, and a row may differ
from your run for that reason. Read the `verdict:` line with that in mind.
+## Check a time on the website
+
+The per-request times the website shows for SIE come from one public study: the
+`latency-fastest-config/2026-10-11` folder of the Hugging Face dataset
+[`superlinked/sie-task-evidence`](https://huggingface.co/datasets/superlinked/sie-task-evidence).
+It timed each model one request at a time on an L4, an RTX PRO 6000 and an
+H100, and the website shows the median of the fastest of the three, rounded up.
+`run.py latency` repeats that study for two pages against your own server:
+
+| `--page` | On the website | Model | Server bundle | Inputs | One request |
+| --- | --- | --- | --- | --- | --- |
+| `classify` | `/classify`: "Median time per message 13.1 ms" | `fastino/GLiNER2.5-Decide` | `transformers5` | 400 CLINC150 and BANKING77 messages | `extract` with the message's 8 labels and `options={"overflow_policy": "error"}` |
+| `search` | home page and `/about`: 15.7 ms; `/serverless`: 16ms | `Qwen/Qwen3-Embedding-4B` | `sglang-embedding` | 440 questions | `encode` with `is_query=True` and `output_types=["dense"]`, no instruction |
+
+On a Linux machine with an NVIDIA GPU, start the server for the page with its
+bundle image:
+
+```sh
+docker run --gpus all -p 127.0.0.1:8080:8080 \
+ -v sie-hf-cache:/app/.cache/huggingface \
+ -e SIE_PRELOAD_MODELS=fastino/GLiNER2.5-Decide \
+ ghcr.io/superlinked/sie-server:v0.11.0-cuda12-transformers5
+```
+
+Then, from this directory, on the same machine:
+
+```sh
+uv run python run.py latency --page classify --endpoint http://localhost:8080
+```
+
+For `search`, stop that server and start this one instead:
+
+```sh
+docker run --gpus all -p 127.0.0.1:8080:8080 \
+ -v sie-hf-cache:/app/.cache/huggingface \
+ -e SIE_PRELOAD_MODELS=Qwen/Qwen3-Embedding-4B \
+ ghcr.io/superlinked/sie-server:v0.11.0-cuda12-sglang-embedding
+```
+
+```sh
+uv run python run.py latency --page search --endpoint http://localhost:8080
+```
+
+`--endpoint` is required. The key rule is the one in
+[Run it against your own server](#run-it-against-your-own-server): a server
+without a token needs no key.
+
+The run:
+
+1. downloads the study's inputs at their pinned revisions, rebuilds the
+ request list the way the study's build scripts wrote it, and stops before
+ any request when its SHA-256 differs from the one the study published;
+2. sends 20 warm-up requests built from the end of that list, as the study
+ did, and does not time them. The `search` warm-ups carry a `[c1-<n>] `
+ prefix, as the study's did, so the server's prefix cache never holds a
+ timed request. The first warm-up waits up to 15 minutes for the model to
+ load;
+3. sends every input once, in order, one request in flight, one attempt, and
+ times each `SIEClient` call;
+4. prints your n, p50, p95 and mean beside the published values for each GPU,
+ with percentiles interpolated linearly as the study computed them, and
+ writes `results/latency-<page>-<utc>.json` with the time of every request.
+
+Every run also prints what differs from the study:
+
+- the study's client ran inside the server's container and sent each request
+ over the sidecar's local Unix socket, with no HTTP. This run sends HTTP
+ through `sie_sdk.SIEClient`, so your time also includes the HTTP server and
+ the path from the client to the server. Run the client on the GPU machine to
+ keep that path short;
+- your GPU, and the server you started. The study ran the v0.10.0 images with
+ the server package from `main` at `2b3f7d2e`; the commands above start
+ v0.11.0.
+
+A failed request, or one that succeeded only after an SDK retry, is counted,
+listed by status, and left out of the numbers. The run exits 1 only when the
+inputs fail the check or no request succeeds on its first attempt. There is no
+pass or fail: the numbers are set side by side.
+
## Validation
`validation/` holds the example's own output from 2026-11-03: three
@@ -757,6 +838,8 @@ The tests use a fake client, in-memory datasets and the committed
scorer's implementation digest;
- no multi-process client, load ladder, Poisson arrivals or clock calibration;
- no cost, price or accounting fields;
-- no recorded-evidence download: the inputs are the six reference files and
- the pinned public datasets;
+- no recorded-evidence download beyond what `run.py latency` reads: the
+ quality and performance inputs are the six reference files and the pinned
+ public datasets, and `run.py latency` reads the per-request time study's
+ inputs and published results at a pinned revision;
- no PyPI distribution, and the flags are not a compatibility surface.
diff --git a/examples/evaluations/published-benchmarks/latency.py b/examples/evaluations/published-benchmarks/latency.py
new file mode 100644
index 000000000..873c2b231
--- /dev/null
+++ b/examples/evaluations/published-benchmarks/latency.py
@@ -0,0 +1,379 @@
+"""Time one request at a time against your own server, beside the per-request times the SIE website shows."""
+
+import contextlib
+import hashlib
+import json
+import statistics
+import time
+from collections.abc import Callable, Mapping, Sequence
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+from sie_sdk import ModelLoadingError, ProvisioningError, SIEConnectionError
+
+from official import Fetch
+from score import write_json
+
+DATASET = "superlinked/sie-task-evidence"
+RESOLVE_URL = f"https://huggingface.co/datasets/{DATASET}/resolve"
+STUDY_REVISION = "2f74a5c09c3cefa0f5f754f92949600fcd4dc1aa"
+STUDY = "latency-fastest-config/2026-10-11"
+JOBS_SHA256 = f"{STUDY}/prereg/jobs-sha256.json"
+LEVEL = "c1"
+WARMUP_REQUESTS = 20
+WARMUP_TAG_BASE = 10_000_000
+CLASSES = ("l4", "rtx", "h100")
+REQUEST_TIMEOUT_S = 300.0
+READY_TIMEOUT_S = 900.0
+READY_POLL_S = 5.0
+NOT_READY = (SIEConnectionError, ModelLoadingError, ProvisioningError)
+NS_PER_MS = 1_000_000
+
+
+class InputMismatch(Exception):
+ pass
+
+
+@dataclass(frozen=True)
+class Page:
+ name: str
+ input_revision: str
+ input_path: str
+ build: Callable[[bytes], dict[str, Any]]
+
+
+def classify_jobs(raw: bytes) -> dict[str, Any]:
+ items = [json.loads(line) for line in raw.decode("utf-8").splitlines() if line.strip()]
+ jobs = [
+ {"id": it["id"], "text": it["text"], "labels": list(it["labels"]), "meta": {"domain": it["domain"]}}
+ for it in items
+ ]
+ return {
+ "page": "classify",
+ "model": "fastino/GLiNER2.5-Decide",
+ "profile": "default",
+ "op": "extract",
+ "defaults": {"options": {"overflow_policy": "error"}},
+ "source": {
+ "items": "classify-current-arms-2026-10-11/prereg/items.jsonl @4e9f6498",
+ "items_sha256": hashlib.sha256(raw).hexdigest(),
+ "request": "one message per extract call with its 8 labels, options {overflow_policy: error}",
+ },
+ "jobs": jobs,
+ }
+
+
+def search_jobs(raw: bytes) -> dict[str, Any]:
+ questions = json.loads(raw.decode("utf-8"))["questions"]
+ return {
+ "page": "search",
+ "model": "Qwen/Qwen3-Embedding-4B",
+ "profile": "default",
+ "op": "encode",
+ "defaults": {"output_types": ["dense"], "is_query": True},
+ "warm_variant": "tagged",
+ "source": {
+ "questions": "lookalike-search/inputs/questions.json @b939e410 (440 questions)",
+ "sha256": hashlib.sha256(raw).hexdigest(),
+ "request": "one question per encode call, is_query true, output_types [dense], no instruction sent (server default)",
+ },
+ "jobs": [{"id": q["id"], "text": q["question"]} for q in questions],
+ }
+
+
+PAGES = {
+ "classify": Page(
+ "classify",
+ "4e9f649842dd802d353d10fc8dc2347b9a927189",
+ "classify-current-arms-2026-10-11/prereg/items.jsonl",
+ classify_jobs,
+ ),
+ "search": Page(
+ "search",
+ "b939e41046eef6a0c2a9ee60c152161fd3fb7e04",
+ "lookalike-search/inputs/questions.json",
+ search_jobs,
+ ),
+}
+
+
+def dataset_url(revision: str, path: str) -> str:
+ return f"{RESOLVE_URL}/{revision}/{path}"
+
+
+def jobs_bytes(doc: Mapping[str, Any]) -> bytes:
+ return json.dumps(doc).encode("utf-8")
+
+
+def load_jobs(page: Page, fetch: Fetch) -> tuple[dict[str, Any], str]:
+ expected = json.loads(fetch(dataset_url(STUDY_REVISION, JOBS_SHA256), None))[f"{page.name}.json"]["sha256"]
+ doc = page.build(fetch(dataset_url(page.input_revision, page.input_path), None))
+ digest = hashlib.sha256(jobs_bytes(doc)).hexdigest()
+ if digest != expected:
+ raise InputMismatch(f"the rebuilt {page.name} jobs have sha256 {digest}, the published jobs file {expected}")
+ return doc, digest
+
+
+def load_published(page: Page, fetch: Fetch) -> dict[str, Any]:
+ doc = json.loads(fetch(dataset_url(STUDY_REVISION, f"{STUDY}/results/{page.name}.json"), None))
+ classes = {}
+ for key in CLASSES:
+ entry = doc["classes"][key]
+ latency = entry["levels"][LEVEL]["latency"]
+ classes[key] = {
+ "gpu": entry["gpu"],
+ "n": latency["n"],
+ "p50_ms": latency["p50_ms"],
+ "p95_ms": latency["p95_ms"],
+ "mean_ms": latency["mean_ms"],
+ "bundle": entry["bundle"],
+ "image_digest": entry["image_digest"],
+ "server_overlay_revision": entry["server_overlay_revision"],
+ "client_placement": entry["client_placement"],
+ }
+ return {
+ "dataset": DATASET,
+ "revision": STUDY_REVISION,
+ "path": f"{STUDY}/results/{page.name}.json",
+ "level": LEVEL,
+ "best_class": doc["best_class"]["key"],
+ "classes": classes,
+ }
+
+
+def percentile(values: Sequence[float], q: float) -> float:
+ ordered = sorted(values)
+ k = (len(ordered) - 1) * q
+ low = int(k)
+ high = min(low + 1, len(ordered) - 1)
+ return ordered[low] + (ordered[high] - ordered[low]) * (k - low)
+
+
+def latency_stats(values_ms: Sequence[float]) -> dict[str, Any]:
+ if not values_ms:
+ return {"n": 0, "p50_ms": None, "p95_ms": None, "mean_ms": None}
+ return {
+ "n": len(values_ms),
+ "p50_ms": round(percentile(values_ms, 0.5), 2),
+ "p95_ms": round(percentile(values_ms, 0.95), 2),
+ "mean_ms": round(statistics.fmean(values_ms), 2),
+ }
+
+
+def warmup_jobs(doc: Mapping[str, Any]) -> list[dict[str, Any]]:
+ jobs = doc["jobs"]
+ tagged = doc.get("warm_variant") == "tagged"
+ warm = []
+ for i in range(WARMUP_REQUESTS):
+ job = dict(jobs[-1 - (i % len(jobs))])
+ if tagged:
+ job["text"] = f"[{LEVEL}-{WARMUP_TAG_BASE + i}] " + job["text"]
+ warm.append(job)
+ return warm
+
+
+def send(client: Any, doc: Mapping[str, Any], job: Mapping[str, Any], *, wait_for_capacity: bool) -> Any:
+ item = {"id": job["id"], "text": job["text"]}
+ defaults = doc.get("defaults") or {}
+ if doc["op"] == "extract":
+ return client.extract(
+ doc["model"],
+ item,
+ labels=list(job["labels"]),
+ options=dict(defaults["options"]),
+ wait_for_capacity=wait_for_capacity,
+ provision_timeout_s=READY_TIMEOUT_S if wait_for_capacity else REQUEST_TIMEOUT_S,
+ max_oom_retries=0,
+ )
+ return client.encode(
+ doc["model"],
+ item,
+ output_types=list(defaults["output_types"]),
+ is_query=bool(defaults["is_query"]),
+ wait_for_capacity=wait_for_capacity,
+ provision_timeout_s=READY_TIMEOUT_S if wait_for_capacity else REQUEST_TIMEOUT_S,
+ max_oom_retries=0,
+ )
+
+
+def wait_until_ready(
+ client: Any,
+ doc: Mapping[str, Any],
+ job: Mapping[str, Any],
+ *,
+ monotonic: Callable[[], float] = time.monotonic,
+ sleep: Callable[[float], None] = time.sleep,
+) -> None:
+ deadline = monotonic() + READY_TIMEOUT_S
+ while True:
+ try:
+ send(client, doc, job, wait_for_capacity=True)
+ return
+ except NOT_READY:
+ if monotonic() >= deadline:
+ raise
+ sleep(READY_POLL_S)
+
+
+def warm_up(client: Any, doc: Mapping[str, Any], **ready: Any) -> None:
+ jobs = warmup_jobs(doc)
+ wait_until_ready(client, doc, jobs[0], **ready)
+ for job in jobs[1:]:
+ with contextlib.suppress(Exception):
+ send(client, doc, job, wait_for_capacity=False)
+
+
+def timed_requests(client: Any, doc: Mapping[str, Any], clock: Callable[[], int] = time.perf_counter_ns) -> list[dict]:
+ rows = []
+ for job in doc["jobs"]:
+ start = clock()
+ try:
+ send(client, doc, job, wait_for_capacity=False)
+ except Exception as exc: # noqa: BLE001
+ status = f"error:{type(exc).__name__}"
+ else:
+ status = "retried" if getattr(client, "last_retry_count", 0) else "ok"
+ end = clock()
+ rows.append({"id": job["id"], "status": status, "latency_ms": round((end - start) / NS_PER_MS, 3)})
+ return rows
+
+
+def differences(published: Mapping[str, Any]) -> list[str]:
+ best = published["classes"][published["best_class"]]
+ return [
+ (
+ "the published client ran in the server's container and sent each request over the sidecar's local "
+ "Unix socket, with no HTTP; this run sends HTTP through sie_sdk.SIEClient, so its time also includes "
+ "the HTTP server and your network path"
+ ),
+ (
+ "this run uses your GPU and the server you started; the published run used the "
+ f"{best['bundle']} image {best['image_digest']} with the server package from public main "
+ f"{best['server_overlay_revision'][:8]}"
+ ),
+ ]
+
+
+def _timestamp(moment: datetime) -> str:
+ return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def build_record(
+ page: Page,
+ doc: Mapping[str, Any],
+ digest: str,
+ published: Mapping[str, Any],
+ rows: Sequence[Mapping[str, Any]],
+ *,
+ endpoint: str,
+ client_description: str,
+ started_at: datetime,
+ finished_at: datetime,
+) -> dict[str, Any]:
+ ok = [row["latency_ms"] for row in rows if row["status"] == "ok"]
+ stats = latency_stats(ok)
+ return {
+ "kind": "published-benchmark-reproduction",
+ "schema_version": 1,
+ "evaluation_mode": "latency",
+ "page": page.name,
+ "model": doc["model"],
+ "operation": doc["op"],
+ "ingress": {"url": endpoint},
+ "inputs": {
+ "dataset": DATASET,
+ "revisions": {"study": STUDY_REVISION, "inputs": page.input_revision},
+ "path": page.input_path,
+ "jobs_sha256": digest,
+ "jobs": len(doc["jobs"]),
+ },
+ "warmup_requests": WARMUP_REQUESTS,
+ "client": {"description": client_description, "worker_count": 1, "processes_per_worker": 1},
+ "run": {
+ "started_at": _timestamp(started_at),
+ "finished_at": _timestamp(finished_at),
+ "endpoint": endpoint,
+ "request_count": len(rows),
+ "failure_count": len(rows) - len(ok),
+ },
+ "metrics": [
+ {"name": "latency_p50_ms", "unit": "ms", "aggregation": "p50", "value": stats["p50_ms"]},
+ {"name": "latency_p95_ms", "unit": "ms", "aggregation": "p95", "value": stats["p95_ms"]},
+ {"name": "latency_mean_ms", "unit": "ms", "aggregation": "mean", "value": stats["mean_ms"]},
+ ],
+ "published": published,
+ "differences": differences(published),
+ "requests": list(rows),
+ }
+
+
+def _cell(value: float | None) -> str:
+ return "-" if value is None else f"{value:.2f}"
+
+
+def format_report(record: Mapping[str, Any]) -> list[str]:
+ published = record["published"]
+ metrics = {metric["name"]: metric["value"] for metric in record["metrics"]}
+ n = record["run"]["request_count"] - record["run"]["failure_count"]
+ rows = [("yours", n, metrics["latency_p50_ms"], metrics["latency_p95_ms"], metrics["latency_mean_ms"])]
+ for entry in published["classes"].values():
+ rows.append((f"published {entry['gpu']}", entry["n"], entry["p50_ms"], entry["p95_ms"], entry["mean_ms"]))
+ width = max(len(row[0]) for row in rows)
+ lines = [
+ (
+ f"{record['page']}: {record['model']}, {record['operation']}, one request at a time, "
+ f"{record['inputs']['jobs']} inputs after {record['warmup_requests']} warm-up requests"
+ ),
+ f"{'':{width}} {'n':>5} {'p50 ms':>8} {'p95 ms':>8} {'mean ms':>8}",
+ ]
+ lines += [
+ f"{name:{width}} {count:>5} {_cell(p50):>8} {_cell(p95):>8} {_cell(mean):>8}"
+ for name, count, p50, p95, mean in rows
+ ]
+ best = published["classes"][published["best_class"]]
+ lines.append(f"the website shows the published {best['gpu']} p50, rounded up")
+ lines += [f"differs: {line}" for line in record["differences"]]
+ failed = record["run"]["failure_count"]
+ if failed:
+ statuses = sorted({row["status"] for row in record["requests"] if row["status"] != "ok"})
+ lines.append(
+ f"failed: {failed} of {record['run']['request_count']} ({', '.join(statuses)}), left out of the numbers"
+ )
+ return lines
+
+
+def run_latency(
+ page_name: str,
+ client: Any,
+ fetch: Fetch,
+ *,
+ endpoint: str,
+ client_description: str,
+ results_dir: Path,
+ clock: Callable[[], int] = time.perf_counter_ns,
+ **ready: Any,
+) -> tuple[dict[str, Any], Path]:
+ page = PAGES[page_name]
+ doc, digest = load_jobs(page, fetch)
+ published = load_published(page, fetch)
+ started_at = datetime.now(UTC)
+ warm_up(client, doc, **ready)
+ rows = timed_requests(client, doc, clock)
+ finished_at = datetime.now(UTC)
+ record = build_record(
+ page,
+ doc,
+ digest,
+ published,
+ rows,
+ endpoint=endpoint,
+ client_description=client_description,
+ started_at=started_at,
+ finished_at=finished_at,
+ )
+ results_dir.mkdir(parents=True, exist_ok=True)
+ path = results_dir / f"latency-{page.name}-{started_at.strftime('%Y%m%dT%H%M%SZ')}.json"
+ write_json(path, record)
+ return record, path
diff --git a/examples/evaluations/published-benchmarks/run.py b/examples/evaluations/published-benchmarks/run.py
index bcb299059..52157fe07 100644
--- a/examples/evaluations/published-benchmarks/run.py
+++ b/examples/evaluations/published-benchmarks/run.py
@@ -26,11 +26,14 @@ import sie_sdk
from scipy.sparse import csr_matrix
from sie_sdk import SIEClient
+import latency as latency_mode
from official import (
MODEL_ID,
SKIPPED,
Fetch,
Lookup,
+ LookupFailed,
+ NotFound,
checked_baseline_value,
http_fetch,
lookup_official,
@@ -249,6 +252,9 @@ def build_parser() -> argparse.ArgumentParser:
performance.add_argument("--rate", type=float, help="Requests per second; the reference's published level")
performance.add_argument("--duration", type=float, help="Seconds of scheduled arrivals (default 60)")
performance.add_argument("--warmup", type=float, help="Seconds of unrecorded warmup (default 30; 0 skips it)")
+ latency = commands.add_parser("latency", help="Time one request at a time beside a per-request time on the website")
+ latency.add_argument("--page", required=True, choices=sorted(latency_mode.PAGES), help="The website page")
+ latency.add_argument("--endpoint", required=True, help="Your SIE server, for example http://localhost:8080")
return parser
@@ -1548,6 +1554,32 @@ def performance_command(parser: argparse.ArgumentParser, args: argparse.Namespac
raise SystemExit(1)
+def latency_command(parser: argparse.ArgumentParser, args: argparse.Namespace, fetch: Fetch = http_fetch) -> None:
+ try:
+ endpoint = normalize_endpoint(args.endpoint)
+ except ValueError as exc:
+ parser.error(str(exc))
+ api_key = _resolve_api_key(parser, endpoint)
+ try:
+ with SIEClient(endpoint, api_key=api_key, timeout_s=latency_mode.REQUEST_TIMEOUT_S) as client:
+ record, result_path = latency_mode.run_latency(
+ args.page,
+ client,
+ fetch,
+ endpoint=_without_credentials(endpoint),
+ client_description=client_description(),
+ results_dir=RESULTS_DIR,
+ )
+ except (latency_mode.InputMismatch, NotFound, LookupFailed) as exc:
+ print(f"stopped: {exc}", file=sys.stderr)
+ raise SystemExit(1) from None
+ print(result_path)
+ for line in latency_mode.format_report(record):
+ print(line)
+ if record["run"]["failure_count"] == record["run"]["request_count"]:
+ raise SystemExit(1)
+
+
def main(argv: Sequence[str] | None = None) -> None:
parser = build_parser()
args = parser.parse_args(argv)
@@ -1555,6 +1587,8 @@ def main(argv: Sequence[str] | None = None) -> None:
quality_command(parser, args)
elif args.command == "performance":
performance_command(parser, args)
+ elif args.command == "latency":
+ latency_command(parser, args)
if __name__ == "__main__":
diff --git a/examples/evaluations/published-benchmarks/tests/test_latency.py b/examples/evaluations/published-benchmarks/tests/test_latency.py
new file mode 100644
index 000000000..12b4fc55a
--- /dev/null
+++ b/examples/evaluations/published-benchmarks/tests/test_latency.py
@@ -0,0 +1,362 @@
+import contextlib
+import hashlib
+import io
+import json
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from sie_sdk import RequestError, SIEConnectionError
+
+import latency
+import run
+from official import NotFound
+
+ITEMS = [
+ {"id": "a-1", "domain": "banking", "text": "first message", "labels": ["x", "y"], "gold": "x"},
+ {"id": "a-2", "domain": "banking", "text": "second message", "labels": ["y", "z"], "gold": "z"},
+ {"id": "b-3", "domain": "travel", "text": "third message", "labels": ["p", "q"], "gold": "p"},
+]
+ITEMS_RAW = "".join(json.dumps(item) + "\n" for item in ITEMS).encode()
+QUESTIONS_RAW = json.dumps(
+ {
+ "questions": [
+ {"id": "q1", "question": "first question", "gold": "g"},
+ {"id": "q2", "question": "second question"},
+ ]
+ }
+).encode()
+
+
+def published_doc(page: str) -> dict:
+ classes = {}
+ for key, gpu, p50 in (("l4", "L4", 49.09), ("rtx", "RTX PRO 6000", 13.04), ("h100", "H100", 18.6)):
+ classes[key] = {
+ "gpu": gpu,
+ "bundle": "transformers5" if page == "classify" else "sglang-embedding",
+ "image_digest": "sha256:" + "a" * 64,
+ "server_overlay_revision": "2b3f7d2ed6d79d880c249d9ef9efb72ae3a36135",
+ "client_placement": "same container, sidecar local-ingest Unix socket",
+ "levels": {
+ "c1": {"latency": {"n": 400, "p50_ms": p50, "p95_ms": p50 + 2, "mean_ms": p50 + 0.2}},
+ "c8": {"latency": {"n": 400, "p50_ms": 99.0, "p95_ms": 120.0, "mean_ms": 100.0}},
+ },
+ }
+ return {"page": page, "classes": classes, "best_class": {"gpu": "RTX PRO 6000", "key": "rtx"}}
+
+
+class FakeFetch:
+ def __init__(self, *, jobs_sha256: dict | None = None, missing: str | None = None):
+ classify_sha = hashlib.sha256(latency.jobs_bytes(latency.classify_jobs(ITEMS_RAW))).hexdigest()
+ search_sha = hashlib.sha256(latency.jobs_bytes(latency.search_jobs(QUESTIONS_RAW))).hexdigest()
+ sha = jobs_sha256 or {"classify.json": {"sha256": classify_sha}, "search.json": {"sha256": search_sha}}
+ study = latency.STUDY_REVISION
+ self.files = {
+ latency.dataset_url(study, latency.JOBS_SHA256): json.dumps(sha).encode(),
+ latency.dataset_url(
+ latency.PAGES["classify"].input_revision, latency.PAGES["classify"].input_path
+ ): ITEMS_RAW,
+ latency.dataset_url(
+ latency.PAGES["search"].input_revision, latency.PAGES["search"].input_path
+ ): QUESTIONS_RAW,
+ latency.dataset_url(study, f"{latency.STUDY}/results/classify.json"): json.dumps(
+ published_doc("classify")
+ ).encode(),
+ latency.dataset_url(study, f"{latency.STUDY}/results/search.json"): json.dumps(
+ published_doc("search")
+ ).encode(),
+ }
+ self.missing = missing
+ self.urls: list[str] = []
+
+ def __call__(self, url: str, accept: str | None = None) -> bytes:
+ self.urls.append(url)
+ if self.missing and self.missing in url:
+ raise NotFound(url)
+ return self.files[url]
+
+
+class FakeClient:
+ def __init__(self, *, fail_ids: frozenset[str] = frozenset(), not_ready: int = 0, retried_ids=frozenset()):
+ self.calls: list[tuple[str, str, dict, dict]] = []
+ self.fail_ids = fail_ids
+ self.not_ready = not_ready
+ self.retried_ids = retried_ids
+ self.last_retry_count = 0
+
+ def _call(self, op: str, model: str, item: dict, kwargs: dict) -> dict:
+ self.calls.append((op, model, item, kwargs))
+ if self.not_ready:
+ self.not_ready -= 1
+ raise SIEConnectionError("connection refused")
+ self.last_retry_count = 1 if item["id"] in self.retried_ids and not kwargs["wait_for_capacity"] else 0
+ if item["id"] in self.fail_ids and not kwargs["wait_for_capacity"]:
+ raise RequestError("bad request", status_code=400)
+ return {}
+
+ def extract(self, model, item, **kwargs):
+ return self._call("extract", model, item, kwargs)
+
+ def encode(self, model, item, **kwargs):
+ return self._call("encode", model, item, kwargs)
+
+
+def ticking_clock(step_ms: float = 10.0):
+ now = [0]
+
+ def clock() -> int:
+ now[0] += int(step_ms * latency.NS_PER_MS)
+ return now[0]
+
+ return clock
+
+
+class Clock:
+ def __init__(self):
+ self.now = 0.0
+ self.sleeps: list[float] = []
+
+ def monotonic(self) -> float:
+ return self.now
+
+ def sleep(self, seconds: float) -> None:
+ self.sleeps.append(seconds)
+ self.now += seconds
+
+
+class JobsTests(unittest.TestCase):
+ def test_classify_jobs_are_written_as_the_build_script_writes_them(self):
+ doc = latency.classify_jobs(ITEMS_RAW)
+ self.assertEqual(list(doc), ["page", "model", "profile", "op", "defaults", "source", "jobs"])
+ self.assertEqual(doc["defaults"], {"options": {"overflow_policy": "error"}})
+ self.assertEqual(doc["source"]["items_sha256"], hashlib.sha256(ITEMS_RAW).hexdigest())
+ self.assertEqual(
+ doc["jobs"][0], {"id": "a-1", "text": "first message", "labels": ["x", "y"], "meta": {"domain": "banking"}}
+ )
+ self.assertTrue(latency.jobs_bytes(doc).startswith(b'{"page": "classify", "model": "fastino/GLiNER2.5-Decide"'))
+
+ def test_search_jobs_are_written_as_the_build_script_writes_them(self):
+ doc = latency.search_jobs(QUESTIONS_RAW)
+ self.assertEqual(list(doc), ["page", "model", "profile", "op", "defaults", "warm_variant", "source", "jobs"])
+ self.assertEqual(doc["defaults"], {"output_types": ["dense"], "is_query": True})
+ self.assertEqual(doc["jobs"], [{"id": "q1", "text": "first question"}, {"id": "q2", "text": "second question"}])
+
+ def test_matching_jobs_load_with_their_digest(self):
+ doc, digest = latency.load_jobs(latency.PAGES["classify"], FakeFetch())
+ self.assertEqual(len(doc["jobs"]), 3)
+ self.assertEqual(digest, hashlib.sha256(latency.jobs_bytes(doc)).hexdigest())
+
+ def test_a_digest_mismatch_stops_the_run(self):
+ fetch = FakeFetch(jobs_sha256={"classify.json": {"sha256": "0" * 64}})
+ with self.assertRaisesRegex(latency.InputMismatch, "0000"):
+ latency.load_jobs(latency.PAGES["classify"], fetch)
+
+ def test_inputs_come_from_their_pinned_revisions(self):
+ fetch = FakeFetch()
+ latency.load_jobs(latency.PAGES["search"], fetch)
+ self.assertEqual(
+ fetch.urls,
+ [
+ (
+ "https://huggingface.co/datasets/superlinked/sie-task-evidence/resolve/"
+ "2f74a5c09c3cefa0f5f754f92949600fcd4dc1aa/latency-fastest-config/2026-10-11/prereg/jobs-sha256.json"
+ ),
+ (
+ "https://huggingface.co/datasets/superlinked/sie-task-evidence/resolve/"
+ "b939e41046eef6a0c2a9ee60c152161fd3fb7e04/lookalike-search/inputs/questions.json"
+ ),
+ ],
+ )
+
+
+class StatisticsTests(unittest.TestCase):
+ def test_percentiles_are_linear_interpolated(self):
+ self.assertEqual(latency.percentile([4.0, 1.0, 3.0, 2.0], 0.5), 2.5)
+ self.assertAlmostEqual(latency.percentile([1.0, 2.0, 3.0, 4.0], 0.95), 3.85)
+ self.assertEqual(latency.percentile([7.0], 0.95), 7.0)
+
+ def test_stats_of_nothing_are_null(self):
+ self.assertEqual(latency.latency_stats([]), {"n": 0, "p50_ms": None, "p95_ms": None, "mean_ms": None})
+
+ def test_published_c1_values_are_read_per_class(self):
+ published = latency.load_published(latency.PAGES["classify"], FakeFetch())
+ self.assertEqual(list(published["classes"]), ["l4", "rtx", "h100"])
+ self.assertEqual(published["classes"]["rtx"]["p50_ms"], 13.04)
+ self.assertEqual(published["best_class"], "rtx")
+ self.assertEqual(published["classes"]["l4"]["bundle"], "transformers5")
+
+
+class WarmupTests(unittest.TestCase):
+ def test_warmups_come_from_the_tail_of_the_list(self):
+ warm = latency.warmup_jobs(latency.classify_jobs(ITEMS_RAW))
+ self.assertEqual(len(warm), 20)
+ self.assertEqual([job["id"] for job in warm[:4]], ["b-3", "a-2", "a-1", "b-3"])
+ self.assertEqual(warm[0]["text"], "third message")
+
+ def test_search_warmups_are_tagged(self):
+ warm = latency.warmup_jobs(latency.search_jobs(QUESTIONS_RAW))
+ self.assertEqual(warm[0]["text"], "[c1-10000000] second question")
+ self.assertEqual(warm[19]["text"], "[c1-10000019] first question")
+
+ def test_the_first_warmup_waits_for_the_server(self):
+ client, clock = FakeClient(not_ready=3), Clock()
+ doc = latency.classify_jobs(ITEMS_RAW)
+ latency.wait_until_ready(client, doc, doc["jobs"][0], monotonic=clock.monotonic, sleep=clock.sleep)
+ self.assertEqual(len(client.calls), 4)
+ self.assertEqual(clock.sleeps, [latency.READY_POLL_S] * 3)
+ self.assertTrue(all(call[3]["wait_for_capacity"] for call in client.calls))
+
+ def test_waiting_gives_up_at_the_deadline(self):
+ client, clock = FakeClient(not_ready=10_000), Clock()
+ doc = latency.classify_jobs(ITEMS_RAW)
+ with self.assertRaises(SIEConnectionError):
+ latency.wait_until_ready(client, doc, doc["jobs"][0], monotonic=clock.monotonic, sleep=clock.sleep)
+ self.assertGreaterEqual(clock.now, latency.READY_TIMEOUT_S)
+
+
+class RunTests(unittest.TestCase):
+ def run_page(self, page: str, client: FakeClient, fetch: FakeFetch | None = None):
+ with tempfile.TemporaryDirectory() as tmp:
+ record, path = latency.run_latency(
+ page,
+ client,
+ fetch or FakeFetch(),
+ endpoint="http://localhost:8080",
+ client_description="test client",
+ results_dir=Path(tmp),
+ clock=ticking_clock(),
+ )
+ self.assertEqual(json.loads(path.read_text()), record)
+ self.assertTrue(path.name.startswith(f"latency-{page}-"))
+ return record
+
+ def test_classify_sends_one_extract_per_message_after_the_warmups(self):
+ client = FakeClient()
+ record = self.run_page("classify", client)
+ self.assertEqual(len(client.calls), 20 + 3)
+ op, model, item, kwargs = client.calls[20]
+ self.assertEqual(
+ (op, model, item), ("extract", "fastino/GLiNER2.5-Decide", {"id": "a-1", "text": "first message"})
+ )
+ self.assertEqual(
+ kwargs,
+ {
+ "labels": ["x", "y"],
+ "options": {"overflow_policy": "error"},
+ "wait_for_capacity": False,
+ "provision_timeout_s": latency.REQUEST_TIMEOUT_S,
+ "max_oom_retries": 0,
+ },
+ )
+ self.assertEqual([call[2]["id"] for call in client.calls[20:]], ["a-1", "a-2", "b-3"])
+ self.assertTrue(client.calls[0][3]["wait_for_capacity"])
+ self.assertFalse(any(call[3]["wait_for_capacity"] for call in client.calls[1:]))
+ self.assertEqual(record["kind"], "published-benchmark-reproduction")
+ self.assertEqual(record["evaluation_mode"], "latency")
+ self.assertEqual(record["run"]["request_count"], 3)
+ self.assertEqual(record["run"]["failure_count"], 0)
+ self.assertEqual({m["name"]: m["value"] for m in record["metrics"]}["latency_p50_ms"], 10.0)
+ self.assertEqual(record["inputs"]["jobs"], 3)
+ self.assertEqual(record["published"]["classes"]["h100"]["p50_ms"], 18.6)
+
+ def test_search_sends_one_query_encode_per_question(self):
+ client = FakeClient()
+ self.run_page("search", client)
+ op, model, item, kwargs = client.calls[20]
+ self.assertEqual(
+ (op, model, item), ("encode", "Qwen/Qwen3-Embedding-4B", {"id": "q1", "text": "first question"})
+ )
+ self.assertEqual(kwargs["output_types"], ["dense"])
+ self.assertIs(kwargs["is_query"], True)
+ self.assertNotIn("instruction", kwargs)
+
+ def test_failed_and_retried_requests_are_counted_and_left_out(self):
+ client = FakeClient(fail_ids=frozenset({"a-2"}), retried_ids=frozenset({"b-3"}))
+ record = self.run_page("classify", client)
+ self.assertEqual([row["status"] for row in record["requests"]], ["ok", "error:RequestError", "retried"])
+ self.assertEqual(record["run"]["failure_count"], 2)
+ report = "\n".join(latency.format_report(record))
+ self.assertIn("failed: 2 of 3 (error:RequestError, retried)", report)
+ self.assertRegex(report, r"yours\s+1\s+10\.00")
+
+ def test_the_report_sets_the_run_beside_every_published_class(self):
+ record = self.run_page("classify", FakeClient())
+ lines = latency.format_report(record)
+ self.assertRegex(lines[2], r"^yours\s+3\s+10\.00\s+10\.00\s+10\.00$")
+ self.assertRegex(lines[3], r"^published L4\s+400\s+49\.09\s+51\.09\s+49\.29$")
+ self.assertRegex(lines[4], r"^published RTX PRO 6000\s+400\s+13\.04")
+ self.assertRegex(lines[5], r"^published H100\s+400\s+18\.60")
+ self.assertIn("the website shows the published RTX PRO 6000 p50, rounded up", lines)
+ differs = [line for line in lines if line.startswith("differs: ")]
+ self.assertEqual(len(differs), 2)
+ self.assertIn("Unix socket, with no HTTP", differs[0])
+ self.assertIn("transformers5 image sha256:", differs[1])
+ self.assertIn("public main 2b3f7d2e", differs[1])
+
+
+class CommandTests(unittest.TestCase):
+ def command(self, argv: list[str], fetch: FakeFetch, client: FakeClient):
+ parser = run.build_parser()
+ args = parser.parse_args(argv)
+ out, err = io.StringIO(), io.StringIO()
+ with (
+ tempfile.TemporaryDirectory() as tmp,
+ patch.object(run, "RESULTS_DIR", Path(tmp)),
+ patch.object(run, "SIEClient", return_value=contextlib.nullcontext(client)),
+ patch.dict("os.environ", {}, clear=True),
+ contextlib.redirect_stdout(out),
+ contextlib.redirect_stderr(err),
+ ):
+ try:
+ run.latency_command(parser, args, fetch)
+ code = 0
+ except SystemExit as exc:
+ code = exc.code
+ return code, out.getvalue(), err.getvalue()
+
+ def test_the_endpoint_is_required(self):
+ with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
+ run.build_parser().parse_args(["latency", "--page", "classify"])
+
+ def test_only_the_two_pages_are_accepted(self):
+ with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
+ run.build_parser().parse_args(["latency", "--page", "rerank", "--endpoint", "http://localhost:8080"])
+
+ def test_a_run_prints_the_result_path_and_the_table(self):
+ argv = ["latency", "--page", "classify", "--endpoint", "http://LOCALHOST:8080/"]
+ code, out, _ = self.command(argv, FakeFetch(), FakeClient())
+ self.assertEqual(code, 0)
+ self.assertIn("latency-classify-", out.splitlines()[0])
+ self.assertIn("published RTX PRO 6000", out)
+
+ def test_a_mismatch_stops_before_any_request(self):
+ client = FakeClient()
+ fetch = FakeFetch(jobs_sha256={"classify.json": {"sha256": "0" * 64}})
+ code, out, err = self.command(
+ ["latency", "--page", "classify", "--endpoint", "http://localhost:8080"], fetch, client
+ )
+ self.assertEqual(code, 1)
+ self.assertIn("stopped: the rebuilt classify jobs have sha256", err)
+ self.assertEqual(client.calls, [])
+ self.assertEqual(out, "")
+
+ def test_a_missing_download_stops_the_run(self):
+ fetch = FakeFetch(missing="questions.json")
+ code, _, err = self.command(
+ ["latency", "--page", "search", "--endpoint", "http://localhost:8080"], fetch, FakeClient()
+ )
+ self.assertEqual(code, 1)
+ self.assertIn("stopped:", err)
+
+ def test_a_run_where_every_request_fails_exits_1(self):
+ client = FakeClient(fail_ids=frozenset({"a-1", "a-2", "b-3"}))
+ code, out, _ = self.command(
+ ["latency", "--page", "classify", "--endpoint", "http://localhost:8080"], FakeFetch(), client
+ )
+ self.assertEqual(code, 1)
+ self.assertIn("failed: 3 of 3", out)
+
+
+if __name__ == "__main__":
+ unittest.main()