ci / check (push) Successful in 32s
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>
758 lines
36 KiB
Python
758 lines
36 KiB
Python
#!/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:]))
|