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
feat(examples): time eight more website pages one request at a time (#931)
Shai Shmuele91c9a28bc53
diff --git a/examples/evaluations/published-benchmarks/README.md b/examples/evaluations/published-benchmarks/README.mdindex 857bd7bbd..7967572ac 100644--- a/examples/evaluations/published-benchmarks/README.md+++ b/examples/evaluations/published-benchmarks/README.md@@ -627,20 +627,28 @@ 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+The per-request times the website shows for SIE come from public studies in 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 |+Each study timed a model one request at a time, with the client inside the+server's container. `run.py latency` repeats that timing against your own+server for ten pages:++| `--page` | On the website | Model | Bundle | GPU it was timed on | Inputs | One request |+| --- | --- | --- | --- | --- | --- | --- |+| `classify` | `/classify`: 13.1 ms | `fastino/GLiNER2.5-Decide` | `transformers5` | RTX PRO 6000 | 400 CLINC150 and BANKING77 messages | `extract` with the message's 8 labels, `options={"overflow_policy": "error"}` |+| `search` | home page and `/about`: 15.7 ms | `Qwen/Qwen3-Embedding-4B` | `sglang-embedding` | RTX PRO 6000 | 440 questions | `encode` with `is_query=True` and `output_types=["dense"]`, no instruction |+| `named-entities` | industry pages, extract entities: 24 ms | `numind/NuNER_Zero-span` | `default` | RTX PRO 6000 | 652 sentences in 7 sets | `extract` with the set's labels, `options={"threshold": 0.5}` |+| `redact` | `/redact`: 61 ms | `superlinked/pii-redact` | `default` | RTX PRO 6000 | 660 documents | `extract` with the study's 39 labels |+| `typed-decisions` | `/typed-decisions`: 13.8 ms | `MoritzLaurer/deberta-v3-large-zeroshot-v2.0` | `default` | RTX PRO 6000 | the first 200 test comments of the comment-spam set | `extract` with one label statement, `options={"hypothesis_template": "{}", "multi_label": true}` |+| `rerank` | `/rerank`: 55 ms | `Qwen/Qwen3-Reranker-4B:fast` | `default` | H100 | 499 questions with 20 candidates each | `score` with the study's instruction |+| `request-routing` | `/request-routing`: 8.5 ms | `Qwen/Qwen3-Reranker-4B:fast` | `default` | H100 | 200 requests | `score`: one request against one description, with the study's instruction |+| `ocr` | industry pages, OCR a page: 287 ms | `zai-org/GLM-OCR` | `sglang-vision-extract` | H100 | 372 photos (115 MB) | `extract` with the photo, instruction `Text Recognition:` |+| `chat` | `/chat`: 0.74 s | `Qwen/Qwen3.8-27B-FP8` | `sglang-cu130` | H100 | 330 turns of 55 conversations | a chat completion, 400 new tokens at most, temperature 0 |+| `structured-output` | industry pages, structured output: 938 ms | `Qwen/Qwen3.8-27B-FP8` | `sglang-cu130` | H100 | 100 Structured Output Benchmark records | a chat completion with a strict JSON schema, 2,048 new tokens at most, temperature 0 |On a Linux machine with an NVIDIA GPU, start the server for the page with its-bundle image:+bundle image. For `classify`:```shdocker run --gpus all -p 127.0.0.1:8080:8080 \@@ -655,18 +663,12 @@ Then, from this directory, on the same machine: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-```+For another page, stop that server and start the page's bundle with its model+in `SIE_PRELOAD_MODELS`. The images are+`ghcr.io/superlinked/sie-server:v0.11.0-cuda12-<bundle>`, except `sglang-cu130`,+which is `v0.11.0-cuda13-sglang-cu130`. For `rerank` and `request-routing`,+preload `Qwen/Qwen3-Reranker-4B:fast`. `chat` and `structured-output` need an+80 GB GPU.`--endpoint` is required. The key rule is the one in[Run it against your own server](#run-it-against-your-own-server): a server@@ -676,17 +678,30 @@ The run:1. downloads the study's inputs at their pinned revisions, rebuilds therequest 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;+ any request when its SHA-256 differs from the one the study published. The+ `redact` and `typed-decisions` studies published no such hash, so the check+ uses the hash of the rebuild, pinned in `latency.py`. `ocr` also downloads+ its 372 photos;+2. sends the study's warm-up requests, built from the end of that list, and+ does not time them: 20 for `classify`, `search` and `named-entities`, 10 for+ `redact`, 5 for `typed-decisions`, `rerank`, `request-routing` and `ocr`, 3+ for `chat` and 2 for `structured-output`. Where the server keeps a cache,+ a warm-up carries a `[<level>-<n>] ` text prefix or one changed pixel, as+ the study's did, so it never equals 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.+ times each `SIEClient` call. A chat completion is timed to the complete+ reply;+4. prints your n, p50, p95 and mean beside the published values, with+ percentiles interpolated linearly as the studies computed them, says how+ the published figure was made, and writes+ `results/latency-<page>-<utc>.json` with the time of every request.++The published figure is one run per GPU, except `rerank` and+`request-routing`, which are the median of three runs on fresh servers, and+`typed-decisions`, which is the median of five containers of three runs each.+Your run is one run. For `chat`, the website shows a run of 2026-10-13; the+same requests from the 2026-10-11 study are shown beside it.Every run also prints what differs from the study:@@ -695,15 +710,20 @@ Every run also prints what differs from the study:through `sie_sdk.SIEClient`, so your time also includes the HTTP server andthe path from the client to the server. Run the client on the GPU machine tokeep 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.+- your GPU, and the server you started. The studies ran v0.10.0 images with a+ newer server package; the commands above start v0.11.0;+- for `chat` and `structured-output`, a chat completion on a standalone server+ goes to the SGLang server it runs, while the study's client used the+ sidecar's generation stream.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 theinputs fail the check or no request succeeds on its first attempt. There is nopass or fail: the numbers are set side by side.+`/detect` (82.2 ms) is not covered: its 300 photos are not in the dataset, and+fetching them from their original archives means streaming about 11.5 GB.+## Validation`validation/` holds the example's own output from 2026-11-03: three@@ -840,6 +860,6 @@ The tests use a fake client, in-memory datasets and the committed- no cost, price or accounting fields;- no recorded-evidence download beyond what `run.py latency` reads: thequality 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;+ public datasets, and `run.py latency` reads the per-request time studies'+ inputs and published results at pinned revisions;- 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.pyindex 873c2b231..f683e64cf 100644--- a/examples/evaluations/published-benchmarks/latency.py+++ b/examples/evaluations/published-benchmarks/latency.py@@ -1,8 +1,11 @@"""Time one request at a time against your own server, beside the per-request times the SIE website shows."""import contextlib+import copyimport hashlib+import ioimport json+import randomimport statisticsimport timefrom collections.abc import Callable, Mapping, Sequence@@ -17,7 +20,7 @@ from official import Fetchfrom score import write_jsonDATASET = "superlinked/sie-task-evidence"-RESOLVE_URL = f"https://huggingface.co/datasets/{DATASET}/resolve"+RESOLVE_URL = "https://huggingface.co/datasets/{dataset}/resolve"STUDY_REVISION = "2f74a5c09c3cefa0f5f754f92949600fcd4dc1aa"STUDY = "latency-fastest-config/2026-10-11"JOBS_SHA256 = f"{STUDY}/prereg/jobs-sha256.json"@@ -30,22 +33,65 @@ READY_TIMEOUT_S = 900.0READY_POLL_S = 5.0NOT_READY = (SIEConnectionError, ModelLoadingError, ProvisioningError)NS_PER_MS = 1_000_000+MAX_DOWNLOAD_BYTES = 32 * 1024 * 1024+SOCKET_DIFFERENCE = (+ "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"+)class InputMismatch(Exception):pass+@dataclass(frozen=True)+class Ref:+ revision: str+ path: str+ dataset: str = DATASET++@dataclass(frozen=True)class Page:+ """One website time: the study inputs that rebuild its jobs file, where its hash and its result are, and how it ran.++ ``jobs_sha256`` is the published hash file (read at key ``jobs_key``), or a hash pinned here when the study+ published none. ``model`` is the id to call when it differs from the jobs file's model (a profile such as+ ``:fast``). ``timed`` keeps only the first jobs for timing when the study sent the rest as warm-ups. ``photos``+ is the folder that holds the images the jobs name.+ """+name: str- input_revision: str- input_path: str- build: Callable[[bytes], dict[str, Any]]+ inputs: tuple[Ref, ...]+ build: Callable[..., dict[str, Any]]+ jobs_sha256: Ref | str+ jobs_key: str+ published: Callable[[Fetch], dict[str, Any]]+ website: str+ level: str = LEVEL+ warmups: int = WARMUP_REQUESTS+ timed: int | None = None+ model: str | None = None+ photos: Ref | None = None+ differences: tuple[str, ...] = ()+++def sha256(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++def jsonl(raw: bytes, *, split_on_newline: bool = False) -> list[dict[str, Any]]:+ text = raw.decode("utf-8")+ lines = text.split("\n") if split_on_newline else text.splitlines()+ return [json.loads(line) for line in lines if line.strip()]+++# ---- jobs files, each written exactly as the study's builder wrote it ------------------------------------------def classify_jobs(raw: bytes) -> dict[str, Any]:- items = [json.loads(line) for line in raw.decode("utf-8").splitlines() if line.strip()]+ items = jsonl(raw)jobs = [{"id": it["id"], "text": it["text"], "labels": list(it["labels"]), "meta": {"domain": it["domain"]}}for it in items@@ -58,7 +104,7 @@ def classify_jobs(raw: bytes) -> dict[str, Any]:"defaults": {"options": {"overflow_policy": "error"}},"source": {"items": "classify-current-arms-2026-10-11/prereg/items.jsonl @4e9f6498",- "items_sha256": hashlib.sha256(raw).hexdigest(),+ "items_sha256": sha256(raw),"request": "one message per extract call with its 8 labels, options {overflow_policy: error}",},"jobs": jobs,@@ -76,70 +122,730 @@ def search_jobs(raw: bytes) -> dict[str, Any]:"warm_variant": "tagged","source": {"questions": "lookalike-search/inputs/questions.json @b939e410 (440 questions)",- "sha256": hashlib.sha256(raw).hexdigest(),+ "sha256": sha256(raw),"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],}+NER_SETS = ("ai", "literature", "music", "politics", "science", "mit_movie", "mit_restaurant")+++def named_entities_jobs(study_raw: bytes, *set_raws: bytes) -> dict[str, Any]:+ study = json.loads(study_raw)+ if tuple(study["labels"]) != NER_SETS:+ raise InputMismatch(f"the study lists the sentence sets {list(study['labels'])}, not {list(NER_SETS)}")+ sentences = dict(zip(NER_SETS, set_raws, strict=True))+ jobs = []+ for set_name, labels in study["labels"].items():+ for row in jsonl(sentences[set_name]):+ jobs.append(+ {+ "id": f"{set_name}/{row['id']}",+ "text": row["text"],+ "labels": list(labels.values()),+ "meta": {"set": set_name},+ }+ )+ return {+ "page": "named-entities",+ "model": "numind/NuNER_Zero-span",+ "profile": "default",+ "op": "extract",+ "defaults": {"options": {"threshold": 0.5}},+ "source": {+ "sentences": "custom-entity-types/data/main/*.jsonl @8736554b (652 sentences)",+ "labels": "reproducibility/nuner652-current/2026-10-10/STUDY.json labels",+ "study_sha256": sha256(study_raw),+ "request": "one sentence per extract call with its set's label list, options {threshold: 0.5}",+ },+ "jobs": jobs,+ }+++def redact_jobs(documents_raw: bytes, frozen_raw: bytes) -> dict[str, Any]:+ frozen = json.loads(frozen_raw)+ if sha256(documents_raw) != frozen["documents"]["sha256"]:+ raise InputMismatch("the documents do not have the SHA-256 the study froze")+ labels = frozen["label_lists"]["L39"]+ return {+ "page": "redact",+ "model": frozen["sie"]["model"],+ "profile": "default",+ "op": "extract",+ "warm_variant": "tagged",+ "source": {+ "documents": "redact/inputs/gretel-main.jsonl @31383ae9",+ "sha256": frozen["documents"]["sha256"],+ "request": f"one document per extract call; labels = the {len(labels)}-label list L39; no options",+ },+ "defaults": {"labels": labels},+ "jobs": [+ {"id": str(d["index"]), "text": d["text"], "meta": {"index": d["index"]}} for d in jsonl(documents_raw)+ ],+ }+++TYPED_DECISIONS_LABEL = (+ "The comment promotes something unrelated to the video: a channel, a link, a website or a product, "+ "or asks people to subscribe, follow, vote or send money."+)+TYPED_DECISIONS_TIMED = 200+TYPED_DECISIONS_WARMUPS = 5+++def typed_decisions_jobs(data_raw: bytes, gold_raw: bytes) -> dict[str, Any]:+ split = {row["id"]: row["split"] for row in jsonl(gold_raw, split_on_newline=True)}+ test = [row for row in jsonl(data_raw, split_on_newline=True) if split[row["id"]] == "test"]+ return {+ "model": "MoritzLaurer/deberta-v3-large-zeroshot-v2.0",+ "profile": "default",+ "op": "extract",+ "defaults": {+ "labels": [TYPED_DECISIONS_LABEL],+ "options": {"hypothesis_template": "{}", "multi_label": True},+ },+ "jobs": [{"id": r["id"], "text": r["text"]} for r in test[: TYPED_DECISIONS_TIMED + TYPED_DECISIONS_WARMUPS]],+ }+++def rerank_jobs(cases_raw: bytes, frozen_raw: bytes) -> dict[str, Any]:+ frozen = json.loads(frozen_raw)+ if frozen["cases_test_sha256"] != sha256(cases_raw):+ raise InputMismatch("the rerank cases do not have the SHA-256 the study froze")+ rule = frozen["rules"]["w2"]["proposed"]+ cases = json.loads(cases_raw)["cases"]+ return {+ "page": "rerank",+ "model": "Qwen/Qwen3-Reranker-4B",+ "profile": "default",+ "op": "score",+ "defaults": {"instruction": rule},+ "source": {+ "cases": "rerank-relevance-rules/inputs/cases_test.json @e5b19d75 (499 cases, 20 candidates each)",+ "sha256": sha256(cases_raw),+ "request": (+ "one score call per case: the query, its 20 candidate texts, instruction = wording w2, "+ "proposed-rule arm (the arm the rivals' latency pass used)"+ ),+ "instruction": rule,+ },+ "jobs": [{"id": c["id"], "query": c["query"], "docs": [x["text"] for x in c["candidates"]]} for c in cases],+ }+++def request_routing_jobs(inputs_raw: bytes, specs_raw: bytes) -> dict[str, Any]:+ body = json.loads(specs_raw)["qwen3_rr4b_q1"]["body"]+ requests = json.loads(inputs_raw)["queries"]+ return {+ "page": "request-routing",+ "model": "Qwen/Qwen3-Reranker-4B",+ "profile": "default",+ "op": "score",+ "defaults": {"instruction": body["instruction"], "query": body["query"]["text"]},+ "source": {+ "requests": (+ "evaluations/2026-10-11/request-routing-cost-results-v1/direct-latency-2026-10-11/"+ "inputs.json, the 200 requests of the study's latency pass, in its order"+ ),+ "request": (+ "arm qwen3_rr4b_q1 of "+ "evaluations/2026-10-13/request-routing-decision-routers-v1: one score call, query = the "+ "description, one document = the request, with the arm's instruction"+ ),+ "description": body["query"]["text"],+ "instruction": body["instruction"],+ },+ "jobs": [{"id": r["id"], "docs": [r["prompt"]]} for r in requests],+ }+++OCR_MANIFEST_SHA256 = "532ae51d590acef816b97662a65fb5ea1819a56311763fcef752bc5139f65c19"+++def ocr_jobs(manifest_raw: bytes) -> dict[str, Any]:+ if sha256(manifest_raw) != OCR_MANIFEST_SHA256:+ raise InputMismatch("the photo manifest does not have the SHA-256 the study's builder checks")+ records = json.loads(manifest_raw)["records"]+ jobs = [+ {+ "id": r["id"],+ "image": f"ocr-photo372/{Path(r['input_image']['path']).name}",+ "image_format": "jpeg",+ "meta": {"domain": r["domain"], "pixels": r["input_image"]["size"][0] * r["input_image"]["size"][1]},+ }+ for r in records+ ]+ return {+ "page": "ocr",+ "model": "zai-org/GLM-OCR",+ "profile": "default",+ "op": "extract",+ "defaults": {"instruction": "Text Recognition:", "options": {"max_new_tokens": 8192, "num_beams": 1}},+ "source": {+ "photos": (+ "ocr-photo372-prereg/2026-10-11/images/input/*.jpg @d03e04fd (372 photos; sha256 checked against "+ "ocr-photo372-source-v1.json @6daad480)"+ ),+ "request": "one photo per extract call, instruction 'Text Recognition:', options {max_new_tokens: 8192, num_beams: 1}",+ },+ "jobs": jobs,+ }+++def chat_jobs(system_raw: bytes, transcripts_raw: bytes) -> dict[str, Any]:+ system = system_raw.decode("utf-8")+ jobs = []+ for conversation in json.loads(transcripts_raw)["conversations"]:+ history = [{"role": "system", "content": system}]+ for turn in conversation["turns"]:+ messages = [*history, {"role": "user", "content": turn["text"]}]+ jobs.append(+ {+ "id": f"{conversation['slug']}#{turn['index']}",+ "messages": messages,+ "meta": {+ "turn": turn["index"],+ "recorded_tokens_in": turn.get("tokensIn"),+ "recorded_tokens_out": turn.get("tokensOut"),+ },+ }+ )+ history = [*messages, {"role": "assistant", "content": turn["reply"]}]+ return {+ "page": "chat",+ "model": "Qwen/Qwen3.8-27B-FP8",+ "profile": "default",+ "op": "generate",+ "defaults": {"max_new_tokens": 400, "temperature": 0.0},+ "warm_variant": "tagged",+ "source": {+ "conversations": (+ "support-assistant-policy/transcripts/Qwen_Qwen3.8-27B-FP8.json @4fbd23b7 (55 conversations, 6 turns "+ "each; customer turns and the recorded replies)"+ ),+ "system_prompt": "support-assistant-policy/inputs/system_prompt.md @4fbd23b7",+ "transcript_sha256": sha256(transcripts_raw),+ "request": (+ "one chat completion per turn: system prompt, the conversation so far with the recorded replies, "+ "the new customer turn; max 400 new tokens, temperature 0"+ ),+ },+ "jobs": jobs,+ }+++# The Structured Output Benchmark's (SOB) prompt and strict-schema rule, as the study's items were built with them.+SOB_SYSTEM = (+ "Answer the question using only the provided context. "+ "Return a valid JSON object that strictly follows the given JSON schema. "+ "Do not output anything except the JSON object.\n\n"+ "Rules:\n"+ "- No explanations: Do not include reasoning, analysis, or any sentences outside the JSON.\n"+ "- No markdown: Do not wrap the JSON in code blocks or add formatting like ``` or 'json'.\n"+ "- No extra text: Do not add prefixes or suffixes such as 'Answer:' or 'Output:'.\n"+ "- Follow the schema exactly: Use only the keys defined in the schema and ensure correct data types.\n"+ "- Include all required fields: Every field listed as required in the schema must appear in the JSON.\n"+ "- If unknown, return null: If the context does not contain the answer, set the field value to null "+ "instead of guessing."+)+SOB_PARQUET_SHA256 = "b86a475557aa65028a0d2c71aac780c8258a2a8cf15cd76e1300d9cc241c81a5"+SOB_ITEMS_SHA256 = "54b006028f6091c3aff1322c4a5eb1bce881fab30623bc58a0dc0357f699c0e5"+STRUCTURED_TIMED = 100+++def strict_schema(schema: Any) -> Any:+ if isinstance(schema, dict):+ if schema.get("type") == "object" and isinstance(schema.get("properties"), dict):+ schema["required"] = list(schema["properties"].keys())+ schema["additionalProperties"] = False+ for value in schema["properties"].values():+ strict_schema(value)+ if schema.get("type") == "array" and "items" in schema:+ strict_schema(schema["items"])+ return schema+++def sob_draw(records: Sequence[Mapping[str, Any]], n: int, seed: int) -> list[str]:+ strata: dict[tuple[Any, Any], list[str]] = {}+ for record in records:+ strata.setdefault((record["question_difficulty"], record["schema_complexity"]), []).append(record["record_id"])+ total = sum(len(ids) for ids in strata.values())+ rng = random.Random(seed)+ keys = sorted(strata)+ quotas = {k: n * len(strata[k]) // total for k in keys}+ for k in sorted(keys, key=lambda k: -(n * len(strata[k]) / total - quotas[k]))[: n - sum(quotas.values())]:+ quotas[k] += 1+ picked: list[str] = []+ for k in keys:+ ids = sorted(strata[k])+ rng.shuffle(ids)+ picked += ids[: quotas[k]]+ rng.shuffle(picked)+ return picked+++def structured_output_jobs(sample_raw: bytes, parquet_raw: bytes) -> dict[str, Any]:+ import pyarrow.parquet as pq # only this page reads a parquet file++ if sha256(parquet_raw) != SOB_PARQUET_SHA256:+ raise InputMismatch("the SOB test split does not have the SHA-256 the study used")+ sample = json.loads(sample_raw)+ rows = pq.read_table(io.BytesIO(parquet_raw)).to_pylist()+ if sob_draw(rows, sample["n"], sample["seed"]) != sample["e1"]:+ raise InputMismatch("the sample is not the one its seed draws from the SOB test split")+ records = {row["record_id"]: row for row in rows}+ items = []+ for record_id in sample["e1"]:+ record = records[record_id]+ schema = json.loads(record["json_schema"]) if isinstance(record["json_schema"], str) else record["json_schema"]+ user = (+ f"Context:\n{record['context']}\n\nQuestion: {record['question']}\n\n"+ f"Respond with JSON matching this schema:\n{json.dumps(schema, indent=2)}"+ )+ items.append(+ {"id": record_id, "system": SOB_SYSTEM, "user": user, "schema": strict_schema(copy.deepcopy(schema))}+ )+ items_sha256 = sha256(json.dumps(items).encode())+ if items_sha256 != SOB_ITEMS_SHA256:+ raise InputMismatch(f"the SOB items have sha256 {items_sha256}, the study's items {SOB_ITEMS_SHA256}")+ jobs = [+ {+ "id": it["id"][:16],+ "messages": [{"role": "system", "content": it["system"]}, {"role": "user", "content": it["user"]}],+ "grammar": {"kind": "json_schema", "value": it["schema"], "label": "answer", "strict": True},+ }+ for it in items[:STRUCTURED_TIMED]+ ]+ return {+ "page": "structured-output",+ "model": "Qwen/Qwen3.8-27B-FP8",+ "profile": "default",+ "op": "generate",+ "defaults": {"max_new_tokens": 2048, "temperature": 0.0},+ "warm_variant": "tagged",+ "source": {+ "records": (+ "the first 100 of the 500 SOB records in structured-output-accuracy/inputs/sob_sample.json @0e1fb325 "+ "(texts from interfaze-ai/sob @c118e38a, built by the public example's score.sob_items)"+ ),+ "items_sha256": items_sha256,+ "request": (+ "one chat completion per record: SOB system prompt and user message, strict json_schema grammar, "+ "max 2,048 new tokens, temperature 0"+ ),+ },+ "jobs": jobs,+ }+++# ---- published values ------------------------------------------------------------------------------------------+++def dataset_url(revision: str, path: str, dataset: str = DATASET) -> str:+ return f"{RESOLVE_URL.format(dataset=dataset)}/{revision}/{path}"+++def fetch_ref(ref: Ref, fetch: Fetch) -> bytes:+ return fetch(dataset_url(ref.revision, ref.path, ref.dataset), None)+++def fetch_json(ref: Ref, fetch: Fetch) -> Any:+ return json.loads(fetch_ref(ref, fetch))+++def row(gpu: str, n: int | None, p50: float, p95: float | None, mean: float | None, note: str = "") -> dict[str, Any]:+ entry: dict[str, Any] = {"gpu": gpu, "n": n, "p50_ms": p50, "p95_ms": p95, "mean_ms": mean}+ if note:+ entry["note"] = note+ return entry+++def server_text(bundle: str | None, image: str, revision: str) -> str:+ image_name = f"the {bundle} image" if bundle else "the image"+ return f"{image_name} {image} with the server package from {revision[:8]}"+++def study_published(page: str, level: str = LEVEL) -> Callable[[Fetch], dict[str, Any]]:+ """A page of the 2026-10-11 study: one run per GPU, read from ``results/<page>.json``."""++ def read(fetch: Fetch) -> dict[str, Any]:+ ref = Ref(STUDY_REVISION, f"{STUDY}/results/{page}.json")+ doc = fetch_json(ref, fetch)+ classes = {}+ for key in CLASSES:+ entry = doc["classes"].get(key)+ if entry is None or level not in entry["levels"]:+ continue+ latency = entry["levels"][level]["latency"]+ classes[key] = {+ **row(entry["gpu"], latency["n"], latency["p50_ms"], latency["p95_ms"], latency["mean_ms"]),+ "bundle": entry["bundle"],+ "image_digest": entry["image_digest"],+ "server_overlay_revision": entry["server_overlay_revision"],+ "client_placement": entry["client_placement"],+ }+ best = classes[doc["best_class"]["key"]]+ return {+ "dataset": ref.dataset,+ "revision": ref.revision,+ "path": ref.path,+ "level": level,+ "figure": f"the p50 of one run per GPU, level {level}",+ "best_class": doc["best_class"]["key"],+ "classes": classes,+ "server": server_text(best["bundle"], best["image_digest"], best["server_overlay_revision"]),+ }++ return read+++CHAT_SITE = Ref(+ "f2152b039ae0ce92a3846ba28cbd862625b8b496",+ "chat-value-prop/2026-10-13/results/latency/sie-Qwen3.8-27B-c1-base55.json",+)+++def chat_published(fetch: Fetch) -> dict[str, Any]:+ published = study_published("chat", "chat-c1")(fetch)+ site = fetch_json(CHAT_SITE, fetch)["complete_reply_s"]+ shown = row(+ "H100", site["n"], round(site["p50"] * 1000, 2), round(site["p95"] * 1000, 2), round(site["mean"] * 1000, 2)+ )+ earlier = {f"{key}-2026-10-11": {**entry, "note": "2026-10-11"} for key, entry in published["classes"].items()}+ return {+ **published,+ "dataset": CHAT_SITE.dataset,+ "revision": CHAT_SITE.revision,+ "path": CHAT_SITE.path,+ "figure": (+ "the p50 of one run on an H100, 2026-10-13, time to the complete reply; the same requests ran on "+ "2026-10-11 in the latency study, shown below it"+ ),+ "best_class": "h100",+ "classes": {"h100": shown, **earlier},+ "also": {"revision": published["revision"], "path": published["path"]},+ }+++RERANK_SITE = Ref("aa6c734c11063105e2c27ade8de5e014f053a0e9", "reranker-serving/2026-10-12/results/summary.json")+RERANK_CONTAINERS = (("h100", "H100", "h100-4b"), ("rtx", "RTX PRO 6000", "rtx-4b"), ("l4", "L4", "l4-4b"))+++def rerank_published(fetch: Fetch) -> dict[str, Any]:+ doc = fetch_json(RERANK_SITE, fetch)+ classes = {}+ for key, gpu, container in RERANK_CONTAINERS:+ level = doc["containers"][container]["arms"]["graphs"]["levels"]["rerank-c1"]+ n = level["runs"][0]["requests"]+ note = "" if n == 499 else f"{n} questions only"+ classes[key] = row(gpu, n, level["p50_ms"], level["p95_ms"], level["mean_ms"], note)+ h100 = doc["containers"]["h100-4b"]+ revisions = dict(h100["revisions"])+ return {+ "dataset": RERANK_SITE.dataset,+ "revision": RERANK_SITE.revision,+ "path": RERANK_SITE.path,+ "level": "rerank-c1, arm graphs (the fast profile's options)",+ "figure": "the median of the p50s of 3 runs, each on a fresh server",+ "best_class": "h100",+ "classes": classes,+ "server": f"the image {h100['server_image'].split('@')[-1]} with the server package from {revisions['pr'][:8]}",+ }+++ROUTING_SITE = Ref(+ "6cad8837b01bfd3b91e9fc7de47a5a9d46c73e9d", "rerank-fast-default/2026-10-13/results/q1-h100-summary.json"+)+++def request_routing_published(fetch: Fetch) -> dict[str, Any]:+ doc = fetch_json(ROUTING_SITE, fetch)+ runs = [run["latency"] for name, run in sorted(doc["runs"].items()) if name.startswith("promoted-q1-r")]+ shown = row(+ "H100",+ runs[0]["n"],+ doc["promoted_median_of_three_medians_ms"],+ statistics.median(r["p95_ms"] for r in runs),+ statistics.median(r["mean_ms"] for r in runs),+ )+ return {+ "dataset": ROUTING_SITE.dataset,+ "revision": ROUTING_SITE.revision,+ "path": ROUTING_SITE.path,+ "level": "promoted-q1 (the fast profile)",+ "figure": "the median of the p50s of 3 runs, each on a fresh server",+ "best_class": "h100",+ "classes": {"h100": shown},+ "server": server_text("default", doc["image_digest"], doc["sie_rev"]),+ }+++REDACT_SITE = Ref("f025dd3cd8b916921a05c163525172fb2cf5ab08", "redact-fair-prompt/2026-10-12/results/results.json")+++def redact_published(fetch: Fetch) -> dict[str, Any]:+ timing = fetch_json(REDACT_SITE, fetch)["timing"]["sie+L39"]+ latency = timing["latency"]+ return {+ "dataset": REDACT_SITE.dataset,+ "revision": REDACT_SITE.revision,+ "path": REDACT_SITE.path,+ "level": "c1-L39",+ "figure": "the p50 of one run",+ "best_class": "rtx",+ "classes": {"rtx": row("RTX PRO 6000", latency["n"], latency["p50_ms"], latency["p95_ms"], latency["mean_ms"])},+ "server": server_text("default", timing["image_digest"], timing["sie_rev"]),+ }+++TYPED_DECISIONS_SITE = Ref(+ "5283bf0751c1f9fce2ef443eb4d0316c68a230d7",+ "typed-decisions-untuned-confirm/2026-10-13/addendum-speed-pin/results/results.json",+)+++def typed_decisions_published(fetch: Fetch) -> dict[str, Any]:+ task = fetch_json(TYPED_DECISIONS_SITE, fetch)["tasks"]["comment-spam"]+ note = f"containers {task['min_ms']:.2f} to {task['max_ms']:.2f}"+ return {+ "dataset": TYPED_DECISIONS_SITE.dataset,+ "revision": TYPED_DECISIONS_SITE.revision,+ "path": TYPED_DECISIONS_SITE.path,+ "level": "comment-spam",+ "figure": "the median of 5 containers, each the median of 3 runs' p50s over the first 200 test comments",+ "best_class": "rtx",+ "classes": {"rtx": row("RTX PRO 6000", TYPED_DECISIONS_TIMED, task["model_ms"], task["p95_ms"], None, note)},+ "server": "the v0.10.0 image with the sidecar's local-ingest mode",+ }+++# ---- pages -----------------------------------------------------------------------------------------------------++# The redact and typed-decisions studies published no hash of their jobs files. These are the SHA-256s of the+# rebuilds below, whose request ids and order match the studies' published per-request rows.+REDACT_JOBS_SHA256 = "02ac2236ab388e7785d1b165aba2a5eb1bfd5b816c3e0521f7aa5413ebc0cf29"+TYPED_DECISIONS_JOBS_SHA256 = "13064349537f8b33f65ed1f249cd291568e49dd17eeecd244bb601cf5ceb53ae"+++def study_hash() -> Ref:+ return Ref(STUDY_REVISION, JOBS_SHA256)+++ROUND_UP = "rounded up to 0.1 ms"+FAST = "Qwen/Qwen3-Reranker-4B:fast"+GENERATE = (+ "on a standalone sie-server, a chat completion goes to the SGLang server it runs; the published client "+ "used the sidecar's generation stream and timed it to the final frame"+)+FRESH_SERVERS = "the published figure is a median over 3 fresh servers; this is one run on the server you started"+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,- ),+ page.name: page+ for page in (+ Page(+ "classify",+ (Ref("4e9f649842dd802d353d10fc8dc2347b9a927189", "classify-current-arms-2026-10-11/prereg/items.jsonl"),),+ classify_jobs,+ study_hash(),+ "classify.json",+ study_published("classify"),+ f"13.1 ms on /classify and its model page: the RTX PRO 6000 p50, {ROUND_UP}",+ ),+ Page(+ "search",+ (Ref("b939e41046eef6a0c2a9ee60c152161fd3fb7e04", "lookalike-search/inputs/questions.json"),),+ search_jobs,+ study_hash(),+ "search.json",+ study_published("search"),+ f"15.7 ms on the home and about pages: the RTX PRO 6000 p50, {ROUND_UP}",+ ),+ Page(+ "named-entities",+ (+ Ref(+ "531c444b42539228ad0c231c3a0e9b917c6018ba", "reproducibility/nuner652-current/2026-10-10/STUDY.json"+ ),+ *(+ Ref("8736554b7afd71f05a9e53daef6be72fb8fe176f", f"custom-entity-types/data/main/{name}.jsonl")+ for name in NER_SETS+ ),+ ),+ named_entities_jobs,+ study_hash(),+ "named-entities.json",+ study_published("named-entities"),+ "24 ms on the industry pages (extract entities, NuNER Zero): the RTX PRO 6000 p50, rounded",+ ),+ Page(+ "redact",+ (+ Ref("31383ae9986d9dc9edd4e3a06ee9fb40b223d6fb", "redact/inputs/gretel-main.jsonl"),+ Ref(+ "f025dd3cd8b916921a05c163525172fb2cf5ab08", "redact-fair-prompt/2026-10-12/results/code/frozen.json"+ ),+ ),+ redact_jobs,+ REDACT_JOBS_SHA256,+ "redact.json",+ redact_published,+ "61 ms on /redact, its model page and the industry pages: the RTX PRO 6000 p50, rounded up",+ level="c1-L39",+ warmups=10,+ ),+ Page(+ "typed-decisions",+ (+ Ref(+ "5283bf0751c1f9fce2ef443eb4d0316c68a230d7",+ "typed-decisions-untuned-confirm/2026-10-13/data/comment-spam.jsonl",+ ),+ Ref(+ "5283bf0751c1f9fce2ef443eb4d0316c68a230d7",+ "typed-decisions-untuned-confirm/2026-10-13/gold/comment-spam.jsonl",+ ),+ ),+ typed_decisions_jobs,+ TYPED_DECISIONS_JOBS_SHA256,+ "typed-decisions.json",+ typed_decisions_published,+ "13.8 ms on /typed-decisions and its model page: the RTX PRO 6000 figure, to 0.1 ms",+ warmups=TYPED_DECISIONS_WARMUPS,+ timed=TYPED_DECISIONS_TIMED,+ differences=(+ "the published figure is a median over 15 runs in 5 containers with 4 CPU cores each; this is one run",+ ),+ ),+ Page(+ "rerank",+ (+ Ref("e5b19d7589fc3a982fcfeeabb071cf833c22455f", "rerank-relevance-rules/inputs/cases_test.json"),+ Ref(+ "aa5d3ed2074afce7bb5b2ed6f9dcd4ed8bcacd5a",+ "current-comparators/2026-10-11/rerank/prereg/frozen.json",+ ),+ ),+ rerank_jobs,+ study_hash(),+ "rerank.json",+ rerank_published,+ "55 ms on /rerank, its model page and the industry pages: the H100 figure, rounded up",+ warmups=5,+ model=FAST,+ differences=(FRESH_SERVERS,),+ ),+ Page(+ "request-routing",+ (+ Ref(+ "bdf9f45218b292b60512fa404595b17abc1cacd1",+ "evaluations/2026-10-11/request-routing-cost-results-v1/direct-latency-2026-10-11/inputs.json",+ ),+ Ref(+ "bdf9f45218b292b60512fa404595b17abc1cacd1",+ "evaluations/2026-10-13/request-routing-decision-routers-v1/results/code/specs.json",+ ),+ ),+ request_routing_jobs,+ Ref("6cad8837b01bfd3b91e9fc7de47a5a9d46c73e9d", "rerank-fast-default/2026-10-13/jobs-sha256.json"),+ "routing-q1-latency200.json",+ request_routing_published,+ "8.5 ms on /request-routing: the H100 figure, rounded",+ warmups=5,+ model=FAST,+ differences=(FRESH_SERVERS,),+ ),+ Page(+ "ocr",+ (+ Ref(+ "6daad480d988ec1596a51ba61462be0e013028f5",+ "ocr-photo372-results/2026-10-11/source-manifest/ocr-photo372-source-v1.json",+ ),+ ),+ ocr_jobs,+ study_hash(),+ "ocr.json",+ study_published("ocr"),+ "287 ms on the industry pages (OCR a page, GLM-OCR): the H100 p50, rounded",+ warmups=5,+ photos=Ref("d03e04fd2f7f768afcc753b952fb9c9abc47748b", "ocr-photo372-prereg/2026-10-11/images/input"),+ ),+ Page(+ "chat",+ (+ Ref("4fbd23b7a53de46b52532722d2f37fc17feb60d5", "support-assistant-policy/inputs/system_prompt.md"),+ Ref(+ "4fbd23b7a53de46b52532722d2f37fc17feb60d5",+ "support-assistant-policy/transcripts/Qwen_Qwen3.8-27B-FP8.json",+ ),+ ),+ chat_jobs,+ study_hash(),+ "chat.json",+ chat_published,+ "0.74 s on /chat and its model page: the 2026-10-13 H100 p50, rounded",+ level="chat-c1",+ warmups=3,+ differences=(GENERATE, "the 2026-10-13 run also sent top_p 1.0"),+ ),+ Page(+ "structured-output",+ (+ Ref("0e1fb325cf25bd403ff678dd6031f649981eb434", "structured-output-accuracy/inputs/sob_sample.json"),+ Ref("c118e38abdef6a8e1beba183405c70b28ff7d5a8", "data/test-00000-of-00001.parquet", "interfaze-ai/sob"),+ ),+ structured_output_jobs,+ study_hash(),+ "structured-output.json",+ study_published("structured-output", "structured-c1"),+ "938 ms on the industry pages (structured output, Qwen3.8 27B): the H100 p50, rounded",+ level="structured-c1",+ warmups=2,+ differences=(GENERATE,),+ ),+ )}-def dataset_url(revision: str, path: str) -> str:- return f"{RESOLVE_URL}/{revision}/{path}"+# ---- the run ---------------------------------------------------------------------------------------------------def jobs_bytes(doc: Mapping[str, Any]) -> bytes:return json.dumps(doc).encode("utf-8")+def expected_jobs_sha256(page: Page, fetch: Fetch) -> str:+ if isinstance(page.jobs_sha256, Ref):+ return fetch_json(page.jobs_sha256, fetch)[page.jobs_key]["sha256"]+ return page.jobs_sha256+++def jobs_hash_source(page: Page) -> dict[str, Any]:+ if isinstance(page.jobs_sha256, Ref):+ ref = page.jobs_sha256+ return {"dataset": ref.dataset, "revision": ref.revision, "path": ref.path, "key": page.jobs_key}+ return {"pinned": "this example; the study published no hash of its jobs file"}++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()+ expected = expected_jobs_sha256(page, fetch)+ doc = page.build(*(fetch_ref(ref, fetch) for ref in page.inputs))+ digest = sha256(jobs_bytes(doc))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"],- }+def load_photos(page: Page, doc: Mapping[str, Any], fetch: Fetch) -> dict[str, bytes]:+ if page.photos is None:+ return {}+ folder = page.photosreturn {- "dataset": DATASET,- "revision": STUDY_REVISION,- "path": f"{STUDY}/results/{page.name}.json",- "level": LEVEL,- "best_class": doc["best_class"]["key"],- "classes": classes,+ job["image"]: fetch_ref(Ref(folder.revision, f"{folder.path}/{Path(job['image']).name}", folder.dataset), fetch)+ for job in doc["jobs"]}@@ -162,54 +868,113 @@ def latency_stats(values_ms: Sequence[float]) -> dict[str, Any]:}-def warmup_jobs(doc: Mapping[str, Any]) -> list[dict[str, Any]]:+def pixel_variant(data: bytes, fmt: str, k: int) -> bytes:+ """The same picture with one pixel changed, as the study's client made its image warm-ups."""+ from PIL import Image # only image pages need it++ image = Image.open(io.BytesIO(data))+ image.load()+ x, y = (37 + k) % image.width, (53 + 3 * k) % image.height+ pixel = image.getpixel((x, y))+ pixel = tuple((c + 1) % 256 for c in pixel) if isinstance(pixel, tuple) else (pixel + 1) % 256+ image.putpixel((x, y), pixel)+ buffer = io.BytesIO()+ if fmt in ("jpeg", "jpg"):+ try:+ image.save(buffer, "JPEG", quality="keep", subsampling="keep")+ except Exception: # noqa: BLE001+ image.convert("RGB").save(buffer, "JPEG", quality=95)+ else:+ image.save(buffer, fmt.upper())+ return buffer.getvalue()+++def warm_variant(doc: Mapping[str, Any]) -> str:+ return doc.get("warm_variant") or ("tagged" if doc["op"] == "generate" else "exact")+++def warmup_jobs(page: Page, doc: Mapping[str, Any], photos: Mapping[str, bytes]) -> list[dict[str, Any]]:+ """The last jobs of the list, changed so that none equals a timed request where the server keeps a cache."""jobs = doc["jobs"]- tagged = doc.get("warm_variant") == "tagged"+ variant = warm_variant(doc)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"]+ for i in range(page.warmups):+ k = WARMUP_TAG_BASE + i+ job = copy.deepcopy(jobs[-1 - (i % len(jobs))])+ tag = f"[{page.level}-{k}] "+ if "image" in job:+ job["image_bytes"] = pixel_variant(photos[job["image"]], job.get("image_format", "jpeg"), k)+ elif variant == "tagged":+ if "messages" in job:+ user = next(m for m in job["messages"] if m["role"] == "user")+ user["content"] = tag + user["content"]+ elif "query" in job:+ job["query"] = tag + job["query"]+ elif "text" in job:+ job["text"] = tag + 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 response_format(grammar: Mapping[str, Any]) -> dict[str, Any]:+ schema = {"name": grammar["label"], "schema": grammar["value"], "strict": grammar["strict"]}+ return {"type": "json_schema", "json_schema": schema}-def wait_until_ready(+def send(client: Any,doc: Mapping[str, Any],job: Mapping[str, Any],*,+ wait_for_capacity: bool,+ model: str | None = None,+ photos: Mapping[str, bytes] | None = None,+) -> Any:+ """One request, built as the study's client built it; fields the job does not set are not sent."""+ spec = {**(doc.get("defaults") or {}), **job}+ model = model or doc["model"]+ calls = {+ "wait_for_capacity": wait_for_capacity,+ "provision_timeout_s": READY_TIMEOUT_S if wait_for_capacity else REQUEST_TIMEOUT_S,+ "max_oom_retries": 0,+ }+ op = doc["op"]+ if op == "generate":+ if spec.get("grammar"):+ calls = {"response_format": response_format(spec["grammar"]), **calls}+ return client.chat_completions(+ model, spec["messages"], max_tokens=spec["max_new_tokens"], temperature=spec["temperature"], **calls+ )+ if op == "score":+ if spec.get("instruction"):+ calls = {"instruction": spec["instruction"], **calls}+ return client.score(model, {"text": spec["query"]}, [{"text": text} for text in spec["docs"]], **calls)+ if "image" in spec:+ data = spec.get("image_bytes") or (photos or {})[spec["image"]]+ item = {"id": spec["id"], "images": [{"data": data, "format": spec.get("image_format", "jpeg")}]}+ else:+ item = {"id": spec["id"], "text": spec["text"]}+ if op == "extract":+ fields = {+ "labels": list(spec["labels"]) if spec.get("labels") else None,+ "instruction": spec.get("instruction"),+ "options": dict(spec["options"]) if spec.get("options") else None,+ }+ return client.extract(model, item, **{k: v for k, v in fields.items() if v is not None}, **calls)+ return client.encode(model, item, output_types=list(spec["output_types"]), is_query=bool(spec["is_query"]), **calls)+++def wait_until_ready(+ send_job: Callable[..., Any],+ job: Mapping[str, Any],+ *,monotonic: Callable[[], float] = time.monotonic,sleep: Callable[[float], None] = time.sleep,) -> None:deadline = monotonic() + READY_TIMEOUT_Swhile True:try:- send(client, doc, job, wait_for_capacity=True)+ send_job(job, wait_for_capacity=True)returnexcept NOT_READY:if monotonic() >= deadline:@@ -217,20 +982,26 @@ def wait_until_ready(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)+def warm_up(send_job: Callable[..., Any], jobs: Sequence[Mapping[str, Any]], **ready: Any) -> None:+ if not jobs:+ return+ wait_until_ready(send_job, jobs[0], **ready)for job in jobs[1:]:with contextlib.suppress(Exception):- send(client, doc, job, wait_for_capacity=False)+ send_job(job, wait_for_capacity=False)-def timed_requests(client: Any, doc: Mapping[str, Any], clock: Callable[[], int] = time.perf_counter_ns) -> list[dict]:+def timed_requests(+ client: Any,+ send_job: Callable[..., Any],+ jobs: Sequence[Mapping[str, Any]],+ clock: Callable[[], int] = time.perf_counter_ns,+) -> list[dict]:rows = []- for job in doc["jobs"]:+ for job in jobs:start = clock()try:- send(client, doc, job, wait_for_capacity=False)+ send_job(job, wait_for_capacity=False)except Exception as exc: # noqa: BLE001status = f"error:{type(exc).__name__}"else:@@ -240,19 +1011,11 @@ def timed_requests(client: Any, doc: Mapping[str, Any], clock: Callable[[], int]return rows-def differences(published: Mapping[str, Any]) -> list[str]:- best = published["classes"][published["best_class"]]+def differences(page: Page, published: Mapping[str, Any]) -> list[str]: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]}"- ),+ SOCKET_DIFFERENCE,+ f"this run uses your GPU and the server you started; the published run used {published['server']}",+ *page.differences,]@@ -272,24 +1035,29 @@ def build_record(started_at: datetime,finished_at: datetime,) -> dict[str, Any]:- ok = [row["latency_ms"] for row in rows if row["status"] == "ok"]+ ok = [r["latency_ms"] for r in rows if r["status"] == "ok"]stats = latency_stats(ok)return {"kind": "published-benchmark-reproduction","schema_version": 1,"evaluation_mode": "latency","page": page.name,- "model": doc["model"],+ "model": page.model or doc["model"],"operation": doc["op"],+ "website": page.website,"ingress": {"url": endpoint},"inputs": {- "dataset": DATASET,- "revisions": {"study": STUDY_REVISION, "inputs": page.input_revision},- "path": page.input_path,+ "files": [{"dataset": ref.dataset, "revision": ref.revision, "path": ref.path} for ref in page.inputs],+ "photos": (+ {"dataset": page.photos.dataset, "revision": page.photos.revision, "path": page.photos.path}+ if page.photos+ else None+ ),"jobs_sha256": digest,- "jobs": len(doc["jobs"]),+ "jobs_sha256_source": jobs_hash_source(page),+ "jobs": len(rows),},- "warmup_requests": WARMUP_REQUESTS,+ "warmup_requests": page.warmups,"client": {"description": client_description, "worker_count": 1, "processes_per_worker": 1},"run": {"started_at": _timestamp(started_at),@@ -303,8 +1071,8 @@ def build_record({"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),+ "published": dict(published),+ "differences": differences(page, published),"requests": list(rows),}@@ -319,8 +1087,9 @@ def format_report(record: Mapping[str, Any]) -> list[str]: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)+ label = f"published {entry['gpu']}" + (f" ({entry['note']})" if entry.get("note") else "")+ rows.append((label, entry["n"], entry["p50_ms"], entry["p95_ms"], entry["mean_ms"]))+ width = max(len(name) for name, *_ in rows)lines = [(f"{record['page']}: {record['model']}, {record['operation']}, one request at a time, "@@ -329,15 +1098,15 @@ def format_report(record: Mapping[str, Any]) -> list[str]: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}"+ f"{name:{width}} {'-' if count is None else 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.append(f"the website shows {record['website']}")+ lines.append(f"published figure: {published['figure']}")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"})+ statuses = sorted({r["status"] for r in record["requests"] if r["status"] != "ok"})lines.append(f"failed: {failed} of {record['run']['request_count']} ({', '.join(statuses)}), left out of the numbers")@@ -357,10 +1126,16 @@ def run_latency() -> tuple[dict[str, Any], Path]:page = PAGES[page_name]doc, digest = load_jobs(page, fetch)- published = load_published(page, fetch)+ published = page.published(fetch)+ photos = load_photos(page, doc, fetch)++ def send_job(job: Mapping[str, Any], *, wait_for_capacity: bool) -> Any:+ return send(client, doc, job, wait_for_capacity=wait_for_capacity, model=page.model, photos=photos)++ timed = doc["jobs"][: page.timed] if page.timed else doc["jobs"]started_at = datetime.now(UTC)- warm_up(client, doc, **ready)- rows = timed_requests(client, doc, clock)+ warm_up(send_job, warmup_jobs(page, doc, photos), **ready)+ rows = timed_requests(client, send_job, timed, clock)finished_at = datetime.now(UTC)record = build_record(page,diff --git a/examples/evaluations/published-benchmarks/official.py b/examples/evaluations/published-benchmarks/official.pyindex d4e4b01e7..fd6e482ac 100644--- a/examples/evaluations/published-benchmarks/official.py+++ b/examples/evaluations/published-benchmarks/official.py@@ -65,13 +65,13 @@ def plain_text(value: Any) -> str | None:return None-def http_fetch(url: str, accept: str | None = None) -> bytes:+def http_fetch(url: str, accept: str | None = None, *, max_bytes: int = MAX_BYTES) -> bytes:headers = {"User-Agent": USER_AGENT}if accept is not None:headers["Accept"] = accepttry:with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=TIMEOUT_S) as response:- body = response.read(MAX_BYTES + 1)+ body = response.read(max_bytes + 1)except urllib.error.HTTPError as exc:if exc.code == 404:raise NotFound(url) from None@@ -79,8 +79,8 @@ def http_fetch(url: str, accept: str | None = None) -> bytes:raise LookupFailed(f"HTTP {exc.code} from {urlsplit(url).hostname}{hint}") from Noneexcept OSError as exc:raise LookupFailed(f"could not reach {urlsplit(url).hostname} ({type(exc).__name__})") from None- if len(body) > MAX_BYTES:- raise LookupFailed(f"a response from {urlsplit(url).hostname} is larger than {MAX_BYTES} bytes")+ if len(body) > max_bytes:+ raise LookupFailed(f"a response from {urlsplit(url).hostname} is larger than {max_bytes} bytes")return bodydiff --git a/examples/evaluations/published-benchmarks/run.py b/examples/evaluations/published-benchmarks/run.pyindex 52157fe07..4f0e1a381 100644--- a/examples/evaluations/published-benchmarks/run.py+++ b/examples/evaluations/published-benchmarks/run.py@@ -1554,7 +1554,11 @@ def performance_command(parser: argparse.ArgumentParser, args: argparse.Namespacraise SystemExit(1)-def latency_command(parser: argparse.ArgumentParser, args: argparse.Namespace, fetch: Fetch = http_fetch) -> None:+def latency_fetch(url: str, accept: str | None = None) -> bytes:+ return http_fetch(url, accept, max_bytes=latency_mode.MAX_DOWNLOAD_BYTES)+++def latency_command(parser: argparse.ArgumentParser, args: argparse.Namespace, fetch: Fetch = latency_fetch) -> None:try:endpoint = normalize_endpoint(args.endpoint)except ValueError as exc:diff --git a/examples/evaluations/published-benchmarks/tests/test_latency.py b/examples/evaluations/published-benchmarks/tests/test_latency.pyindex 12b4fc55a..1421eb055 100644--- a/examples/evaluations/published-benchmarks/tests/test_latency.py+++ b/examples/evaluations/published-benchmarks/tests/test_latency.py@@ -1,4 +1,5 @@import contextlib+import dataclassesimport hashlibimport ioimport json@@ -7,6 +8,7 @@ import unittestfrom pathlib import Pathfrom unittest.mock import patch+from PIL import Imagefrom sie_sdk import RequestError, SIEConnectionErrorimport latency@@ -27,14 +29,56 @@ QUESTIONS_RAW = json.dumps(]}).encode()+CASES_RAW = json.dumps(+ {+ "cases": [+ {"id": "c1", "query": "first query", "candidates": [{"text": "d1"}, {"text": "d2"}]},+ {"id": "c2", "query": "second query", "candidates": [{"text": "d3"}]},+ ]+ }+).encode()+RERANK_FROZEN_RAW = json.dumps(+ {"cases_test_sha256": hashlib.sha256(CASES_RAW).hexdigest(), "rules": {"w2": {"proposed": "Judge it."}}}+).encode()+CHAT_SYSTEM_RAW = b"Be helpful."+CHAT_RAW = json.dumps(+ {+ "conversations": [+ {+ "slug": "s1",+ "turns": [+ {"index": 1, "text": "hi", "reply": "hello", "tokensIn": 5, "tokensOut": 2},+ {"index": 2, "text": "help", "reply": "sure"},+ ],+ }+ ]+ }+).encode()-def published_doc(page: str) -> dict:+def jpeg(color: int) -> bytes:+ buffer = io.BytesIO()+ Image.new("RGB", (8, 8), (color, color, color)).save(buffer, "JPEG")+ return buffer.getvalue()+++PHOTOS = {"p1.jpg": jpeg(10), "p2.jpg": jpeg(200)}+MANIFEST_RAW = json.dumps(+ {+ "records": [+ {"id": "r1", "domain": "receipt", "input_image": {"path": "x/p1.jpg", "size": [8, 8]}},+ {"id": "r2", "domain": "sign", "input_image": {"path": "x/p2.jpg", "size": [8, 8]}},+ ]+ }+).encode()+++def study_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",+ "bundle": "transformers5","image_digest": "sha256:" + "a" * 64,"server_overlay_revision": "2b3f7d2ed6d79d880c249d9ef9efb72ae3a36135","client_placement": "same container, sidecar local-ingest Unix socket",@@ -43,63 +87,107 @@ def published_doc(page: str) -> dict:"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"}}+ best = {"ocr": "h100"}.get(page, "rtx")+ return {"page": page, "classes": classes, "best_class": {"key": best}}+++def url(ref: latency.Ref) -> str:+ return latency.dataset_url(ref.revision, ref.path, ref.dataset)+++INPUTS = {+ "classify": (ITEMS_RAW,),+ "search": (QUESTIONS_RAW,),+ "rerank": (CASES_RAW, RERANK_FROZEN_RAW),+ "chat": (CHAT_SYSTEM_RAW, CHAT_RAW),+ "ocr": (MANIFEST_RAW,),+}class FakeFetch:+ """The pages' inputs, hashes and published files for the pages tested end to end."""+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.files: dict[str, bytes] = {}+ sha = {}+ with patch.object(latency, "OCR_MANIFEST_SHA256", hashlib.sha256(MANIFEST_RAW).hexdigest()):+ for name, raws in INPUTS.items():+ page = latency.PAGES[name]+ for ref, raw in zip(page.inputs, raws, strict=True):+ self.files[url(ref)] = raw+ sha[page.jobs_key] = {"sha256": hashlib.sha256(latency.jobs_bytes(page.build(*raws))).hexdigest()}+ self.files[url(latency.Ref(latency.STUDY_REVISION, latency.JOBS_SHA256))] = json.dumps(+ jobs_sha256 or sha+ ).encode()+ for name in ("classify", "search", "ocr"):+ ref = latency.Ref(latency.STUDY_REVISION, f"{latency.STUDY}/results/{name}.json")+ self.files[url(ref)] = json.dumps(study_doc(name)).encode()+ chat = study_doc("chat")+ for entry in chat["classes"].values():+ entry["levels"] = {"chat-c1": entry["levels"]["c1"]}+ del chat["classes"]["l4"]+ chat["best_class"] = {"key": "h100"}+ self.files[url(latency.Ref(latency.STUDY_REVISION, f"{latency.STUDY}/results/chat.json"))] = json.dumps(+ chat+ ).encode()+ self.files[url(latency.CHAT_SITE)] = json.dumps(+ {"complete_reply_s": {"n": 330, "p50": 0.73709, "p95": 1.36999, "mean": 0.80285}}+ ).encode()+ self.files[url(latency.RERANK_SITE)] = json.dumps(rerank_summary()).encode()+ photos = latency.PAGES["ocr"].photos+ for name, data in PHOTOS.items():+ self.files[url(latency.Ref(photos.revision, f"{photos.path}/{name}"))] = dataself.missing = missingself.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]+ def __call__(self, address: str, accept: str | None = None) -> bytes:+ self.urls.append(address)+ if self.missing and self.missing in address:+ raise NotFound(address)+ return self.files[address]+++def rerank_summary() -> dict:+ def container(p50: float, requests: int = 499) -> dict:+ level = {"p50_ms": p50, "p95_ms": p50 + 10, "mean_ms": p50 + 1, "runs": [{"requests": requests}] * 3}+ return {+ "arms": {"graphs": {"levels": {"rerank-c1": level}}},+ "server_image": "ghcr.io/superlinked/sie-server@sha256:" + "b" * 64,+ "revisions": [["base", "a" * 40], ["pr", "5bfa9ea48a172ea6397194efe703ab8977f95811"]],+ }++ return {"containers": {"h100-4b": container(54.22), "rtx-4b": container(88.22), "l4-4b": container(479.69, 60)}}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.calls: list[tuple] = []self.fail_ids = fail_idsself.not_ready = not_readyself.retried_ids = retried_idsself.last_retry_count = 0- def _call(self, op: str, model: str, item: dict, kwargs: dict) -> dict:- self.calls.append((op, model, item, kwargs))+ def _call(self, op: str, model: str, key: str, payload, kwargs: dict) -> dict:+ self.calls.append((op, model, payload, kwargs))if self.not_ready:self.not_ready -= 1raise 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"]:+ self.last_retry_count = 1 if key in self.retried_ids and not kwargs["wait_for_capacity"] else 0+ if key 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)+ return self._call("extract", model, item["id"], item, kwargs)def encode(self, model, item, **kwargs):- return self._call("encode", model, item, kwargs)+ return self._call("encode", model, item["id"], item, kwargs)++ def score(self, model, query, items, **kwargs):+ return self._call("score", model, query["text"], (query, items), kwargs)++ def chat_completions(self, model, messages, **kwargs):+ return self._call("chat", model, messages[-1]["content"], messages, kwargs)def ticking_clock(step_ms: float = 10.0):@@ -142,6 +230,102 @@ class JobsTests(unittest.TestCase):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_named_entities_take_each_set_with_its_labels_in_the_study_order(self):+ study = {"labels": {name: {"a": f"{name} thing"} for name in latency.NER_SETS}}+ sets = [json.dumps({"id": 1, "text": f"{name} sentence"}).encode() for name in latency.NER_SETS]+ doc = latency.named_entities_jobs(json.dumps(study).encode(), *sets)+ self.assertEqual(doc["defaults"], {"options": {"threshold": 0.5}})+ self.assertEqual(+ doc["jobs"][0], {"id": "ai/1", "text": "ai sentence", "labels": ["ai thing"], "meta": {"set": "ai"}}+ )+ self.assertEqual([job["meta"]["set"] for job in doc["jobs"]], list(latency.NER_SETS))+ reordered = {"labels": dict(reversed(list(study["labels"].items())))}+ with self.assertRaisesRegex(latency.InputMismatch, "sentence sets"):+ latency.named_entities_jobs(json.dumps(reordered).encode(), *sets)++ def test_redact_sends_the_frozen_label_list_and_checks_the_documents(self):+ documents = b'{"index": 0, "text": "Call Ann", "domain": "x"}\n{"index": 1, "text": "Hi", "domain": "y"}\n'+ frozen = {+ "documents": {"sha256": hashlib.sha256(documents).hexdigest()},+ "label_lists": {"L39": ["name", "phone"]},+ "sie": {"model": "superlinked/pii-redact"},+ }+ doc = latency.redact_jobs(documents, json.dumps(frozen).encode())+ self.assertEqual(doc["defaults"], {"labels": ["name", "phone"]})+ self.assertEqual(doc["warm_variant"], "tagged")+ self.assertEqual(doc["jobs"][1], {"id": "1", "text": "Hi", "meta": {"index": 1}})+ frozen["documents"]["sha256"] = "0" * 64+ with self.assertRaises(latency.InputMismatch):+ latency.redact_jobs(documents, json.dumps(frozen).encode())++ def test_typed_decisions_keep_the_first_test_messages_and_split_lines_on_newline_only(self):+ rows = [{"id": f"m{i}", "text": f"text {i}\u0085more"} for i in range(500)]+ gold = [{"id": f"m{i}", "split": "test" if i % 2 else "development"} for i in range(500)]+ data_raw = "\n".join(json.dumps(r, ensure_ascii=False) for r in rows).encode()+ gold_raw = "\n".join(json.dumps(g) for g in gold).encode()+ doc = latency.typed_decisions_jobs(data_raw, gold_raw)+ self.assertEqual(len(doc["jobs"]), latency.TYPED_DECISIONS_TIMED + latency.TYPED_DECISIONS_WARMUPS)+ self.assertEqual(doc["jobs"][0], {"id": "m1", "text": "text 1\u0085more"})+ self.assertEqual(+ doc["defaults"],+ {+ "labels": [latency.TYPED_DECISIONS_LABEL],+ "options": {"hypothesis_template": "{}", "multi_label": True},+ },+ )++ def test_rerank_jobs_carry_the_frozen_instruction_and_check_the_cases(self):+ doc = latency.rerank_jobs(CASES_RAW, RERANK_FROZEN_RAW)+ self.assertEqual(doc["defaults"], {"instruction": "Judge it."})+ self.assertEqual(doc["jobs"][0], {"id": "c1", "query": "first query", "docs": ["d1", "d2"]})+ with self.assertRaises(latency.InputMismatch):+ latency.rerank_jobs(CASES_RAW + b" ", RERANK_FROZEN_RAW)++ def test_request_routing_scores_each_request_against_the_description(self):+ specs = {"qwen3_rr4b_q1": {"body": {"instruction": "Judge.", "query": {"text": "A cheap request."}}}}+ inputs = {"queries": [{"id": "r1", "prompt": "What is 2+2?"}]}+ doc = latency.request_routing_jobs(json.dumps(inputs).encode(), json.dumps(specs).encode())+ self.assertEqual(doc["defaults"], {"instruction": "Judge.", "query": "A cheap request."})+ self.assertEqual(doc["jobs"], [{"id": "r1", "docs": ["What is 2+2?"]}])++ def test_ocr_jobs_name_each_photo_and_check_the_manifest(self):+ with self.assertRaises(latency.InputMismatch):+ latency.ocr_jobs(MANIFEST_RAW)+ with patch.object(latency, "OCR_MANIFEST_SHA256", hashlib.sha256(MANIFEST_RAW).hexdigest()):+ doc = latency.ocr_jobs(MANIFEST_RAW)+ self.assertEqual(doc["jobs"][0]["image"], "ocr-photo372/p1.jpg")+ self.assertEqual(doc["defaults"]["instruction"], "Text Recognition:")++ def test_chat_turns_carry_the_conversation_so_far_with_the_recorded_replies(self):+ doc = latency.chat_jobs(CHAT_SYSTEM_RAW, CHAT_RAW)+ self.assertEqual([job["id"] for job in doc["jobs"]], ["s1#1", "s1#2"])+ self.assertEqual(+ doc["jobs"][1]["messages"],+ [+ {"role": "system", "content": "Be helpful."},+ {"role": "user", "content": "hi"},+ {"role": "assistant", "content": "hello"},+ {"role": "user", "content": "help"},+ ],+ )+ self.assertEqual(doc["defaults"], {"max_new_tokens": 400, "temperature": 0.0})++ def test_strict_schemas_require_every_property_at_every_depth(self):+ schema = {+ "type": "object",+ "properties": {"a": {"type": "array", "items": {"type": "object", "properties": {"b": {}}}}},+ }+ strict = latency.strict_schema(schema)+ self.assertEqual(strict["required"], ["a"])+ self.assertIs(strict["additionalProperties"], False)+ self.assertEqual(strict["properties"]["a"]["items"]["required"], ["b"])++ def test_the_sob_draw_is_stratified_and_repeatable(self):+ records = [{"record_id": f"r{i}", "question_difficulty": i % 2, "schema_complexity": "low"} for i in range(10)]+ first = latency.sob_draw(records, 4, 7)+ self.assertEqual(first, latency.sob_draw(records, 4, 7))+ self.assertEqual(sorted(int(r[1:]) % 2 for r in first), [0, 0, 1, 1])+def test_matching_jobs_load_with_their_digest(self):doc, digest = latency.load_jobs(latency.PAGES["classify"], FakeFetch())self.assertEqual(len(doc["jobs"]), 3)@@ -152,6 +336,14 @@ class JobsTests(unittest.TestCase):with self.assertRaisesRegex(latency.InputMismatch, "0000"):latency.load_jobs(latency.PAGES["classify"], fetch)+ def test_a_page_without_a_published_hash_checks_the_hash_pinned_here(self):+ page = dataclasses.replace(latency.PAGES["search"], jobs_sha256="0" * 64)+ with self.assertRaisesRegex(latency.InputMismatch, "0000"):+ latency.load_jobs(page, FakeFetch())+ self.assertEqual(latency.jobs_hash_source(page), {"pinned": latency.jobs_hash_source(page)["pinned"]})+ self.assertIsInstance(latency.PAGES["redact"].jobs_sha256, str)+ self.assertIsInstance(latency.PAGES["typed-decisions"].jobs_sha256, str)+def test_inputs_come_from_their_pinned_revisions(self):fetch = FakeFetch()latency.load_jobs(latency.PAGES["search"], fetch)@@ -169,6 +361,72 @@ class JobsTests(unittest.TestCase):],)+ def test_every_page_pins_full_revisions(self):+ for page in latency.PAGES.values():+ refs = [*page.inputs, *([page.photos] if page.photos else [])]+ if isinstance(page.jobs_sha256, latency.Ref):+ refs.append(page.jobs_sha256)+ else:+ self.assertRegex(page.jobs_sha256, r"^[0-9a-f]{64}$")+ for ref in refs:+ self.assertRegex(ref.revision, r"^[0-9a-f]{40}$", page.name)+++class PublishedTests(unittest.TestCase):+ def test_study_pages_read_their_level_per_class(self):+ published = latency.PAGES["classify"].published(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.assertIn("transformers5 image sha256:", published["server"])++ def test_chat_shows_the_website_run_beside_the_earlier_run(self):+ published = latency.PAGES["chat"].published(FakeFetch())+ self.assertEqual(published["classes"]["h100"]["p50_ms"], 737.09)+ self.assertEqual(published["classes"]["h100-2026-10-11"]["note"], "2026-10-11")+ self.assertEqual(published["path"], latency.CHAT_SITE.path)+ self.assertEqual(published["best_class"], "h100")++ def test_rerank_reads_the_fast_arm_for_each_gpu(self):+ published = latency.PAGES["rerank"].published(FakeFetch())+ self.assertEqual(published["classes"]["h100"]["p50_ms"], 54.22)+ self.assertEqual(published["classes"]["l4"]["note"], "60 questions only")+ self.assertNotIn("note", published["classes"]["rtx"])+ self.assertIn("5bfa9ea4", published["server"])++ def test_request_routing_reads_the_median_of_the_three_runs(self):+ runs = {+ f"promoted-q1-r{i}": {"latency": {"n": 200, "p50_ms": p50, "p95_ms": p50 * 3, "mean_ms": p50 + 4}}+ for i, p50 in enumerate((8.57, 8.49, 8.46), start=1)+ }+ doc = {+ "runs": {**runs, "default-q1": {"latency": {"n": 200, "p50_ms": 24.0, "p95_ms": 30.0, "mean_ms": 24.0}}},+ "promoted_median_of_three_medians_ms": 8.49,+ "image_digest": "sha256:" + "c" * 64,+ "sie_rev": "530dcde89dd0a35500a2346308d30c8e708d7688",+ }+ published = latency.request_routing_published(lambda address, accept=None: json.dumps(doc).encode())+ self.assertEqual(published["classes"], {"h100": latency.row("H100", 200, 8.49, 25.47, 12.49)})++ def test_redact_and_typed_decisions_read_their_one_rtx_figure(self):+ redact = {+ "timing": {+ "sie+L39": {+ "latency": {"n": 660, "p50_ms": 60.65, "p95_ms": 76.37, "mean_ms": 62.71},+ "image_digest": "sha256:" + "d" * 64,+ "sie_rev": "2b3f7d2ed6d79d880c249d9ef9efb72ae3a36135",+ }+ }+ }+ published = latency.redact_published(lambda address, accept=None: json.dumps(redact).encode())+ self.assertEqual(published["classes"]["rtx"]["p50_ms"], 60.65)+ typed = {"tasks": {"comment-spam": {"model_ms": 13.76, "p95_ms": 15.42, "min_ms": 12.23, "max_ms": 15.25}}}+ published = latency.typed_decisions_published(lambda address, accept=None: json.dumps(typed).encode())+ self.assertEqual(+ published["classes"]["rtx"],+ latency.row("RTX PRO 6000", 200, 13.76, 15.42, None, "containers 12.23 to 15.25"),+ )+class StatisticsTests(unittest.TestCase):def test_percentiles_are_linear_interpolated(self):@@ -179,30 +437,57 @@ class StatisticsTests(unittest.TestCase):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))+ doc = latency.classify_jobs(ITEMS_RAW)+ warm = latency.warmup_jobs(latency.PAGES["classify"], doc, {})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")+ self.assertEqual(doc["jobs"][2]["text"], "third message")def test_search_warmups_are_tagged(self):- warm = latency.warmup_jobs(latency.search_jobs(QUESTIONS_RAW))+ warm = latency.warmup_jobs(latency.PAGES["search"], 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_generation_warmups_tag_the_first_user_message_with_the_level(self):+ doc = latency.chat_jobs(CHAT_SYSTEM_RAW, CHAT_RAW)+ warm = latency.warmup_jobs(latency.PAGES["chat"], doc, {})+ self.assertEqual(len(warm), 3)+ self.assertEqual(warm[0]["messages"][1]["content"], "[chat-c1-10000000] hi")+ self.assertEqual(doc["jobs"][1]["messages"][1]["content"], "hi")++ def test_score_warmups_are_exact_copies(self):+ doc = latency.rerank_jobs(CASES_RAW, RERANK_FROZEN_RAW)+ warm = latency.warmup_jobs(latency.PAGES["rerank"], doc, {})+ self.assertEqual(warm[:2], [doc["jobs"][1], doc["jobs"][0]])++ def test_image_warmups_change_one_pixel(self):+ with patch.object(latency, "OCR_MANIFEST_SHA256", hashlib.sha256(MANIFEST_RAW).hexdigest()):+ doc = latency.ocr_jobs(MANIFEST_RAW)+ photos = {"ocr-photo372/p1.jpg": PHOTOS["p1.jpg"], "ocr-photo372/p2.jpg": PHOTOS["p2.jpg"]}+ warm = latency.warmup_jobs(latency.PAGES["ocr"], doc, photos)+ self.assertEqual([job["id"] for job in warm], ["r2", "r1", "r2", "r1", "r2"])+ self.assertEqual(Image.open(io.BytesIO(warm[0]["image_bytes"])).size, (8, 8))++ def test_a_pixel_variant_changes_exactly_one_pixel(self):+ buffer = io.BytesIO()+ Image.new("RGB", (8, 8), (10, 20, 30)).save(buffer, "PNG")+ changed = Image.open(io.BytesIO(latency.pixel_variant(buffer.getvalue(), "png", 3)))+ different = [(x, y) for x in range(8) for y in range(8) if changed.getpixel((x, y)) != (10, 20, 30)]+ self.assertEqual(different, [((37 + 3) % 8, (53 + 9) % 8)])+ self.assertEqual(changed.getpixel(different[0]), (11, 21, 31))+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)++ def send_job(job, *, wait_for_capacity):+ return latency.send(client, doc, job, wait_for_capacity=wait_for_capacity)++ latency.wait_until_ready(send_job, 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))@@ -210,14 +495,86 @@ class WarmupTests(unittest.TestCase):def test_waiting_gives_up_at_the_deadline(self):client, clock = FakeClient(not_ready=10_000), Clock()doc = latency.classify_jobs(ITEMS_RAW)++ def send_job(job, *, wait_for_capacity):+ return latency.send(client, doc, job, wait_for_capacity=wait_for_capacity)+with self.assertRaises(SIEConnectionError):- latency.wait_until_ready(client, doc, doc["jobs"][0], monotonic=clock.monotonic, sleep=clock.sleep)+ latency.wait_until_ready(send_job, doc["jobs"][0], monotonic=clock.monotonic, sleep=clock.sleep)self.assertGreaterEqual(clock.now, latency.READY_TIMEOUT_S)+class SendTests(unittest.TestCase):+ def test_extract_sends_only_the_fields_the_job_sets(self):+ client = FakeClient()+ doc = latency.redact_jobs(*self.redact_inputs())+ latency.send(client, doc, doc["jobs"][0], wait_for_capacity=False)+ op, model, item, kwargs = client.calls[0]+ self.assertEqual((op, model, item), ("extract", "superlinked/pii-redact", {"id": "0", "text": "Call Ann"}))+ self.assertEqual(set(kwargs), {"labels", "wait_for_capacity", "provision_timeout_s", "max_oom_retries"})++ @staticmethod+ def redact_inputs():+ documents = b'{"index": 0, "text": "Call Ann", "domain": "x"}\n'+ frozen = {+ "documents": {"sha256": hashlib.sha256(documents).hexdigest()},+ "label_lists": {"L39": ["name"]},+ "sie": {"model": "superlinked/pii-redact"},+ }+ return documents, json.dumps(frozen).encode()++ def test_images_go_as_bytes_with_the_instruction_and_options(self):+ client = FakeClient()+ with patch.object(latency, "OCR_MANIFEST_SHA256", hashlib.sha256(MANIFEST_RAW).hexdigest()):+ doc = latency.ocr_jobs(MANIFEST_RAW)+ latency.send(+ client, doc, doc["jobs"][0], wait_for_capacity=False, photos={"ocr-photo372/p1.jpg": PHOTOS["p1.jpg"]}+ )+ _, model, item, kwargs = client.calls[0]+ self.assertEqual(model, "zai-org/GLM-OCR")+ self.assertEqual(item, {"id": "r1", "images": [{"data": PHOTOS["p1.jpg"], "format": "jpeg"}]})+ self.assertEqual(kwargs["instruction"], "Text Recognition:")+ self.assertEqual(kwargs["options"], {"max_new_tokens": 8192, "num_beams": 1})++ def test_score_calls_name_the_served_profile(self):+ client = FakeClient()+ doc = latency.rerank_jobs(CASES_RAW, RERANK_FROZEN_RAW)+ latency.send(client, doc, doc["jobs"][0], wait_for_capacity=False, model=latency.FAST)+ op, model, (query, items), kwargs = client.calls[0]+ self.assertEqual((op, model), ("score", "Qwen/Qwen3-Reranker-4B:fast"))+ self.assertEqual(query, {"text": "first query"})+ self.assertEqual(items, [{"text": "d1"}, {"text": "d2"}])+ self.assertEqual(kwargs["instruction"], "Judge it.")++ def test_structured_output_asks_for_a_strict_json_schema(self):+ client = FakeClient()+ doc = {+ "model": "m",+ "op": "generate",+ "defaults": {"max_new_tokens": 2048, "temperature": 0.0},+ "jobs": [],+ }+ job = {+ "id": "j",+ "messages": [{"role": "user", "content": "x"}],+ "grammar": {"kind": "json_schema", "value": {"type": "object"}, "label": "answer", "strict": True},+ }+ latency.send(client, doc, job, wait_for_capacity=False)+ _, _, messages, kwargs = client.calls[0]+ self.assertEqual(messages, job["messages"])+ self.assertEqual(+ kwargs["response_format"],+ {"type": "json_schema", "json_schema": {"name": "answer", "schema": {"type": "object"}, "strict": True}},+ )+ self.assertEqual((kwargs["max_tokens"], kwargs["temperature"]), (2048, 0.0))++class RunTests(unittest.TestCase):def run_page(self, page: str, client: FakeClient, fetch: FakeFetch | None = None):- with tempfile.TemporaryDirectory() as tmp:+ with (+ tempfile.TemporaryDirectory() as tmp,+ patch.object(latency, "OCR_MANIFEST_SHA256", hashlib.sha256(MANIFEST_RAW).hexdigest()),+ ):record, path = latency.run_latency(page,client,@@ -258,6 +615,7 @@ class RunTests(unittest.TestCase):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["inputs"]["jobs_sha256_source"]["key"], "classify.json")self.assertEqual(record["published"]["classes"]["h100"]["p50_ms"], 18.6)def test_search_sends_one_query_encode_per_question(self):@@ -271,6 +629,40 @@ class RunTests(unittest.TestCase):self.assertIs(kwargs["is_query"], True)self.assertNotIn("instruction", kwargs)+ def test_rerank_calls_the_fast_profile_once_per_question(self):+ client = FakeClient()+ record = self.run_page("rerank", client)+ self.assertEqual(len(client.calls), 5 + 2)+ self.assertTrue(all(call[1] == latency.FAST for call in client.calls))+ self.assertEqual(record["model"], latency.FAST)+ self.assertIn(latency.FRESH_SERVERS, record["differences"])++ def test_ocr_downloads_each_photo_and_sends_it(self):+ client, fetch = FakeClient(), FakeFetch()+ record = self.run_page("ocr", client, fetch)+ self.assertEqual([call[2]["images"][0]["data"] for call in client.calls[5:]], list(PHOTOS.values()))+ self.assertEqual(record["inputs"]["photos"]["revision"], latency.PAGES["ocr"].photos.revision)+ self.assertTrue(any(address.endswith("images/input/p1.jpg") for address in fetch.urls))++ def test_chat_times_one_completion_per_turn(self):+ client = FakeClient()+ record = self.run_page("chat", client)+ self.assertEqual([call[0] for call in client.calls], ["chat"] * 5)+ self.assertEqual(client.calls[3][2][-1], {"role": "user", "content": "hi"})+ self.assertNotIn("response_format", client.calls[3][3])+ lines = latency.format_report(record)+ self.assertRegex(lines[3], r"^published H100\s+330\s+737\.09")+ self.assertTrue(any(line.startswith("published H100 (2026-10-11)") for line in lines[4:6]))+ self.assertTrue(any(line.startswith("published RTX PRO 6000 (2026-10-11)") for line in lines[4:6]))++ def test_only_the_first_jobs_are_timed_when_the_page_says_so(self):+ client = FakeClient()+ page = dataclasses.replace(latency.PAGES["classify"], timed=2, warmups=1)+ with patch.dict(latency.PAGES, {"classify": page}):+ record = self.run_page("classify", client)+ self.assertEqual([call[2]["id"] for call in client.calls], ["b-3", "a-1", "a-2"])+ self.assertEqual(record["inputs"]["jobs"], 2)+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)@@ -287,12 +679,19 @@ class RunTests(unittest.TestCase):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)+ self.assertIn(f"the website shows {latency.PAGES['classify'].website}", lines)+ self.assertIn("published figure: the p50 of one run per GPU, level c1", 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])+ self.assertIn("server package from 2b3f7d2e", differs[1])++ def test_a_published_row_without_a_mean_prints_a_dash(self):+ record = self.run_page("classify", FakeClient())+ record["published"]["classes"] = {"rtx": latency.row("RTX PRO 6000", 200, 13.76, 15.42, None, "note")}+ lines = latency.format_report(record)+ self.assertRegex(lines[3], r"^published RTX PRO 6000 \(note\)\s+200\s+13\.76\s+15\.42\s+-$")class CommandTests(unittest.TestCase):@@ -319,9 +718,12 @@ class CommandTests(unittest.TestCase):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):+ def test_every_page_is_accepted_and_no_other(self):+ parser = run.build_parser()+ for name in latency.PAGES:+ self.assertEqual(parser.parse_args(["latency", "--page", name, "--endpoint", "http://x"]).page, name)with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):- run.build_parser().parse_args(["latency", "--page", "rerank", "--endpoint", "http://localhost:8080"])+ parser.parse_args(["latency", "--page", "detect", "--endpoint", "http://localhost:8080"])def test_a_run_prints_the_result_path_and_the_table(self):argv = ["latency", "--page", "classify", "--endpoint", "http://LOCALHOST:8080/"]@@ -357,6 +759,11 @@ class CommandTests(unittest.TestCase):self.assertEqual(code, 1)self.assertIn("failed: 3 of 3", out)+ def test_the_command_downloads_files_larger_than_the_lookup_limit(self):+ with patch.object(run, "http_fetch", return_value=b"x") as fetch:+ run.latency_fetch("https://example.test/a")+ fetch.assert_called_once_with("https://example.test/a", None, max_bytes=latency.MAX_DOWNLOAD_BYTES)+if __name__ == "__main__":unittest.main()