File size: 4,125 Bytes
045aa44 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | """PS-09 benchmark harness: runs a team's encode(), measures throughput, checks cosine tolerance, replays a query trace.
Team file contract: define `encode(texts: list[str]) -> numpy.ndarray` of shape [len(texts), 768], L2-normalised, in
input order. Optional `setup()` is called once before timing (load weights, compile, warm up; not timed).
The same `encode` is called with the whole passage list (batch run) and with one query at a time (live trace).
Usage: python bench.py --team team.py --passages practice_passages.jsonl --ref ref.npy
[--trace practice_trace.jsonl --ref-queries ref_queries.npy] [--ref-throughput FILE] --out result.json
"""
import argparse, hashlib, importlib.util, json, sys, time
from pathlib import Path
import numpy as np
TOLERANCE = 0.999
def sha(p):
return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def cos_check(got, ref, tol):
got = np.asarray(got, dtype=np.float32); ref = np.asarray(ref, dtype=np.float32)
if got.shape != ref.shape or not np.isfinite(got).all():
return {"shape_ok": False, "n_violations": int(len(ref)), "min_cosine": None}
c = (got * ref).sum(1) / (np.linalg.norm(got, axis=1) * np.linalg.norm(ref, axis=1))
return {"shape_ok": True, "n_violations": int((c < tol).sum()), "min_cosine": float(c.min())}
def live(encode, trace, ref_q, tol):
"""Replay arrivals in real time; one query at a time, FIFO, so a burst makes later queries wait."""
lat, outs, start = [], [], time.perf_counter()
for r in trace:
wait = r["t"] - (time.perf_counter() - start)
if wait > 0:
time.sleep(wait)
outs.append(np.asarray(encode([r["text"]]))[0])
lat.append((time.perf_counter() - start - r["t"]) * 1000)
res = {"n": len(lat), "p50_ms": float(np.percentile(lat, 50)), "p99_ms": float(np.percentile(lat, 99))}
if ref_q is not None:
res.update(cos_check(np.stack(outs), ref_q, tol))
return res
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--team", required=True); ap.add_argument("--passages", required=True)
ap.add_argument("--ref", required=True, help="reference embeddings .npy for the passages (or first K of them)")
ap.add_argument("--trace"); ap.add_argument("--ref-queries")
ap.add_argument("--ref-throughput", help="JSON with passages_per_second of reference.py on this machine")
ap.add_argument("--limit", type=int, help="use only the first N passages (smoke test)")
ap.add_argument("--tolerance", type=float, default=TOLERANCE); ap.add_argument("--out", required=True)
a = ap.parse_args()
sys.path.insert(0, str(Path(a.team).resolve().parent))
spec = importlib.util.spec_from_file_location("team_encode", a.team)
mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
t = time.time()
if hasattr(mod, "setup"):
mod.setup()
setup_s = time.time() - t
texts = [json.loads(l)["text"] for l in open(a.passages)][: a.limit]
ref = np.load(a.ref)[: a.limit]
t = time.perf_counter(); emb = mod.encode(texts); secs = time.perf_counter() - t
res = {"n_passages": len(texts), "seconds": secs, "passages_per_second": len(texts) / secs, "setup_seconds": setup_s,
"tolerance": a.tolerance, "passages_sha256": sha(a.passages)}
# Reference may cover only the first K passages (a subset); throughput still uses all of them.
res.update(cos_check(np.asarray(emb)[: len(ref)], ref, a.tolerance) if len(emb) >= len(ref)
else {"shape_ok": False, "n_violations": len(ref), "min_cosine": None})
res["n_checked"] = int(len(ref))
if a.ref_throughput:
res["reference_passages_per_second"] = json.load(open(a.ref_throughput))["passages_per_second"]
res["speedup"] = res["passages_per_second"] / res["reference_passages_per_second"]
if a.trace:
trace = [json.loads(l) for l in open(a.trace)]
res["live"] = live(mod.encode, trace, np.load(a.ref_queries) if a.ref_queries else None, a.tolerance)
json.dump(res, open(a.out, "w"), indent=1)
print(json.dumps(res, indent=1))
|