Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 61 additions & 1 deletion cascade/eval/lane_d_bench_sweep.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import argparse
import json
import logging
import math
import shutil
import subprocess
import sys
Expand Down Expand Up @@ -159,6 +160,57 @@ def _error_rows(suites: Sequence[str]) -> dict:
return {s: {"status": "error", "rows": []} for s in suites}


def _positive(v) -> float | None:
if isinstance(v, bool) or not isinstance(v, (int, float)):
return None
f = float(v)
return f if math.isfinite(f) and f > 0 else None


def suite_aggregates(report: Mapping | None) -> dict:
"""Each suite's aggregate CRPS / MASE of one sidecar report, keyed by gate
key: ``{"gift": {"status", "crps", "mase", "partial"[, "data_revision"]
[, "bench_method"]}, …}``. The suite-level ``metrics`` lane A's six
numbers come from (:func:`cascade.eval.benchmarks.extract_bench_scores`:
same metric aliases, same coverage rule), so a lane D king's public
numbers compare with the lane A king's signed ones. Display only (the
gate pairs item rows, never these). A non-finite or non-positive metric
is ``None``; ``{}`` for a missing report. Never raises."""
if not isinstance(report, Mapping):
return {}
from .benchmarks import (
_CRPS_ALIASES,
_MASE_ALIASES,
ITEM_SUITE_KEY,
_pick_metric,
suite_incomplete,
)

out: dict[str, dict] = {}
try:
method = report.get("bench_method")
revisions = report.get("data_revisions") or {}
for s in report.get("suites") or []:
key = ITEM_SUITE_KEY.get(s.get("suite")) if isinstance(s, Mapping) else None
if key is None:
continue
m = s.get("metrics") if isinstance(s.get("metrics"), Mapping) else {}
agg = {"status": s.get("status"),
"crps": _positive(_pick_metric(dict(m), _CRPS_ALIASES)),
"mase": _positive(_pick_metric(dict(m), _MASE_ALIASES)),
"partial": bool(suite_incomplete(dict(s)))}
rev = revisions.get(s.get("suite")) if isinstance(revisions, Mapping) else None
if rev:
agg["data_revision"] = str(rev)
if isinstance(method, str) and method:
agg["bench_method"] = method
out[key] = agg
except Exception as e: # noqa: BLE001 — display numbers, never a verdict
log.warning("lane_d_bench: could not parse suite aggregates: %s", e)
return {}
return out


def serve_sweep(request, *, cache, work_dir, contract=None, expect=None,
sidecar: Callable | None = None, fingerprint: Mapping | None = None) -> dict:
"""Answer one :data:`REQUEST_SCHEMA` request (see the module docstring).
Expand All @@ -169,6 +221,7 @@ def serve_sweep(request, *, cache, work_dir, contract=None, expect=None,
digests, suites, contexts, grants, settings = _checked(request)
names = _gate_keys()
rows: dict[str, dict] = {}
aggregates: dict[str, dict] = {}
dirs: list[tuple[str, Path]] = []
for dg in digests:
# W15 lease: no process sharing the cache root evicts the entry between
Expand Down Expand Up @@ -199,8 +252,15 @@ def serve_sweep(request, *, cache, work_dir, contract=None, expect=None,
for (dg, _), rep in zip(dirs, reports, strict=True):
got = item_rows_from_report(rep)
rows[dg] = _error_rows(suites) if got is None else got
agg = suite_aggregates(rep)
if agg:
aggregates[dg] = {s: agg[s] for s in suites if s in agg}
fp = probe_fingerprint() if fingerprint is None else dict(fingerprint)
# ``aggregates`` (the lane D king's public numbers, display only) rides
# beside ``rows``: the gate reads ``rows`` alone, so a box that predates
# it reads this reply unchanged.
reply = {"schema": REPLY_SCHEMA, "rows": {dg: rows[dg] for dg in digests},
"aggregates": {dg: aggregates[dg] for dg in digests if dg in aggregates},
"fingerprint": fp}
json.dumps(reply, allow_nan=False)
return reply
Expand Down Expand Up @@ -255,4 +315,4 @@ def main(argv: list[str] | None = None) -> int:


__all__ = ["REPLY_SCHEMA", "REQUEST_SCHEMA", "SWEEP_ERROR_CODES", "LaneDBenchSweepError",
"materialise", "probe_fingerprint", "serve_sweep"]
"materialise", "probe_fingerprint", "serve_sweep", "suite_aggregates"]
63 changes: 55 additions & 8 deletions cascade/validator/lane_d_bench_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ def set_contexts(self, contexts: Mapping[str, int]) -> None:
"""Each digest's effective context for this settlement (W8c source)."""
self._contexts = {str(d): int(c) for d, c in contexts.items()}

def context_of(self, digest: str) -> int | None:
"""``digest``'s effective context of the last settlement (``None``:
not set)."""
c = self._contexts.get(str(digest))
return None if c is None else int(c)

def _resolve(self):
from ..trainer.remote import load_hosts

Expand All @@ -86,16 +92,19 @@ def _resolve(self):
raise LaneDBenchHostError(f"{self.hosts_path}: no final/any bench host")
return hosts[0]

def _request(self, digests: list[str], suites: list[str]) -> dict:
missing = [d for d in digests if d not in self._contexts]
def _request(self, digests: list[str], suites: list[str],
contexts: Mapping[str, int] | None = None) -> dict:
ctx = self._contexts if contexts is None else {str(d): int(c)
for d, c in contexts.items()}
missing = [d for d in digests if d not in ctx]
if missing:
raise LaneDBenchHostError(f"no effective context for {[d[:16] for d in missing]}")
grants = {}
for d in digests:
g = None if self._grants is None else self._grants(d)
grants[d] = None if g is None else dict(g)
return {"schema": REQUEST_SCHEMA, "digests": digests, "suites": suites,
"contexts": {d: self._contexts[d] for d in digests}, "grants": grants,
"contexts": {d: ctx[d] for d in digests}, "grants": grants,
"settings": {k: self.settings[k] for k in SETTINGS_KEYS}}

@staticmethod
Expand All @@ -114,10 +123,40 @@ def _checked(reply, digests: list[str]) -> dict:
raise LaneDBenchHostError(f"reply rows for {dg[:16]} are malformed")
return rows

@staticmethod
def _aggregates(reply: dict, digests: list[str]) -> dict:
"""The reply's optional per-suite aggregates (display only; ``{}``
from a bench host that predates them)."""
raw = reply.get("aggregates")
if not isinstance(raw, dict):
return {}
return {dg: {s: dict(a) for s, a in per.items()
if isinstance(s, str) and isinstance(a, dict)}
for dg, per in raw.items() if dg in digests and isinstance(per, dict)}

def __call__(self, digests, suites) -> dict:
ds = [str(d) for d in digests]
ss = [str(s) for s in suites]
request = self._request(ds, ss)
return self._checked(self._sweep(ds, [str(s) for s in suites]), ds)

def sweep_full(self, digests, suites, *, contexts: Mapping[str, int] | None = None,
timeout_s: float | None = None) -> dict:
"""One display-only sweep (the lane D king's full public bench): the
``__call__`` rows, each suite entry carrying the reply's
``aggregate`` (``{"status", "crps", "mase", "partial", …}``) when the
bench host sent one. ``contexts`` overrides the settlement's map,
``timeout_s`` caps the allowance. Raises as ``__call__`` does."""
ds = [str(d) for d in digests]
reply = self._sweep(ds, [str(s) for s in suites], contexts=contexts,
timeout_s=timeout_s)
rows = self._checked(reply, ds)
aggs = self._aggregates(reply, ds)
return {dg: {s: ({**e, "aggregate": aggs[dg][s]} if s in aggs.get(dg, {}) else e)
for s, e in per.items()} for dg, per in rows.items()}

def _sweep(self, ds: list[str], ss: list[str], *,
contexts: Mapping[str, int] | None = None,
timeout_s: float | None = None) -> dict:
request = self._request(ds, ss, contexts)
host = self._resolve()
from ..trainer.remote import build_ssh_argv

Expand All @@ -128,10 +167,16 @@ def __call__(self, digests, suites) -> dict:
"--cache-dir", self.cache_dir, "--budget-bytes", str(self.budget_bytes)]
if host.chain_toml:
args += ["--chain-toml", host.chain_toml]
cmd = f"cd {shlex.quote(host.workdir)} && {env}" + " ".join(shlex.quote(a) for a in args)
timeout = self.timeout_per_checkpoint_s * len(ds)
if timeout_s is not None:
timeout = min(timeout, float(timeout_s))
# IR008: the sweep ends ON the host too (subprocess timeout= kills only
# the local ssh client; the remote sidecar would keep running)
cmd = (f"cd {shlex.quote(host.workdir)} && {env}timeout -k 30 {max(1, int(timeout))} "
+ " ".join(shlex.quote(a) for a in args))
payload = json.dumps(request, sort_keys=True).encode("utf-8")
proc = self._run(build_ssh_argv(host, cmd), input=payload, capture_output=True,
timeout=self.timeout_per_checkpoint_s * len(ds), check=False)
timeout=timeout, check=False)
err = (proc.stderr or b"").decode("utf-8", "replace")[-600:]
if proc.returncode != 0:
raise LaneDBenchHostError(f"{host.name}: lane D bench sweep exited "
Expand All @@ -144,7 +189,9 @@ def __call__(self, digests, suites) -> dict:
reply = json.loads(lines[-1])
except ValueError as e:
raise LaneDBenchHostError(f"{host.name}: reply is not JSON ({e})") from e
return self._checked(reply, ds)
if not isinstance(reply, dict):
raise LaneDBenchHostError(f"not a {REPLY_SCHEMA} reply")
return reply


__all__ = ["REPLY_SCHEMA", "REQUEST_SCHEMA", "SETTINGS_KEYS", "LaneDBenchHostError", "SSHBenchHost",
Expand Down
Loading
Loading