Recipes for running the bench-standard models fastest on Intel Arc GPUs, each backed by a bench.sh result folder in results/. tools/cookbook.py validates recipes against their runs and generates the number tables and site/index.html. All results are synthetic DEMO data so far, made by tools/demo/make_demo.py; nothing has been measured yet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
4673f0afb6
151 files changed
+87304
No files matched your search
@@ -0,0 +1,757 @@
|
||||
#!/usr/bin/env python3
|
||||
"""cookbook.py - checks every recipe against its benchmark results, and builds
|
||||
what is generated from them: the number tables in the Markdown files and
|
||||
site/index.html.
|
||||
|
||||
usage: cookbook.py validate
|
||||
cookbook.py build [--check]
|
||||
|
||||
validate prints errors and warnings; exits 1 on any error.
|
||||
build validates, then rewrites the generated blocks and site/index.html.
|
||||
With --check it writes nothing and exits 1 when a file is out of
|
||||
date (CI).
|
||||
|
||||
Standard library only (Python 3.11+).
|
||||
"""
|
||||
import datetime as dt
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import statistics
|
||||
import sys
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
# profile: (metric, label, unit, higher is better)
|
||||
PROFILES = {
|
||||
"single-user": ("decode_tps", "decode at batch 1", "t/s", True),
|
||||
"throughput": ("peak_tps", "peak aggregate throughput", "t/s", True),
|
||||
"long-context": ("prefill_tps", "prefill at the deepest context", "t/s", True),
|
||||
"efficiency": ("decode_j_per_token", "decode energy", "J/tok", False),
|
||||
}
|
||||
FIELDS = ("title", "summary", "model", "quant", "kv", "engine", "gpu", "profile",
|
||||
"spec", "thinking", "results")
|
||||
ZERO_DIGEST = "0" * 64
|
||||
|
||||
|
||||
def slug(s):
|
||||
"""bench.sh's file-name slug."""
|
||||
return re.sub(r"[^a-z0-9.]+", "-", s.lower()).strip("-")
|
||||
|
||||
|
||||
def anchor(s):
|
||||
return re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-")
|
||||
|
||||
|
||||
def redact(s):
|
||||
"""bench.sh's redaction of server-cmd.txt, so a recipe compares equal."""
|
||||
s = re.sub(r'(?i)\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY)[A-Z0-9_]*=)\S+',
|
||||
r'\1<redacted>', s)
|
||||
return re.sub(r'(?i)(--(?:api-key|hf-token|token)[= ])\S+', r'\1<redacted>', s)
|
||||
|
||||
|
||||
def command_words(s):
|
||||
"""A launch command as words: comments, line continuations and spacing
|
||||
don't matter, and secrets are redacted the way bench.sh does it."""
|
||||
s = redact(s).replace("\\\n", " ")
|
||||
s = "\n".join(l for l in s.splitlines() if not l.lstrip().startswith("#"))
|
||||
return shlex.split(s)
|
||||
|
||||
|
||||
FRONT = re.compile(r"\A\+\+\+\n(.*?)\n\+\+\+\n", re.S)
|
||||
|
||||
|
||||
def split_front(text):
|
||||
m = FRONT.match(text)
|
||||
if not m:
|
||||
raise ValueError("no TOML front matter between +++ lines")
|
||||
return tomllib.loads(m.group(1)), text[m.end():]
|
||||
|
||||
|
||||
def fill(text, name, content):
|
||||
"""Replace the generated block <!-- cookbook:NAME --> ... <!-- /cookbook:NAME -->."""
|
||||
pat = re.compile(rf"(<!-- cookbook:{name} -->\n).*?(<!-- /cookbook:{name} -->)", re.S)
|
||||
if not pat.search(text):
|
||||
raise ValueError(f"no <!-- cookbook:{name} --> block")
|
||||
return pat.sub(lambda m: m.group(1) + content.rstrip("\n") + "\n" + m.group(2), text, count=1)
|
||||
|
||||
|
||||
def launch_block(body):
|
||||
"""The first ```sh block under '## Launch'."""
|
||||
m = re.search(r"^## Launch[ \t]*\n(.*?)(?=^## |\Z)", body, re.M | re.S)
|
||||
c = m and re.search(r"^```(?:sh|bash)[ \t]*\n(.*?)^```", m.group(1), re.M | re.S)
|
||||
return c.group(1) if c else None
|
||||
|
||||
|
||||
def median(xs):
|
||||
xs = [x for x in xs if x is not None]
|
||||
return statistics.median(xs) if xs else None
|
||||
|
||||
|
||||
def metrics(meta, res):
|
||||
"""The headline figures of one run, computed the way bench.sh's summary does."""
|
||||
single = [r for recs in (res.get("single_stream") or {}).values() for r in recs
|
||||
if r.get("ok", True)]
|
||||
conc = {int(x["level"]): x["aggregate_tps"] for x in res.get("concurrency") or []
|
||||
if x.get("aggregate_tps")}
|
||||
pre = {int(p["target_depth"]): median(p.get("pp_tps") or [])
|
||||
for p in res.get("prefill") or [] if not p.get("skipped")}
|
||||
pre = {k: v for k, v in pre.items() if v}
|
||||
post = meta.get("post_run") or {}
|
||||
roof = post.get("roofline") or {}
|
||||
decode_e = ((post.get("energy") or {}).get("phases") or {}).get("decode") or {}
|
||||
deepest = max(pre) if pre else None
|
||||
return {"decode_tps": median([r.get("decode_tps") for r in single]),
|
||||
"ttft_ms": median([r.get("ttft_ms") for r in single]),
|
||||
"concurrency": conc, "peak_tps": max(conc.values()) if conc else None,
|
||||
"prefill": pre, "prefill_depth": deepest, "prefill_tps": pre.get(deepest),
|
||||
"bw_pct": roof.get("pct_of_mem_bw"), "mem_bw_gbs": roof.get("mem_bw_gbs"),
|
||||
"decode_j_per_token": decode_e.get("j_per_token"), "decode_w": decode_e.get("avg_w")}
|
||||
|
||||
|
||||
def num(x, dec=1):
|
||||
return "—" if x is None else f"{x:,.{dec}f}"
|
||||
|
||||
|
||||
def first_diff(a, b):
|
||||
for i, (x, y) in enumerate(zip(a, b)):
|
||||
if x != y:
|
||||
return f"word {i + 1}: {x!r} vs {y!r}"
|
||||
return f"{len(a)} vs {len(b)} words"
|
||||
|
||||
|
||||
class Cookbook:
|
||||
def __init__(self, root=ROOT):
|
||||
self.root = Path(root)
|
||||
self.errors, self.warnings = [], []
|
||||
self.config = tomllib.loads((self.root / "cookbook.toml").read_text(encoding="utf-8"))
|
||||
self.results = self._load_results()
|
||||
self.recipes = self._load_docs("recipes", self._recipe)
|
||||
self.tried = self._load_docs("tried", self._tried)
|
||||
for r in self.results.values():
|
||||
if not r["used"]:
|
||||
self.warning(f"results/{r['id']}", "not cited by any recipe or tried log")
|
||||
|
||||
def error(self, where, msg):
|
||||
self.errors.append(f"{where}: {msg}")
|
||||
|
||||
def warning(self, where, msg):
|
||||
self.warnings.append(f"{where}: {msg}")
|
||||
|
||||
# ------------------------------------------------------------ loading
|
||||
def _load_results(self):
|
||||
out = {}
|
||||
base = self.root / "results"
|
||||
for d in sorted(p for p in base.iterdir() if p.is_dir()) if base.exists() else []:
|
||||
where = f"results/{d.name}"
|
||||
try:
|
||||
meta = json.loads((d / "meta.json").read_text(encoding="utf-8"))
|
||||
res = json.loads((d / f"{d.name}.json").read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as e:
|
||||
self.error(where, f"unreadable: {e}")
|
||||
continue
|
||||
for f in (f"{d.name}.html", "config.json"):
|
||||
if not (d / f).exists():
|
||||
self.error(where, f"{f} missing")
|
||||
if ((res.get("env") or {}).get("notes") or {}) != meta.get("notes"):
|
||||
self.error(where, "the notes in meta.json and the results file differ (edited?)")
|
||||
m = meta.get("mandatory") or {}
|
||||
cmd = d / "server-cmd.txt"
|
||||
out[d.name] = {"id": d.name, "dir": d, "meta": meta, "res": res,
|
||||
"demo": (d / "DEMO").exists(), "submitter": m.get("submitter"),
|
||||
"full": m.get("run_mode") == "full",
|
||||
"created": (meta.get("created") or "")[:10],
|
||||
"cmd": cmd.read_text(encoding="utf-8") if cmd.exists() else None,
|
||||
"metrics": metrics(meta, res), "used": False}
|
||||
return out
|
||||
|
||||
def _load_docs(self, sub, parse):
|
||||
out = []
|
||||
for p in sorted((self.root / sub).rglob("*.md")):
|
||||
if p.name == "README.md":
|
||||
continue
|
||||
rel = p.relative_to(self.root).as_posix()
|
||||
try:
|
||||
front, body = split_front(p.read_text(encoding="utf-8"))
|
||||
except (ValueError, tomllib.TOMLDecodeError) as e:
|
||||
self.error(rel, str(e))
|
||||
continue
|
||||
doc = parse(rel, p, front, body)
|
||||
if doc:
|
||||
out.append(doc)
|
||||
return out
|
||||
|
||||
def _recipe(self, rel, path, f, body):
|
||||
missing = [k for k in FIELDS if k not in f]
|
||||
if missing:
|
||||
self.error(rel, "front matter lacks " + ", ".join(missing))
|
||||
return None
|
||||
rid = rel[len("recipes/"):-len(".md")]
|
||||
tp, pp = int(f.get("tp", 1)), int(f.get("pp", 1))
|
||||
want = f"{slug(f['model'])}/{slug(f['gpu'])}/{slug(f['engine'])}-{f['profile']}"
|
||||
if rid != want:
|
||||
self.error(rel, f"should be recipes/{want}.md for its model, gpu, engine and profile")
|
||||
if f["profile"] not in PROFILES:
|
||||
self.error(rel, f"profile {f['profile']!r}: use one of {', '.join(PROFILES)}")
|
||||
return None
|
||||
if f["gpu"] not in self.config["gpus"]:
|
||||
self.error(rel, f"gpu {f['gpu']!r} is not an Intel Arc GPU listed in cookbook.toml")
|
||||
if f["model"] not in self.config["models"]:
|
||||
self.error(rel, f"model {f['model']!r} is not a standard model listed in cookbook.toml")
|
||||
cmd = launch_block(body)
|
||||
if cmd is None:
|
||||
self.error(rel, "no ```sh block under '## Launch'")
|
||||
runs = []
|
||||
for rid_ in f["results"]:
|
||||
res = self.results.get(rid_)
|
||||
if res is None:
|
||||
self.error(rel, f"result {rid_} is not in results/")
|
||||
continue
|
||||
res["used"] = True
|
||||
self._check_run(rel, f, tp, pp, res)
|
||||
if cmd is not None:
|
||||
if res["cmd"] is None:
|
||||
self.error(rel, f"{rid_} has no server-cmd.txt")
|
||||
elif command_words(res["cmd"]) != command_words(cmd):
|
||||
self.error(rel, f"{rid_}: its server-cmd.txt is not the recipe's launch command "
|
||||
f"({first_diff(command_words(cmd), command_words(res['cmd']))})")
|
||||
runs.append(res)
|
||||
if not f["results"]:
|
||||
self.error(rel, "no results: every recipe needs at least one --full run")
|
||||
demo = any(r["demo"] for r in runs)
|
||||
if demo and not all(r["demo"] for r in runs):
|
||||
self.error(rel, "mixes DEMO and real results")
|
||||
if cmd and re.search(r"\b(docker|podman)\s+run\b", cmd):
|
||||
digests = re.findall(r"@sha256:([0-9a-f]{64})\b", cmd)
|
||||
if not digests:
|
||||
self.error(rel, "pin the container image by digest (image@sha256:...)")
|
||||
elif ZERO_DIGEST in digests and not demo:
|
||||
self.error(rel, "the image digest is the all-zero placeholder")
|
||||
|
||||
metric, label, _, _ = PROFILES[f["profile"]]
|
||||
status, agreeing = "no runs", []
|
||||
if runs:
|
||||
ref = runs[0]["metrics"][metric]
|
||||
for r in runs:
|
||||
v = r["metrics"][metric]
|
||||
if r is runs[0] or (ref and v and abs(v - ref) / ref * 100 <= self.config["agree_pct"]):
|
||||
agreeing.append(r)
|
||||
else:
|
||||
self.warning(rel, f"{r['id']}: {label} {num(v)} is "
|
||||
f"{num(100 * (v - ref) / ref if ref and v else None)}% off the first run")
|
||||
subs = {r["submitter"] for r in agreeing}
|
||||
status = f"verified by {len(subs)}" if len(subs) >= 2 else "one submitter"
|
||||
newest = max(r["created"] for r in runs)
|
||||
age = (dt.date.today() - dt.date.fromisoformat(newest)).days if newest else 0
|
||||
if age > self.config["stale_after_days"]:
|
||||
self.warning(rel, f"stale: the newest run is {age} days old; re-run it on a current engine")
|
||||
return {"id": rid, "rel": rel, "path": path, "front": f, "body": body, "cmd": cmd,
|
||||
"runs": runs, "demo": demo, "status": status, "tp": tp, "pp": pp,
|
||||
"value": runs[0]["metrics"][metric] if runs else None}
|
||||
|
||||
def _check_run(self, rel, f, tp, pp, res):
|
||||
m = res["meta"].get("mandatory") or {}
|
||||
c = res["meta"].get("collected") or {}
|
||||
notes = res["meta"].get("notes") or {}
|
||||
w = res["id"]
|
||||
if not res["full"]:
|
||||
self.error(rel, f"{w} is a quick run; recipes cite --full runs only")
|
||||
if m.get("bench_standard") not in self.config["bench_standard"]:
|
||||
self.error(rel, f"{w}: bench-standard {m.get('bench_standard')} is not one of "
|
||||
f"{', '.join(self.config['bench_standard'])} (cookbook.toml)")
|
||||
if f"standard: {f['model']} {f['quant']}" not in notes.get("model_file", ""):
|
||||
self.error(rel, f"{w}: not the standard {f['model']} {f['quant']} file "
|
||||
f"(model_file: {notes.get('model_file', 'missing')})")
|
||||
for k in ("quant", "kv", "spec", "thinking"):
|
||||
if m.get(k) != f[k]:
|
||||
self.error(rel, f"{w}: {k} is {f[k]!r} in the recipe but {m.get(k)!r} in the run")
|
||||
if (m.get("tp"), m.get("pp")) != (str(tp), str(pp)):
|
||||
self.error(rel, f"{w}: tp/pp {tp}/{pp} in the recipe but {m.get('tp')}/{m.get('pp')} in the run")
|
||||
self._check_where(rel, f, res)
|
||||
|
||||
def _check_where(self, rel, f, res):
|
||||
c = res["meta"].get("collected") or {}
|
||||
if c.get("gpu_vendor") != "intel" or c.get("gpu_model") != f["gpu"]:
|
||||
self.error(rel, f"{res['id']} ran on {c.get('gpu_vendor')} {c.get('gpu_model')}, "
|
||||
f"not {f['gpu']}")
|
||||
if c.get("engine") != f["engine"]:
|
||||
self.error(rel, f"{res['id']} ran on {c.get('engine')}, not {f['engine']}")
|
||||
|
||||
def _tried(self, rel, path, f, body):
|
||||
for k in ("model", "gpu"):
|
||||
if k not in f:
|
||||
self.error(rel, f"front matter lacks {k}")
|
||||
return None
|
||||
want = f"tried/{slug(f['model'])}/{slug(f['gpu'])}.md"
|
||||
if rel != want:
|
||||
self.error(rel, f"should be {want}")
|
||||
entries = []
|
||||
for t in f.get("tried", []):
|
||||
base = next((r for r in self.recipes if r["id"] == t.get("recipe")), None)
|
||||
res = self.results.get(t.get("result", ""))
|
||||
if base is None:
|
||||
self.error(rel, f"recipe {t.get('recipe')!r} does not exist")
|
||||
continue
|
||||
if res is None:
|
||||
self.error(rel, f"result {t.get('result')!r} is not in results/")
|
||||
continue
|
||||
if not t.get("change"):
|
||||
self.error(rel, f"{res['id']}: say what changed (change = ...)")
|
||||
res["used"] = True
|
||||
bf = base["front"]
|
||||
if (bf["model"], bf["gpu"]) != (f["model"], f["gpu"]):
|
||||
self.error(rel, f"recipe {base['id']} is for another model or GPU")
|
||||
if f"standard: {bf['model']} " not in res["meta"].get("notes", {}).get("model_file", ""):
|
||||
self.error(rel, f"{res['id']}: not the standard {bf['model']} file")
|
||||
self._check_where(rel, bf, res)
|
||||
entries.append({"change": t.get("change", ""), "note": t.get("note", ""),
|
||||
"recipe": base, "result": res})
|
||||
return {"rel": rel, "path": path, "front": f, "body": body, "entries": entries}
|
||||
|
||||
# ------------------------------------------------------------ generated Markdown
|
||||
def link(self, target, src):
|
||||
return Path(os.path.relpath(target, Path(src).parent)).as_posix()
|
||||
|
||||
def numbers_md(self, rc):
|
||||
f = rc["front"]
|
||||
metric, label, unit, _ = PROFILES[f["profile"]]
|
||||
dec = 2 if unit == "J/tok" else 1
|
||||
L = []
|
||||
if rc["demo"]:
|
||||
L += ["> **Demo data.** These numbers are synthetic, made by `tools/demo/make_demo.py` "
|
||||
"to show the layout. Nothing here was measured.", ""]
|
||||
if not rc["runs"]:
|
||||
return "No runs yet."
|
||||
p = rc["runs"][0]["metrics"]
|
||||
n = len(rc["runs"])
|
||||
L += [f"**{label}: {num(rc['value'], dec)} {unit}** · {rc['status']} · "
|
||||
f"{n} run{'s' if n > 1 else ''}", "",
|
||||
"| metric | first run |", "|---|---|",
|
||||
f"| decode at batch 1 (median) | {num(p['decode_tps'])} t/s |",
|
||||
f"| time to first token (median) | {num(p['ttft_ms'], 0)} ms |"]
|
||||
if p["concurrency"]:
|
||||
L.append("| concurrency, aggregate | " + " · ".join(
|
||||
f"{k}: {num(v, 0)}" for k, v in sorted(p["concurrency"].items())) + " t/s |")
|
||||
if p["prefill"]:
|
||||
L.append("| prefill | " + " · ".join(
|
||||
f"{k // 1000}k: {num(v, 0)}" for k, v in sorted(p["prefill"].items())) + " t/s |")
|
||||
if f["spec"] != "none":
|
||||
L.append("| memory bandwidth reached | n/a: speculative decoding makes several tokens "
|
||||
"per pass over the weights |")
|
||||
elif p["bw_pct"] is not None:
|
||||
L.append(f"| memory bandwidth reached | {num(p['bw_pct'], 0)}% of "
|
||||
f"{num(p['mem_bw_gbs'], 0)} GB/s measured |")
|
||||
if p["decode_j_per_token"] is not None:
|
||||
L.append(f"| decode energy | {num(p['decode_j_per_token'], 2)} J/token at "
|
||||
f"{num(p['decode_w'], 0)} W |")
|
||||
L += ["", f"| run | submitter | date | {label} | TTFT | report |", "|---|---|---|---|---|---|"]
|
||||
for r in rc["runs"]:
|
||||
rep = self.link(r["dir"] / f"{r['id']}.html", rc["path"])
|
||||
L.append(f"| `{r['id']}` | {r['submitter']} | {r['created']} | "
|
||||
f"{num(r['metrics'][metric], dec)} {unit} | {num(r['metrics']['ttft_ms'], 0)} ms | "
|
||||
f"[html]({rep}) |")
|
||||
meta = rc["runs"][0]["meta"]
|
||||
L += ["", "Reproduce it: start the server with the launch command below, save that command "
|
||||
"as `server-cmd.txt`, then run "
|
||||
"[bench-standard](https://git.linxweiler.xyz/miga/benchmarks):", "", "```sh",
|
||||
f"./bench.sh --endpoint {meta.get('endpoint', 'URL')} --model {meta.get('model', 'ID')} \\",
|
||||
f" --tp {rc['tp']} --pp {rc['pp']} --quant {f['quant']} --kv {f['kv']} "
|
||||
f"--spec {f['spec']} --thinking {f['thinking']} \\",
|
||||
" --submitter YOUR_NAME --server-cmd-file server-cmd.txt --full", "```"]
|
||||
return "\n".join(L)
|
||||
|
||||
def tried_md(self, td):
|
||||
L = ["Quick runs unless marked full: good for a direction, not for exact numbers.", "",
|
||||
"| change | decode t/s | TTFT | peak t/s | vs. the recipe | run |", "|---|---|---|---|---|---|"]
|
||||
for e in td["entries"]:
|
||||
rc, r = e["recipe"], e["result"]
|
||||
metric, label, unit, higher = PROFILES[rc["front"]["profile"]]
|
||||
m, ref = r["metrics"], rc["value"]
|
||||
v = m[metric]
|
||||
delta = f"{100 * (v - ref) / ref:+.0f}% {label}" if ref and v else "—"
|
||||
change = e["change"] + (f" — {e['note']}" if e["note"] else "")
|
||||
rec = self.link(rc["path"], td["path"])
|
||||
kind = "" if not r["full"] else " (full)"
|
||||
rep = self.link(r["dir"] / f"{r['id']}.html", td["path"])
|
||||
L.append(f"| {change} | {num(m['decode_tps'])} | {num(m['ttft_ms'], 0)} ms | "
|
||||
f"{num(m['peak_tps'], 0)} | {delta} vs [{rc['id'].split('/')[-1]}]({rec}) | "
|
||||
f"[{r['created']}{kind}]({rep}) |")
|
||||
if any(e["result"]["demo"] for e in td["entries"]):
|
||||
L += ["", "> **Demo data.** These runs are synthetic. Nothing here was measured."]
|
||||
return "\n".join(L)
|
||||
|
||||
def best(self):
|
||||
"""The fastest recipe per (gpu, model, profile)."""
|
||||
top = {}
|
||||
for rc in self.recipes:
|
||||
f = rc["front"]
|
||||
key = (f["gpu"], f["model"], f["profile"])
|
||||
higher = PROFILES[f["profile"]][3]
|
||||
cur = top.get(key)
|
||||
if rc["value"] is not None and (cur is None or
|
||||
(rc["value"] > cur["value"]) == higher and rc["value"] != cur["value"]):
|
||||
top[key] = rc
|
||||
return top
|
||||
|
||||
def index_md(self):
|
||||
best = self.best()
|
||||
L = []
|
||||
gpus = list(self.config["gpus"])
|
||||
for gpu in gpus:
|
||||
rows = sorted((r for r in self.recipes if r["front"]["gpu"] == gpu),
|
||||
key=lambda r: (r["front"]["model"], list(PROFILES).index(r["front"]["profile"]),
|
||||
r["front"]["engine"]))
|
||||
if not rows:
|
||||
continue
|
||||
L += [f"### {gpu}", "", "| model | profile | engine | headline | status | recipe |",
|
||||
"|---|---|---|---|---|---|"]
|
||||
for rc in rows:
|
||||
f = rc["front"]
|
||||
_, label, unit, _ = PROFILES[f["profile"]]
|
||||
star = " ★" if best.get((gpu, f["model"], f["profile"])) is rc else ""
|
||||
status = "demo" if rc["demo"] else rc["status"]
|
||||
L.append(f"| {f['model']} | {f['profile']} | {f['engine']} | "
|
||||
f"{num(rc['value'], 2 if unit == 'J/tok' else 1)} {unit} {label}{star} | "
|
||||
f"{status} | [{rc['id']}](recipes/{rc['id']}.md) |")
|
||||
L.append("")
|
||||
L.append("★ the fastest recipe for that GPU, model and profile.")
|
||||
wanted = self.wanted()
|
||||
if wanted:
|
||||
L += ["", "**Wanted** (fits in VRAM, no single-user recipe yet): " +
|
||||
", ".join(f"{m} on {g}" for g, m in wanted) + "."]
|
||||
return "\n".join(L)
|
||||
|
||||
def wanted(self):
|
||||
have = {(r["front"]["gpu"], r["front"]["model"]) for r in self.recipes
|
||||
if r["front"]["profile"] == "single-user"}
|
||||
return [(g, m) for g, gv in self.config["gpus"].items()
|
||||
for m, mv in self.config["models"].items()
|
||||
if gv["vram_gb"] >= mv["min_vram_gb"] and (g, m) not in have]
|
||||
|
||||
# ------------------------------------------------------------ build
|
||||
def outputs(self):
|
||||
"""{path: new content} for every generated file."""
|
||||
out = {}
|
||||
for rc in self.recipes:
|
||||
text = rc["path"].read_text(encoding="utf-8")
|
||||
out[rc["path"]] = fill(text, "numbers", self.numbers_md(rc))
|
||||
for td in self.tried:
|
||||
text = td["path"].read_text(encoding="utf-8")
|
||||
out[td["path"]] = fill(text, "tried", self.tried_md(td))
|
||||
readme = self.root / "README.md"
|
||||
out[readme] = fill(readme.read_text(encoding="utf-8"), "index", self.index_md())
|
||||
out[self.root / "site" / "index.html"] = site_html(self, out)
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Markdown -> HTML
|
||||
def md_inline(s, link):
|
||||
out = []
|
||||
for part in re.split(r"(`[^`]+`)", s):
|
||||
if len(part) > 1 and part.startswith("`") and part.endswith("`"):
|
||||
out.append(f"<code>{html.escape(part[1:-1])}</code>")
|
||||
continue
|
||||
t = html.escape(part, quote=False)
|
||||
t = re.sub(r"\[([^\]]+)\]\(([^)\s]+)\)",
|
||||
lambda m: f'<a href="{html.escape(link(html.unescape(m.group(2))))}">{m.group(1)}</a>', t)
|
||||
t = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", t)
|
||||
t = re.sub(r"(?<![\w*])\*(?!\s)(.+?)(?<!\s)\*(?![\w*])", r"<em>\1</em>", t)
|
||||
out.append(t)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
LIST_ITEM = re.compile(r"^(\s*)([-*]|\d+\.) (.*)$")
|
||||
|
||||
|
||||
def md_to_html(text, link=lambda u: u, shift=0, prefix=""):
|
||||
"""The Markdown the cookbook uses: headings, paragraphs, fenced code,
|
||||
tables, lists, block quotes, inline code, bold, italics and links."""
|
||||
text = re.sub(r"<!--.*?-->\n?", "", text, flags=re.S)
|
||||
lines = text.split("\n")
|
||||
out, i = [], 0
|
||||
|
||||
def starts_block(l):
|
||||
return (l.startswith(("```", "#", "|", ">")) or LIST_ITEM.match(l)) is not None and bool(l.strip())
|
||||
|
||||
while i < len(lines):
|
||||
l = lines[i]
|
||||
if not l.strip():
|
||||
i += 1
|
||||
elif l.startswith("```"):
|
||||
j, buf = i + 1, []
|
||||
while j < len(lines) and not lines[j].startswith("```"):
|
||||
buf.append(lines[j])
|
||||
j += 1
|
||||
out.append(f"<pre><code>{html.escape(chr(10).join(buf))}</code></pre>")
|
||||
i = j + 1
|
||||
elif m := re.match(r"(#{1,5}) (.*)", l):
|
||||
n = min(6, len(m.group(1)) + shift)
|
||||
out.append(f'<h{n} id="{prefix}{anchor(m.group(2))}">{md_inline(m.group(2), link)}</h{n}>')
|
||||
i += 1
|
||||
elif l.startswith("|"):
|
||||
rows = []
|
||||
while i < len(lines) and lines[i].startswith("|"):
|
||||
rows.append([c.strip() for c in lines[i].strip().strip("|").split("|")])
|
||||
i += 1
|
||||
head, body = rows[0], [r for r in rows[1:] if not all(re.fullmatch(r":?-+:?", c) for c in r)]
|
||||
out.append('<div class="table"><table><thead><tr>' +
|
||||
"".join(f"<th>{md_inline(c, link)}</th>" for c in head) + "</tr></thead><tbody>" +
|
||||
"".join("<tr>" + "".join(f"<td>{md_inline(c, link)}</td>" for c in r) + "</tr>"
|
||||
for r in body) + "</tbody></table></div>")
|
||||
elif l.startswith(">"):
|
||||
buf = []
|
||||
while i < len(lines) and lines[i].startswith(">"):
|
||||
buf.append(lines[i][1:].removeprefix(" "))
|
||||
i += 1
|
||||
out.append(f"<blockquote>{md_to_html(chr(10).join(buf), link, shift, prefix)}</blockquote>")
|
||||
elif m := LIST_ITEM.match(l):
|
||||
tag = "ol" if m.group(2)[0].isdigit() else "ul"
|
||||
items = []
|
||||
while i < len(lines) and (m := LIST_ITEM.match(lines[i])):
|
||||
item = [m.group(3)]
|
||||
i += 1
|
||||
while i < len(lines) and lines[i].startswith(" ") and not LIST_ITEM.match(lines[i]):
|
||||
item.append(lines[i].strip())
|
||||
i += 1
|
||||
items.append(" ".join(item))
|
||||
out.append(f"<{tag}>" + "".join(f"<li>{md_inline(x, link)}</li>" for x in items) + f"</{tag}>")
|
||||
else:
|
||||
buf = []
|
||||
while i < len(lines) and lines[i].strip() and not starts_block(lines[i]):
|
||||
buf.append(lines[i].strip())
|
||||
i += 1
|
||||
out.append(f"<p>{md_inline(' '.join(buf), link)}</p>")
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- site
|
||||
CSS = """
|
||||
:root{--bg:#f7f7f5;--panel:#fff;--text:#1d1d1f;--muted:#5f6368;--line:#e2e2de;--accent:#0b5cad;
|
||||
--accent-soft:#e6f0fa;--code:#f1f1ee;--warn-bg:#fff6dc;--warn-line:#e5c56a;--good:#1d7a46;--good-soft:#e3f3e9}
|
||||
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#141518;--panel:#1c1d21;--text:#e8e8ea;
|
||||
--muted:#a0a3a9;--line:#2e3036;--accent:#7cb4f0;--accent-soft:#1d2a3a;--code:#24262b;--warn-bg:#2e2715;
|
||||
--warn-line:#7a6526;--good:#6fcf97;--good-soft:#17291f}}
|
||||
:root[data-theme="dark"]{--bg:#141518;--panel:#1c1d21;--text:#e8e8ea;--muted:#a0a3a9;--line:#2e3036;
|
||||
--accent:#7cb4f0;--accent-soft:#1d2a3a;--code:#24262b;--warn-bg:#2e2715;--warn-line:#7a6526;--good:#6fcf97;--good-soft:#17291f}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;background:var(--bg);color:var(--text);font:15px/1.55 system-ui,-apple-system,"Segoe UI",sans-serif}
|
||||
main{max-width:1080px;margin:0 auto;padding:24px 16px 64px}
|
||||
a{color:var(--accent)}
|
||||
header h1{font-size:28px;margin:0 0 4px}
|
||||
header p{margin:0;color:var(--muted)}
|
||||
.banner{background:var(--warn-bg);border:1px solid var(--warn-line);border-radius:8px;padding:10px 14px;margin:16px 0}
|
||||
.filters{display:flex;flex-wrap:wrap;gap:12px;margin:20px 0;padding:12px;background:var(--panel);
|
||||
border:1px solid var(--line);border-radius:8px}
|
||||
.filters label{display:flex;flex-direction:column;font-size:12px;color:var(--muted);gap:4px}
|
||||
select{font:inherit;padding:6px 8px;border-radius:6px;border:1px solid var(--line);background:var(--bg);color:var(--text);min-width:160px}
|
||||
section{margin-top:32px}
|
||||
h2{font-size:20px;border-bottom:1px solid var(--line);padding-bottom:6px}
|
||||
article{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:4px 20px 16px;margin:16px 0}
|
||||
article>h2{border:0;margin-bottom:4px}
|
||||
.chips{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 12px}
|
||||
.chip{font-size:12px;padding:2px 8px;border-radius:999px;background:var(--accent-soft);color:var(--accent)}
|
||||
.chip.good{background:var(--good-soft);color:var(--good)}
|
||||
.chip.demo{background:var(--warn-bg);color:var(--text);border:1px solid var(--warn-line)}
|
||||
.table{overflow-x:auto}
|
||||
table{border-collapse:collapse;width:100%;font-size:14px;margin:8px 0}
|
||||
th,td{text-align:left;padding:6px 10px;border-bottom:1px solid var(--line);vertical-align:top}
|
||||
th{color:var(--muted);font-weight:600}
|
||||
code{font:13px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--code);padding:1px 4px;border-radius:4px}
|
||||
pre{position:relative;background:var(--code);padding:12px;border-radius:8px;overflow-x:auto}
|
||||
pre code{padding:0;background:none;white-space:pre}
|
||||
pre button{position:absolute;top:6px;right:6px;font:12px system-ui;padding:3px 8px;border-radius:6px;
|
||||
border:1px solid var(--line);background:var(--panel);color:var(--text);cursor:pointer}
|
||||
blockquote{margin:12px 0;padding:8px 14px;background:var(--warn-bg);border-left:4px solid var(--warn-line);border-radius:4px}
|
||||
blockquote p{margin:4px 0}
|
||||
details>summary{cursor:pointer;color:var(--accent);margin:8px 0}
|
||||
.hidden{display:none}
|
||||
footer{margin-top:48px;color:var(--muted);font-size:13px}
|
||||
"""
|
||||
|
||||
JS = """
|
||||
const sel = [...document.querySelectorAll('.filters select')];
|
||||
function apply() {
|
||||
const want = Object.fromEntries(sel.map(s => [s.name, s.value]));
|
||||
document.querySelectorAll('[data-gpu]').forEach(el => {
|
||||
const ok = Object.entries(want).every(([k, v]) => !v || !el.dataset[k] || el.dataset[k] === v);
|
||||
el.classList.toggle('hidden', !ok);
|
||||
});
|
||||
}
|
||||
sel.forEach(s => s.addEventListener('change', apply));
|
||||
document.querySelectorAll('pre').forEach(pre => {
|
||||
const b = document.createElement('button');
|
||||
b.textContent = 'copy';
|
||||
b.addEventListener('click', () => {
|
||||
navigator.clipboard.writeText(pre.querySelector('code').innerText)
|
||||
.then(() => { b.textContent = 'copied'; setTimeout(() => b.textContent = 'copy', 1200); })
|
||||
.catch(() => { b.textContent = 'select + copy'; });
|
||||
});
|
||||
pre.appendChild(b);
|
||||
});
|
||||
"""
|
||||
|
||||
|
||||
def site_html(cb, generated):
|
||||
site = cb.root / "site"
|
||||
targets = {rc["path"].resolve(): "#r-" + anchor(rc["id"]) for rc in cb.recipes}
|
||||
targets.update({td["path"].resolve(): "#t-" + anchor(td["rel"]) for td in cb.tried})
|
||||
|
||||
def linker(src):
|
||||
def link(u):
|
||||
if re.match(r"^(https?:|mailto:|#)", u):
|
||||
return u
|
||||
path, _, frag = u.partition("#")
|
||||
target = (Path(src).parent / path).resolve()
|
||||
if target in targets:
|
||||
return targets[target]
|
||||
return Path(os.path.relpath(target, site)).as_posix() + (f"#{frag}" if frag else "")
|
||||
return link
|
||||
|
||||
def attrs(f):
|
||||
return (f'data-gpu="{html.escape(f["gpu"])}" data-model="{html.escape(f["model"])}" '
|
||||
f'data-profile="{html.escape(f["profile"])}"')
|
||||
|
||||
def opts(name, values):
|
||||
return (f'<label>{name}<select name="{name}"><option value="">all</option>' +
|
||||
"".join(f'<option>{html.escape(v)}</option>' for v in values) + "</select></label>")
|
||||
|
||||
best = cb.best()
|
||||
rows = []
|
||||
for rc in sorted(cb.recipes, key=lambda r: (list(cb.config["gpus"]).index(r["front"]["gpu"])
|
||||
if r["front"]["gpu"] in cb.config["gpus"] else 99,
|
||||
r["front"]["model"], r["front"]["profile"], -(r["value"] or 0))):
|
||||
f = rc["front"]
|
||||
_, label, unit, _ = PROFILES[f["profile"]]
|
||||
star = best.get((f["gpu"], f["model"], f["profile"])) is rc
|
||||
rows.append(f'<tr {attrs(f)}><td>{html.escape(f["gpu"])}</td><td>{html.escape(f["model"])}</td>'
|
||||
f'<td>{f["profile"]}</td><td>{html.escape(f["engine"])}</td>'
|
||||
f'<td><strong>{num(rc["value"], 2 if unit == "J/tok" else 1)} {unit}</strong> '
|
||||
f'{label}{" ★" if star else ""}</td>'
|
||||
f'<td>{"demo" if rc["demo"] else rc["status"]}</td>'
|
||||
f'<td><a href="#r-{anchor(rc["id"])}">{html.escape(f["title"])}</a></td></tr>')
|
||||
|
||||
articles = []
|
||||
for rc in cb.recipes:
|
||||
f = rc["front"]
|
||||
_, body = split_front(generated[rc["path"]])
|
||||
chips = [f["engine"], f"{f['quant']} · kv {f['kv']}", f"spec {f['spec']}",
|
||||
f"thinking {f['thinking']}", f"tp {rc['tp']} · pp {rc['pp']}"]
|
||||
status = ('<span class="chip demo">demo data</span>' if rc["demo"] else
|
||||
f'<span class="chip{" good" if rc["status"].startswith("verified") else ""}">'
|
||||
f'{rc["status"]}</span>')
|
||||
articles.append(
|
||||
f'<article id="r-{anchor(rc["id"])}" {attrs(f)}><h2>{html.escape(f["title"])}</h2>'
|
||||
f'<p>{md_inline(f["summary"], linker(rc["path"]))}</p><div class="chips">{status}' +
|
||||
"".join(f'<span class="chip">{html.escape(c)}</span>' for c in chips) + "</div>" +
|
||||
md_to_html(body, linker(rc["path"]), shift=1, prefix=anchor(rc["id"]) + "-") +
|
||||
f'<p><a href="{Path(os.path.relpath(rc["path"], site)).as_posix()}">{rc["rel"]}</a></p></article>')
|
||||
|
||||
tried = []
|
||||
for td in cb.tried:
|
||||
f = td["front"]
|
||||
_, body = split_front(generated[td["path"]])
|
||||
body = re.sub(r"\A\s*# .*\n", "", body) # the article has its own heading
|
||||
tried.append(f'<article id="t-{anchor(td["rel"])}" data-gpu="{html.escape(f["gpu"])}" '
|
||||
f'data-model="{html.escape(f["model"])}"><h2>{html.escape(f["model"])} on '
|
||||
f'{html.escape(f["gpu"])}: what lost</h2>' +
|
||||
md_to_html(body, linker(td["path"]), shift=1, prefix=anchor(td["rel"]) + "-") + "</article>")
|
||||
|
||||
gpus = sorted({r["front"]["gpu"] for r in cb.recipes}, key=lambda g: list(cb.config["gpus"]).index(g)
|
||||
if g in cb.config["gpus"] else 99)
|
||||
models = sorted({r["front"]["model"] for r in cb.recipes})
|
||||
profiles = [p for p in PROFILES if any(r["front"]["profile"] == p for r in cb.recipes)]
|
||||
newest = max((r["created"] for r in cb.results.values()), default="—")
|
||||
demo = any(r["demo"] for r in cb.results.values())
|
||||
wanted = cb.wanted()
|
||||
gpu_rows = "".join(f'<tr><td>{html.escape(g)}</td><td>{v["vram_gb"]} GB</td><td>{v["mem_bw_gbs"]} GB/s</td>'
|
||||
f'<td>{html.escape(v.get("arch", ""))}</td></tr>' for g, v in cb.config["gpus"].items())
|
||||
return f"""<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Arc LLM Cookbook</title>
|
||||
<style>{CSS}</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<header>
|
||||
<h1>Arc LLM Cookbook</h1>
|
||||
<p>The fastest way to run each model on Intel Arc GPUs. Every number comes from a
|
||||
<a href="https://git.linxweiler.xyz/miga/benchmarks">bench-standard</a> run in <code>results/</code>.</p>
|
||||
</header>
|
||||
{'<div class="banner"><strong>Demo data.</strong> The results in this build are synthetic, made to show the layout. Nothing here was measured yet.</div>' if demo else ''}
|
||||
<div class="filters">{opts("gpu", gpus)}{opts("model", models)}{opts("profile", profiles)}</div>
|
||||
<section>
|
||||
<h2>Fastest setups</h2>
|
||||
<div class="table"><table><thead><tr><th>GPU</th><th>model</th><th>profile</th><th>engine</th><th>headline</th>
|
||||
<th>status</th><th>recipe</th></tr></thead><tbody>{"".join(rows)}</tbody></table></div>
|
||||
<p>★ the fastest recipe for that GPU, model and profile.
|
||||
{("<strong>Wanted:</strong> " + ", ".join(f"{html.escape(m)} on {html.escape(g)}" for g, m in wanted) + ".") if wanted else ""}</p>
|
||||
</section>
|
||||
<section>
|
||||
<h2>Recipes</h2>
|
||||
{"".join(articles)}
|
||||
</section>
|
||||
<section>
|
||||
<h2>Tried and lost</h2>
|
||||
{"".join(tried) or "<p>Nothing yet.</p>"}
|
||||
</section>
|
||||
<section>
|
||||
<h2>Arc GPUs</h2>
|
||||
<div class="table"><table><thead><tr><th>GPU</th><th>VRAM</th><th>memory bandwidth (spec)</th><th>architecture</th></tr></thead>
|
||||
<tbody>{gpu_rows}</tbody></table></div>
|
||||
</section>
|
||||
<footer>Generated by <code>tools/cookbook.py build</code> from {len(cb.recipes)} recipes and
|
||||
{len(cb.results)} result folders · newest run {newest}.</footer>
|
||||
</main>
|
||||
<script>{JS}</script>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- CLI
|
||||
def report(cb):
|
||||
for w in cb.warnings:
|
||||
print(f"warning: {w}", file=sys.stderr)
|
||||
for e in cb.errors:
|
||||
print(f"error: {e}", file=sys.stderr)
|
||||
print(f"{len(cb.recipes)} recipes, {len(cb.tried)} tried logs, {len(cb.results)} results: "
|
||||
f"{len(cb.errors)} errors, {len(cb.warnings)} warnings", file=sys.stderr)
|
||||
return not cb.errors
|
||||
|
||||
|
||||
def main(argv):
|
||||
if not argv or argv[0] not in ("validate", "build") or argv[1:] not in ([], ["--check"]) or \
|
||||
(argv[0] == "validate" and argv[1:]):
|
||||
print(__doc__.strip(), file=sys.stderr)
|
||||
return 2
|
||||
cb = Cookbook()
|
||||
if not report(cb):
|
||||
return 1
|
||||
if argv[0] == "validate":
|
||||
return 0
|
||||
stale = []
|
||||
for path, text in cb.outputs().items():
|
||||
old = path.read_text(encoding="utf-8") if path.exists() else None
|
||||
if old == text:
|
||||
continue
|
||||
stale.append(path.relative_to(cb.root).as_posix())
|
||||
if "--check" not in argv:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8")
|
||||
if "--check" in argv and stale:
|
||||
print("out of date (run tools/cookbook.py build): " + ", ".join(stale), file=sys.stderr)
|
||||
return 1
|
||||
for s in stale:
|
||||
print(f"wrote {s}", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,350 @@
|
||||
#!/usr/bin/env python3
|
||||
"""make_demo.py - writes the synthetic DEMO result folders in results/.
|
||||
|
||||
usage: python3 tools/demo/make_demo.py [--benchmarks DIR]
|
||||
|
||||
This is not a benchmark: it makes the numbers up, so the cookbook's layout,
|
||||
checks and site can be seen before real runs exist. The folders have the shape
|
||||
of bench.sh output. The launch command comes from the recipe, and the
|
||||
benchmarks repo's own notes.py and postrun.py (from --benchmarks, default
|
||||
../benchmarks, run unchanged) turn the made-up samples into the notes, energy
|
||||
and bandwidth figures. `betterbench report --html` renders the report. Every
|
||||
folder gets a DEMO file, and rerunning replaces only folders that have one.
|
||||
|
||||
Delete the DEMO folders and this directory once real results replace them.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import shutil
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parent.parent
|
||||
sys.path.insert(0, str(HERE.parent))
|
||||
import cookbook # noqa: E402
|
||||
|
||||
# completion tokens, prompt tokens, relative speed with speculative decoding
|
||||
CATEGORIES = {
|
||||
"chat": (200, 144, 0.70), "code": (600, 96, 1.05), "file_edit": (288, 133, 1.35),
|
||||
"json": (179, 103, 1.40), "math": (500, 101, 1.12), "prose": (900, 86, 0.62),
|
||||
"reasoning": (600, 122, 0.98), "summarization": (180, 143, 1.10),
|
||||
}
|
||||
SPEC_MID = statistics.median(c[2] for c in CATEGORIES.values())
|
||||
|
||||
GPUS = {
|
||||
"Arc Pro B65": {"vram": "32", "power": "200", "link": "Gen4 x16", "bw": "532", "mhz": 2800},
|
||||
"Arc B580": {"vram": "12", "power": "190", "link": "Gen4 x8", "bw": "401", "mhz": 2850},
|
||||
}
|
||||
# (model, engine): served id, file, bytes, loaded GiB as vLLM logs it
|
||||
MODELS = {
|
||||
("Qwen3.5-9B", "llama.cpp"): ("qwen3.5-9b", "/models/Qwen3.5-9B-Q4_K_M.gguf", 5_680_000_000, None),
|
||||
("Qwen3.8-27B", "llama.cpp"): ("qwen3.8-27b", "/models/Qwen3.8-27B-UD-Q4_K_M.gguf", 16_460_000_000, None),
|
||||
("Qwen3.5-9B", "vllm"): ("qwen3.5-9b", "/models/RedHatAI/Qwen3.5-9B-quantized.w4a16", 7_010_000_000, "6.12"),
|
||||
("Qwen3.8-27B", "vllm"): ("qwen3.8-27b", "/models/RedHatAI/Qwen3.8-27B-INT4", 18_900_000_000, "16.94"),
|
||||
}
|
||||
ENGINES = {
|
||||
"llama.cpp": {"version": "b11913-7aca0d2ea", "slots": "1", "port": 8080,
|
||||
"image": "ghcr.io/ggml-org/llama.cpp:server-intel@000000000000"},
|
||||
"vllm": {"version": "0.30.0", "slots": "", "port": 8000,
|
||||
"image": "intel/vllm:0.30.0-xpu@000000000000"},
|
||||
}
|
||||
SPEC5 = """ --speculative-config '{"method":"mtp","num_speculative_tokens":5}' \\\n"""
|
||||
|
||||
# decode/ttft/pp: the medians to aim for; conc: aggregate t/s at 1, 2, 4, 8; watts: decode
|
||||
RUNS = [
|
||||
{"recipe": "qwen3.5-9b/arc-pro-b65/llama.cpp-single-user", "date": "261019",
|
||||
"decode": 64.0, "ttft": 95, "pp": 3400, "conc": [63, 63, 64, 64], "watts": 148},
|
||||
{"recipe": "qwen3.5-9b/arc-pro-b65/llama.cpp-single-user", "date": "261019", "quick": True,
|
||||
"sub": [("-fa on -ctk q8_0 -ctv q8_0", "-fa off")], "declare": {"kv": "f16"},
|
||||
"decode": 57.1, "ttft": 118, "pp": 2650, "conc": [56, 56, 57, 57], "watts": 150},
|
||||
{"recipe": "qwen3.5-9b/arc-pro-b65/llama.cpp-single-user", "date": "261019", "quick": True,
|
||||
"sub": [("-e ZES_ENABLE_SYSMAN=1", "-e ZES_ENABLE_SYSMAN=1 -e GGML_SYCL_DISABLE_OPT=1")],
|
||||
"decode": 49.8, "ttft": 131, "pp": 2100, "conc": [49, 49, 50, 50], "watts": 139},
|
||||
{"recipe": "qwen3.5-9b/arc-pro-b65/vllm-single-user", "date": "261020",
|
||||
"decode": 118.0, "ttft": 140, "pp": 4100, "conc": [114, 115, 115, 115], "watts": 165},
|
||||
{"recipe": "qwen3.8-27b/arc-pro-b65/llama.cpp-single-user", "date": "261021",
|
||||
"decode": 22.6, "ttft": 210, "pp": 980, "conc": [22, 22, 23, 23], "watts": 160},
|
||||
{"recipe": "qwen3.8-27b/arc-pro-b65/llama.cpp-single-user", "date": "261021", "quick": True,
|
||||
"sub": [("-ub 512", "-ub 1024")],
|
||||
"decode": 22.5, "ttft": 200, "pp": 1070, "conc": [22, 22, 22, 23], "watts": 161},
|
||||
{"recipe": "qwen3.8-27b/arc-pro-b65/llama.cpp-single-user", "date": "261021", "quick": True,
|
||||
"sub": [("-ctk q8_0 -ctv q8_0", "-ctk f16 -ctv f16")], "declare": {"kv": "f16"},
|
||||
"decode": 22.8, "ttft": 205, "pp": 1000, "conc": [22, 23, 23, 23], "watts": 160},
|
||||
{"recipe": "qwen3.8-27b/arc-pro-b65/vllm-single-user", "date": "261022",
|
||||
"decode": 84.5, "ttft": 190, "pp": 1520, "conc": [83, 83, 84, 84], "watts": 172},
|
||||
{"recipe": "qwen3.8-27b/arc-pro-b65/vllm-single-user", "date": "261022", "quick": True,
|
||||
"sub": [(SPEC5, "")], "declare": {"spec": "none"},
|
||||
"decode": 31.0, "ttft": 185, "pp": 1530, "conc": [31, 31, 31, 31], "watts": 168},
|
||||
{"recipe": "qwen3.8-27b/arc-pro-b65/vllm-single-user", "date": "261022", "quick": True,
|
||||
"sub": [('"num_speculative_tokens":5', '"num_speculative_tokens":3')], "declare": {"spec": "mtp:3"},
|
||||
"decode": 76.4, "ttft": 188, "pp": 1515, "conc": [75, 75, 76, 76], "watts": 171},
|
||||
{"recipe": "qwen3.8-27b/arc-pro-b65/vllm-single-user", "date": "261022", "quick": True,
|
||||
"sub": [('"num_speculative_tokens":5', '"num_speculative_tokens":7')], "declare": {"spec": "mtp:7"},
|
||||
"decode": 80.2, "ttft": 192, "pp": 1520, "conc": [79, 79, 80, 80], "watts": 174},
|
||||
{"recipe": "qwen3.8-27b/arc-pro-b65/vllm-throughput", "date": "261023",
|
||||
"decode": 64.0, "ttft": 205, "pp": 1500, "conc": [62, 118, 205, 296], "watts": 170},
|
||||
{"recipe": "qwen3.5-9b/arc-b580/llama.cpp-single-user", "date": "261024",
|
||||
"decode": 48.2, "ttft": 120, "pp": 2500, "conc": [47, 48, 48, 48], "watts": 140},
|
||||
{"recipe": "qwen3.8-27b/arc-pro-b65/vllm-single-user", "date": "261026", "submitter": "demo-2",
|
||||
"decode": 82.1, "ttft": 196, "pp": 1490, "conc": [81, 81, 82, 82], "watts": 175},
|
||||
]
|
||||
|
||||
|
||||
def kv_file(path, d):
|
||||
path.write_text("".join(f"{k}={v}\n" for k, v in d.items()), encoding="utf-8")
|
||||
|
||||
|
||||
def recipe_front(rid):
|
||||
front, body = cookbook.split_front((ROOT / "recipes" / f"{rid}.md").read_text(encoding="utf-8"))
|
||||
return front, cookbook.launch_block(body)
|
||||
|
||||
|
||||
def context(cmd):
|
||||
m = re.search(r"(?:-c|--ctx-size|--max-model-len)\s+(\d+)", cmd)
|
||||
return int(m.group(1)) if m else 32768
|
||||
|
||||
|
||||
def synth(run, front, cmd, rng, quick):
|
||||
"""The BetterBench sections plus the timeline and power samples."""
|
||||
spec = run.get("declare", {}).get("spec", front["spec"]) != "none"
|
||||
n, warm = (5, 1) if quick else (20, 3)
|
||||
single, timeline, phases, t = {}, [], [], 0.0
|
||||
for cat, (ctoks, ptoks, sf) in CATEGORIES.items():
|
||||
f = sf / SPEC_MID if spec else 1.0
|
||||
recs = []
|
||||
for i in range(n):
|
||||
d = run["decode"] * f * rng.gauss(1, 0.035 if spec else 0.012)
|
||||
ttft = run["ttft"] * rng.gauss(1, 0.04)
|
||||
gaps = [round(1000 / d * rng.uniform(2, 5), 2) for _ in range(6)]
|
||||
recs.append({
|
||||
"ok": True, "category": cat, "prompt_id": f"{cat}-{i % 3}", "ttft_ms": ttft,
|
||||
"update_gaps_ms": gaps, "tokens_per_update": 3.5 if spec else 1.0,
|
||||
"chunking": "batched" if spec else "per-token", "decode_tps": d,
|
||||
"total_tps": ctoks / (ctoks / d + ttft / 1000), "pp_tps": ptoks / ttft * 1000,
|
||||
"prompt_tokens": ptoks, "completion_tokens": ctoks, "cached_tokens": None,
|
||||
"n_chunks": ctoks // 3 if spec else ctoks, "chunk_token_mismatch": spec,
|
||||
"finish_reason": "length", "ttfa_ms": None, "reasoning_source": "channel",
|
||||
"reasoning_chars": ctoks * 2, "answer_chars": ctoks * 2,
|
||||
"reasoning_chunks": ctoks // 6, "answer_chunks": ctoks // 6,
|
||||
"reasoning_tokens_est": ctoks // 2, "answer_tokens_est": ctoks // 2,
|
||||
"truncated_in_reasoning": False, "wall_ms": ttft + ctoks / d * 1000, "error": None})
|
||||
single[cat] = recs
|
||||
dur = (warm + n) * statistics.mean(r["wall_ms"] for r in recs) / 1000
|
||||
timeline.append((t, f"[single] {cat}: warmup {warm} + {n} runs"))
|
||||
phases.append((t, t + dur, "decode"))
|
||||
t += dur
|
||||
|
||||
ctx = context(cmd)
|
||||
prefill = []
|
||||
pn, pw = (3, 1) if quick else (8, 2)
|
||||
for depth in ([2000, 8000] if quick else [2000, 8000, 16000, 32000, 64000]):
|
||||
if depth + 256 > ctx:
|
||||
timeline.append((t, f"[prefill] skip depth ~{depth}: needs more context than {ctx}"))
|
||||
prefill.append({"target_depth": depth, "skipped": True,
|
||||
"reason": f"needs ~{depth + 256} tokens, max_model_len {ctx}"})
|
||||
continue
|
||||
speed = run["pp"] * (1 - 0.13 * math.log2(depth / 2000))
|
||||
toks = [int(depth * 0.775) + rng.randint(-4, 4) for _ in range(pn)]
|
||||
pps = [speed * rng.gauss(1, 0.006) for _ in toks]
|
||||
ttfts = [k / p * 1000 for k, p in zip(toks, pps)]
|
||||
prefill.append({"target_depth": depth, "prompt_tokens": toks, "ttft_ms": ttfts, "pp_tps": pps,
|
||||
"tokens_per_update": [3.0] * pn, "cached_tokens": [], "batched_runs": pn})
|
||||
dur = (pw + pn) * statistics.mean(ttfts) / 1000 + 1
|
||||
timeline.append((t, f"[prefill] depth ~{depth} tok: warmup {pw} + {pn}"))
|
||||
phases.append((t, t + dur, "prefill"))
|
||||
t += dur
|
||||
|
||||
conc = []
|
||||
reqs = 12 if quick else 48
|
||||
for level, agg in zip([1, 2, 4, 8], run["conc"]):
|
||||
if quick and level in (2, 8):
|
||||
continue
|
||||
agg = agg * rng.gauss(1, 0.01)
|
||||
wall = reqs * 400 / agg
|
||||
per = agg / level
|
||||
conc.append({"level": level, "requests": reqs, "ok": reqs, "wall_s": wall, "aggregate_tps": agg,
|
||||
"ttft_ms": [run["ttft"] * (1 + 0.3 * math.log2(level)) * rng.gauss(1, 0.05)
|
||||
for _ in range(reqs)],
|
||||
"decode_tps": [per * rng.gauss(1, 0.03) for _ in range(reqs)],
|
||||
"tokens_per_update": [3.0] * reqs, "cached_tokens": [], "batched_runs": reqs})
|
||||
timeline.append((t, f"[concurrency] level {level}: {reqs} requests"))
|
||||
phases.append((t, t + wall, f"conc{level}"))
|
||||
t += wall
|
||||
return single, prefill, conc, timeline, phases, t, ctx
|
||||
|
||||
|
||||
def power_rows(run, gpu, phases, t_end, t0, rng):
|
||||
limit = float(gpu["power"])
|
||||
rows, joules, t = [], 0.0, 0.0
|
||||
while t <= t_end:
|
||||
ph = next((p[2] for p in phases if p[0] <= t < p[1]), "decode")
|
||||
if ph == "prefill":
|
||||
w, mhz = limit * 0.97, gpu["mhz"] - 250
|
||||
elif ph.startswith("conc"):
|
||||
w, mhz = min(limit * 0.97, run["watts"] * (1 + 0.12 * math.log2(int(ph[4:])))), gpu["mhz"] - 100
|
||||
else:
|
||||
w, mhz = run["watts"], gpu["mhz"]
|
||||
w = min(limit, w * rng.gauss(1, 0.02))
|
||||
rows.append(f"{t0 + t:.1f},{w:.1f},{joules:.1f},{mhz + rng.randint(-50, 0)}")
|
||||
joules += 2 * w
|
||||
t += 2
|
||||
return rows
|
||||
|
||||
|
||||
def make(run, out_dir, bench, ids):
|
||||
front, launch = recipe_front(run["recipe"])
|
||||
cmd = launch
|
||||
for old, new in run.get("sub", []):
|
||||
if old not in cmd:
|
||||
sys.exit(f"{run['recipe']}: {old!r} is not in the launch command")
|
||||
cmd = cmd.replace(old, new)
|
||||
declared = {k: front[k] for k in ("quant", "kv", "spec", "thinking")} | run.get("declare", {})
|
||||
quick = run.get("quick", False)
|
||||
submitter = run.get("submitter", "demo")
|
||||
gpu, engine = GPUS[front["gpu"]], ENGINES[front["engine"]]
|
||||
served, mfile, mbytes, loaded = MODELS[(front["model"], front["engine"])]
|
||||
sha = next(l.split("\t")[3].strip() for l in (bench / "dev" / "models.tsv").open()
|
||||
if l.startswith(front["model"] + "\t") and f"\t{front['quant']}\t" in l)
|
||||
|
||||
slug = cookbook.slug
|
||||
name = f"{slug(served)}_{slug(front['engine'])}_1x-{slug(front['gpu'])}"
|
||||
rid = f"{run['date']}_{slug(submitter)}_{name}" + ("_quick" if quick else "")
|
||||
base, i = rid, 1
|
||||
while rid in ids:
|
||||
i += 1
|
||||
rid = f"{base}_{i}"
|
||||
ids.add(rid)
|
||||
rng = random.Random(rid)
|
||||
|
||||
single, prefill, conc, timeline, phases, t_end, ctx = synth(run, front, cmd, rng, quick)
|
||||
date = f"20{run['date'][:2]}-{run['date'][2:4]}-{run['date'][4:]}"
|
||||
t0 = 1792000000 + int(run["date"]) % 1000 * 86400 + 36000 + (i - 1) * 7200
|
||||
endpoint = f"http://localhost:{engine['port']}/v1"
|
||||
|
||||
mandatory = {"submitter": submitter, "tp": "1", "pp": "1", **declared,
|
||||
"power_limit": gpu["power"], "power_limit_source": "detected",
|
||||
"special_notes": "DEMO DATA: synthetic, made by tools/demo/make_demo.py, not measured",
|
||||
"betterbench": "0.6.1", "betterbench_build": "v0.6.1", "bench_standard": "0.5.0",
|
||||
"run_mode": "quick" if quick else "full", "concurrency": "on"}
|
||||
mandatory = {k: mandatory[k] for k in ("submitter", "tp", "pp", "quant", "kv", "spec", "thinking",
|
||||
"power_limit", "power_limit_source", "special_notes",
|
||||
"betterbench", "betterbench_build", "bench_standard",
|
||||
"run_mode", "concurrency")}
|
||||
collected = {"gpu_vendor": "intel", "gpu_model": front["gpu"], "gpu_count": "1",
|
||||
"gpu_vram_gb": gpu["vram"], "gpu_driver": "1.17.39395", "gpu_power_limit_w": gpu["power"],
|
||||
"gpu_bdf": "0000:03:00.0", "pcie_link": gpu["link"], "pcie_max": gpu["link"], "rebar": "on",
|
||||
"cpu_model": "AMD Ryzen 7 7700", "ram_gb": "64", "os": "Ubuntu 26.04 LTS",
|
||||
"kernel": "7.0.0-38-generic", "virt": "none", "proxy": "none", "engine": front["engine"],
|
||||
"engine_version": engine["version"], "engine_slots": engine["slots"],
|
||||
"engine_image": engine["image"], "model_file": mfile, "model_bytes": str(mbytes),
|
||||
"model_sha256": sha, "ctx": str(ctx), "gpu_mem_bw_gbs": gpu["bw"],
|
||||
"gpu_mem_bw_tool": "torch copy, random, 1024 MiB"}
|
||||
if loaded:
|
||||
collected["model_loaded_gib"] = loaded
|
||||
measured = {"greedy_check": "identical", "greedy_runs": "3",
|
||||
"greedy_hash": hashlib.sha256(f"{front['model']}{front['quant']}".encode()).hexdigest()[:12],
|
||||
"greedy_reasoning": "yes"}
|
||||
|
||||
d = out_dir / rid
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
d.mkdir(parents=True)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmp = Path(tmp)
|
||||
kv_file(tmp / "mandatory", mandatory)
|
||||
kv_file(tmp / "collected", collected)
|
||||
kv_file(tmp / "measured", measured)
|
||||
red = cookbook.redact(cmd)
|
||||
red = red if red.endswith("\n") else red + "\n"
|
||||
(tmp / "cmd").write_text(red, encoding="utf-8")
|
||||
p = subprocess.run([sys.executable, bench / "dev" / "notes.py", tmp / "mandatory", tmp / "collected",
|
||||
tmp / "measured", tmp / "cmd", tmp / "launch.json", bench / "dev" / "models.tsv"],
|
||||
capture_output=True, text=True, check=True)
|
||||
if p.stderr.strip():
|
||||
print(f"{rid}: {p.stderr.strip()}", file=sys.stderr)
|
||||
notes = dict(l.split("=", 1) for l in p.stdout.splitlines() if "=" in l)
|
||||
launch_json = json.loads((tmp / "launch.json").read_text(encoding="utf-8"))
|
||||
(d / "server-cmd.txt").write_text(red, encoding="utf-8")
|
||||
shutil.copy(bench / "dev" / "config.json", d / "config.json")
|
||||
config = json.loads((d / "config.json").read_text(encoding="utf-8"))
|
||||
|
||||
argv = ["betterbench", "run", "--no-update-check", "--endpoint", endpoint, "--model", served,
|
||||
"--config", f"results/{rid}/config.json", "--name", name, "--out", f"results/{rid}/{rid}.json"]
|
||||
argv += (["--quick"] if quick else []) + ["--max-model-len", str(ctx)]
|
||||
for k, v in notes.items():
|
||||
argv += ["--note", f"{k}={v}"]
|
||||
meta = {"bench_standard": "0.5.0", "created": f"{date}T{10 + (i - 1) * 2:02d}:00:00+0200",
|
||||
"endpoint": endpoint, "model": served, "name": name, "notes": notes, "mandatory": mandatory,
|
||||
"collected": collected, "measured": measured, "launch": launch_json,
|
||||
"server_cmd_file": "server-cmd.txt", "server_cmd_source": "file:server-cmd.txt",
|
||||
"betterbench_argv": argv}
|
||||
(d / "meta.json").write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
bb_config = {"temperature": 0.7, "top_p": 0.95, "top_k": 20, "seed": None, "greedy": False,
|
||||
"warmup": 1 if quick else config["warmup"],
|
||||
"runs_per_category": 5 if quick else config["runs_per_category"],
|
||||
"unique_nonce": True, "run_single_stream": True,
|
||||
"concurrency_levels": [1, 4] if quick else config["concurrency_levels"],
|
||||
"concurrency_requests": 12 if quick else config["concurrency_requests"],
|
||||
"run_concurrency": True, "run_prefill": True,
|
||||
"prefill_depths": [2000, 8000] if quick else [2000, 8000, 16000, 32000, 64000],
|
||||
"prefill_runs": 3 if quick else 8, "prefill_warmup": 1 if quick else 2,
|
||||
"prefill_max_tokens": 16, "prefill_ctx_margin": 256, "max_model_len": ctx,
|
||||
"weights": config["weights"], "conf": config["conf"],
|
||||
"target_mde_pct": config["target_mde_pct"], "ab_max_pairs": config["ab_max_pairs"],
|
||||
"ab_min_pairs": config["ab_min_pairs"], "timeout_s": config["timeout_s"]}
|
||||
res = {"schema": 2, "betterbench_version": "0.6.1", "corpus_version": "1.0", "config": bb_config,
|
||||
"env": {"timestamp": meta["created"], "host": "arc-demo",
|
||||
"os": "Linux-7.0.0-38-generic-x86_64-with-glibc2.43", "python": "3.14.4",
|
||||
"endpoint": endpoint, "model": served, "gpu": {}, "categories": list(CATEGORIES),
|
||||
"notes": notes, "corpus_hash": "e332dceff176d033", "max_model_len": ctx},
|
||||
"single_stream": single, "prefill": prefill, "concurrency": conc,
|
||||
"sample_gate": {"rule": "n * min(pct, 100-pct) / 100 >= 5", "under_sampled": []}}
|
||||
(d / f"{rid}.json").write_text(json.dumps(res, indent=1) + "\n", encoding="utf-8")
|
||||
|
||||
(d / "timeline.tsv").write_text("".join(f"{t0 + t:.3f}\t{line}\n" for t, line in timeline), encoding="utf-8")
|
||||
rows = power_rows(run, gpu, phases, t_end, t0, rng)
|
||||
(d / "power.csv").write_text("\n".join(rows) + "\n", encoding="utf-8")
|
||||
|
||||
env = os.environ | {"T0": str(t0), "T1": str(t0 + t_end)}
|
||||
p = subprocess.run([sys.executable, bench / "dev" / "postrun.py", d, d / f"{rid}.json"],
|
||||
capture_output=True, text=True, env=env, check=True)
|
||||
(d / "betterbench.log").write_text(
|
||||
"DEMO: synthetic run, no BetterBench output. Progress lines as BetterBench prints them:\n" +
|
||||
"".join(f"{line}\n" for _, line in timeline) + p.stderr, encoding="utf-8")
|
||||
if shutil.which("betterbench"):
|
||||
subprocess.run(["betterbench", "report", "--no-update-check", "--html", "--out", d / f"{rid}.html",
|
||||
d / f"{rid}.json"], check=True, capture_output=True)
|
||||
else:
|
||||
print(f"{rid}: betterbench not installed, no HTML report", file=sys.stderr)
|
||||
(d / "DEMO").write_text("Synthetic result made by tools/demo/make_demo.py. Nothing here was "
|
||||
"measured. Delete this folder once real results replace it.\n", encoding="utf-8")
|
||||
print(rid)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||||
ap.add_argument("--benchmarks", type=Path, default=ROOT.parent / "benchmarks",
|
||||
help="a checkout of the benchmarks repo (default: ../benchmarks)")
|
||||
a = ap.parse_args()
|
||||
bench = a.benchmarks.resolve()
|
||||
if not (bench / "dev" / "postrun.py").exists():
|
||||
sys.exit(f"no benchmarks checkout at {bench} (pass --benchmarks DIR)")
|
||||
out = ROOT / "results"
|
||||
for d in out.glob("*/DEMO"):
|
||||
shutil.rmtree(d.parent)
|
||||
ids = set()
|
||||
for run in RUNS:
|
||||
make(run, out, bench, ids)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,135 @@
|
||||
"""cookbook.py: command matching, generated blocks, Markdown, and validate on
|
||||
copies of this repo with one thing broken."""
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
import cookbook # noqa: E402
|
||||
|
||||
RECIPE = "recipes/qwen3.8-27b/arc-pro-b65/vllm-single-user.md"
|
||||
|
||||
|
||||
def test_command_words_ignores_layout_and_comments():
|
||||
a = "docker run --rm \\\n -e A=1 img \\\n --flag 'x y'\n"
|
||||
b = "# start it\ndocker run --rm -e A=1 img --flag 'x y'"
|
||||
assert cookbook.command_words(a) == cookbook.command_words(b)
|
||||
assert cookbook.command_words("x --flag 1") != cookbook.command_words("x --flag 2")
|
||||
|
||||
|
||||
def test_command_words_redacts_like_bench_sh():
|
||||
assert cookbook.command_words("HF_TOKEN=abc vllm serve m --api-key s3cret") == \
|
||||
["HF_TOKEN=<redacted>", "vllm", "serve", "m", "--api-key", "<redacted>"]
|
||||
|
||||
|
||||
def test_slug_matches_bench_sh():
|
||||
assert cookbook.slug("Arc Pro B65") == "arc-pro-b65"
|
||||
assert cookbook.slug("llama.cpp") == "llama.cpp"
|
||||
assert cookbook.slug("Qwen3.8-27B") == "qwen3.8-27b"
|
||||
|
||||
|
||||
def test_fill_replaces_only_the_block():
|
||||
text = "a\n<!-- cookbook:x -->\nold\n<!-- /cookbook:x -->\nb\n"
|
||||
assert cookbook.fill(text, "x", "new") == "a\n<!-- cookbook:x -->\nnew\n<!-- /cookbook:x -->\nb\n"
|
||||
with pytest.raises(ValueError):
|
||||
cookbook.fill(text, "y", "new")
|
||||
|
||||
|
||||
def test_launch_block_takes_the_first_sh_block_under_launch():
|
||||
body = "## Requirements\n```sh\nnot this\n```\n## Launch\ntext\n```sh\nthis\n```\n```sh\nnor this\n```\n"
|
||||
assert cookbook.launch_block(body) == "this\n"
|
||||
assert cookbook.launch_block("## Other\n```sh\nx\n```\n") is None
|
||||
|
||||
|
||||
def test_md_to_html():
|
||||
out = cookbook.md_to_html("## Head\n\n| a | b |\n|---|---|\n| `x` | [l](u.md) |\n\n- one\n- **two**\n\n"
|
||||
"```sh\n<cmd>\n```\n", link=lambda u: "L:" + u)
|
||||
assert '<h2 id="head">Head</h2>' in out
|
||||
assert "<td><code>x</code></td>" in out and '<a href="L:u.md">l</a>' in out
|
||||
assert "<ul><li>one</li><li><strong>two</strong></li></ul>" in out
|
||||
assert "<pre><code><cmd></code></pre>" in out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the repo itself
|
||||
def test_repo_validates_and_is_built():
|
||||
cb = cookbook.Cookbook()
|
||||
assert cb.errors == []
|
||||
for path, text in cb.outputs().items():
|
||||
assert path.read_text(encoding="utf-8") == text, f"{path} is out of date: run cookbook.py build"
|
||||
|
||||
|
||||
def test_verified_needs_two_submitters():
|
||||
cb = cookbook.Cookbook()
|
||||
status = {r["id"]: r["status"] for r in cb.recipes}
|
||||
assert status["qwen3.8-27b/arc-pro-b65/vllm-single-user"] == "verified by 2"
|
||||
assert status["qwen3.8-27b/arc-pro-b65/vllm-throughput"] == "one submitter"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- broken copies
|
||||
@pytest.fixture
|
||||
def repo(tmp_path):
|
||||
root = tmp_path / "cookbook"
|
||||
shutil.copytree(cookbook.ROOT, root, ignore=shutil.ignore_patterns(".git", "__pycache__", "*.html"))
|
||||
for d in (root / "results").iterdir(): # validate only needs the reports to exist
|
||||
if d.is_dir():
|
||||
(d / f"{d.name}.html").touch()
|
||||
return root
|
||||
|
||||
|
||||
def edit(path, old, new):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
assert old in text
|
||||
path.write_text(text.replace(old, new, 1), encoding="utf-8")
|
||||
|
||||
|
||||
def errors(root):
|
||||
return "\n".join(cookbook.Cookbook(root).errors)
|
||||
|
||||
|
||||
def test_copy_is_clean(repo):
|
||||
assert errors(repo) == ""
|
||||
|
||||
|
||||
def test_quick_run_cannot_back_a_recipe(repo):
|
||||
edit(repo / RECIPE, '"261026_demo-2_qwen3.8-27b_vllm_1x-arc-pro-b65"',
|
||||
'"261022_demo_qwen3.8-27b_vllm_1x-arc-pro-b65_quick_2"')
|
||||
assert "is a quick run" in errors(repo)
|
||||
|
||||
|
||||
def test_declared_values_must_match(repo):
|
||||
edit(repo / RECIPE, 'kv = "fp16"', 'kv = "fp8"')
|
||||
assert "kv is 'fp8' in the recipe but 'fp16' in the run" in errors(repo)
|
||||
|
||||
|
||||
def test_launch_command_must_be_the_benchmarked_one(repo):
|
||||
edit(repo / RECIPE, "--max-num-seqs 1", "--max-num-seqs 2")
|
||||
assert "server-cmd.txt is not the recipe's launch command" in errors(repo)
|
||||
|
||||
|
||||
def test_only_arc_gpus(repo):
|
||||
edit(repo / RECIPE, 'gpu = "Arc Pro B65"', 'gpu = "RTX 4090"')
|
||||
e = errors(repo)
|
||||
assert "not an Intel Arc GPU" in e and "should be recipes/" in e
|
||||
|
||||
|
||||
def test_edited_results_are_caught(repo):
|
||||
d = repo / "results" / "261022_demo_qwen3.8-27b_vllm_1x-arc-pro-b65"
|
||||
meta = json.loads((d / "meta.json").read_text(encoding="utf-8"))
|
||||
meta["notes"]["spec"] = "none"
|
||||
(d / "meta.json").write_text(json.dumps(meta), encoding="utf-8")
|
||||
assert "differ (edited?)" in errors(repo)
|
||||
|
||||
|
||||
def test_placeholder_digest_only_for_demo(repo):
|
||||
(repo / "results" / "261019_demo_qwen3.5-9b_llama.cpp_1x-arc-pro-b65" / "DEMO").unlink()
|
||||
e = errors(repo)
|
||||
assert "all-zero placeholder" in e
|
||||
|
||||
|
||||
def test_tried_needs_an_existing_result(repo):
|
||||
edit(repo / "tried/qwen3.5-9b/arc-pro-b65.md", "_quick_2", "_quick_9")
|
||||
assert "is not in results/" in errors(repo)
|
||||
Reference in new issue
Block a user