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(remote): measure equivalence through a cluster gateway (#579)

Krisztian Gajdare96459863c4f
diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.md
index c80ced9f0..96652be45 100644
--- a/packages/sie_server/REMOTE_BACKENDS.md
+++ b/packages/sie_server/REMOTE_BACKENDS.md
@@ -318,6 +318,22 @@ metadata. A load balancer mixing workers cannot produce admissible evidence.
The record names the local execution identity it measured, not the process, so
it also covers other processes that report the same identity.
+In a cluster, add `--cluster` and pass the gateway URL as `--local-url`. The
+probe then takes process provenance from cluster status, so it needs no
+upstream credential and runs no model itself. The local processes are those of
+non-remote workers that list the model in their numerical diagnostics, and they
+must all report one identity and the supplied model contract. A worker that has
+the model loaded but reports no diagnostics refuses the run. The remote
+processes are those of remote workers that report the model's remote contract,
+and they must agree with the supplied files. When the model runs on several
+machine profiles with different identities, measure each one with `--gpu
+<machine profile>`, which pins the local calls to that profile. The probe first
+sends one local and one remote call that wait for capacity, so a cold lane
+starts through ordinary demand before cluster status is read. Cluster status is
+read again after the run, and any change in the processes, identities or
+contracts refuses the result, including a lane that scales up or down during
+the run.
+
Exit status is `0` for passing evidence, `1` for a measured failure, or `2` when
valid evidence could not be produced. Records contain input hashes, token
counts, serving identities, contract hashes and measured errors; they contain
diff --git a/packages/sie_server/tests/config/test_equivalence.py b/packages/sie_server/tests/config/test_equivalence.py
index a82ddc6f2..618d753d5 100644
--- a/packages/sie_server/tests/config/test_equivalence.py
+++ b/packages/sie_server/tests/config/test_equivalence.py
@@ -1,5 +1,7 @@
"""Evidence admits only complete, fresh suites bounded by measured local noise."""
+import base64
+import hashlib
import importlib.util
import json
import os
@@ -21,6 +23,7 @@ from sie_server.config.equivalence import (
ProbeCase,
canonical_digest,
measure_values,
+ model_contract_digest,
read_equivalence_record,
remote_profile_contract_digest,
)
@@ -633,3 +636,299 @@ def test_process_bound_records_are_refused() -> None:
data.update(version=2, local_instance_id="a" * 64)
with pytest.raises(ValidationError):
EquivalenceRecord.model_validate_json(json.dumps(data))
+
+
+_CLUSTER_MODEL = """sie_id: local/model
+hf_id: weights/model
+hf_revision: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+inputs: {text: true}
+tasks: {encode: {dense: {dim: 2}}}
+max_sequence_length: 32
+profiles:
+ default:
+ adapter_path: sie_server.adapters.bge_m3:BGEM3Adapter
+ max_batch_tokens: 8192
+ compute_precision: float32
+ remote:
+ adapter_path: sie_server.adapters.remote.openai:OpenAIUpstreamAdapter
+ max_batch_tokens: 8192
+ adapter_options:
+ loadtime: {upstream: upstream, upstream_model: vendor/model}
+"""
+_CLUSTER_UPSTREAMS = """upstreams:
+ upstream:
+ kind: openai
+ base_url: https://vendor.example/v1
+ endpoints: [embeddings]
+ rate_cap: {requests_per_minute: 600, max_concurrency: 32}
+"""
+_IDENTITY_L4 = "v2:sha256:" + "1" * 64
+_IDENTITY_A100 = "v2:sha256:" + "2" * 64
+_REMOTE_EXECUTION = "7" * 64
+
+
+def _websocket_frame(payload: bytes, opcode: int) -> bytes:
+ size = len(payload)
+ if size < 126:
+ header = bytes([0x80 | opcode, size])
+ elif size < 1 << 16:
+ header = bytes([0x80 | opcode, 126]) + size.to_bytes(2, "big")
+ else:
+ header = bytes([0x80 | opcode, 127]) + size.to_bytes(8, "big")
+ return header + payload
+
+
+def _worker(name: str, gpu: str, bundle: str, profiles: list[dict[str, Any]], instance: str) -> dict[str, Any]:
+ return {
+ "name": name,
+ "url": f"http://{name}:8080",
+ "gpu": gpu,
+ "bundle": bundle,
+ "loaded_models": [],
+ "numerical_process_inventory": {
+ "observed_at_unix_ms": 1,
+ "children": [
+ {
+ "child_index": 0,
+ "status": "observed",
+ "snapshot": {"runtime_instance_id": instance, "complete": True, "profiles": profiles},
+ }
+ ],
+ },
+ }
+
+
+def _cluster_fixture(tmp_path: Path) -> tuple[Path, Path, ModelConfig, str, str]:
+ config_file, upstream_file = tmp_path / "model.yaml", tmp_path / "upstreams.yaml"
+ config_file.write_text(_CLUSTER_MODEL)
+ upstream_file.write_text(_CLUSTER_UPSTREAMS)
+ config = ModelConfig.model_validate(yaml.safe_load(_CLUSTER_MODEL))
+ remote_contract = remote_profile_contract_digest(config, "remote", load_upstreams(upstream_file))
+ assert remote_contract is not None
+ return config_file, upstream_file, config, model_contract_digest(config), remote_contract
+
+
+def _fleet(contract: str, remote_contract: str, *, identities: tuple[str, str]) -> list[dict[str, Any]]:
+ def local(identity: str) -> list[dict[str, Any]]:
+ return [{"model_id": "local/model", "model_contract_sha256": contract, "local_identity": identity}]
+
+ return [
+ _worker("l4-0", "l4", "default", local(identities[0]), "a" * 64),
+ _worker("a100-0", "a100-80gb", "default", local(identities[1]), "b" * 64),
+ _worker(
+ "remote-0",
+ "cpu",
+ "remote",
+ [
+ {
+ "model_id": "local/model",
+ "model_contract_sha256": contract,
+ "local_identity": None,
+ "remote_contract_sha256": remote_contract,
+ "remote_execution_sha256": _REMOTE_EXECUTION,
+ }
+ ],
+ "c" * 64,
+ ),
+ ]
+
+
+events: list[str] = []
+
+
+def _run_cluster_probe(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, statuses: list[list[dict[str, Any]]], extra: list[str]
+) -> tuple[int, list[tuple[dict[str, Any], dict[str, str]]], Path]:
+ config_file, upstream_file = tmp_path / "model.yaml", tmp_path / "upstreams.yaml"
+ requests: list[tuple[dict[str, Any], dict[str, str]]] = []
+ connections: list[int] = []
+ events.clear()
+
+ class Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def do_GET(self) -> None:
+ if self.path != "/ws/cluster-status" or self.headers.get("Upgrade", "").lower() != "websocket":
+ self.send_error(404)
+ return
+ accept = base64.b64encode(
+ hashlib.sha1( # noqa: S324 - the WebSocket handshake digest is defined as SHA-1
+ (self.headers["Sec-WebSocket-Key"] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode()
+ ).digest()
+ ).decode()
+ self.send_response(101)
+ self.send_header("Upgrade", "websocket")
+ self.send_header("Connection", "Upgrade")
+ self.send_header("Sec-WebSocket-Accept", accept)
+ self.end_headers()
+ workers = statuses[min(len(connections), len(statuses) - 1)]
+ connections.append(1)
+ events.append("status")
+ self.wfile.write(_websocket_frame(json.dumps({"timestamp": 1.0, "workers": workers}).encode(), 0x1))
+ self.wfile.write(_websocket_frame(b"\x03\xe8", 0x8))
+ self.wfile.flush()
+ self.close_connection = True
+
+ def do_POST(self) -> None:
+ body = unpackb(self.rfile.read(int(self.headers["Content-Length"])), numeric_arrays=False)
+ headers = {key.lower(): value for key, value in self.headers.items() if key.lower().startswith("x-sie")}
+ requests.append((body, headers))
+ events.append("wake" if body["items"][0]["id"] == "probe-wake" else "probe")
+ remote = self.headers.get("X-SIE-Remote") != "forbid"
+ rows = [
+ {"id": item["id"], "dense": {"dims": 2, "values": np.asarray([1.0, 2.0], dtype=np.float32)}}
+ for item in body["items"]
+ ]
+ payload = packb({"model": "local/model", "items": rows})
+ self.send_response(200)
+ self.send_header("Content-Type", "application/msgpack")
+ self.send_header("Content-Length", str(len(payload)))
+ self.send_header("X-SIE-Served-By", "remote" if remote else "local")
+ if remote:
+ self.send_header("X-SIE-Upstream", "upstream")
+ self.end_headers()
+ self.wfile.write(payload)
+
+ def log_message(self, format: str, *args: Any) -> None:
+ return None
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ server.daemon_threads = True
+ thread = threading.Thread(target=server.serve_forever, args=(0.01,), daemon=True)
+ thread.start()
+ monkeypatch.setattr(probe, "load_tokenizer", lambda *args, **kwargs: _Tokenizer())
+ monkeypatch.setattr(probe, "_execution_code", lambda: {"sources": "e" * 64})
+ output = tmp_path / "evidence.json"
+ try:
+ result = probe.main(
+ [
+ "--model-file",
+ str(config_file),
+ "--upstreams-file",
+ str(upstream_file),
+ "--local-url",
+ f"http://127.0.0.1:{server.server_port}",
+ "--output",
+ str(output),
+ "--cluster",
+ *extra,
+ ]
+ )
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+ return result, requests, output
+
+
+def test_cluster_probe_attributes_observations_to_one_identity_from_cluster_status(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _, _, _, contract, remote_contract = _cluster_fixture(tmp_path)
+ fleet = _fleet(contract, remote_contract, identities=(_IDENTITY_L4, _IDENTITY_L4))
+ result, requests, output = _run_cluster_probe(tmp_path, monkeypatch, [fleet], [])
+ assert result == 0
+ evidence = EquivalenceRecord.model_validate_json(output.read_bytes())
+ assert evidence.local_identity == _IDENTITY_L4
+ assert evidence.remote_execution_sha256 == _REMOTE_EXECUTION
+ assert evidence.remote_contract_sha256 == remote_contract
+ assert evidence.local_observation_sha256 == canonical_digest({"identity": _IDENTITY_L4, "revision": "a" * 40})
+ assert events == ["wake", "wake", "status", *["probe"] * 24, "status"]
+ assert [headers.get("x-sie-remote") for _, headers in requests] == ["forbid", None] + ["forbid", "forbid", None] * 8
+ assert all("x-sie-machine-profile" not in headers for _, headers in requests)
+ assert all(body["params"]["options"]["profile"] in ("default", "remote") for body, _ in requests)
+
+
+def test_cluster_probe_refuses_two_identities_unless_one_machine_profile_is_selected(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _, _, _, contract, remote_contract = _cluster_fixture(tmp_path)
+ fleet = _fleet(contract, remote_contract, identities=(_IDENTITY_L4, _IDENTITY_A100))
+ result, _, output = _run_cluster_probe(tmp_path, monkeypatch, [fleet], [])
+ assert (result, events, output.exists()) == (2, ["wake", "wake", "status"], False)
+ result, requests, output = _run_cluster_probe(tmp_path, monkeypatch, [fleet], ["--gpu", "a100-80gb"])
+ assert result == 0
+ assert EquivalenceRecord.model_validate_json(output.read_bytes()).local_identity == _IDENTITY_A100
+ local = [headers for body, headers in requests if body["params"]["options"]["profile"] == "default"]
+ remote = [headers for body, headers in requests if body["params"]["options"]["profile"] == "remote"]
+ assert {headers.get("x-sie-machine-profile") for headers in local} == {"a100-80gb"}
+ assert {headers.get("x-sie-machine-profile") for headers in remote} == {None}
+
+
+def test_cluster_probe_refuses_a_fleet_that_changes_during_the_run(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _, _, _, contract, remote_contract = _cluster_fixture(tmp_path)
+ before = _fleet(contract, remote_contract, identities=(_IDENTITY_L4, _IDENTITY_L4))
+ after = json.loads(json.dumps(before))
+ after[0]["numerical_process_inventory"]["children"][0]["snapshot"]["runtime_instance_id"] = "d" * 64
+ result, _, output = _run_cluster_probe(tmp_path, monkeypatch, [before, after], [])
+ assert result == 2
+ assert events == ["wake", "wake", "status", *["probe"] * 24, "status"]
+ assert not output.exists()
+
+
[email protected]("change", ["remote_contract", "remote_execution", "model_contract", "unattributed", "status"])
+def test_cluster_probe_refuses_incomplete_or_mismatched_provenance(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, change: str
+) -> None:
+ _, _, _, contract, remote_contract = _cluster_fixture(tmp_path)
+ fleet = _fleet(contract, remote_contract, identities=(_IDENTITY_L4, _IDENTITY_L4))
+ remote_profile = fleet[2]["numerical_process_inventory"]["children"][0]["snapshot"]["profiles"][0]
+ if change == "remote_contract":
+ remote_profile["remote_contract_sha256"] = "0" * 64
+ elif change == "remote_execution":
+ remote_profile["remote_execution_sha256"] = None
+ elif change == "model_contract":
+ fleet[0]["numerical_process_inventory"]["children"][0]["snapshot"]["profiles"][0]["model_contract_sha256"] = (
+ "0" * 64
+ )
+ elif change == "unattributed":
+ fleet.append({**_worker("legacy-0", "l4", "default", [], "e" * 64), "loaded_models": ["local/model"]})
+ fleet[-1]["numerical_process_inventory"] = None
+ else:
+ fleet[1]["numerical_process_inventory"]["children"][0]["status"] = "incomplete"
+ result, _, output = _run_cluster_probe(tmp_path, monkeypatch, [fleet], [])
+ assert (result, events, output.exists()) == (2, ["wake", "wake", "status"], False)
+
+
[email protected]("malformed", ["inventory", "children", "child", "snapshot", "profiles", "profile"])
+def test_cluster_probe_refuses_malformed_status_without_a_traceback(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], malformed: str
+) -> None:
+ _, _, _, contract, remote_contract = _cluster_fixture(tmp_path)
+ fleet = _fleet(contract, remote_contract, identities=(_IDENTITY_L4, _IDENTITY_L4))
+ inventory = fleet[0]["numerical_process_inventory"]
+ if malformed == "inventory":
+ fleet[0]["numerical_process_inventory"] = ["not", "a", "map"]
+ elif malformed == "children":
+ inventory["children"] = {"0": inventory["children"][0]}
+ elif malformed == "child":
+ inventory["children"] = ["not a child"]
+ elif malformed == "snapshot":
+ inventory["children"][0]["snapshot"] = ["not", "a", "snapshot"]
+ elif malformed == "profiles":
+ inventory["children"][0]["snapshot"]["profiles"] = {"model_id": "local/model"}
+ else:
+ inventory["children"][0]["snapshot"]["profiles"] = ["not a profile"]
+ result, _, output = _run_cluster_probe(tmp_path, monkeypatch, [fleet], [])
+ assert (result, events, output.exists()) == (2, ["wake", "wake", "status"], False)
+ assert "Traceback" not in capsys.readouterr().err
+
+
+def test_machine_profile_selection_requires_cluster_mode(tmp_path: Path) -> None:
+ with pytest.raises(SystemExit):
+ probe.main(
+ [
+ "--model-file",
+ str(tmp_path / "model.yaml"),
+ "--upstreams-file",
+ str(tmp_path / "upstreams.yaml"),
+ "--local-url",
+ "http://127.0.0.1:9",
+ "--output",
+ str(tmp_path / "evidence.json"),
+ "--gpu",
+ "l4",
+ ]
+ )
diff --git a/tools/remote_equivalence.py b/tools/remote_equivalence.py
index 7d27ddaac..0b6813277 100755
--- a/tools/remote_equivalence.py
+++ b/tools/remote_equivalence.py
@@ -6,6 +6,10 @@ variables; no credential, request body or vector is written to the evidence.
The local model must expose a verified profile identity. The record covers
every process that reports that identity. Hybrid routing remains disabled while
the explicit remote profile is evaluated.
+
+With --cluster the URL is a cluster gateway. Every observation then comes from
+the processes that cluster status lists for the model, and the probe refuses
+unless they all report one identity and stay the same throughout the run.
"""
from __future__ import annotations
@@ -15,6 +19,7 @@ import hashlib
import os
import re
import sys
+from collections.abc import Mapping
from dataclasses import dataclass
from datetime import UTC, datetime
from http import HTTPStatus
@@ -171,6 +176,162 @@ def _values(
return arrays
+@dataclass(frozen=True)
+class _Provenance:
+ identity: str
+ revision: str
+ remote_execution: str
+ local_instance: str | None
+ processes: tuple[tuple[str, ...], ...] = ()
+
+
+def _hex_digest(value: object) -> bool:
+ return isinstance(value, str) and len(value) == _HASH_LENGTH and all(char in "0123456789abcdef" for char in value)
+
+
+def _server_provenance(local: SIEClient, config: ModelConfig, profile: str, expected_remote: str) -> _Provenance:
+ metadata = local.get_model(config.sie_id)
+ profiles = metadata.get("profiles") or {}
+ identity = profiles.get("default", {}).get("identity")
+ local_instance = profiles.get("default", {}).get("runtime_instance_id")
+ if not _hex_digest(local_instance):
+ raise ValueError("probe requires a direct worker runtime instance")
+ if profiles.get(profile, {}).get("remote_contract_sha256") != expected_remote:
+ raise ValueError("serving endpoint/model contract differs from the supplied files")
+ remote_execution = profiles.get(profile, {}).get("remote_execution_sha256")
+ if not _hex_digest(remote_execution):
+ raise ValueError("serving remote execution cannot be identified")
+ if not isinstance(identity, str) or not _IDENTITY.fullmatch(identity):
+ raise ValueError("local execution cannot be identified; no equivalence record can authorize it")
+ if (
+ metadata.get("revision") != config.hf_revision
+ or metadata.get("max_sequence_length") != config.max_sequence_length
+ ):
+ raise ValueError("local model metadata differs from the supplied model contract")
+ return _Provenance(
+ identity, cast("str", config.hf_revision), cast("str", remote_execution), cast("str", local_instance)
+ )
+
+
+def _cluster_workers(client: SIEClient) -> list[Mapping[str, Any]]:
+ for message in client.watch(mode="cluster"):
+ workers = message.get("workers") if isinstance(message, dict) else None
+ if isinstance(workers, list) and all(isinstance(worker, dict) for worker in workers):
+ return cast("list[Mapping[str, Any]]", workers)
+ break
+ raise ValueError("cluster status is unavailable")
+
+
+def _model_observations(worker: Mapping[str, Any], model: str) -> list[tuple[object, object, Mapping[str, Any]]]:
+ inventory = worker.get("numerical_process_inventory") or {}
+ if not isinstance(inventory, dict):
+ raise ValueError("cluster status is malformed")
+ children = inventory.get("children") or []
+ if not isinstance(children, list):
+ raise ValueError("cluster status is malformed")
+ found = []
+ for child in children:
+ if not isinstance(child, dict):
+ raise ValueError("cluster status is malformed")
+ snapshot = child.get("snapshot") or {}
+ if not isinstance(snapshot, dict):
+ raise ValueError("cluster status is malformed")
+ profiles = snapshot.get("profiles") or []
+ if not isinstance(profiles, list) or not all(isinstance(observation, dict) for observation in profiles):
+ raise ValueError("cluster status is malformed")
+ found.extend(
+ (child.get("status"), snapshot.get("runtime_instance_id"), observation)
+ for observation in profiles
+ if observation.get("model_id") == model
+ )
+ return found
+
+
+def _wake_lanes(
+ local: SIEClient, remote: SIEClient, config: ModelConfig, profile: str, machine_profile: str | None
+) -> None:
+ """Send one local and one remote call that wait for capacity, so cold lanes start before provenance."""
+ encode_outputs = sorted(set(config.outputs) & {"dense", "sparse", "multivector"})
+ items: list[Item] = [{"id": "probe-wake", "text": "wake"}]
+ for client, selected in ((local, "default"), (remote, profile)):
+ common: dict[str, Any] = {
+ "options": {**config.resolve_profile("default").runtime, "profile": selected},
+ "wait_for_capacity": True,
+ "max_oom_retries": 0,
+ }
+ if machine_profile is not None and selected == "default":
+ common["gpu"] = machine_profile
+ if encode_outputs:
+ client.encode(
+ config.sie_id,
+ items,
+ output_types=cast("Any", encode_outputs),
+ output_dtype=DEFAULT_OUTPUT_DTYPE,
+ **common,
+ )
+ else:
+ client.score(config.sie_id, {"text": _SCORE_QUERY}, items, **common)
+
+
+def _cluster_provenance(
+ client: SIEClient, config: ModelConfig, expected_remote: str, machine_profile: str | None
+) -> _Provenance:
+ """Attribute every probe observation to processes listed by cluster status.
+
+ The local processes are those of non-remote workers (of one machine profile
+ when given) that list the model, and they must all report one identity and
+ the supplied model contract. The remote processes are those of remote
+ workers that report the model's remote contract, and they must agree.
+ """
+ model, contract = config.sie_id, model_contract_digest(config)
+ local: dict[str, object] = {}
+ remote: dict[str, tuple[object, object]] = {}
+ for worker in _cluster_workers(client):
+ observations = _model_observations(worker, model)
+ if worker.get("bundle") == "remote":
+ for status, instance, observation in observations:
+ if observation.get("remote_contract_sha256") is None:
+ continue
+ if status != "observed" or not _hex_digest(instance):
+ raise ValueError("remote process provenance is incomplete")
+ remote[cast("str", instance)] = (
+ observation.get("remote_contract_sha256"),
+ observation.get("remote_execution_sha256"),
+ )
+ continue
+ if machine_profile is not None and worker.get("gpu") != machine_profile:
+ continue
+ if not observations and model in (worker.get("loaded_models") or []):
+ raise ValueError("a worker serving the model reports no process provenance")
+ for status, instance, observation in observations:
+ if (
+ status != "observed"
+ or not _hex_digest(instance)
+ or observation.get("model_contract_sha256") != contract
+ ):
+ raise ValueError("local process provenance is incomplete or differs from the supplied model")
+ local[cast("str", instance)] = observation.get("local_identity")
+ identities = set(local.values())
+ if len(identities) != 1:
+ raise ValueError("local processes do not report exactly one execution identity")
+ (identity,) = identities
+ if not isinstance(identity, str) or not _IDENTITY.fullmatch(identity):
+ raise ValueError("local execution cannot be identified; no equivalence record can authorize it")
+ contracts = set(remote.values())
+ if len(contracts) != 1:
+ raise ValueError("remote processes do not report exactly one remote contract")
+ ((remote_contract, remote_execution),) = contracts
+ if remote_contract != expected_remote:
+ raise ValueError("serving endpoint/model contract differs from the supplied files")
+ if not _hex_digest(remote_execution):
+ raise ValueError("serving remote execution cannot be identified")
+ processes = (
+ *sorted((instance, cast("str", value)) for instance, value in local.items()),
+ *sorted((instance, *cast("tuple[str, str]", value)) for instance, value in remote.items()),
+ )
+ return _Provenance(identity, cast("str", config.hf_revision), cast("str", remote_execution), None, processes)
+
+
def _request(
client: SIEClient,
config: ModelConfig,
@@ -180,15 +341,18 @@ def _request(
*,
profile: str,
upstream: str,
- local_instance: str,
+ local_instance: str | None,
+ machine_profile: str | None = None,
) -> tuple[str, Any]:
common: dict[str, Any] = {
"options": {**config.resolve_profile("default").runtime, "profile": profile},
"instruction": case.instruction,
- "wait_for_capacity": False,
- "provision_timeout_s": 60.0,
+ "wait_for_capacity": local_instance is None,
+ "provision_timeout_s": None if local_instance is None else 60.0,
"max_oom_retries": 0,
}
+ if machine_profile is not None and profile == "default":
+ common["gpu"] = machine_profile
try:
items: list[Item] = [{"id": f"probe-{index}", "text": text} for index, text in enumerate(case.texts)]
if operation == "score":
@@ -215,11 +379,11 @@ def _request(
expected = "local" if profile == "default" else "remote"
if evidence.get("served_by") != expected or (expected == "remote" and evidence.get("upstream") != upstream):
raise ValueError("probe serving provenance is missing or differs")
- if evidence.get("runtime_instance_id") != local_instance:
+ if local_instance is not None and evidence.get("runtime_instance_id") != local_instance:
raise ValueError("probe serving runtime instance differs")
return "ok", result
except RequestError as error:
- if (error.request or {}).get("runtime_instance_id") != local_instance:
+ if local_instance is not None and (error.request or {}).get("runtime_instance_id") != local_instance:
raise ValueError("probe refusal runtime instance differs") from None
code = (error.code or "").upper()
if error.status_code == HTTPStatus.BAD_REQUEST and code in ("INVALID_INPUT", "INPUT_TOO_LONG"):
@@ -228,7 +392,14 @@ def _request(
def run_probe(
- config: ModelConfig, upstreams: Any, local: SIEClient, remote: SIEClient, profile: str
+ config: ModelConfig,
+ upstreams: Any,
+ local: SIEClient,
+ remote: SIEClient,
+ profile: str,
+ *,
+ cluster: bool = False,
+ machine_profile: str | None = None,
) -> EquivalenceRecord:
if config.weights_path is not None or not is_immutable_revision(config.hf_revision) or not config.hf_id:
raise ValueError("probe requires immutable local Hub weights")
@@ -244,32 +415,18 @@ def run_probe(
raise ValueError("probe requires the default float32 output dtype")
upstream_name, upstream_model = resolved.loadtime["upstream"], resolved.loadtime["upstream_model"]
upstream = upstreams[upstream_name]
- before = local.get_model(config.sie_id)
- identity = (before.get("profiles") or {}).get("default", {}).get("identity")
- local_instance = (before.get("profiles") or {}).get("default", {}).get("runtime_instance_id")
- if (
- not isinstance(local_instance, str)
- or len(local_instance) != _HASH_LENGTH
- or any(char not in "0123456789abcdef" for char in local_instance)
- ):
- raise ValueError("probe requires a direct worker runtime instance")
expected_remote = remote_profile_contract_digest(config, profile, upstreams)
- if (
- expected_remote is None
- or (before.get("profiles") or {}).get(profile, {}).get("remote_contract_sha256") != expected_remote
- ):
+ if expected_remote is None:
raise ValueError("serving endpoint/model contract differs from the supplied files")
- remote_execution = (before.get("profiles") or {}).get(profile, {}).get("remote_execution_sha256")
- if (
- not isinstance(remote_execution, str)
- or len(remote_execution) != _HASH_LENGTH
- or any(char not in "0123456789abcdef" for char in remote_execution)
- ):
- raise ValueError("serving remote execution cannot be identified")
- if not isinstance(identity, str) or not _IDENTITY.fullmatch(identity):
- raise ValueError("local execution cannot be identified; no equivalence record can authorize it")
- if before.get("revision") != config.hf_revision or before.get("max_sequence_length") != config.max_sequence_length:
- raise ValueError("local model metadata differs from the supplied model contract")
+
+ def provenance() -> _Provenance:
+ if cluster:
+ return _cluster_provenance(local, config, expected_remote, machine_profile)
+ return _server_provenance(local, config, profile, expected_remote)
+
+ if cluster:
+ _wake_lanes(local, remote, config, profile, machine_profile)
+ before = provenance()
outputs = set(config.outputs) & {"dense", "sparse", "multivector", "score"}
if not outputs:
raise ValueError("probe requires encode or score outputs")
@@ -293,7 +450,8 @@ def run_probe(
selected_outputs,
profile=selected,
upstream=upstream_name,
- local_instance=local_instance,
+ local_instance=before.local_instance,
+ machine_profile=machine_profile,
)
for client, selected in ((local, "default"), (local, "default"), (remote, profile))
]
@@ -332,13 +490,7 @@ def run_probe(
measurements=cast("Any", measurements),
)
)
- after = local.get_model(config.sie_id)
- if (
- (after.get("profiles") or {}).get("default", {}).get("runtime_instance_id") != local_instance
- or (after.get("profiles") or {}).get("default", {}).get("identity") != identity
- or (after.get("profiles") or {}).get(profile, {}).get("remote_contract_sha256") != expected_remote
- or (after.get("profiles") or {}).get(profile, {}).get("remote_execution_sha256") != remote_execution
- ):
+ if provenance() != before:
raise ValueError("local execution changed during the probe")
return EquivalenceRecord(
measured_at=datetime.now(UTC),
@@ -350,11 +502,11 @@ def run_probe(
{"cli": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "library": _execution_code()["sources"]}
),
remote_contract_sha256=expected_remote,
- remote_execution_sha256=remote_execution,
- local_observation_sha256=canonical_digest({"identity": identity, "revision": before.get("revision")}),
+ remote_execution_sha256=before.remote_execution,
+ local_observation_sha256=canonical_digest({"identity": before.identity, "revision": before.revision}),
runtime_options_sha256=canonical_digest(dict(config.resolve_profile("default").runtime)),
output_dtype="float32",
- local_identity=identity,
+ local_identity=before.identity,
model=config.sie_id,
remote_profile=profile,
context_length=config.max_sequence_length,
@@ -371,7 +523,11 @@ def main(argv: list[str] | None = None) -> int:
parser.add_argument("--api-key-env")
parser.add_argument("--remote-profile", default="remote")
parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--cluster", action="store_true", help="--local-url is a cluster gateway")
+ parser.add_argument("--gpu", help="with --cluster, the machine profile whose processes are measured")
args = parser.parse_args(argv)
+ if args.gpu is not None and not args.cluster:
+ parser.error("--gpu requires --cluster")
try:
if args.output.exists():
raise ValueError("evidence output already exists")
@@ -386,7 +542,9 @@ def main(argv: list[str] | None = None) -> int:
SIEClient(base_url, api_key=key, remote="forbid", timeout_s=60) as local,
SIEClient(base_url, api_key=key, timeout_s=60) as remote,
):
- record = run_probe(config, upstreams, local, remote, args.remote_profile)
+ record = run_probe(
+ config, upstreams, local, remote, args.remote_profile, cluster=args.cluster, machine_profile=args.gpu
+ )
# Refuse to clobber existing evidence; a scheduled run chooses a new path.
with args.output.open("x", encoding="utf-8") as output:
output.write(record.model_dump_json(indent=2) + "\n")