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 the /detect page one request at a time (#937)

Shai Shmuel58748cdfb349
diff --git a/examples/evaluations/published-benchmarks/README.md b/examples/evaluations/published-benchmarks/README.md
index e07e7b2dd..bbf020cf1 100644
--- a/examples/evaluations/published-benchmarks/README.md
+++ b/examples/evaluations/published-benchmarks/README.md
@@ -632,7 +632,7 @@ Hugging Face dataset
[`superlinked/sie-task-evidence`](https://huggingface.co/datasets/superlinked/sie-task-evidence).
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:
+server for eleven pages:
| `--page` | On the website | Model | Bundle | GPU it was timed on | Inputs | One request |
| --- | --- | --- | --- | --- | --- | --- |
@@ -644,6 +644,7 @@ server for ten pages:
| `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:` |
+| `detect` | `/detect`: 82.2 ms | `facebook/sam3` | `transformers5` | RTX PRO 6000 | 300 drone and aerial photos (379 MB) | `extract` with the photo and its dataset's labels, no options |
| `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 |
@@ -669,7 +670,10 @@ in `SIE_PRELOAD_MODELS`. The images are
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, and their CUDA 13 image needs an NVIDIA driver from the 580 series
-or newer.
+or newer. `facebook/sam3`, the `detect` model, is gated on Hugging Face: accept
+its terms on the model page, set `HF_TOKEN` to your token in your shell's
+environment, and add `-e HF_TOKEN` to `docker run`, which passes it on without
+writing the token in the command.
`--endpoint` is required. The key rule is the one in
[Run it against your own server](#run-it-against-your-own-server): a server
@@ -682,11 +686,12 @@ The run:
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;
+ its 372 photos. `detect` downloads its 300 photos and checks each one
+ against the SHA-256 the study recorded for it;
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,
+ `redact`, 5 for `typed-decisions`, `rerank`, `request-routing`, `ocr` and
+ `detect`, 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;
@@ -722,8 +727,9 @@ 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.
-`/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.
+The `detect` photos come from four datasets under CC BY 4.0. Their creators,
+sources and the one change made (GeoTIFF tiles saved as PNG) are in
+`detect-photo300/2026-11-10/README.md` in the dataset.
## Validation
diff --git a/examples/evaluations/published-benchmarks/latency.py b/examples/evaluations/published-benchmarks/latency.py
index f683e64cf..831f32e50 100644
--- a/examples/evaluations/published-benchmarks/latency.py
+++ b/examples/evaluations/published-benchmarks/latency.py
@@ -13,6 +13,7 @@ from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
+from urllib.parse import quote
from sie_sdk import ModelLoadingError, ProvisioningError, SIEConnectionError
@@ -59,7 +60,7 @@ class Page:
``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.
+ is the folder that holds the images the jobs name, and ``photo_name`` the file name there of a job's image.
"""
name: str
@@ -74,6 +75,7 @@ class Page:
timed: int | None = None
model: str | None = None
photos: Ref | None = None
+ photo_name: Callable[[str], str] = lambda image: Path(image).name
differences: tuple[str, ...] = ()
@@ -294,6 +296,57 @@ def ocr_jobs(manifest_raw: bytes) -> dict[str, Any]:
}
+DETECT_REVISION = "7e5ba8a5cc0e49f7a9cdd5d61ebb31eb7a79617b"
+
+
+def detect_jobs(subset_raw: bytes, listing_raw: bytes, manifest_raw: bytes) -> dict[str, Any]:
+ """The study's ``detect.json``: one job per D1 photo, in the subset's order, with its dataset's labels.
+
+ Each job names its photo as ``detect/images/<dataset>/<file>`` and records the photo's size and SHA-256
+ from the image listing, as the study's builder wrote them.
+ """
+ listing = {(r["dataset"], r["image_id"]): r for r in json.loads(listing_raw)}
+ labels = {(r["dataset"], r["image_id"]): r["labels"] for r in json.loads(manifest_raw)["rows"]}
+ source = {
+ "subset": f"detect-current-arms-2026-10-11/prereg/d1-subset.json @{DETECT_REVISION[:8]}",
+ "subset_sha256": sha256(subset_raw),
+ "photos": "the D1 study photos staged from the pinned Zenodo archives; every byte matches the study's image listing",
+ "request": "one photo per extract call with that dataset's labels, no options (shipped threshold)",
+ }
+ jobs = []
+ for photo in json.loads(subset_raw)["photos"]:
+ key = (photo["dataset"], photo["image_id"])
+ r = listing[key]
+ meta = {
+ "dataset": r["dataset"],
+ "bucket": photo["bucket"],
+ "hero": photo["hero"],
+ "pixels": r["size"][0] * r["size"][1],
+ "sha256": r["sha256"],
+ }
+ jobs.append(
+ {
+ "id": f"{r['dataset']}/{r['image_id']}",
+ "image": f"detect/{r['path']}",
+ "labels": list(labels[key]),
+ "meta": meta,
+ }
+ )
+ return {
+ "page": "detect",
+ "model": "facebook/sam3",
+ "profile": "default",
+ "op": "extract",
+ "source": source,
+ "jobs": jobs,
+ }
+
+
+def detect_photo_name(image: str) -> str:
+ """``detect/images/<dataset>/<file>`` is stored as ``<dataset>__<file>``."""
+ return "__".join(Path(image).parts[-2:])
+
+
def chat_jobs(system_raw: bytes, transcripts_raw: bytes) -> dict[str, Any]:
system = system_raw.decode("utf-8")
jobs = []
@@ -444,7 +497,7 @@ def structured_output_jobs(sample_raw: bytes, parquet_raw: bytes) -> dict[str, A
def dataset_url(revision: str, path: str, dataset: str = DATASET) -> str:
- return f"{RESOLVE_URL.format(dataset=dataset)}/{revision}/{path}"
+ return f"{RESOLVE_URL.format(dataset=dataset)}/{revision}/{quote(path)}"
def fetch_ref(ref: Ref, fetch: Fetch) -> bytes:
@@ -773,6 +826,22 @@ PAGES = {
warmups=5,
photos=Ref("d03e04fd2f7f768afcc753b952fb9c9abc47748b", "ocr-photo372-prereg/2026-10-11/images/input"),
),
+ Page(
+ "detect",
+ (
+ Ref(DETECT_REVISION, "detect-current-arms-2026-10-11/prereg/d1-subset.json"),
+ Ref(DETECT_REVISION, "detect-dense-results/2026-10-08/inputs/image-listing.json"),
+ Ref(DETECT_REVISION, "detect-current-arms-2026-10-11/prereg/items-manifest.json"),
+ ),
+ detect_jobs,
+ study_hash(),
+ "detect.json",
+ study_published("detect"),
+ "82.2 ms on /detect: the RTX PRO 6000 p50, rounded",
+ warmups=5,
+ photos=Ref("dfbd42d1e2ff4ef6baf8435c9c0af79f2cda6bfb", "detect-photo300/2026-11-10/images"),
+ photo_name=detect_photo_name,
+ ),
Page(
"chat",
(
@@ -840,13 +909,18 @@ def load_jobs(page: Page, fetch: Fetch) -> tuple[dict[str, Any], str]:
def load_photos(page: Page, doc: Mapping[str, Any], fetch: Fetch) -> dict[str, bytes]:
+ """Each photo the jobs name; one whose job records a SHA-256 must have it."""
if page.photos is None:
return {}
folder = page.photos
- return {
- job["image"]: fetch_ref(Ref(folder.revision, f"{folder.path}/{Path(job['image']).name}", folder.dataset), fetch)
- for job in doc["jobs"]
- }
+ photos = {}
+ for job in doc["jobs"]:
+ data = fetch_ref(Ref(folder.revision, f"{folder.path}/{page.photo_name(job['image'])}", folder.dataset), fetch)
+ expected = (job.get("meta") or {}).get("sha256")
+ if expected and sha256(data) != expected:
+ raise InputMismatch(f"the photo for {job['id']} has sha256 {sha256(data)}, the study's {expected}")
+ photos[job["image"]] = data
+ return photos
def percentile(values: Sequence[float], q: float) -> float:
@@ -889,6 +963,11 @@ def pixel_variant(data: bytes, fmt: str, k: int) -> bytes:
return buffer.getvalue()
+def image_format(spec: Mapping[str, Any]) -> str:
+ """The job's format, else PNG for a ``.png`` file and JPEG otherwise, as the study's client chose."""
+ return spec.get("image_format") or ("png" if spec["image"].lower().endswith(".png") else "jpeg")
+
+
def warm_variant(doc: Mapping[str, Any]) -> str:
return doc.get("warm_variant") or ("tagged" if doc["op"] == "generate" else "exact")
@@ -903,7 +982,7 @@ def warmup_jobs(page: Page, doc: Mapping[str, Any], photos: Mapping[str, bytes])
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)
+ job["image_bytes"] = pixel_variant(photos[job["image"]], image_format(job), k)
elif variant == "tagged":
if "messages" in job:
user = next(m for m in job["messages"] if m["role"] == "user")
@@ -951,7 +1030,7 @@ def send(
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")}]}
+ item = {"id": spec["id"], "images": [{"data": data, "format": image_format(spec)}]}
else:
item = {"id": spec["id"], "text": spec["text"]}
if op == "extract":
diff --git a/examples/evaluations/published-benchmarks/tests/test_latency.py b/examples/evaluations/published-benchmarks/tests/test_latency.py
index 1421eb055..ce7af32ea 100644
--- a/examples/evaluations/published-benchmarks/tests/test_latency.py
+++ b/examples/evaluations/published-benchmarks/tests/test_latency.py
@@ -73,6 +73,43 @@ MANIFEST_RAW = json.dumps(
).encode()
+def png(color: int) -> bytes:
+ buffer = io.BytesIO()
+ Image.new("RGB", (8, 8), (color, 0, 0)).save(buffer, "PNG")
+ return buffer.getvalue()
+
+
+DETECT_PHOTOS = {"images/amvd/a.jpg": jpeg(30), "images/neon/t.png": png(60)}
+DETECT_SUBSET_RAW = json.dumps(
+ {
+ "photos": [
+ {"dataset": "amvd", "image_id": "a", "bucket": "b1", "hero": True},
+ {"dataset": "neon", "image_id": "t", "bucket": "b2", "hero": False},
+ ]
+ }
+).encode()
+DETECT_LISTING_RAW = json.dumps(
+ [
+ {
+ "dataset": ds,
+ "image_id": iid,
+ "path": path,
+ "sha256": hashlib.sha256(DETECT_PHOTOS[path]).hexdigest(),
+ "size": [8, 8],
+ }
+ for ds, iid, path in (("amvd", "a", "images/amvd/a.jpg"), ("neon", "t", "images/neon/t.png"))
+ ]
+).encode()
+DETECT_MANIFEST_RAW = json.dumps(
+ {
+ "rows": [
+ {"dataset": "amvd", "image_id": "a", "labels": ["car"]},
+ {"dataset": "neon", "image_id": "t", "labels": ["tree"]},
+ ]
+ }
+).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)):
@@ -101,6 +138,7 @@ INPUTS = {
"rerank": (CASES_RAW, RERANK_FROZEN_RAW),
"chat": (CHAT_SYSTEM_RAW, CHAT_RAW),
"ocr": (MANIFEST_RAW,),
+ "detect": (DETECT_SUBSET_RAW, DETECT_LISTING_RAW, DETECT_MANIFEST_RAW),
}
@@ -108,6 +146,7 @@ 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):
+ """Serve every tested page's inputs, the jobs hashes their builds give, results and photos."""
self.files: dict[str, bytes] = {}
sha = {}
with patch.object(latency, "OCR_MANIFEST_SHA256", hashlib.sha256(MANIFEST_RAW).hexdigest()):
@@ -119,7 +158,7 @@ class FakeFetch:
self.files[url(latency.Ref(latency.STUDY_REVISION, latency.JOBS_SHA256))] = json.dumps(
jobs_sha256 or sha
).encode()
- for name in ("classify", "search", "ocr"):
+ for name in ("classify", "search", "ocr", "detect"):
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")
@@ -137,6 +176,10 @@ class FakeFetch:
photos = latency.PAGES["ocr"].photos
for name, data in PHOTOS.items():
self.files[url(latency.Ref(photos.revision, f"{photos.path}/{name}"))] = data
+ detect = latency.PAGES["detect"]
+ for path, data in DETECT_PHOTOS.items():
+ name = detect.photo_name(f"detect/{path}")
+ self.files[url(latency.Ref(detect.photos.revision, f"{detect.photos.path}/{name}"))] = data
self.missing = missing
self.urls: list[str] = []
@@ -296,6 +339,33 @@ class JobsTests(unittest.TestCase):
self.assertEqual(doc["jobs"][0]["image"], "ocr-photo372/p1.jpg")
self.assertEqual(doc["defaults"]["instruction"], "Text Recognition:")
+ def test_detect_jobs_name_each_photo_with_its_labels_and_hash(self):
+ """A job carries the photo's path, its dataset's labels and the listing's SHA-256."""
+ doc = latency.detect_jobs(DETECT_SUBSET_RAW, DETECT_LISTING_RAW, DETECT_MANIFEST_RAW)
+ self.assertEqual((doc["model"], doc["op"]), ("facebook/sam3", "extract"))
+ self.assertNotIn("defaults", doc)
+ self.assertEqual(doc["source"]["subset_sha256"], hashlib.sha256(DETECT_SUBSET_RAW).hexdigest())
+ first = doc["jobs"][0]
+ self.assertEqual(
+ (first["id"], first["image"], first["labels"]), ("amvd/a", "detect/images/amvd/a.jpg", ["car"])
+ )
+ self.assertEqual(first["meta"]["sha256"], hashlib.sha256(DETECT_PHOTOS["images/amvd/a.jpg"]).hexdigest())
+ self.assertEqual((first["meta"]["pixels"], first["meta"]["hero"]), (64, True))
+
+ def test_detect_photos_are_stored_under_dataset_and_file_name(self):
+ """A job's image path maps to the ``<dataset>__<file>`` name in the photo folder."""
+ self.assertEqual(latency.detect_photo_name("detect/images/amvd/DJI-1.jpg.jpg"), "amvd__DJI-1.jpg.jpg")
+
+ def test_a_photo_with_another_hash_stops_the_run(self):
+ """A downloaded photo whose bytes differ from the recorded SHA-256 raises InputMismatch."""
+ fetch = FakeFetch()
+ page = latency.PAGES["detect"]
+ doc = latency.detect_jobs(DETECT_SUBSET_RAW, DETECT_LISTING_RAW, DETECT_MANIFEST_RAW)
+ address = url(latency.Ref(page.photos.revision, f"{page.photos.path}/amvd__a.jpg"))
+ fetch.files[address] = jpeg(31)
+ with self.assertRaises(latency.InputMismatch):
+ latency.load_photos(page, doc, fetch)
+
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"])
@@ -361,6 +431,11 @@ class JobsTests(unittest.TestCase):
],
)
+ def test_a_file_name_with_spaces_or_brackets_is_escaped(self):
+ """Spaces and brackets in a dataset path are percent-encoded in the URL."""
+ address = latency.dataset_url("a" * 40, "x/amvd__DJI 1 (7_42).jpg")
+ self.assertTrue(address.endswith("/x/amvd__DJI%201%20%287_42%29.jpg"))
+
def test_every_page_pins_full_revisions(self):
for page in latency.PAGES.values():
refs = [*page.inputs, *([page.photos] if page.photos else [])]
@@ -644,6 +719,20 @@ class RunTests(unittest.TestCase):
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_detect_sends_each_photo_in_its_format_with_its_labels(self):
+ """Each timed request sends the photo bytes, PNG or JPEG by extension, with that photo's labels."""
+ client, fetch = FakeClient(), FakeFetch()
+ record = self.run_page("detect", client, fetch)
+ timed = client.calls[5:]
+ self.assertEqual([call[2]["images"][0]["data"] for call in timed], list(DETECT_PHOTOS.values()))
+ self.assertEqual([call[2]["images"][0]["format"] for call in timed], ["jpeg", "png"])
+ self.assertEqual([call[3]["labels"] for call in timed], [["car"], ["tree"]])
+ self.assertNotIn("options", timed[0][3])
+ self.assertEqual(client.calls[0][2]["images"][0]["format"], "png")
+ self.assertNotEqual(client.calls[0][2]["images"][0]["data"], DETECT_PHOTOS["images/neon/t.png"])
+ self.assertEqual(record["inputs"]["photos"]["revision"], latency.PAGES["detect"].photos.revision)
+ self.assertTrue(any(address.endswith("images/neon__t.png") for address in fetch.urls))
+
def test_chat_times_one_completion_per_turn(self):
client = FakeClient()
record = self.run_page("chat", client)
@@ -723,7 +812,7 @@ class CommandTests(unittest.TestCase):
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):
- parser.parse_args(["latency", "--page", "detect", "--endpoint", "http://localhost:8080"])
+ parser.parse_args(["latency", "--page", "speech-to-text", "--endpoint", "http://localhost:8080"])
def test_a_run_prints_the_result_path_and_the_table(self):
argv = ["latency", "--page", "classify", "--endpoint", "http://LOCALHOST:8080/"]