Files
cookbook/tools/demo/make_demo.py
T
ClaudeandClaude Opus 5.5 4673f0afb6
ci / check (push) Successful in 32s
Arc LLM Cookbook: recipes, validator, site, demo content
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>
2026-10-29 15:34:00 +01:00

351 lines
19 KiB
Python

#!/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()