File size: 22,101 Bytes
17b0632 | 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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 | """A/B runtime comparison of two OpenAI-compatible endpoints on the same prompts.
Runs pipeline/eval_openai.py once per endpoint (via its ``evaluate`` function
when importable, otherwise as a subprocess) and compares the two result sets.
Usage:
python pipeline/runtime_ab.py ^
--base-url-a http://127.0.0.1:8080/v1 --label-a "base Q8_0" ^
--base-url-b http://127.0.0.1:8081/v1 --label-b "tuned Q8_0" ^
--data data_native/test.jsonl --limit 100 --out reports/runtime_ab
Outputs:
<out>.md two-column metrics table (A vs B), per-category deltas,
per-prompt agreement rate, disagreement count, mean
latency + tok/s from usage.
<out>.json the same numbers in raw form.
Assumes pipeline/eval_openai.py and pipeline/metrics_lib.py exist
(this script is not responsible for creating them).
"""
import argparse
import importlib.util
import inspect
import json
import subprocess
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
EVAL_SCRIPT = HERE / "eval_openai.py"
try:
import requests
except ImportError: # pragma: no cover
requests = None
# ---------------------------------------------------------------- health check
def check_endpoint(base_url, label):
"""Return (ok, detail). Never raises: unreachable -> (False, reason)."""
url = base_url.rstrip("/") + "/models"
if requests is None:
return False, "the 'requests' package is not installed"
try:
r = requests.get(url, timeout=10)
if r.status_code < 500:
return True, f"HTTP {r.status_code}"
return False, f"HTTP {r.status_code}: {r.text[:200]}"
except Exception as e: # connection refused, timeout, DNS, ...
return False, f"{type(e).__name__}: {e}"
def start_hint(base_url):
try:
from urllib.parse import urlparse
port = urlparse(base_url).port or 8080
except Exception:
port = 8080
return (
f"llama-server -m <model.gguf> --port {port} "
f"--jinja -c 2048 -ngl 0 # or: .\\pipeline\\start_servers.ps1"
)
def fail_unreachable(problems):
print("ERROR: one or more endpoints are unreachable.\n", file=sys.stderr)
for label, base_url, detail in problems:
print(f" [{label}] {base_url}\n reason: {detail}", file=sys.stderr)
print(f" start it, e.g.: {start_hint(base_url)}\n", file=sys.stderr)
print(
"Fix the endpoints above, then re-run the same runtime_ab.py command.",
file=sys.stderr,
)
sys.exit(2)
# --------------------------------------------------------------- run one side
def _try_import_evaluate():
"""Return the evaluate callable from eval_openai.py, or None."""
if not EVAL_SCRIPT.exists():
return None
try:
spec = importlib.util.spec_from_file_location("eval_openai_mod", EVAL_SCRIPT)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
except Exception:
return None
for name in ("evaluate", "run_eval", "main"):
fn = getattr(mod, name, None)
if callable(fn):
return fn
return None
def _call_imported_evaluate(fn, base_url, model, data, limit, out_dir):
"""Call evaluate() with whatever kwargs it accepts. Returns its result."""
sig = inspect.signature(fn)
kwargs = {}
candidates = {
"base_url": base_url,
"baseurl": base_url,
"url": base_url,
"model": model,
"model_name": model,
"data": data,
"data_path": data,
"limit": limit,
"max_n": limit,
"n": limit,
"out": str(out_dir),
"out_dir": str(out_dir),
"outdir": str(out_dir),
"output_dir": str(out_dir),
}
params = sig.parameters
accepts_kwargs = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values())
for pname, p in params.items():
for key, val in candidates.items():
if pname == key or (accepts_kwargs and pname in candidates):
kwargs[pname] = val
break
# fill the obvious positional slots if the signature is positional-only
args = []
if not kwargs and params:
vals = [base_url, model, str(data), limit, str(out_dir)]
for i, pname in enumerate(params):
if i < len(vals):
args.append(vals[i])
if args:
return fn(*args)
return fn(**kwargs)
def run_eval_side(base_url, label, model, data, limit, tmp_root, timeout_s):
"""Evaluate one endpoint. Returns the output directory Path.
Prefers the imported evaluate() function; falls back to a subprocess
call of pipeline/eval_openai.py.
"""
out_dir = tmp_root / ("eval_" + "".join(c if c.isalnum() else "_" for c in label))
out_dir.mkdir(parents=True, exist_ok=True)
fn = _try_import_evaluate()
if fn is not None and fn.__name__ != "main":
try:
_call_imported_evaluate(fn, base_url, model, data, limit, out_dir)
return out_dir
except SystemExit as e: # evaluate() called sys.exit on its own
if e.code not in (None, 0):
raise RuntimeError(f"evaluate() for [{label}] exited with {e.code}")
return out_dir
except Exception as e:
print(
f"WARN: imported evaluate() failed for [{label}] ({e}); "
"falling back to subprocess.",
file=sys.stderr,
)
if not EVAL_SCRIPT.exists():
raise RuntimeError(
f"Cannot evaluate [{label}]: pipeline/eval_openai.py not found "
"and no usable evaluate() import. "
"(runtime_ab.py assumes pipeline/eval_openai.py exists.)"
)
cmd = [
sys.executable, str(EVAL_SCRIPT),
"--base-url", base_url,
"--model", model,
"--data", str(data),
"--limit", str(limit),
"--out", str(out_dir),
]
try:
subprocess.run(cmd, check=True, timeout=timeout_s)
except subprocess.CalledProcessError as e:
raise RuntimeError(
f"eval_openai.py subprocess for [{label}] failed "
f"(exit {e.returncode}). Command: {' '.join(cmd)}"
)
return out_dir
# --------------------------------------------------------------- load results
def _load_json(path):
try:
with open(path, encoding="utf-8") as f:
return json.load(f)
except Exception:
return None
def find_metrics(out_dir):
"""Find the metrics dict produced by eval_openai.py (best effort)."""
for name in ("metrics.json", "summary.json", "results.json", "eval.json"):
d = _load_json(out_dir / name)
if isinstance(d, dict):
# unwrap common envelopes: {"metrics": {...}}, {"summary": {...}}
for key in ("metrics", "summary", "scores", "results"):
if isinstance(d.get(key), dict) and d.get(key):
inner = d[key]
if any(isinstance(v, (int, float)) for v in inner.values()):
return inner
if any(isinstance(v, (int, float)) for v in d.values()):
return d
for p in sorted(out_dir.glob("*.json")):
d = _load_json(p)
if isinstance(d, dict) and any(isinstance(v, (int, float)) for v in d.values()):
return d
return {}
def find_predictions(out_dir):
"""Find per-prompt records (list of dicts), best effort."""
for name in ("predictions.jsonl", "outputs.jsonl", "results.jsonl",
"preds.jsonl", "completions.jsonl"):
p = out_dir / name
if p.exists():
rows = []
with open(p, encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
try:
rows.append(json.loads(line))
except Exception:
pass
if rows:
return rows
for p in sorted(out_dir.glob("*.jsonl")):
rows = []
with open(p, encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
try:
rows.append(json.loads(line))
except Exception:
pass
if rows and isinstance(rows[0], dict):
return rows
for p in sorted(out_dir.glob("*.json")):
d = _load_json(p)
if isinstance(d, list) and d and isinstance(d[0], dict):
return d
if isinstance(d, dict):
for key in ("predictions", "outputs", "rows", "data", "items"):
v = d.get(key)
if isinstance(v, list) and v and isinstance(v[0], dict):
return v
return []
def norm_output(rec):
for key in ("output", "prediction", "completion", "text", "response", "pred"):
v = rec.get(key)
if isinstance(v, str) and v.strip():
return v.strip()
if v is not None and not isinstance(v, str):
return json.dumps(v, sort_keys=True, ensure_ascii=False)
# OpenAI-style message envelope
msg = rec.get("message")
if isinstance(msg, dict):
tc = msg.get("tool_calls")
if tc:
return json.dumps(tc, sort_keys=True, ensure_ascii=False)
c = msg.get("content")
if isinstance(c, str):
return c.strip()
tc = rec.get("tool_calls")
if tc:
return json.dumps(tc, sort_keys=True, ensure_ascii=False)
return ""
def rec_latency(rec):
for key in ("latency_s", "latency", "elapsed_s", "elapsed", "duration_s",
"request_time_s"):
v = rec.get(key)
if isinstance(v, (int, float)):
return float(v)
return None
def rec_completion_tokens(rec):
u = rec.get("usage")
if isinstance(u, dict):
for key in ("completion_tokens", "output_tokens", "generated_tokens"):
v = u.get(key)
if isinstance(v, (int, float)):
return float(v)
for key in ("completion_tokens", "output_tokens", "num_tokens"):
v = rec.get(key)
if isinstance(v, (int, float)):
return float(v)
return None
def rec_score(rec):
for key in ("score", "correct", "exact_match", "passed", "ok", "accuracy"):
v = rec.get(key)
if isinstance(v, bool):
return float(v)
if isinstance(v, (int, float)):
return float(v)
return None
def rec_category(rec, i):
for key in ("category", "split", "task", "domain", "dataset"):
v = rec.get(key)
if v:
return str(v)
return "all"
def mean(xs):
xs = [x for x in xs if x is not None]
return sum(xs) / len(xs) if xs else None
def fmt(x, digits=4):
if x is None:
return "n/a"
if isinstance(x, float):
return f"{x:.{digits}f}"
return str(x)
def fmt_delta(d, digits=4):
if d is None:
return "n/a"
sign = "+" if d >= 0 else ""
return f"{sign}{d:.{digits}f}"
# ------------------------------------------------------------------- main
def parse_args(argv=None):
p = argparse.ArgumentParser(
description="Compare two OpenAI-compatible endpoints on the same prompts.")
p.add_argument("--base-url-a", required=True,
help="Base URL of endpoint A, e.g. http://127.0.0.1:8080/v1")
p.add_argument("--label-a", default="A", help="Display label for A")
p.add_argument("--base-url-b", required=True,
help="Base URL of endpoint B, e.g. http://127.0.0.1:8081/v1")
p.add_argument("--label-b", default="B", help="Display label for B")
p.add_argument("--data", default="data_native/test.jsonl",
help="Prompt file evaluated by eval_openai.py")
p.add_argument("--limit", type=int, default=100,
help="Max prompts per endpoint (default: 100)")
p.add_argument("--model", default="local",
help="Model name sent to the servers (default: local)")
p.add_argument("--out", default="reports/runtime_ab",
help="Output prefix; writes <out>.md and <out>.json")
p.add_argument("--timeout", type=int, default=600,
help="Per-endpoint eval timeout in seconds (subprocess mode)")
return p.parse_args(argv)
def main(argv=None):
args = parse_args(argv)
# 1) Reachability first: clean error, no traceback.
problems = []
for label, url in ((args.label_a, args.base_url_a),
(args.label_b, args.base_url_b)):
ok, detail = check_endpoint(url, label)
print(f"[{label}] {url} -> {'OK' if ok else 'UNREACHABLE'} ({detail})",
flush=True)
if not ok:
problems.append((label, url, detail))
if problems:
fail_unreachable(problems)
# 2) Evaluate each side into a temp dir.
with tempfile.TemporaryDirectory(prefix="runtime_ab_") as tmp:
tmp_root = Path(tmp)
try:
dir_a = run_eval_side(args.base_url_a, args.label_a, args.model,
args.data, args.limit, tmp_root, args.timeout)
dir_b = run_eval_side(args.base_url_b, args.label_b, args.model,
args.data, args.limit, tmp_root, args.timeout)
except RuntimeError as e:
print(f"ERROR: {e}", file=sys.stderr)
sys.exit(3)
metrics_a, metrics_b = find_metrics(dir_a), find_metrics(dir_b)
preds_a, preds_b = find_predictions(dir_a), find_predictions(dir_b)
# 3) Aggregate comparison.
n = max(len(preds_a), len(preds_b))
if not n:
# eval produced metrics but no per-prompt file; still report metrics
n = args.limit
lat_a = [rec_latency(r) for r in preds_a]
lat_b = [rec_latency(r) for r in preds_b]
tok_a = [rec_completion_tokens(r) for r in preds_a]
tok_b = [rec_completion_tokens(r) for r in preds_b]
tps_a = [t / l for t, l in zip(tok_a, lat_a)
if t is not None and l not in (None, 0)]
tps_b = [t / l for t, l in zip(tok_b, lat_b)
if t is not None and l not in (None, 0)]
mean_lat_a, mean_lat_b = mean(lat_a), mean(lat_b)
mean_tps_a, mean_tps_b = mean(tps_a), mean(tps_b)
# Per-prompt agreement (pair by index; ids when available).
def rec_id(rec, i):
for key in ("id", "prompt_id", "idx", "index"):
if rec.get(key) is not None:
return str(rec[key])
return f"prompt_{i}"
m = min(len(preds_a), len(preds_b))
agree, disagreements = 0, []
for i in range(m):
oa, ob = norm_output(preds_a[i]), norm_output(preds_b[i])
if oa == ob:
agree += 1
else:
disagreements.append(rec_id(preds_a[i], i))
agreement_rate = (agree / m) if m else None
# Per-category score deltas (uses per-prompt scores when the eval
# records them; otherwise falls back to n/agreement per category).
cats = {}
for i in range(m):
c = rec_category(preds_a[i], i)
sa, sb = rec_score(preds_a[i]), rec_score(preds_b[i])
cats.setdefault(c, {"n": 0, "sa": [], "sb": [],
"agree": 0, "total": 0})
cats[c]["n"] += 1
cats[c]["total"] += 1
if norm_output(preds_a[i]) == norm_output(preds_b[i]):
cats[c]["agree"] += 1
if sa is not None:
cats[c]["sa"].append(sa)
if sb is not None:
cats[c]["sb"].append(sb)
have_scores = any(c["sa"] or c["sb"] for c in cats.values())
# Metrics union table (numeric entries from each metrics.json).
metric_keys = [k for k in metrics_a.keys() | metrics_b.keys()]
metric_keys.sort()
rows = []
for k in metric_keys:
va, vb = metrics_a.get(k), metrics_b.get(k)
if isinstance(va, (int, float)) and isinstance(vb, (int, float)):
d = vb - va
else:
d = None
rows.append((k, va, vb, d))
result = {
"label_a": args.label_a,
"label_b": args.label_b,
"base_url_a": args.base_url_a,
"base_url_b": args.base_url_b,
"model": args.model,
"data": str(args.data),
"limit": args.limit,
"n_compared": m,
"n_a": len(preds_a),
"n_b": len(preds_b),
"metrics_a": metrics_a,
"metrics_b": metrics_b,
"metric_deltas_b_minus_a": {
k: d for k, _, _, d in rows if d is not None
},
"agreement_rate": agreement_rate,
"agreement_count": agree,
"disagreement_count": len(disagreements),
"disagreement_ids": disagreements[:50],
"mean_latency_s": {"a": mean_lat_a, "b": mean_lat_b},
"mean_tok_per_s": {"a": mean_tps_a, "b": mean_tps_b},
"per_category": {
c: {
"n": v["n"],
"mean_score_a": mean(v["sa"]),
"mean_score_b": mean(v["sb"]),
"delta_b_minus_a": (
(mean(v["sb"]) - mean(v["sa"]))
if v["sa"] and v["sb"] else None
),
"agreement_rate": (v["agree"] / v["total"]) if v["total"] else None,
}
for c, v in sorted(cats.items())
},
}
# 4) Write <out>.json and <out>.md.
out_prefix = Path(args.out)
out_prefix.parent.mkdir(parents=True, exist_ok=True)
with open(str(out_prefix) + ".json", "w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
la, lb = args.label_a, args.label_b
L = []
L.append(f"# Runtime A/B: {la} vs {lb}")
L.append("")
L.append(f"- A: `{args.base_url_a}` ({la})")
L.append(f"- B: `{args.base_url_b}` ({lb})")
L.append(f"- model: `{args.model}`, data: `{args.data}`, "
f"limit: {args.limit}, compared: {m}")
L.append("")
L.append("## Metrics (A vs B)")
L.append("")
L.append(f"| metric | {la} (A) | {lb} (B) | delta (B-A) |")
L.append("|---|---|---|---|")
if rows:
for k, va, vb, d in rows:
L.append(f"| {k} | {fmt(va)} | {fmt(vb)} | {fmt_delta(d)} |")
else:
L.append("| _no numeric metrics found in eval output_ | n/a | n/a | n/a |")
L.append("")
L.append("## Per-category deltas")
L.append("")
if cats:
if have_scores:
L.append("| category | n | mean A | mean B | delta (B-A) | agree |")
L.append("|---|---|---|---|---|---|")
for c in sorted(cats):
v = result["per_category"][c]
L.append(f"| {c} | {v['n']} | {fmt(v['mean_score_a'])} | "
f"{fmt(v['mean_score_b'])} | "
f"{fmt_delta(v['delta_b_minus_a'])} | "
f"{fmt(v['agreement_rate'])} |")
else:
L.append("_Per-prompt scores not recorded by the eval; "
"showing n and A-vs-B agreement per category._")
L.append("")
L.append("| category | n | agreement | |")
L.append("|---|---|---|---|")
for c in sorted(cats):
v = result["per_category"][c]
L.append(f"| {c} | {v['n']} | {fmt(v['agreement_rate'])} | |")
else:
L.append("_No per-prompt records found; per-category breakdown "
"unavailable._")
L.append("")
L.append("## Agreement")
L.append("")
L.append(f"- per-prompt agreement rate: **{fmt(agreement_rate)}** "
f"({agree}/{m})")
L.append(f"- disagreement count: **{len(disagreements)}**")
if disagreements:
shown = disagreements[:10]
L.append(f"- first disagreements: {', '.join(shown)}"
+ (" ..." if len(disagreements) > 10 else ""))
L.append("")
L.append("## Latency / throughput (from usage)")
L.append("")
L.append(f"| side | mean latency (s) | mean tok/s | n timed |")
L.append("|---|---|---|---|")
L.append(f"| {la} (A) | {fmt(mean_lat_a)} | {fmt(mean_tps_a)} | "
f"{len([x for x in lat_a if x is not None])} |")
L.append(f"| {lb} (B) | {fmt(mean_lat_b)} | {fmt(mean_tps_b)} | "
f"{len([x for x in lat_b if x is not None])} |")
if mean_lat_a is None and mean_lat_b is None:
L.append("")
L.append("_No latency/usage fields recorded by the eval; "
"tok/s unavailable._")
L.append("")
L.append("## Reproduce")
L.append("")
L.append("```powershell")
L.append(f".\\pipeline\\start_servers.ps1 -BaseGguf <base.gguf> "
f"-TunedGguf <tuned.gguf> # ports {args.base_url_a} / {args.base_url_b}")
L.append(f"python pipeline/runtime_ab.py --base-url-a {args.base_url_a} "
f"--label-a \"{la}\" --base-url-b {args.base_url_b} "
f"--label-b \"{lb}\" --data {args.data} --limit {args.limit} "
f"--out {args.out}")
L.append("```")
L.append("")
with open(str(out_prefix) + ".md", "w", encoding="utf-8") as f:
f.write("\n".join(L))
print(f"Wrote {args.out}.md and {args.out}.json (compared {m} prompts).")
return 0
if __name__ == "__main__":
sys.exit(main())
|