ci / check (push) Successful in 11s
Several of one GPU: <gpu>/<model>/<N>x-<engine>-<profile>.md with gpus, tp and pp (tp × pp = gpus) and a declared PCIe topology. Different GPUs: mixed/<setup>/, named after its cards, with the same layout as a GPU folder and a generated mixed/README.md. Runs must sit in their recipe's setup folder. Energy, and bandwidth for pipeline parallel or mixed, are left out where bench-standard measures one GPU only; docs/ bench-standard-gaps.md lists those gaps for the benchmarks repo. The wanted lists take the fewest of one GPU a model fits in. Demo: 2x Arc B580 with vLLM TP 2 and llama.cpp layer split for Qwen3.8-27B, -sm row as what lost, and Arc Pro B60 + Arc B580 mixed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
934 lines
47 KiB
Python
934 lines
47 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
|
||
# Top-level folders that are not GPU folders.
|
||
RESERVED = {"docs", "tools", "site", "mixed"}
|
||
|
||
|
||
def setup(gpu, n=1):
|
||
"""(folder, gpu_model as bench.sh records it, label) for a recipe's GPUs:
|
||
one name with a count, or for a mixed setup a list with one name per card."""
|
||
if isinstance(gpu, list):
|
||
names = sorted(gpu)
|
||
counts = {g: names.count(g) for g in dict.fromkeys(names)}
|
||
return ("mixed/" + "_".join(f"{c}x-{slug(g)}" for g, c in counts.items()), "+".join(counts),
|
||
" + ".join(f"{c}× {g}" if c > 1 else g for g, c in counts.items()))
|
||
return slug(gpu), gpu, gpu if n == 1 else f"{n}× {gpu}"
|
||
|
||
|
||
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 plural(n, word):
|
||
return f"{n} {word}{'' if n == 1 else 's'}"
|
||
|
||
|
||
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"))
|
||
# One folder per GPU: <gpu>/<model>/[<N>x-]<engine>-<profile>.md,
|
||
# <gpu>/<model>/tried.md and <gpu>/results/<run>/. Setups of different GPUs
|
||
# get the same layout under mixed/<setup>/.
|
||
self.gpu_dirs = {slug(g): g for g in self.config["gpus"]}
|
||
for d in sorted(self.root.iterdir()):
|
||
if d.is_dir() and not d.name.startswith(".") and d.name not in RESERVED | set(self.gpu_dirs):
|
||
self.warning(d.name, "not a GPU in cookbook.toml, so nothing in it is checked")
|
||
mixed = self.root / "mixed"
|
||
self.homes = list(self.gpu_dirs) + (
|
||
[d.relative_to(self.root).as_posix() for d in sorted(mixed.iterdir()) if d.is_dir()]
|
||
if mixed.exists() else [])
|
||
self.results = self._load_results()
|
||
docs = [p for h in self.homes for p in sorted((self.root / h).glob("*/*.md"))
|
||
if p.parent.name != "results"]
|
||
self.recipes = self._load_docs([p for p in docs if p.name != "tried.md"], self._recipe)
|
||
self.tried = self._load_docs([p for p in docs if p.name == "tried.md"], self._tried)
|
||
for r in self.results.values():
|
||
if not r["used"]:
|
||
self.warning(f"{r['home']}/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 = {}
|
||
dirs = [(h, d) for h in self.homes if (self.root / h / "results").exists()
|
||
for d in sorted((self.root / h / "results").iterdir()) if d.is_dir()]
|
||
for home, d in dirs:
|
||
gpu = self.gpu_dirs.get(home) # None in mixed/: the recipes check those
|
||
where = d.relative_to(self.root).as_posix()
|
||
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?)")
|
||
if gpu and (meta.get("collected") or {}).get("gpu_model") != gpu:
|
||
self.error(where, f"ran on {(meta.get('collected') or {}).get('gpu_model')}, "
|
||
f"but it is in the {gpu} folder")
|
||
m = meta.get("mandatory") or {}
|
||
cmd = d / "server-cmd.txt"
|
||
out[d.name] = {"id": d.name, "dir": d, "home": home, "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, paths, parse):
|
||
out = []
|
||
for p in paths:
|
||
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(".md")]
|
||
tp, pp = int(f.get("tp", 1)), int(f.get("pp", 1))
|
||
mixed = isinstance(f["gpu"], list)
|
||
names = list(f["gpu"]) if mixed else [f["gpu"]]
|
||
n = len(names) if mixed else int(f.get("gpus", 1))
|
||
if mixed and len(set(names)) < 2:
|
||
self.error(rel, "a mixed setup needs two different GPUs; for N of one GPU use "
|
||
"gpu = NAME and gpus = N")
|
||
if mixed and int(f.get("gpus", n)) != n:
|
||
self.error(rel, f"gpus = {f['gpus']} but gpu lists {n}")
|
||
home, gpu_model, setup_label = setup(f["gpu"], n)
|
||
prefix = f"{n}x-" if n > 1 and not mixed else ""
|
||
want = f"{home}/{slug(f['model'])}/{prefix}{slug(f['engine'])}-{f['profile']}"
|
||
if rid != want:
|
||
self.error(rel, f"should be {want}.md for its gpu, gpus, model, engine and profile")
|
||
if f["profile"] not in PROFILES:
|
||
self.error(rel, f"profile {f['profile']!r}: use one of {', '.join(PROFILES)}")
|
||
return None
|
||
for g in dict.fromkeys(names):
|
||
if g not in self.config["gpus"]:
|
||
self.error(rel, f"gpu {g!r} is not an Intel Arc GPU listed in cookbook.toml")
|
||
if tp * pp != n:
|
||
self.error(rel, f"tp × pp is {tp * pp}, but the recipe runs on {n} GPU{'s' if n > 1 else ''}")
|
||
topology = f.get("topology")
|
||
if n > 1 and not (isinstance(topology, list) and len(topology) == n):
|
||
example = ", ".join(['"Gen5 x8 CPU"'] * n)
|
||
self.error(rel, f"declare topology: one PCIe link per GPU, e.g. topology = [{example}]")
|
||
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
|
||
if res["home"] != home:
|
||
self.error(rel, f"{rid_} is in {res['home']}/results, not {home}/results")
|
||
self._check_run(rel, f, tp, pp, gpu_model, 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, "n": n,
|
||
"mixed": mixed, "home": home, "gpu_model": gpu_model, "label": setup_label,
|
||
"group": f"mixed: {setup_label}" if mixed else f["gpu"], "topology": topology or [],
|
||
"value": runs[0]["metrics"][metric] if runs else None}
|
||
|
||
def _check_run(self, rel, f, tp, pp, gpu_model, 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, gpu_model, f["engine"], res)
|
||
|
||
def _check_where(self, rel, gpu_model, engine, res):
|
||
# gpu_count isn't checked: bench.sh counts every GPU in the machine, not
|
||
# the ones the server uses. tp × pp says how many it uses.
|
||
c = res["meta"].get("collected") or {}
|
||
if c.get("gpu_vendor") != "intel" or c.get("gpu_model") != gpu_model:
|
||
self.error(rel, f"{res['id']} ran on {c.get('gpu_vendor')} {c.get('gpu_model')}, "
|
||
f"not {gpu_model}")
|
||
if c.get("engine") != engine:
|
||
self.error(rel, f"{res['id']} ran on {c.get('engine')}, not {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
|
||
home, _, label = setup(f["gpu"])
|
||
want = f"{home}/{slug(f['model'])}/tried.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"], base["home"]) != (f["model"], home):
|
||
self.error(rel, f"recipe {base['id']} is for another model or GPU")
|
||
if res["home"] != home:
|
||
self.error(rel, f"{res['id']} is in {res['home']}/results, not {home}/results")
|
||
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, base["gpu_model"], bf["engine"], res)
|
||
entries.append({"change": t.get("change", ""), "note": t.get("note", ""),
|
||
"recipe": base, "result": res})
|
||
mixed = isinstance(f["gpu"], list)
|
||
return {"rel": rel, "path": path, "front": f, "body": body, "entries": entries, "home": home,
|
||
"label": label, "group": f"mixed: {label}" if mixed else f["gpu"]}
|
||
|
||
# ------------------------------------------------------------ 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"]
|
||
runs = len(rc["runs"])
|
||
L += [f"**{label}: {num(rc['value'], dec)} {unit}** · {rc['status']} · "
|
||
f"{runs} run{'s' if runs > 1 else ''}", "",
|
||
"| metric | first run |", "|---|---|"]
|
||
if rc["n"] > 1:
|
||
L += [f"| GPUs | {rc['label']} · tp {rc['tp']} · pp {rc['pp']} |",
|
||
f"| PCIe topology (declared) | {' · '.join(rc['topology'])} |"]
|
||
L += [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 rc["n"] > 1 and unit == "t/s" and rc["value"]:
|
||
L.append(f"| {label} per GPU | {num(rc['value'] / rc['n'])} t/s |")
|
||
# bench-standard scales bandwidth by tp only, and samples the power of one GPU.
|
||
if f["spec"] != "none":
|
||
L.append("| memory bandwidth reached | n/a: speculative decoding makes several tokens "
|
||
"per pass over the weights |")
|
||
elif rc["pp"] > 1 or rc["mixed"]:
|
||
L.append("| memory bandwidth reached | n/a: bench-standard computes it for tensor parallel "
|
||
"over equal GPUs only |")
|
||
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 rc["n"] > 1:
|
||
L.append("| decode energy | n/a: bench-standard samples the power of one GPU |")
|
||
elif 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", "```"]
|
||
if rc["n"] > 1:
|
||
L += ["", "bench.sh records PCIe and power for one GPU only: put the link of every GPU in "
|
||
"`--special-notes`, as in the recipe's `topology`."]
|
||
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 (setup folder, GPU count, model, profile)."""
|
||
top = {}
|
||
for rc in self.recipes:
|
||
f = rc["front"]
|
||
key = (rc["home"], rc["n"], 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 starred(self, rc):
|
||
return self.best().get((rc["home"], rc["n"], rc["front"]["model"], rc["front"]["profile"])) is rc
|
||
|
||
def home_recipes(self, home):
|
||
return sorted((r for r in self.recipes if r["home"] == home),
|
||
key=lambda r: (r["front"]["model"], r["n"], list(PROFILES).index(r["front"]["profile"]),
|
||
r["front"]["engine"]))
|
||
|
||
def headline(self, rc, star=False):
|
||
_, label, unit, _ = PROFILES[rc["front"]["profile"]]
|
||
return f"{num(rc['value'], 2 if unit == 'J/tok' else 1)} {unit} {label}{' ★' if star else ''}"
|
||
|
||
def fastest_single_user(self, homes):
|
||
"""Per model, the fastest single-user recipe in these folders, any GPU count."""
|
||
top = {}
|
||
for rc in self.recipes:
|
||
m = rc["front"]["model"]
|
||
if rc["home"] in homes and rc["front"]["profile"] == "single-user" and rc["value"] is not None \
|
||
and (m not in top or rc["value"] > top[m]["value"]):
|
||
top[m] = rc
|
||
def count(rc):
|
||
return "" if rc["n"] == 1 or rc["mixed"] else f", {rc['n']}×"
|
||
return " · ".join(f"{m}: {num(rc['value'])} t/s ({rc['front']['engine']}{count(rc)})"
|
||
for m, rc in sorted(top.items()))
|
||
|
||
def index_md(self):
|
||
"""The GPU table in the top-level README."""
|
||
L = ["| GPU | VRAM | bandwidth (spec) | recipes | fastest for one user |", "|---|---|---|---|---|"]
|
||
for gpu, g in self.config["gpus"].items():
|
||
d = slug(gpu)
|
||
L.append(f"| [{gpu}]({d}/README.md) | {g['vram_gb']} GB | {g['mem_bw_gbs']} GB/s | "
|
||
f"{len(self.home_recipes(d))} | {self.fastest_single_user([d]) or 'none yet: wanted'} |")
|
||
mixed = [h for h in self.homes if h.startswith("mixed/")]
|
||
n = sum(len(self.home_recipes(h)) for h in mixed)
|
||
L.append(f"| [Mixed setups](mixed/README.md) | {len(mixed)} setup{'s' if len(mixed) != 1 else ''} | — | "
|
||
f"{n} | {self.fastest_single_user(mixed) or 'none yet'} |")
|
||
return "\n".join(L)
|
||
|
||
def recipe_table(self, rows, home):
|
||
L = ["| model | GPUs | profile | engine | headline | status | recipe |", "|---|---|---|---|---|---|---|"]
|
||
for rc in rows:
|
||
f = rc["front"]
|
||
L.append(f"| {f['model']} | {rc['n']} | {f['profile']} | {f['engine']} | "
|
||
f"{self.headline(rc, self.starred(rc))} | {'demo' if rc['demo'] else rc['status']} | "
|
||
f"[{f['title']}]({rc['id'].removeprefix(home + '/')}.md) |")
|
||
return L
|
||
|
||
def results_md(self, home, up):
|
||
n = sum(1 for r in self.results.values() if r["home"] == home)
|
||
where = (f"{plural(n, 'result folder')} in [`results/`](results/), as bench.sh wrote them."
|
||
if n else "None yet. Runs go in `results/` here, as bench.sh writes them.")
|
||
return ["", "## Results", "", where,
|
||
f"Host setup for every recipe: [docs/host-setup.md]({up}docs/host-setup.md)."]
|
||
|
||
def gpu_md(self, gpu):
|
||
"""A GPU folder's README, generated whole."""
|
||
g, d = self.config["gpus"][gpu], slug(gpu)
|
||
rows = self.home_recipes(d)
|
||
L = [f"# {gpu}", "",
|
||
"<!-- Generated by tools/cookbook.py build from cookbook.toml and this folder. Don't edit. -->",
|
||
"", f"{g['vram_gb']} GB VRAM · {g['mem_bw_gbs']} GB/s memory bandwidth (spec) · {g['arch']}", ""]
|
||
if g.get("notes"):
|
||
L += [g["notes"].strip(), ""]
|
||
if any(r["demo"] for r in rows):
|
||
L += ["> **Demo data.** The results in this folder are synthetic, made by "
|
||
"`tools/demo/make_demo.py`. Nothing here was measured.", ""]
|
||
L += ["## Recipes", ""]
|
||
if rows:
|
||
L += self.recipe_table(rows, d)
|
||
L += ["", "★ the fastest recipe for that model, GPU count and profile. Several of this GPU: "
|
||
"files named `<N>x-<engine>-<profile>.md`. With other GPUs: [mixed setups](../mixed/README.md)."]
|
||
else:
|
||
L.append("None yet.")
|
||
tried = [t for t in self.tried if t["home"] == d]
|
||
if tried:
|
||
L += ["", "## What lost", ""] + [
|
||
f"- [{t['front']['model']}]({t['rel'].removeprefix(d + '/')}): {plural(len(t['entries']), 'variant')}"
|
||
for t in tried]
|
||
wanted = [m + (f" on {setup(gpu, n)[2]}" if n > 1 else "") for gg, n, m in self.wanted() if gg == gpu]
|
||
if wanted:
|
||
L += ["", "## Wanted", "", "Fits in VRAM, no single-user recipe yet: " + ", ".join(wanted) +
|
||
". See [CONTRIBUTING.md](../CONTRIBUTING.md)."]
|
||
return "\n".join(L + self.results_md(d, "../")) + "\n"
|
||
|
||
def mixed_md(self):
|
||
"""mixed/README.md: setups of different Arc GPUs in one server."""
|
||
homes = [h for h in self.homes if h.startswith("mixed/")]
|
||
rows = [rc for h in homes for rc in self.home_recipes(h)]
|
||
L = ["# Mixed setups", "",
|
||
"<!-- Generated by tools/cookbook.py build from cookbook.toml and this folder. Don't edit. -->", "",
|
||
"Different Arc GPUs in one server. Each setup has a folder named after its cards, "
|
||
"`<N>x-<gpu>_<N>x-<gpu>` in name order (e.g. `1x-arc-b580_1x-arc-pro-b60`), with the same "
|
||
"layout as a GPU folder. Several of the *same* GPU go in that GPU's folder.", ""]
|
||
if any(r["demo"] for r in rows):
|
||
L += ["> **Demo data.** The results in this folder are synthetic, made by "
|
||
"`tools/demo/make_demo.py`. Nothing here was measured.", ""]
|
||
L += ["## Recipes", ""]
|
||
if rows:
|
||
L += ["| setup | model | GPUs | profile | engine | headline | status | recipe |",
|
||
"|---|---|---|---|---|---|---|---|"]
|
||
for rc in rows:
|
||
f = rc["front"]
|
||
L.append(f"| {rc['label']} | {f['model']} | {rc['n']} | {f['profile']} | {f['engine']} | "
|
||
f"{self.headline(rc, self.starred(rc))} | {'demo' if rc['demo'] else rc['status']} | "
|
||
f"[{f['title']}]({rc['id'].removeprefix('mixed/')}.md) |")
|
||
else:
|
||
L.append("None yet.")
|
||
tried = [t for t in self.tried if t["home"].startswith("mixed/")]
|
||
if tried:
|
||
L += ["", "## What lost", ""] + [
|
||
f"- [{t['front']['model']} on {t['label']}]({t['rel'].removeprefix('mixed/')}): "
|
||
f"{plural(len(t['entries']), 'variant')}" for t in tried]
|
||
L += ["", "## Results", ""] + [
|
||
f"- {h.removeprefix('mixed/')}: [{plural(sum(1 for r in self.results.values() if r['home'] == h), 'result folder')}]"
|
||
f"({h.removeprefix('mixed/')}/results/)" for h in homes
|
||
if (self.root / h / "results").exists()]
|
||
L += ["", "Host setup for every recipe: [docs/host-setup.md](../docs/host-setup.md)."]
|
||
return "\n".join(L) + "\n"
|
||
|
||
def wanted(self):
|
||
"""(gpu, count, model): the fewest of one GPU the model fits in, without a
|
||
single-user recipe for that count yet."""
|
||
have = {(r["home"], r["n"], r["front"]["model"]) for r in self.recipes
|
||
if r["front"]["profile"] == "single-user"}
|
||
out = []
|
||
for g, gv in self.config["gpus"].items():
|
||
for m, mv in self.config["models"].items():
|
||
n = next((k for k in sorted(self.config.get("gpu_counts", [1, 2]))
|
||
if gv["vram_gb"] * k >= mv["min_vram_gb"]), None)
|
||
if n and (slug(g), n, m) not in have:
|
||
out.append((g, n, m))
|
||
return out
|
||
|
||
# ------------------------------------------------------------ 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())
|
||
for gpu in self.config["gpus"]:
|
||
out[self.root / slug(gpu) / "README.md"] = self.gpu_md(gpu)
|
||
out[self.root / "mixed" / "README.md"] = self.mixed_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(rc):
|
||
f = rc["front"]
|
||
return (f'data-gpu="{html.escape(rc["group"])}" 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>")
|
||
|
||
rows = []
|
||
for rc in sorted(cb.recipes, key=lambda r: (cb.homes.index(r["home"]), r["front"]["model"], r["n"],
|
||
r["front"]["profile"], -(r["value"] or 0))):
|
||
f = rc["front"]
|
||
_, label, unit, _ = PROFILES[f["profile"]]
|
||
star = cb.starred(rc)
|
||
rows.append(f'<tr {attrs(rc)}><td>{html.escape(rc["label"])}</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']}"]
|
||
if rc["n"] > 1:
|
||
chips[:0] = [rc["label"], "PCIe " + " · ".join(rc["topology"])]
|
||
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(rc)}><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(td["group"])}" '
|
||
f'data-model="{html.escape(f["model"])}"><h2>{html.escape(f["model"])} on '
|
||
f'{html.escape(td["label"])}: what lost</h2>' +
|
||
md_to_html(body, linker(td["path"]), shift=1, prefix=anchor(td["rel"]) + "-") + "</article>")
|
||
|
||
gpus = list(dict.fromkeys(r["group"] for r in sorted(cb.recipes, key=lambda r: cb.homes.index(r["home"]))))
|
||
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 setup, model and profile.
|
||
{("<strong>Wanted:</strong> " + ", ".join(f"{html.escape(m)} on {setup(g, n)[2]}" for g, n, 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:]))
|