AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
perf(onnx): add reproducible fused FP32 model recipe (#154)
Leonid Bugaev4d635c644801
diff --git a/.github/workflows/onnx-model-optimization-recipe.yml b/.github/workflows/onnx-model-optimization-recipe.ymlnew file mode 100644index 000000000..0cd9299cc--- /dev/null+++ b/.github/workflows/onnx-model-optimization-recipe.yml@@ -0,0 +1,37 @@+name: ONNX model optimization recipe++on:+ pull_request:+ paths:+ - ".github/workflows/onnx-model-optimization-recipe.yml"+ - "demo/playbooks/onnx-model-optimization/**"+ push:+ branches:+ - main+ paths:+ - ".github/workflows/onnx-model-optimization-recipe.yml"+ - "demo/playbooks/onnx-model-optimization/**"++permissions:+ contents: read++jobs:+ locked-recipe-tests:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-python@v5+ with:+ python-version: "3.13.5"+ cache: pip+ cache-dependency-path: demo/playbooks/onnx-model-optimization/requirements-linux-x86_64-cp313.lock+ - name: Install checksum-locked optimizer environment+ run: >-+ python -m pip install+ --only-binary=:all:+ --require-hashes+ -r demo/playbooks/onnx-model-optimization/requirements-linux-x86_64-cp313.lock+ - name: Run recipe unit tests+ run: >-+ python -m unittest+ demo/playbooks/onnx-model-optimization/test_optimize_minilm_fp32.pydiff --git a/demo/playbooks/onnx-model-optimization/.gitignore b/demo/playbooks/onnx-model-optimization/.gitignorenew file mode 100644index 000000000..7a60b85e1--- /dev/null+++ b/demo/playbooks/onnx-model-optimization/.gitignore@@ -0,0 +1,2 @@+__pycache__/+*.pycdiff --git a/demo/playbooks/onnx-model-optimization/README.md b/demo/playbooks/onnx-model-optimization/README.mdnew file mode 100644index 000000000..e12fc1730--- /dev/null+++ b/demo/playbooks/onnx-model-optimization/README.md@@ -0,0 +1,155 @@+# Transform the exact pinned MiniLM export into a fused FP32 graph++This offline recipe transforms one exact, previously recorded+`sentence-transformers/all-MiniLM-L6-v2`-compatible ONNX export into one exact+transformer-fused FP32 graph. It does **not** download, commit, install, select,+or recreate the source model. The approximately 90 MB source and output remain+external runtime assets.++This is a checksum-locked transformation recipe, not a from-upstream+reproduction recipe. You must already possess the exact source model and+tokenizer bytes listed below. The repository does not publish those assets or+an immutable exporter revision, and a fresh generic `optimum-cli export` is not+expected to reproduce them.++The recipe is intentionally narrow and fail-closed:++- CPython 3.13.5 and every optimizer package are exactly version-pinned; every+ selected wheel is SHA-256 pinned;+- source model and tokenizer must match measured lengths and SHA-256 hashes;+- the result must match the measured bytes, hash, interface, opsets,+ initializer types, and complete operator inventory;+- a lock is acquired with `O_EXCL`;+- candidate and manifest are staged and synced inside one private sibling+ directory, then the complete directory is atomically published without+ replacement;+- any mismatch exits non-zero without publishing an artifact.++The final output directory does not become visible until both files are+complete. A process or machine failure may leave a hidden sibling staging+directory or lock, but cannot publish a partial final directory. First confirm+that the PID in `.<output-directory>.optimize.lock` is no longer alive; then+remove the hidden staging directory and stale lock before rerunning. Never+delete a live lock.++## Locked environment++The lock targets ordinary CPython 3.13.5 on GNU/Linux glibc x86-64, the only+generation environment used for the exact byte result. It is not a general+cross-platform Python lock.++```bash+python3.13 -m venv /path/to/xerj-onnx-recipe-venv+/path/to/xerj-onnx-recipe-venv/bin/python -m pip install \+ --only-binary=:all: \+ --require-hashes \+ -r demo/playbooks/onnx-model-optimization/requirements-linux-x86_64-cp313.lock+```++## Transform the pinned source++```bash+/path/to/xerj-onnx-recipe-venv/bin/python \+ demo/playbooks/onnx-model-optimization/optimize_minilm_fp32.py \+ --source /models/minilm-source/model.onnx \+ --tokenizer /models/minilm-source/tokenizer.json \+ --output-dir /models/minilm-fused-v1+```++The published directory contains `model.bert-fused-fp32.onnx` and+`model.bert-fused-fp32.manifest.json`.++Required inputs:++| Asset | Bytes | SHA-256 |+|---|---:|---|+| source model | 90,405,214 | `6fd5d72fe4589f189f8ebc006442dbb529bb7ce38f8082112682524616046452` |+| tokenizer | 466,247 | `be50c3628f2bf5bb5e3a7f17b1f74611b2561a3a27eeab05e5aa30f411572037` |++Required result:++| Asset | Bytes | SHA-256 |+|---|---:|---|+| fused model | 90,276,689 | `d45c738311abe1488b6d9e2862e1db08267fc31d6f301d8f26163e2fb4956b9c` |++The manifest embeds the complete checked-in artifact contract and records the+observed source and candidate graph inventories plus the exact toolchain.+Before publication, the recipe enforces the observed source and tokenizer+bytes and hashes, candidate bytes, hash and complete graph inventory, package+versions, interpreter, and the optimizer arguments that it actually executes.++Other contract fields are recorded metadata, not observations made by this+script: artifact name/version, source license and provenance, the XERJ+embedding contract, and the compatibility support boundary. In particular,+the original experiment did not preserve an immutable upstream export+revision. Exact source bytes are pinned, but a stronger upstream provenance+claim would be dishonest.++[`artifact-contract.json`](artifact-contract.json) is the checked-in expected+contract. The generated manifest adds the complete inspected source and+candidate inventories and must agree with it.++## Use with XERJ++Build and start XERJ as described in+[`docs/EXPERIMENTAL_ONNX.md`](../../../docs/EXPERIMENTAL_ONNX.md), using the+generated model:++```bash+target/release/xerj \+ --insecure \+ --data-dir /var/lib/xerj-fused \+ --embed-mode onnx-experimental \+ --onnx-model /models/minilm-fused-v1/model.bert-fused-fp32.onnx \+ --onnx-tokenizer /models/minilm-source/tokenizer.json++target/release/xerj autoindex /path/to/corpus \+ --url http://localhost:9200 \+ --prefix finance-minilm-fused-v1 \+ --fresh+```++The fused graph is a **new embedding identity**. Its output is numerically+distinct from the source graph for XERJ because the model hashes differ. Never+resume an index created with the source model under the fused model. Retain the+old asset for the old index, or use `autoindex --fresh` with a new prefix. Do+not bypass `embedding_identity.json`.++## Compatibility boundary++This is offline transformer fusion (`opt_level=0`), not a hardware-specific+ONNX Runtime optimized-session cache. The graph nevertheless contains+`com.microsoft` contrib operators. The proven product path is ONNX Runtime+transformer optimizer 1.22.1 for generation, then XERJ's `ort`/`ort-sys`+2.0.0-rc.12 API-24 CPU path on GNU/Linux glibc x86-64. The generation-tool+version is not a claim that XERJ consumes the graph through runtime 1.22.1.++Do not infer support for another runtime/API line, CPU architecture, execution+provider, musl build, or non-ORT consumer. Even where the graph loads,+different kernels or CPUs can change floating-point output. Run the+asset/runtime and retrieval gates before expanding the support matrix.++XERJ already requests ONNX Runtime Level3 graph optimization when it creates a+session, including for an unfused source graph. This repository contains no+published measurement showing that the offline-fused asset improves session+initialization time, steady-state throughput, or retrieval quality beyond that+runtime optimization. Those are separate measurements: a cold-start result+cannot establish a steady-state benefit. The recipe currently provides a+byte-pinned fused artifact and inspection trail, not a public performance+claim. Adopting it also creates a new model identity and therefore requires a+fresh index, as described above.++## Evidence boundary++This recipe was extracted from an internal optimizer screen whose evidence is+not published in this repository. Therefore this playbook makes no public+speed or retrieval-quality claim. Any future claim needs checked-in sanitized+evidence and the repository's applicable quality and performance gates.++Run focused tests without invoking the 90 MB optimizer:++```bash+PYTHONPATH=/path/to/xerj-onnx-recipe-venv/lib/python3.13/site-packages \+ python3.13 -m unittest \+ demo/playbooks/onnx-model-optimization/test_optimize_minilm_fp32.py+```diff --git a/demo/playbooks/onnx-model-optimization/artifact-contract.json b/demo/playbooks/onnx-model-optimization/artifact-contract.jsonnew file mode 100644index 000000000..2b6271b2c--- /dev/null+++ b/demo/playbooks/onnx-model-optimization/artifact-contract.json@@ -0,0 +1,135 @@+{+ "format": "xerj-onnx-minilm-fp32-artifact-contract-v1",+ "artifact": {+ "bytes": 90276689,+ "name": "all-MiniLM-L6-v2-bert-fused-fp32",+ "sha256": "d45c738311abe1488b6d9e2862e1db08267fc31d6f301d8f26163e2fb4956b9c",+ "version": "1"+ },+ "compatibility": {+ "proven": {+ "architecture": "x86_64",+ "execution_provider": "CPUExecutionProvider",+ "os": "GNU/Linux glibc",+ "xerj_ort_crate": "2.0.0-rc.12",+ "xerj_ort_api": 24+ },+ "unproven": [+ "GNU/Linux AArch64",+ "musl",+ "CUDA",+ "TensorRT",+ "DirectML",+ "CoreML",+ "non-ONNX-Runtime consumers",+ "other XERJ ort crate / ONNX Runtime API lines"+ ]+ },+ "graph": {+ "ir_version": 7,+ "initializer_types": {+ "FLOAT": 77+ },+ "inputs": [+ {+ "element_type": "INT64",+ "name": "input_ids",+ "shape": [+ "batch_size",+ "sequence_length"+ ]+ },+ {+ "element_type": "INT64",+ "name": "attention_mask",+ "shape": [+ "batch_size",+ "sequence_length"+ ]+ },+ {+ "element_type": "INT64",+ "name": "token_type_ids",+ "shape": [+ "batch_size",+ "sequence_length"+ ]+ }+ ],+ "nodes": 46,+ "operators": {+ "Attention": 6,+ "BiasGelu": 6,+ "Cast": 3,+ "EmbedLayerNormalization": 1,+ "MatMul": 18,+ "SkipLayerNormalization": 12+ },+ "opsets": {+ "": 14,+ "com.microsoft": 1+ },+ "outputs": [+ {+ "element_type": "FLOAT",+ "name": "last_hidden_state",+ "shape": [+ "batch_size",+ "sequence_length",+ 384+ ]+ }+ ],+ "uses_external_data": false+ },+ "optimizer": {+ "arguments": {+ "hidden_size": 384,+ "model_type": "bert",+ "num_heads": 12,+ "only_onnxruntime": false,+ "opt_level": 0,+ "use_external_data_format": false,+ "use_gpu": false+ },+ "entrypoint": "onnxruntime.transformers.optimizer.optimize_model",+ "packages": {+ "coloredlogs": "15.0.1",+ "flatbuffers": "25.12.19",+ "humanfriendly": "10.0",+ "mpmath": "1.3.0",+ "numpy": "2.2.6",+ "onnx": "1.18.0",+ "onnxruntime": "1.22.1",+ "packaging": "26.2",+ "protobuf": "7.35.1",+ "sympy": "1.14.0",+ "typing_extensions": "4.16.0"+ },+ "python": "CPython 3.13.5"+ },+ "source": {+ "license": "Apache-2.0",+ "model": {+ "bytes": 90405214,+ "sha256": "6fd5d72fe4589f189f8ebc006442dbb529bb7ce38f8082112682524616046452"+ },+ "provenance": {+ "immutable_export_revision": null,+ "note": "Exact export bytes are pinned; the original experiment did not record an immutable upstream export revision.",+ "repository": "sentence-transformers/all-MiniLM-L6-v2"+ },+ "tokenizer": {+ "bytes": 466247,+ "sha256": "be50c3628f2bf5bb5e3a7f17b1f74611b2561a3a27eeab05e5aa30f411572037"+ }+ },+ "xerj_contract": {+ "dimensions": 384,+ "embedding_mode": "onnx-experimental",+ "identity": "Distinct from the source graph; autoindex --fresh under a new prefix is mandatory.",+ "maximum_tokens": 512,+ "normalization": "L2",+ "pooling": "attention-mask mean pooling"+ }+}diff --git a/demo/playbooks/onnx-model-optimization/optimize_minilm_fp32.py b/demo/playbooks/onnx-model-optimization/optimize_minilm_fp32.pynew file mode 100755index 000000000..b9022b133--- /dev/null+++ b/demo/playbooks/onnx-model-optimization/optimize_minilm_fp32.py@@ -0,0 +1,543 @@+#!/usr/bin/env python3+"""Transform XERJ's exact pinned MiniLM export into its fused FP32 artifact."""++from __future__ import annotations++import argparse+import collections+import contextlib+import copy+import ctypes+import errno+import hashlib+import importlib.metadata+import json+import os+import pathlib+import platform+import re+import shutil+import sys+import tempfile+from typing import Any, Iterator++import onnx+from onnxruntime.transformers.optimizer import optimize_model+++FORMAT = "xerj-onnx-minilm-fp32-recipe-v1"+MODEL_FILENAME = "model.bert-fused-fp32.onnx"+MANIFEST_FILENAME = "model.bert-fused-fp32.manifest.json"+HERE = pathlib.Path(__file__).resolve().parent+CONTRACT_PATH = HERE / "artifact-contract.json"+CONTRACT = json.loads(CONTRACT_PATH.read_text())++SOURCE_SHA256 = CONTRACT["source"]["model"]["sha256"]+SOURCE_BYTES = CONTRACT["source"]["model"]["bytes"]+TOKENIZER_SHA256 = CONTRACT["source"]["tokenizer"]["sha256"]+TOKENIZER_BYTES = CONTRACT["source"]["tokenizer"]["bytes"]+CANDIDATE_SHA256 = CONTRACT["artifact"]["sha256"]+CANDIDATE_BYTES = CONTRACT["artifact"]["bytes"]+PACKAGE_VERSIONS = CONTRACT["optimizer"]["packages"]+EXPECTED_INPUTS = CONTRACT["graph"]["inputs"]+EXPECTED_OUTPUTS = CONTRACT["graph"]["outputs"]+EXPECTED_CANDIDATE_OPERATORS = CONTRACT["graph"]["operators"]+EXPECTED_OPSETS = CONTRACT["graph"]["opsets"]+EXPECTED_IR_VERSION = CONTRACT["graph"]["ir_version"]+OPTIMIZER_ARGUMENT_SCHEMA = {+ "hidden_size": int,+ "model_type": str,+ "num_heads": int,+ "only_onnxruntime": bool,+ "opt_level": int,+ "use_external_data_format": bool,+ "use_gpu": bool,+}+OPTIMIZER_ENTRYPOINT = "onnxruntime.transformers.optimizer.optimize_model"+++class RecipeError(RuntimeError):+ """A fail-closed recipe or artifact-contract error."""+++def sha256(path: pathlib.Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as source:+ for block in iter(lambda: source.read(1024 * 1024), b""):+ digest.update(block)+ return digest.hexdigest()+++def verify_file(+ path: pathlib.Path, *, label: str, expected_bytes: int, expected_sha256: str+) -> None:+ if not path.is_file():+ raise RecipeError(f"{label} does not exist or is not a regular file: {path}")+ actual_bytes = path.stat().st_size+ if actual_bytes != expected_bytes:+ raise RecipeError(+ f"{label} byte length mismatch: expected {expected_bytes}, got "+ f"{actual_bytes}; refusing to optimize an unknown asset"+ )+ actual_sha256 = sha256(path)+ if actual_sha256 != expected_sha256:+ raise RecipeError(+ f"{label} SHA-256 mismatch: expected {expected_sha256}, got "+ f"{actual_sha256}; refusing to optimize an unknown asset"+ )+++def _checked_value_type(name: str, value: Any, expected: type) -> None:+ # bool is a subclass of int, but is not a valid integer optimizer setting.+ if type(value) is not expected:+ raise RecipeError(+ f"optimizer.arguments.{name} must be {expected.__name__}, "+ f"got {type(value).__name__}"+ )+++def optimizer_configuration(+ contract: dict[str, Any] | None = None,+) -> tuple[dict[str, Any], bool]:+ """Return the strictly validated optimizer and serializer configuration."""+ selected = CONTRACT if contract is None else contract+ optimizer = selected.get("optimizer")+ if not isinstance(optimizer, dict):+ raise RecipeError("contract optimizer must be an object")+ if optimizer.get("entrypoint") != OPTIMIZER_ENTRYPOINT:+ raise RecipeError(+ f"optimizer.entrypoint must be {OPTIMIZER_ENTRYPOINT!r}"+ )+ arguments = optimizer.get("arguments")+ if not isinstance(arguments, dict):+ raise RecipeError("optimizer.arguments must be an object")+ expected_names = set(OPTIMIZER_ARGUMENT_SCHEMA)+ actual_names = set(arguments)+ if actual_names != expected_names:+ raise RecipeError(+ "optimizer.arguments keys mismatch: expected "+ f"{sorted(expected_names)!r}, got {sorted(actual_names)!r}"+ )+ for name, expected_type in OPTIMIZER_ARGUMENT_SCHEMA.items():+ _checked_value_type(name, arguments[name], expected_type)+ if arguments["hidden_size"] <= 0 or arguments["num_heads"] <= 0:+ raise RecipeError("optimizer hidden_size and num_heads must be positive")+ if arguments["hidden_size"] % arguments["num_heads"] != 0:+ raise RecipeError("optimizer hidden_size must be divisible by num_heads")+ if not arguments["model_type"]:+ raise RecipeError("optimizer model_type must not be empty")+ optimize_arguments = dict(arguments)+ external_data = optimize_arguments.pop("use_external_data_format")+ return optimize_arguments, external_data+++def required_python(+ contract: dict[str, Any] | None = None,+) -> tuple[str, tuple[int, int, int]]:+ selected = CONTRACT if contract is None else contract+ optimizer = selected.get("optimizer")+ if not isinstance(optimizer, dict):+ raise RecipeError("contract optimizer must be an object")+ value = optimizer.get("python")+ if not isinstance(value, str):+ raise RecipeError("optimizer.python must be a string")+ match = re.fullmatch(r"(CPython) ([0-9]+)\.([0-9]+)\.([0-9]+)", value)+ if match is None:+ raise RecipeError(+ "optimizer.python must have the form 'CPython <major>.<minor>.<patch>'"+ )+ return match.group(1), tuple(int(part) for part in match.groups()[1:])+++def current_toolchain_matches_contract() -> bool:+ try:+ implementation, version = required_python()+ if platform.python_implementation() != implementation:+ return False+ if sys.version_info[:3] != version:+ return False+ return all(+ importlib.metadata.version(package) == expected+ for package, expected in PACKAGE_VERSIONS.items()+ )+ except (RecipeError, importlib.metadata.PackageNotFoundError):+ return False+++def verify_toolchain() -> dict[str, str]:+ implementation, version = required_python()+ required = f"{implementation} {'.'.join(str(part) for part in version)}"+ actual_implementation = platform.python_implementation()+ if actual_implementation != implementation or sys.version_info[:3] != version:+ raise RecipeError(+ f"this byte-reproduction recipe requires {required}; create the "+ "documented locked environment instead of using another interpreter"+ )+ actual: dict[str, str] = {}+ for package, expected in PACKAGE_VERSIONS.items():+ try:+ version = importlib.metadata.version(package)+ except importlib.metadata.PackageNotFoundError as error:+ raise RecipeError(f"required package is missing: {package}=={expected}") from error+ actual[package] = version+ if version != expected:+ raise RecipeError(+ f"package version mismatch for {package}: expected {expected}, "+ f"got {version}; refusing a non-locked optimization"+ )+ return dict(sorted(actual.items()))+++def _shape(value: onnx.ValueInfoProto) -> list[int | str]:+ dimensions: list[int | str] = []+ for dimension in value.type.tensor_type.shape.dim:+ if dimension.HasField("dim_value"):+ dimensions.append(dimension.dim_value)+ elif dimension.HasField("dim_param"):+ dimensions.append(dimension.dim_param)+ else:+ dimensions.append("")+ return dimensions+++def _value_contract(value: onnx.ValueInfoProto) -> dict[str, Any]:+ return {+ "name": value.name,+ "element_type": onnx.TensorProto.DataType.Name(value.type.tensor_type.elem_type),+ "shape": _shape(value),+ }+++def inspect_graph(path: pathlib.Path) -> dict[str, Any]:+ model = onnx.load(path, load_external_data=True)+ onnx.checker.check_model(model, full_check=True)+ operators = collections.Counter(node.op_type for node in model.graph.node)+ initializer_types = collections.Counter(+ onnx.TensorProto.DataType.Name(value.data_type)+ for value in model.graph.initializer+ )+ return {+ "bytes": path.stat().st_size,+ "sha256": sha256(path),+ "ir_version": model.ir_version,+ "opsets": dict(sorted((value.domain, value.version) for value in model.opset_import)),+ "nodes": len(model.graph.node),+ "operators": dict(sorted(operators.items())),+ "initializer_types": dict(sorted(initializer_types.items())),+ "inputs": [_value_contract(value) for value in model.graph.input],+ "outputs": [_value_contract(value) for value in model.graph.output],+ "uses_external_data": any(+ value.data_location == onnx.TensorProto.EXTERNAL+ for value in model.graph.initializer+ ),+ }+++def verify_graph_contract(graph: dict[str, Any]) -> None:+ expected = {+ "inputs": EXPECTED_INPUTS,+ "outputs": EXPECTED_OUTPUTS,+ "operators": EXPECTED_CANDIDATE_OPERATORS,+ "opsets": EXPECTED_OPSETS,+ "ir_version": EXPECTED_IR_VERSION,+ "nodes": 46,+ "initializer_types": {"FLOAT": 77},+ "uses_external_data": False,+ }+ for key, expected_value in expected.items():+ if graph[key] != expected_value:+ raise RecipeError(+ f"candidate graph {key} mismatch: expected {expected_value!r}, "+ f"got {graph[key]!r}"+ )+++def _fsync_file(path: pathlib.Path) -> None:+ with path.open("rb") as artifact:+ os.fsync(artifact.fileno())+++def _fsync_directory(path: pathlib.Path) -> None:+ descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))+ try:+ os.fsync(descriptor)+ finally:+ os.close(descriptor)+++def _write_all(descriptor: int, payload: bytes) -> None:+ view = memoryview(payload)+ while view:+ written = os.write(descriptor, view)+ if written == 0:+ raise RecipeError("short write while staging the artifact manifest")+ view = view[written:]+++def publish_directory_no_replace(+ staged: pathlib.Path, destination: pathlib.Path+) -> None:+ """Atomically publish one complete directory and refuse replacement."""+ if staged.parent != destination.parent:+ raise RecipeError("staged and destination directories must share one parent")+ _fsync_directory(staged)+ libc = ctypes.CDLL(None, use_errno=True)+ renameat2 = getattr(libc, "renameat2", None)+ if renameat2 is None:+ raise RecipeError(+ "atomic no-replace directory publication requires Linux renameat2"+ )+ renameat2.argtypes = [+ ctypes.c_int,+ ctypes.c_char_p,+ ctypes.c_int,+ ctypes.c_char_p,+ ctypes.c_uint,+ ]+ renameat2.restype = ctypes.c_int+ at_fdcwd = -100+ rename_noreplace = 1+ result = renameat2(+ at_fdcwd,+ os.fsencode(staged),+ at_fdcwd,+ os.fsencode(destination),+ rename_noreplace,+ )+ if result != 0:+ error_number = ctypes.get_errno()+ if error_number in (errno.EEXIST, errno.ENOTEMPTY):+ raise RecipeError(+ f"refusing to overwrite existing output directory: {destination}"+ )+ if error_number in (errno.ENOSYS, errno.EINVAL, errno.ENOTSUP):+ raise RecipeError(+ "the destination filesystem does not support atomic no-replace "+ "directory publication"+ )+ raise RecipeError(+ f"cannot atomically publish {destination}: "+ f"{os.strerror(error_number)}"+ )+ _fsync_directory(destination.parent)+++def exclusive_lock(path: pathlib.Path) -> Iterator[None]:+ """Reserve a recipe output set using O_EXCL; stale locks require inspection."""+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ owner = os.fstat(descriptor)+ try:+ _write_all(descriptor, f"pid={os.getpid()}\n".encode())+ os.fsync(descriptor)+ _fsync_directory(path.parent)+ yield+ finally:+ os.close(descriptor)+ try:+ current = path.stat(follow_symlinks=False)+ except FileNotFoundError:+ current = None+ if (+ current is not None+ and current.st_dev == owner.st_dev+ and current.st_ino == owner.st_ino+ ):+ path.unlink()+ _fsync_directory(path.parent)+++def observed_contract(+ *,+ source: dict[str, Any],+ tokenizer: pathlib.Path,+ candidate: dict[str, Any],+ packages: dict[str, str],+) -> dict[str, Any]:+ projection = copy.deepcopy(CONTRACT)+ projection["artifact"]["bytes"] = candidate["bytes"]+ projection["artifact"]["sha256"] = candidate["sha256"]+ projection["graph"] = {+ key: candidate[key]+ for key in (+ "ir_version",+ "initializer_types",+ "inputs",+ "nodes",+ "operators",+ "opsets",+ "outputs",+ "uses_external_data",+ )+ }+ projection["optimizer"]["packages"] = packages+ projection["source"]["model"] = {+ "bytes": source["bytes"],+ "sha256": source["sha256"],+ }+ projection["source"]["tokenizer"] = {+ "bytes": tokenizer.stat().st_size,+ "sha256": sha256(tokenizer),+ }+ return projection+++def verify_full_contract(projection: dict[str, Any]) -> None:+ if projection != CONTRACT:+ raise RecipeError(+ "observed artifact metadata does not exactly match "+ f"{CONTRACT_PATH.name}; refusing publication"+ )+++def build_manifest(+ *,+ source: dict[str, Any],+ tokenizer: pathlib.Path,+ candidate: dict[str, Any],+ packages: dict[str, str],+) -> dict[str, Any]:+ projection = observed_contract(+ source=source,+ tokenizer=tokenizer,+ candidate=candidate,+ packages=packages,+ )+ verify_full_contract(projection)+ return {+ "format": FORMAT,+ "artifact_contract": projection,+ "observed": {+ "source_graph": source,+ "candidate_graph": candidate,+ "toolchain": {+ "python": "CPython 3.13.5",+ "packages": packages,+ },+ },+ "recipe": (+ "demo/playbooks/onnx-model-optimization/optimize_minilm_fp32.py"+ ),+ }+++def run(args: argparse.Namespace) -> dict[str, Any]:+ source = args.source.resolve()+ tokenizer = args.tokenizer.resolve()+ output_directory = args.output_dir.resolve()+ if output_directory.exists():+ raise RecipeError(+ f"refusing to overwrite existing output directory: {output_directory}"+ )++ verify_file(+ source,+ label="source model",+ expected_bytes=SOURCE_BYTES,+ expected_sha256=SOURCE_SHA256,+ )+ verify_file(+ tokenizer,+ label="tokenizer",+ expected_bytes=TOKENIZER_BYTES,+ expected_sha256=TOKENIZER_SHA256,+ )+ packages = verify_toolchain()+ source_graph = inspect_graph(source)+ if source_graph["inputs"] != EXPECTED_INPUTS or source_graph["outputs"] != EXPECTED_OUTPUTS:+ raise RecipeError("source model does not satisfy the pinned MiniLM I/O contract")++ output_directory.parent.mkdir(parents=True, exist_ok=True)+ lock = output_directory.with_name(f".{output_directory.name}.optimize.lock")+ try:+ lock_context = exclusive_lock(lock)+ lock_context.__enter__()+ except FileExistsError as error:+ raise RecipeError(+ f"another optimizer or an interrupted run owns {lock}; inspect the "+ "recorded PID before removing the lock"+ ) from error++ staged_directory: pathlib.Path | None = None+ try:+ staged_directory = pathlib.Path(+ tempfile.mkdtemp(+ prefix=f".{output_directory.name}.staging-",+ dir=output_directory.parent,+ )+ )+ staged_candidate = staged_directory / MODEL_FILENAME+ staged_report = staged_directory / MANIFEST_FILENAME++ optimize_arguments, use_external_data_format = optimizer_configuration()+ optimized = optimize_model(str(source), **optimize_arguments)+ optimized.save_model_to_file(+ str(staged_candidate),+ use_external_data_format=use_external_data_format,+ )+ verify_file(+ staged_candidate,+ label="optimized candidate",+ expected_bytes=CANDIDATE_BYTES,+ expected_sha256=CANDIDATE_SHA256,+ )+ candidate_graph = inspect_graph(staged_candidate)+ verify_graph_contract(candidate_graph)+ result = build_manifest(+ source=source_graph,+ tokenizer=tokenizer,+ candidate=candidate_graph,+ packages=packages,+ )+ report_bytes = (json.dumps(result, indent=2, sort_keys=True) + "\n").encode()+ descriptor = os.open(staged_report, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ try:+ _write_all(descriptor, report_bytes)+ os.fsync(descriptor)+ finally:+ os.close(descriptor)++ _fsync_file(staged_candidate)+ publish_directory_no_replace(staged_directory, output_directory)+ staged_directory = None+ return result+ finally:+ if staged_directory is not None:+ shutil.rmtree(staged_directory, ignore_errors=True)+ lock_context.__exit__(None, None, None)+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description=(+ "Transform the exact checksum-pinned MiniLM source into the expected "+ "fused FP32 model. "+ "Unknown inputs, tools, topology, or existing outputs fail closed."+ )+ )+ parser.add_argument("--source", type=pathlib.Path, required=True)+ parser.add_argument("--tokenizer", type=pathlib.Path, required=True)+ parser.add_argument(+ "--output-dir",+ type=pathlib.Path,+ required=True,+ help=(+ "new directory atomically published with fixed model and manifest "+ "filenames"+ ),+ )+ return parser.parse_args()+++def main() -> int:+ try:+ result = run(parse_args())+ except (RecipeError, onnx.checker.ValidationError) as error:+ print(f"error: {error}", file=sys.stderr)+ return 2+ print(json.dumps(result, indent=2, sort_keys=True))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/demo/playbooks/onnx-model-optimization/requirements-linux-x86_64-cp313.lock b/demo/playbooks/onnx-model-optimization/requirements-linux-x86_64-cp313.locknew file mode 100644index 000000000..1fc259c70--- /dev/null+++ b/demo/playbooks/onnx-model-optimization/requirements-linux-x86_64-cp313.lock@@ -0,0 +1,24 @@+# CPython 3.13 / GNU/Linux glibc x86-64 byte-reproduction environment.+# Install with pip --only-binary=:all: --require-hashes -r <this file>.+onnx==1.18.0 \+ --hash=sha256:3c137eecf6bc618c2f9398bcc381474b55c817237992b169dfe728e169549e8f+onnxruntime==1.22.1 \+ --hash=sha256:b0c37070268ba4e02a1a9d28560cd00cd1e94f0d4f275cbef283854f861a65fa+numpy==2.2.6 \+ --hash=sha256:1bc23a79bfabc5d056d106f9befb8d50c31ced2fbc70eedb8155aec74a45798f+protobuf==7.35.1 \+ --hash=sha256:4bc97768d8fe4ad6743c8a19403e314511ed9f6d13205b687e52421c023ac1b9+typing_extensions==4.16.0 \+ --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8+coloredlogs==15.0.1 \+ --hash=sha256:612ee75c546f53e92e70049c9dbfcc18c935a2b9a53b66085ce9ef6a6e5c0934+flatbuffers==25.12.19 \+ --hash=sha256:7634f50c427838bb021c2d66a3d1168e9d199b0607e6329399f04846d42e20b4+packaging==26.2 \+ --hash=sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e+sympy==1.14.0 \+ --hash=sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5+humanfriendly==10.0 \+ --hash=sha256:1697e1a8a8f550fd43c2865cd84542fc175a61dcb779b6fee18cf6b6ccba1477+mpmath==1.3.0 \+ --hash=sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2cdiff --git a/demo/playbooks/onnx-model-optimization/test_optimize_minilm_fp32.py b/demo/playbooks/onnx-model-optimization/test_optimize_minilm_fp32.pynew file mode 100644index 000000000..987e982a0--- /dev/null+++ b/demo/playbooks/onnx-model-optimization/test_optimize_minilm_fp32.py@@ -0,0 +1,297 @@+import argparse+import importlib.util+import json+import os+import pathlib+import tempfile+import unittest+from unittest import mock+++HERE = pathlib.Path(__file__).resolve().parent+SPEC = importlib.util.spec_from_file_location(+ "optimize_minilm_fp32", HERE / "optimize_minilm_fp32.py"+)+assert SPEC is not None and SPEC.loader is not None+RECIPE = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(RECIPE)+++class RecipeTests(unittest.TestCase):+ @unittest.skipUnless(+ RECIPE.current_toolchain_matches_contract(),+ "live check requires the documented locked CPython environment",+ )+ def test_current_locked_toolchain_is_exact(self):+ self.assertEqual(RECIPE.verify_toolchain(), RECIPE.PACKAGE_VERSIONS)++ def test_complete_directory_is_published_at_once(self):+ with tempfile.TemporaryDirectory() as directory:+ root = pathlib.Path(directory)+ staged = root / ".staged"+ staged.mkdir()+ (staged / RECIPE.MODEL_FILENAME).write_bytes(b"model")+ (staged / RECIPE.MANIFEST_FILENAME).write_bytes(b"manifest")+ destination = root / "published"++ RECIPE.publish_directory_no_replace(staged, destination)+ self.assertFalse(staged.exists())+ self.assertEqual(+ sorted(path.name for path in destination.iterdir()),+ sorted([RECIPE.MODEL_FILENAME, RECIPE.MANIFEST_FILENAME]),+ )++ def test_directory_publication_never_replaces_collision(self):+ with tempfile.TemporaryDirectory() as directory:+ root = pathlib.Path(directory)+ staged = root / ".staged"+ staged.mkdir()+ (staged / "complete").write_text("candidate")+ destination = root / "published"+ destination.mkdir()+ (destination / "sentinel").write_text("original")++ with self.assertRaisesRegex(RECIPE.RecipeError, "refusing to overwrite"):+ RECIPE.publish_directory_no_replace(staged, destination)+ self.assertEqual((destination / "sentinel").read_text(), "original")+ self.assertEqual((staged / "complete").read_text(), "candidate")++ def test_exclusive_lock_records_owner_cleans_up_and_rejects_conflict(self):+ with tempfile.TemporaryDirectory() as directory:+ lock = pathlib.Path(directory) / "recipe.lock"+ with RECIPE.exclusive_lock(lock):+ self.assertEqual(lock.read_text(), f"pid={os.getpid()}\n")+ with self.assertRaises(FileExistsError):+ with RECIPE.exclusive_lock(lock):+ pass+ self.assertFalse(lock.exists())++ def test_lock_owner_does_not_remove_replacement_lock(self):+ with tempfile.TemporaryDirectory() as directory:+ lock = pathlib.Path(directory) / "recipe.lock"+ with RECIPE.exclusive_lock(lock):+ lock.unlink()+ lock.write_text("replacement\n")+ self.assertEqual(lock.read_text(), "replacement\n")++ def test_unknown_source_is_rejected_by_bytes_before_hash(self):+ with tempfile.TemporaryDirectory() as directory:+ source = pathlib.Path(directory) / "model.onnx"+ source.write_bytes(b"not the model")+ with self.assertRaisesRegex(RECIPE.RecipeError, "byte length mismatch"):+ RECIPE.verify_file(+ source,+ label="source model",+ expected_bytes=RECIPE.SOURCE_BYTES,+ expected_sha256=RECIPE.SOURCE_SHA256,+ )++ def test_same_length_wrong_hash_is_rejected(self):+ with tempfile.TemporaryDirectory() as directory:+ source = pathlib.Path(directory) / "model.onnx"+ source.write_bytes(b"same-size")+ with self.assertRaisesRegex(RECIPE.RecipeError, "SHA-256 mismatch"):+ RECIPE.verify_file(+ source,+ label="source model",+ expected_bytes=len(b"same-size"),+ expected_sha256="0" * 64,+ )++ def test_candidate_topology_must_match_exactly(self):+ valid = {+ "inputs": RECIPE.EXPECTED_INPUTS,+ "outputs": RECIPE.EXPECTED_OUTPUTS,+ "operators": RECIPE.EXPECTED_CANDIDATE_OPERATORS,+ "opsets": RECIPE.EXPECTED_OPSETS,+ "ir_version": RECIPE.EXPECTED_IR_VERSION,+ "nodes": 46,+ "initializer_types": {"FLOAT": 77},+ "uses_external_data": False,+ }+ RECIPE.verify_graph_contract(valid)+ for key in (+ "inputs",+ "outputs",+ "operators",+ "opsets",+ "ir_version",+ "nodes",+ "initializer_types",+ "uses_external_data",+ ):+ invalid = json.loads(json.dumps(valid))+ invalid[key] = None+ with self.subTest(key=key):+ with self.assertRaisesRegex(RECIPE.RecipeError, f"{key} mismatch"):+ RECIPE.verify_graph_contract(invalid)++ def test_generated_manifest_embeds_full_checked_contract(self):+ source = {+ "bytes": RECIPE.SOURCE_BYTES,+ "sha256": RECIPE.SOURCE_SHA256,+ "inputs": RECIPE.EXPECTED_INPUTS,+ "outputs": RECIPE.EXPECTED_OUTPUTS,+ }+ candidate = dict(RECIPE.CONTRACT["graph"])+ candidate.update(+ {+ "bytes": RECIPE.CANDIDATE_BYTES,+ "sha256": RECIPE.CANDIDATE_SHA256,+ }+ )+ with tempfile.TemporaryDirectory() as directory:+ tokenizer = pathlib.Path(directory) / "tokenizer.json"+ tokenizer.write_bytes(b"")+ with tokenizer.open("r+b") as value:+ value.truncate(RECIPE.TOKENIZER_BYTES)+ with mock.patch.object(+ RECIPE, "sha256", return_value=RECIPE.TOKENIZER_SHA256+ ):+ generated = RECIPE.build_manifest(+ source=source,+ tokenizer=tokenizer,+ candidate=candidate,+ packages=RECIPE.PACKAGE_VERSIONS,+ )+ self.assertEqual(generated["artifact_contract"], RECIPE.CONTRACT)+ self.assertNotIn(str(tokenizer), json.dumps(generated))+ self.assertIn(+ "new prefix",+ generated["artifact_contract"]["xerj_contract"]["identity"],+ )++ def test_observed_package_drift_fails_through_manifest_projection(self):+ source = {+ "bytes": RECIPE.SOURCE_BYTES,+ "sha256": RECIPE.SOURCE_SHA256,+ }+ candidate = dict(RECIPE.CONTRACT["graph"])+ candidate.update(+ bytes=RECIPE.CANDIDATE_BYTES,+ sha256=RECIPE.CANDIDATE_SHA256,+ )+ packages = dict(RECIPE.PACKAGE_VERSIONS)+ packages["onnxruntime"] = "0.0.0"+ tokenizer = mock.Mock()+ tokenizer.stat.return_value.st_size = RECIPE.TOKENIZER_BYTES+ with mock.patch.object(+ RECIPE, "sha256", return_value=RECIPE.TOKENIZER_SHA256+ ):+ drifted = RECIPE.observed_contract(+ source=source,+ tokenizer=tokenizer,+ candidate=candidate,+ packages=packages,+ )+ with self.assertRaisesRegex(RECIPE.RecipeError, "does not exactly match"):+ RECIPE.verify_full_contract(drifted)++ def test_python_contract_drives_host_independent_toolchain_gate(self):+ contract = json.loads(json.dumps(RECIPE.CONTRACT))+ contract["optimizer"]["python"] = "CPython 9.8.7"+ with (+ mock.patch.object(RECIPE, "CONTRACT", contract),+ mock.patch.object(RECIPE.platform, "python_implementation", return_value="CPython"),+ mock.patch.object(RECIPE.sys, "version_info", (9, 8, 6)),+ ):+ with self.assertRaisesRegex(RECIPE.RecipeError, "CPython 9.8.7"):+ RECIPE.verify_toolchain()++ def test_optimizer_arguments_are_contract_driven_and_strictly_typed(self):+ contract = json.loads(json.dumps(RECIPE.CONTRACT))+ contract["optimizer"]["arguments"]["num_heads"] = 6+ arguments, external_data = RECIPE.optimizer_configuration(contract)+ self.assertEqual(arguments["num_heads"], 6)+ self.assertNotIn("use_external_data_format", arguments)+ self.assertFalse(external_data)++ contract["optimizer"]["arguments"]["num_heads"] = True+ with self.assertRaisesRegex(RECIPE.RecipeError, "must be int"):+ RECIPE.optimizer_configuration(contract)++ contract = json.loads(json.dumps(RECIPE.CONTRACT))+ contract["optimizer"]["arguments"]["unknown"] = 1+ with self.assertRaisesRegex(RECIPE.RecipeError, "keys mismatch"):+ RECIPE.optimizer_configuration(contract)++ def test_invalid_python_contract_is_rejected(self):+ contract = json.loads(json.dumps(RECIPE.CONTRACT))+ contract["optimizer"]["python"] = "python3"+ with self.assertRaisesRegex(RECIPE.RecipeError, "must have the form"):+ RECIPE.required_python(contract)++ def test_python_patch_version_is_part_of_toolchain_gate(self):+ with (+ mock.patch.object(RECIPE.platform, "python_implementation", return_value="CPython"),+ mock.patch.object(RECIPE.sys, "version_info", (3, 13, 4)),+ ):+ with self.assertRaisesRegex(RECIPE.RecipeError, "CPython 3.13.5"):+ RECIPE.verify_toolchain()++ def test_failure_before_publish_leaves_no_public_directory_or_lock(self):+ class FakeOptimized:+ @staticmethod+ def save_model_to_file(path, use_external_data_format):+ self.assertFalse(use_external_data_format)+ pathlib.Path(path).write_bytes(b"candidate")++ source_graph = {+ "inputs": RECIPE.EXPECTED_INPUTS,+ "outputs": RECIPE.EXPECTED_OUTPUTS,+ }+ operative_contract = json.loads(json.dumps(RECIPE.CONTRACT))+ operative_contract["optimizer"]["arguments"]["num_heads"] = 6+ with tempfile.TemporaryDirectory() as directory:+ root = pathlib.Path(directory)+ source = root / "source.onnx"+ tokenizer = root / "tokenizer.json"+ source.write_bytes(b"source")+ tokenizer.write_bytes(b"tokenizer")+ output = root / "published"+ args = argparse.Namespace(+ source=source,+ tokenizer=tokenizer,+ output_dir=output,+ )+ with (+ mock.patch.object(RECIPE, "CONTRACT", operative_contract),+ mock.patch.object(RECIPE, "verify_file"),+ mock.patch.object(+ RECIPE,+ "verify_toolchain",+ return_value=RECIPE.PACKAGE_VERSIONS,+ ),+ mock.patch.object(+ RECIPE,+ "inspect_graph",+ side_effect=[source_graph, dict(RECIPE.CONTRACT["graph"])],+ ),+ mock.patch.object(+ RECIPE, "optimize_model", return_value=FakeOptimized()+ ) as optimize,+ mock.patch.object(RECIPE, "verify_graph_contract"),+ mock.patch.object(+ RECIPE,+ "build_manifest",+ side_effect=RECIPE.RecipeError("injected contract failure"),+ ),+ ):+ with self.assertRaisesRegex(+ RECIPE.RecipeError, "injected contract failure"+ ):+ RECIPE.run(args)++ expected_arguments = dict(operative_contract["optimizer"]["arguments"])+ expected_arguments.pop("use_external_data_format")+ optimize.assert_called_once_with(str(source), **expected_arguments)+ self.assertFalse(output.exists())+ self.assertFalse((root / ".published.optimize.lock").exists())+ self.assertEqual(+ list(root.glob(".published.staging-*")),+ [],+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/docs/EXPERIMENTAL_ONNX.md b/docs/EXPERIMENTAL_ONNX.mdindex 50f7bb8d6..21b902fba 100644--- a/docs/EXPERIMENTAL_ONNX.md+++ b/docs/EXPERIMENTAL_ONNX.md@@ -48,6 +48,16 @@ Confirm the three required input names, a supported output name, and width 384.Export tools can change their file layout or output names; XERJ deliberatelyfails instead of guessing.+For the checksum-pinned transformer-fused FP32 graph created during an+internal optimizer screen whose evidence is not published here, see the+repository's+[offline transformation recipe](../demo/playbooks/onnx-model-optimization/README.md).+The recipe does not download, bundle, or recreate its source model. It works+only when the operator already has the exact recorded source model and+tokenizer bytes, pins the optimizer environment, and publishes only the exact+checked graph plus its manifest. The generic export above is not an acquisition+path for those checksum-pinned inputs.+Build the opt-in server:```bash@@ -146,6 +156,12 @@ The error tells the operator to restore the original assets or re-runautoindex with `--fresh` and a new prefix. XERJ never silently mixes vectorspaces.+The transformer-fused graph produced by the offline recipe is a different+model identity from its source graph because its model hash differs. Do not+replace a source model in place. Start with the fused model and run `autoindex+--fresh` under a new prefix, or retain the source model for the existing index.+The identity check must not be bypassed.+## Throughput controlsThe default remains one ONNX Runtime session and a 64-passage caller window:@@ -216,6 +232,13 @@ This is not a 12.90x end-to-end indexing claim. It excludes extraction, HTTP,lexical indexing, persistence, HNSW construction, and contention. FullFinanceBench autoindex time must be measured, not projected.+The transformer-fused recipe came from an internal optimizer screen whose+evidence is not published in this repository. It therefore makes no public+speed or quality claim. See the+[evidence boundary](../demo/playbooks/onnx-model-optimization/README.md#evidence-boundary)+and run the applicable repository quality and performance gates before+publishing one.+Measured stripped server binaries:- Candle: 36.06 MiB;@@ -226,3 +249,15 @@ The approximately 90 MiB model is a separate runtime asset. Bundled `ort`binaries do not cover XERJ's musl release targets, so standard musl releasesremain Candle-only. ONNX production adoption still needs a supported targetmatrix, end-to-end quality gates, and full-corpus throughput/resource results.++The fused recipe uses ONNX Runtime transformer optimizer 1.22.1 for offline+generation. Consumption is proven with XERJ's `ort`/`ort-sys` 2.0.0-rc.12+API-24 CPU path on GNU/Linux glibc x86-64. Its `com.microsoft` contrib+operators make other runtime/API lines and providers explicit validation+tasks. It is not a hardware-specific optimized-session cache, but neither+portability nor bit-identical output across CPUs or runtimes should be assumed.+XERJ already requests ONNX Runtime Level3 optimization at session creation for+both source and fused graphs. No published evidence currently shows an+incremental cold-start, steady-state throughput, or retrieval-quality benefit+from supplying the offline-fused graph. These require separate measurements;+the fresh-index identity cost applies regardless.