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): replay document-field extraction evidence (#511)

svonava971f2d4f5568
diff --git a/examples/doc-field-extraction-omni/.gitignore b/examples/doc-field-extraction-omni/.gitignore
new file mode 100644
index 000000000..80cbdd6bb
--- /dev/null
+++ b/examples/doc-field-extraction-omni/.gitignore
@@ -0,0 +1,3 @@
+data/
+__pycache__/
+.venv/
diff --git a/examples/doc-field-extraction-omni/README.md b/examples/doc-field-extraction-omni/README.md
new file mode 100644
index 000000000..85cad0dab
--- /dev/null
+++ b/examples/doc-field-extraction-omni/README.md
@@ -0,0 +1,87 @@
+# Read documents into your own schema
+
+Replay the recorded extraction comparison on 700 Omni business documents and
+100 CORD receipts without an API key, installed dependencies, or model calls:
+
+```bash
+python3 fetch.py
+python3 score.py
+```
+
+The fetch pins an immutable public [evidence packet](https://huggingface.co/datasets/superlinked/sie-task-evidence/tree/61e751a5f7f374cacd84ccace621f71e8a498404/doc-field-extraction-omni/2026-10-01)
+and verifies its manifest, every file hash, and every file size. The replay
+requires all 800 inputs for each of the five models and checks the full and
+fresh scopes against the recorded aggregates. The fresh scope excludes the
+30 pilot documents: 676 business documents and 94 receipts.
+
+On the October 1, 2026 recording, SIE Qwen3.8 27B FP8 improved mean business
+document JSON accuracy over Haiku 4.5: 75.26% versus 65.71% across 700 documents;
+75.05% versus 65.78% on the fresh 676. The registered paired superiority gate
+passes on both scopes. Sonnet 5.5, GPT-6 Luna and GPT-6 Sol scored higher on the
+business documents; the packet retains all of their results. Luna also had a
+lower token-list cost.
+
+`counts.jsonl` contains the 4,000 selected-form score, count, token and response
+hash records. `summary.json` retains the aggregate scores for both Claude
+schema forms, the recorded 10,000-sample bootstrap and eligibility decisions.
+Unparsed and capped replies remain in the denominators. This replay verifies
+saved counts; raw model replies are not included, so it does not independently
+regrade them or rerun the bootstrap. Omni's mean JSON-diff accuracy and CORD's
+mean normalized field accuracy are separate metrics, not whole-document success.
+
+The historical preregistered SIE $0.72/$0.72 token pair and current default
+Cloud rate projection are separately identified in the packet. The measured
+self-hosted profile differs from that default SKU; neither projection is its
+billed Cloud cost or a GPU ownership estimate.
+
+## Try your own document
+
+The exact measured profile is
+`Qwen/Qwen3.8-27B-FP8:h100-256k-batch-no-spec`, on an H100, with public server
+source [`6cccc04de9c6b78d3217854ad2377de36c0ffbd2`](https://github.com/superlinked/sie/tree/6cccc04de9c6b78d3217854ad2377de36c0ffbd2).
+In a checkout of that source with the GPU dependencies configured, start it:
+
+```bash
+mise run serve -- -p 8080 -d cuda:0 \
+ -m 'Qwen/Qwen3.8-27B-FP8:h100-256k-batch-no-spec' \
+ --preload 'Qwen/Qwen3.8-27B-FP8:h100-256k-batch-no-spec'
+```
+
+Write a schema for your own PNG or JPEG, for example:
+
+```json
+{
+ "type": "object",
+ "properties": {
+ "document_number": {"type": "string"},
+ "total": {"type": "number"}
+ }
+}
+```
+
+Inspect the request offline, then send one call to that running server using
+the public `sie_sdk.SIEClient`:
+
+```bash
+python3 run.py --image form.png --schema fields.json --show
+uv run --no-project --with 'sie-sdk>=0.7.3,<0.8' python run.py \
+ --image form.png --schema fields.json --endpoint http://127.0.0.1:8080
+```
+
+The trial uses the study's common strict-schema conversion: every property is
+required, leaf values may be null, and unsupported source-schema constraints
+are omitted. Referenced property schemas must be inlined; `$ref` is rejected.
+String enums retain their non-null choices while the nullable branch allows null.
+It sends temperature 0, presence penalty 0, a 4,096-token cap,
+one image and the exact profile. A new document call is a trial, not a replay
+of the frozen benchmark. The endpoint may be a remote self-hosted server;
+`SIE_API_KEY` supplies its credential when required.
+
+## Source licenses
+
+[OmniAI OCR Benchmark](https://huggingface.co/datasets/getomni-ai/ocr-benchmark)
+is MIT licensed at revision `4ed0d95271ca00107726230f7a0944ed9e90d897`.
+[CORD](https://huggingface.co/datasets/naver-clova-ix/cord-v2), by NAVER Clova,
+is [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).
+The original CORD repository revision was not recorded; the packet preserves
+each frozen image hash. The count packet includes no source images or raw replies.
diff --git a/examples/doc-field-extraction-omni/fetch.py b/examples/doc-field-extraction-omni/fetch.py
new file mode 100644
index 000000000..f382b808a
--- /dev/null
+++ b/examples/doc-field-extraction-omni/fetch.py
@@ -0,0 +1,78 @@
+"""Fetch the immutable, public document-field count evidence; no credentials."""
+# ruff: noqa: INP001 - Standalone example scripts are not a Python package.
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import tempfile
+import urllib.request
+from pathlib import Path
+
+REVISION = "61e751a5f7f374cacd84ccace621f71e8a498404"
+PREFIX = "doc-field-extraction-omni/2026-10-01"
+BASE = f"https://huggingface.co/datasets/superlinked/sie-task-evidence/resolve/{REVISION}/{PREFIX}"
+MANIFEST_SHA256 = "bc4dbde435a57bb243e664ab15fd626e17a7179a177bdb448221bef257c96f95"
+FILES = frozenset({"README.md", "summary.json", "counts.jsonl", "inputs.jsonl"})
+HERE = Path(__file__).resolve().parent
+
+
+def read_public_file(name: str, max_bytes: int) -> bytes:
+ """Read a size-bounded file from the pinned public HTTPS location."""
+ with urllib.request.urlopen(f"{BASE}/{name}", timeout=60) as response: # noqa: S310 - Pinned HTTPS origin.
+ data = response.read(max_bytes + 1)
+ if len(data) > max_bytes:
+ raise ValueError(f"Evidence exceeds its declared size: {name}")
+ return data
+
+
+def load_manifest(data: bytes) -> dict:
+ """Authenticate the immutable manifest before accepting its flat file list."""
+ if hashlib.sha256(data).hexdigest() != MANIFEST_SHA256:
+ raise ValueError("Evidence manifest hash mismatch")
+ manifest = json.loads(data)
+ if set(manifest["files"]) != FILES:
+ raise ValueError("Evidence manifest has an unexpected file set")
+ return manifest
+
+
+def verify_file(name: str, data: bytes, expected: dict) -> None:
+ """Require the declared byte size and SHA-256 for an allowed file."""
+ if name not in FILES:
+ raise ValueError(f"Unexpected evidence file: {name}")
+ if len(data) != expected["bytes"]:
+ raise ValueError(f"Evidence size mismatch: {name}")
+ if hashlib.sha256(data).hexdigest() != expected["sha256"]:
+ raise ValueError(f"Evidence hash mismatch: {name}")
+
+
+def fetch(output: Path) -> None:
+ """Download and verify the whole packet before replacing local files."""
+ manifest_bytes = read_public_file("manifest.json", 64 * 1024)
+ manifest = load_manifest(manifest_bytes)
+ output.parent.mkdir(parents=True, exist_ok=True)
+ # Verify the entire download before replacing any existing local evidence.
+ with tempfile.TemporaryDirectory(prefix="dfe-evidence-", dir=output.parent) as temporary:
+ staging = Path(temporary)
+ for name, expected in manifest["files"].items():
+ data = read_public_file(name, expected["bytes"])
+ verify_file(name, data, expected)
+ (staging / name).write_bytes(data)
+ (staging / "manifest.json").write_bytes(manifest_bytes)
+ output.mkdir(parents=True, exist_ok=True)
+ for name in sorted(FILES | {"manifest.json"}):
+ (staging / name).replace(output / name)
+ print(json.dumps({"revision": REVISION, "files": len(FILES) + 1, "verified": True}))
+
+
+def main() -> None:
+ """Fetch the pinned packet into the requested local directory."""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--output", type=Path, default=HERE / "data")
+ args = parser.parse_args()
+ fetch(args.output)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/doc-field-extraction-omni/run.py b/examples/doc-field-extraction-omni/run.py
new file mode 100644
index 000000000..93be19d3c
--- /dev/null
+++ b/examples/doc-field-extraction-omni/run.py
@@ -0,0 +1,111 @@
+"""Read one document with the exact measured SIE profile, or show the request offline."""
+# ruff: noqa: INP001 - Standalone example scripts are not a Python package.
+
+from __future__ import annotations
+
+import argparse
+import base64
+import hashlib
+import json
+import os
+from pathlib import Path
+from typing import Any
+
+MODEL = "Qwen/Qwen3.8-27B-FP8:h100-256k-batch-no-spec"
+SYSTEM = (
+ "Extract data from the document image into the JSON schema. Copy values as they appear on the document. "
+ "Use null for a field the document does not contain. Return only the JSON."
+)
+
+
+def strict_schema(schema: dict[str, Any]) -> dict[str, Any]:
+ """The study's shared schema conversion: required keys, nullable leaves."""
+ if "$ref" in schema:
+ raise ValueError("Schema references are unsupported; inline the referenced property schema")
+ kind = schema.get("type")
+ if kind == "enum" or (kind is None and "enum" in schema):
+ kind = "string"
+ if isinstance(kind, list):
+ kind = next((value for value in kind if value != "null"), "string")
+ output: dict[str, Any] = {}
+ if schema.get("description"):
+ output["description"] = schema["description"]
+ if kind == "object":
+ properties = {name: strict_schema(value) for name, value in (schema.get("properties") or {}).items()}
+ return output | {
+ "type": "object",
+ "properties": properties,
+ "required": list(properties),
+ "additionalProperties": False,
+ }
+ if kind == "array":
+ items = schema.get("items") if isinstance(schema.get("items"), dict) else {"type": "string"}
+ output |= {"type": "array", "items": strict_schema(items)}
+ return {"anyOf": [output, {"type": "null"}]}
+ output["type"] = kind or "string"
+ enum = schema.get("enum") or schema.get("emum")
+ if enum:
+ choices = [value for value in enum if value is not None]
+ if not choices:
+ raise ValueError("A string enum needs at least one non-null choice")
+ if all(isinstance(value, str) for value in choices):
+ output["enum"] = choices
+ return {"anyOf": [output, {"type": "null"}]}
+
+
+def media_type(data: bytes) -> str:
+ """Identify the supported image format from its signature."""
+ if data.startswith(b"\x89PNG\r\n\x1a\n"):
+ return "image/png"
+ if data.startswith(b"\xff\xd8\xff"):
+ return "image/jpeg"
+ raise ValueError("Use a PNG or JPEG document image")
+
+
+def build_body(image: bytes, schema: dict[str, Any], *, show: bool = False) -> dict[str, Any]:
+ """Build the study's one-image request, optionally replacing bytes with their hash."""
+ if schema.get("type") != "object":
+ raise ValueError("The document schema must have an object root")
+ mime = media_type(image)
+ encoded = f"<image sha256:{hashlib.sha256(image).hexdigest()}>" if show else base64.b64encode(image).decode()
+ return {
+ "messages": [
+ {"role": "system", "content": SYSTEM},
+ {"role": "user", "content": [{"type": "image_url", "image_url": {"url": f"data:{mime};base64,{encoded}"}}]},
+ ],
+ "temperature": 0,
+ "presence_penalty": 0,
+ "max_completion_tokens": 4096,
+ "response_format": {
+ "type": "json_schema",
+ "json_schema": {"name": "fields", "schema": strict_schema(schema), "strict": True},
+ },
+ }
+
+
+def main() -> None:
+ """Inspect a request offline or send one optional document trial."""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--image", type=Path, required=True)
+ parser.add_argument("--schema", type=Path, required=True)
+ parser.add_argument("--endpoint", default="http://127.0.0.1:8080")
+ parser.add_argument(
+ "--show", action="store_true", help="Print the request with image bytes replaced by a hash; no SDK or network"
+ )
+ args = parser.parse_args()
+ body = build_body(args.image.read_bytes(), json.loads(args.schema.read_text(encoding="utf-8")), show=args.show)
+ if args.show:
+ print(json.dumps({"model": MODEL, **body}, indent=2))
+ return
+ from sie_sdk import SIEClient # noqa: PLC0415 - Optional dependency; offline modes need only the standard library.
+
+ with SIEClient(args.endpoint, api_key=os.environ.get("SIE_API_KEY"), read_timeout_s=300) as client:
+ result = client.chat_completions(MODEL, **body, max_oom_retries=0, wait_for_capacity=False)
+ choice = result["choices"][0]
+ if choice.get("finish_reason") in {"length", "max_tokens"}:
+ raise SystemExit("The output limit was reached; this is not a complete extraction")
+ print(json.dumps(json.loads(choice["message"]["content"]), indent=2, ensure_ascii=False))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/doc-field-extraction-omni/score.py b/examples/doc-field-extraction-omni/score.py
new file mode 100644
index 000000000..414aacbf8
--- /dev/null
+++ b/examples/doc-field-extraction-omni/score.py
@@ -0,0 +1,110 @@
+"""Replay document-level count evidence without making model calls."""
+# ruff: noqa: INP001 - Standalone example scripts are not a Python package.
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+from pathlib import Path
+
+from fetch import HERE, load_manifest, verify_file
+
+ARMS = ("sie-qwen3.8-27b", "claude-haiku-4-5", "claude-sonnet-5-5", "gpt-6-luna", "gpt-6-sol")
+FULL_DOCUMENTS = 800
+FRESH_DOCUMENTS = 770
+
+
+def load_evidence(root: Path) -> tuple[dict, list[dict]]:
+ """Verify every declared file before using the published counts."""
+ manifest = load_manifest((root / "manifest.json").read_bytes())
+ verified = {}
+ for name, expected in manifest["files"].items():
+ data = (root / name).read_bytes()
+ verify_file(name, data, expected)
+ verified[name] = data
+ summary = json.loads(verified["summary.json"])
+ rows = [json.loads(line) for line in verified["counts.jsonl"].splitlines()]
+ identities = {(row["arm"], row["document_id"]) for row in rows}
+ if len(identities) != len(rows):
+ raise ValueError("Duplicate arm/document pair")
+ inputs = [json.loads(line) for line in verified["inputs.jsonl"].splitlines()]
+ documents = {row["document_id"]: row for row in inputs}
+ if len(documents) != FULL_DOCUMENTS or len(inputs) != FULL_DOCUMENTS:
+ raise ValueError("Expected exactly 800 distinct input documents")
+ expected_identities = {(arm, document_id) for arm in ARMS for document_id in documents}
+ if identities != expected_identities:
+ raise ValueError("Count evidence must cover every input once for each of the five arms")
+ if set(summary["selected_claude_forms"]) != set(ARMS):
+ raise ValueError("Summary must preserve all five model arms")
+ for row in rows:
+ document = documents[row["document_id"]]
+ if (row["corpus"], row["fresh"]) != (document["corpus"], document["fresh"]):
+ raise ValueError(f"Count/input identity mismatch: {row['document_id']}")
+ return summary, rows
+
+
+def aggregate(rows: list[dict], arm: str, fresh: bool) -> dict:
+ """Average one complete model scope while retaining every failed reply."""
+ selected = [row for row in rows if row["arm"] == arm and (not fresh or row["fresh"])]
+ expected_n = FRESH_DOCUMENTS if fresh else FULL_DOCUMENTS
+ if len(selected) != expected_n:
+ raise ValueError(f"Incomplete scope for {arm}: {len(selected)} of {expected_n}")
+ omni = [row for row in selected if row["corpus"] == "omni"]
+ cord = [row for row in selected if row["corpus"] == "cord"]
+ return {
+ "documents": len(selected),
+ "omni_documents": len(omni),
+ "cord_documents": len(cord),
+ "omni_json_accuracy": sum(row["omni_accuracy"] for row in omni) / len(omni),
+ "cord_normalized_field_accuracy": sum(row["normalized_field_accuracy"] for row in cord) / len(cord),
+ "unparsed": sum(not row["parsed"] for row in selected),
+ "output_limits": sum(row["hit_limit"] for row in selected),
+ "transport_errors": sum(row["error"] for row in selected),
+ "fully_correct_omni": sum(row["fully_right"] for row in omni) / len(omni),
+ "mean_omni_tokens_in": sum(row["tokens_in"] for row in omni) / len(omni),
+ "mean_omni_tokens_out": sum(row["tokens_out"] for row in omni) / len(omni),
+ }
+
+
+def replay(root: Path) -> dict:
+ """Recompute both scopes and require every aggregate to match the recording."""
+ summary, rows = load_evidence(root)
+ results = {scope: {arm: aggregate(rows, arm, scope == "fresh") for arm in ARMS} for scope in ("full", "fresh")}
+ mapping = {
+ "omni_documents": "omni_n",
+ "cord_documents": "cord_n",
+ "omni_json_accuracy": "omni_accuracy",
+ "cord_normalized_field_accuracy": "cord_normalized_field_accuracy",
+ "unparsed": "unparsed",
+ "output_limits": "output_cap_rows",
+ "transport_errors": "transport_errors",
+ "fully_correct_omni": "omni_fully_right",
+ "mean_omni_tokens_in": "tokens_in_mean_omni",
+ "mean_omni_tokens_out": "tokens_out_mean_omni",
+ }
+ for scope, arms in results.items():
+ for arm, result in arms.items():
+ recorded = summary["scopes"][scope]["summary"][arm]
+ for computed_key, recorded_key in mapping.items():
+ if not math.isclose(result[computed_key], recorded[recorded_key], rel_tol=0, abs_tol=1e-12):
+ raise ValueError(f"Count replay mismatch: {scope}/{arm}/{computed_key}")
+ return {
+ "count_replay": results,
+ "verified": True,
+ "registered_bootstrap": summary["bootstrap"],
+ "registered_decisions": summary["eligible_on_both_scopes"],
+ "current_price_projection": summary["current_price_projection"],
+ }
+
+
+def main() -> None:
+ """Print the verified count replay and its saved decision metadata."""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--evidence", type=Path, default=HERE / "data")
+ args = parser.parse_args()
+ print(json.dumps(replay(args.evidence), indent=2))
+
+
+if __name__ == "__main__":
+ main()