"""Latency protocol of the T4 notebook (section 7), for any scorer with ``predict(records)``. One fixed support-ticket state, 1 / 5 / 10 / 50 questions per call (odd = noul urgency question, even = 3-way routing choice), 3 warm-up calls, 20 timed calls with device synchronisation, p50 / p95 / ms per question. Published numbers are Tesla T4 (CUDA); on the Mac the same protocol runs on MPS/CPU, so compare scorers measured here with each other, not with the T4 JSON. TorchScorer scores each question as its own sequence (no shared-prefix reuse); the Mac runtime's shared-state path is measured by the runtime package. PYTHONPATH=src python -m macjev.eval.latency --laya english,multilingual,typed [--weights Qwen/Qwen3.5-0.8B-Base] """ from __future__ import annotations import argparse import json import time import numpy as np import torch from ..schema import make_record LAT_STATE = {"ticket": {"subject": "Payout failing", "messages": [{"from": "customer", "text": "Hi, my Stripe payouts have failed for 3 days and I am losing sales. " "Please help ASAP. " * 6}]}} Q_NOUL = {"t": "noul", "ins": "Does `ticket.messages[0].text` express urgency?", "crit": None} Q_CHOICE = {"t": "choice", "ins": "Which team should handle this?", "crit": {"billing": "payments", "technical": "bugs and integrations", "sales": "pricing"}} def records(nq: int) -> list[dict]: out = [] for i in range(nq): q = Q_NOUL if i % 2 else Q_CHOICE out.append(make_record(id=f"lat:{nq}:{i}", group_id="lat", split="test", source="latency", category="theme_triage", lang="en", license="generated:latency-probe", state=LAT_STATE, question=dict(q), valid=["true" if q["t"] == "noul" else "technical"])) return out def _sync(device: torch.device): if device.type == "cuda": torch.cuda.synchronize() elif device.type == "mps": torch.mps.synchronize() def measure(scorer, n_questions=(1, 5, 10, 50), warmup: int = 3, reps: int = 20) -> dict: res = {} dev = getattr(scorer, "device", torch.device("cpu")) for nq in n_questions: recs = records(nq) for _ in range(warmup): scorer.predict(recs) ts = [] for _ in range(reps): _sync(dev) t = time.perf_counter() scorer.predict(recs) _sync(dev) ts.append((time.perf_counter() - t) * 1000) p50 = float(np.percentile(ts, 50)) res[f"{nq}_questions"] = {"p50_ms": round(p50, 1), "p95_ms": round(float(np.percentile(ts, 95)), 1), "ms_per_question": round(p50 / nq, 2)} return res def main(argv=None): ap = argparse.ArgumentParser() ap.add_argument("--laya", default="") ap.add_argument("--weights", default=None) ap.add_argument("--readout", default="verdict") ap.add_argument("--device", default=None) ap.add_argument("--out", default=None) a = ap.parse_args(argv) out = {"protocol": "T4 notebook section 7 (3 warm-up, 20 timed, p50/p95)", "results": {}} for w in [x for x in a.laya.split(",") if x]: from .laya_scorer import LayaScorer sc = LayaScorer(w, device=a.device) out["results"][f"laya-{w}"] = {"device": str(sc.device), **measure(sc)} print(json.dumps({w: out["results"][f"laya-{w}"]}), flush=True) del sc if a.weights: from .torch_scorer import TorchScorer sc = TorchScorer(a.weights, readout=a.readout, device=a.device) out["results"][sc.name] = {"device": str(sc.device), "dtype": sc.dtype_name, **measure(sc)} print(json.dumps({sc.name: out["results"][sc.name]}), flush=True) if a.out: from pathlib import Path Path(a.out).write_text(json.dumps(out, indent=1) + "\n") if __name__ == "__main__": main()