davanstrien's picture
download
raw
6.04 kB
# /// script
# requires-python = ">=3.11"
# dependencies = ["httpx", "datasets", "numpy", "huggingface_hub", "tokenizers"]
# ///
"""Throughput client for a sys1 server exposed on HF Jobs. Same pages and questions as laya_engine_bench.py."""
import argparse
import asyncio
import json
import time
import httpx
import numpy as np
from datasets import load_dataset
from huggingface_hub import get_token
EDU = {"type": "score", "instructions": "How educational is this web page? Rate its value for teaching or learning.",
"criteria": ["no educational value: ads, entertainment, personal or social content",
"minimal: a few incidental facts, mostly not educational",
"basic: tries to explain something, but scattered or mixed with other content",
"good: clear teaching purpose, well organised, suitable for learning",
"excellent: outstanding teaching material, thorough, with examples"]}
PROB = {"type": "noul", "instructions": "Is this text unreadable, corrupted, machine-generated spam, or inappropriate?"}
async def run(client, url, texts, qs, concurrency):
sem = asyncio.Semaphore(concurrency)
out = [None] * len(texts)
errors = []
async def one(i):
async with sem:
# sys1 truncates to max_len tokens; trim very long pages client-side to keep uploads small
body = {"state": texts[i][:6000], "questions": qs}
for attempt in range(3):
try:
r = await client.post(f"{url}/v1/systemone", json=body, timeout=120)
r.raise_for_status()
out[i] = r.json()
return
except Exception as e: # noqa: BLE001
if attempt == 2:
errors.append(repr(e)[:200])
t = time.perf_counter()
await asyncio.gather(*(one(i) for i in range(len(texts))))
return out, time.perf_counter() - t, errors
async def metrics(client, url):
# v0.0.3 returns JSON; main returns Prometheus text, which is skipped here
try:
return (await client.get(f"{url}/metrics")).json()
except ValueError:
return {}
async def main():
ap = argparse.ArgumentParser()
ap.add_argument("url")
ap.add_argument("--n", type=int, default=2048)
ap.add_argument("--sort", action="store_true", help="send pages in token-length order")
ap.add_argument("--only-full", action="store_true", help="keep only pages that reach the 512-token cap")
ap.add_argument("--label", default="sys1")
ap.add_argument("--concurrency", type=int, default=64)
ap.add_argument("--questions", default="1,3")
ap.add_argument("--out", default="sys1_bench_results.json")
args = ap.parse_args()
ds = load_dataset("WebOrganizer/FormatAnnotations-Llama-3.1-405B-FP8", split="test").shuffle(seed=0)
ds = ds.select(range(args.n))
texts, gold = list(ds["text"]), list(ds["top_choice_index"])
from tokenizers import Tokenizer
tok = Tokenizer.from_pretrained("answerdotai/ModernBERT-large")
lens = [min(len(e.ids), 512) for e in tok.encode_batch([t[:6000] for t in texts])]
order = list(range(len(texts)))
if args.only_full:
order = [i for i in order if lens[i] >= 512]
if args.sort:
order.sort(key=lambda i: -lens[i])
texts, gold_sel = [texts[i] for i in order], [gold[i] for i in order]
print("pages:", len(texts), "mean tokens:", float(np.mean([lens[i] for i in order])), flush=True)
names = {}
for i, c in zip(gold, ds["top_choice"], strict=True):
names.setdefault(i, c.split("\n")[0].strip())
names = [names.get(i, f"format {i}") for i in range(24)]
fmt = {"type": "choice", "instructions": "Which format best describes this web page?",
"criteria": {n: "" for n in names}}
headers = {"Authorization": f"Bearer {get_token()}"}
limits = httpx.Limits(max_connections=256, max_keepalive_connections=256)
async with httpx.AsyncClient(headers=headers, limits=limits, http2=False) as client:
print("health:", (await client.get(f"{args.url}/health")).text[:200], flush=True)
# one example response before the timed runs
ex = await client.post(f"{args.url}/v1/systemone",
json={"state": texts[0][:6000], "questions": {"format": fmt}}, timeout=120)
print("example:", ex.text[:400], flush=True)
results = []
for nq, qs in ((1, {"edu": EDU}), (3, {"edu": EDU, "problematic": PROB, "format": fmt})):
if str(nq) not in args.questions.split(","):
continue
for conc in (args.concurrency,):
await run(client, args.url, texts[:min(128, 2 * conc)], qs, conc) # warm-up
m0 = await metrics(client, args.url)
out, dt, errors = await run(client, args.url, texts, qs, conc)
m1 = await metrics(client, args.url)
ok = [o for o in out if o]
r = {"engine": args.label, "sorted": args.sort, "only_full": args.only_full, "concurrency": conc, "questions": nq, "docs": len(ok),
"errors": len(errors), "seconds": dt, "docs_per_s": len(ok) / dt,
"decisions_per_s": nq * len(ok) / dt,
"metrics_delta": {k: m1[k] - m0[k] for k in m1 if isinstance(m1[k], (int, float))
and isinstance(m0.get(k), (int, float))}}
if nq == 3:
r["format_top1_vs_405b"] = float(np.mean(
[o is not None and names.index(o["answers"]["format"]["choice"]) == g
for o, g in zip(out, gold_sel, strict=True)]))
if errors:
r["first_error"] = errors[0]
print("TP", json.dumps(r), flush=True)
results.append(r)
with open(args.out, "w") as fh:
json.dump(results, fh, indent=1)
if __name__ == "__main__":
asyncio.run(main())

Xet Storage Details

Size:
6.04 kB
·
Xet hash:
cc01f1197fc20358c466ab357fefd6d951bb8cbca2e047ac372c96c36ef6b252

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.