diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..515c3b3 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,17 @@ +name: ci +on: [push, pull_request] +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.10" + - run: pip install pytest shellcheck-py + - name: shellcheck + run: shellcheck -s sh -S warning dev/*.sh bench.sh + - name: bench.sh is built from dev/ + run: sh dev/build.sh --check + - name: tests + run: pytest -q dev/tests diff --git a/.gitignore b/.gitignore index 38e61ed..d192418 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ results/ bench.local.env +__pycache__/ +.pytest_cache/ diff --git a/AGENTS.md b/AGENTS.md index 7da24f8..2622124 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,8 +26,12 @@ one makes the run fail. Correct is more important than fast. ## Models Results only count for the files in the [README's model table](README.md#models). -Check the served file's SHA256 against it, with the commands below the table. On a -mismatch, tell your human before benchmarking. `--quant` for each model is in that table. +`bench.sh` hashes the served file during the dry run and warns on a non-standard file +or a wrong `--quant`. The `model_file` note then says `standard: ...` or +`not a standard model`. On a mismatch, tell your human before benchmarking. If it says +`hash not checked` (the path from the launch command doesn't exist on this machine, +e.g. inside a container), check by hand with the commands below the table. +`--quant` for each model is in that table. ## Procedure @@ -98,7 +102,7 @@ background job, so a dropped session doesn't kill the benchmark. Tell your human: - the result folder (printed after `done:`) -- the summary block: decode t/s, TTFT, concurrency, prefill, bandwidth %, power, energy +- the summary block: decode t/s, TTFT, concurrency, prefill, bandwidth %, power, energy per phase - every warning, and whether the greedy check was `identical` - that the folder is what they send in, and that they should check `server-cmd.txt` for anything private first (tokens, keys and passwords are already redacted) @@ -111,6 +115,8 @@ Tell your human: | `warm-up request failed (HTTP ...)` | server not up, or wrong `--endpoint`/`--model` (step 2). Behind llama-swap the first load can take minutes; `WARM_TIMEOUT=1800` gives it longer | | `missing mandatory value(s)` | pass the listed flags (step 4) | | `GPU power limit not detected here` | ask for the limit, pass `--power-limit W` or `stock` | +| `the model file is not one of the standard models` | the server serves a different file. Tell your human; results with it won't count | +| `--quant X, but the file is the standard ...` | declare the `--quant` the warning names | | `--kv X but the launch command sets Y` | the declared `--kv` is wrong. Use what the command sets | | `greedy_check=differs` | not a failure, but report it. It means nondeterministic kernels or a broken spec-decoding path | | `--thinking X, but the greedy replies ...` | the declared thinking mode doesn't match what the server does. Ask your human which is right; never change the server yourself | diff --git a/README.md b/README.md index a5b6bce..020b274 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,10 @@ longer and keeps the GPU busy the whole time. ## Models -Results only count for these files. Check the hash before you benchmark: a -different file is a different benchmark. +Results only count for these files: a different file is a different benchmark. +`bench.sh` hashes the served file and warns when it isn't one of these, or when +`--quant` doesn't match. The first run takes about a minute for a big file, then the +hash is cached. To check by hand before downloading everything into place: | model | engine | Hugging Face repo | file | `--quant` | |---|---|---|---|---| @@ -137,7 +139,8 @@ file next to `bench.sh`. 4. **BetterBench:** single-stream decode per category, a prefill sweep and a concurrency sweep. GPU power, energy and clock are sampled throughout. 5. **Summary:** decode t/s, TTFT, concurrency and prefill throughput, % of memory - bandwidth reached, average power and clock, and J per token. + bandwidth reached, average power and clock, and energy: J per token for decode and + each concurrency level, J per 1000 tokens for prefill. Everything is recorded as notes in `results.json`, so it shows in the report and in `compare`. Example notes: @@ -146,12 +149,13 @@ Everything is recorded as notes in `results.json`, so it shows in the report and gpu 1x Intel Arc Pro B65 · 32 GB · driver 1.17.39395 pcie Gen4 x16 · ReBAR on engine llama.cpp b11913-7aca0d2ea · 4 slots · image ghcr.io/ggml-org/llama.cpp:server-intel@1a2b3c4d5e6f +model_file /models/Qwen3.8-27B-UD-Q4_K_M.gguf · 16.46 GB · standard: Qwen3.8-27B UD-Q4_K_M launch b 4096 · ub 1024 · fa on · ctk q8_0 · ctv q8_0 · ngl 99 · np 4 env_flags GGML_SYCL_DISABLE_OPT=0 · ZES_ENABLE_SYSMAN=1 mem_bw 532 GB/s measured (torch copy, random, 1024 MiB) · 608 GB/s declared greedy_check identical 3/3 · 1d5105fe09dc thinking default · reasoning seen -run full · concurrency on · bench-standard 0.4.1 · betterbench 0.6.1 +run full · concurrency on · bench-standard 0.5.0 · betterbench 0.6.1 ``` ## Your result @@ -164,7 +168,7 @@ Each run makes a folder `results/----/`: | `results.json` | the results, with all notes | | `meta.json` | every raw value, plus energy and % of bandwidth | | `server-cmd.txt` | your server's launch command, secrets redacted | -| `config.json`, `power.csv`, `betterbench.log` | the config used, power samples, the full output | +| `config.json`, `power.csv`, `timeline.tsv`, `betterbench.log` | the config used, power samples, when each phase ran, the full output | **Send the whole folder of a `--full` run.** Check `server-cmd.txt` for anything private first. Tokens, keys and passwords are redacted automatically. @@ -198,6 +202,8 @@ during the benchmark if you want it. | `warm-up request failed` | is the server up? Are `--endpoint` and `--model` right? `curl URL/models` lists the ids. For a slow first load, try `WARM_TIMEOUT=1800` | | `missing mandatory value(s)` | pass the listed flags | | `GPU power limit not detected` | pass `--power-limit W` (or `stock`) | +| `the model file is not one of the standard models` | you're serving a different file. Download the one from the [table](#models) | +| `--quant X, but the file is the standard ...` | declare the `--quant` the warning names | | `--kv X but the launch command sets Y` | your `--kv` is wrong; use what the command sets | | `greedy_check=differs` | not fatal. Kernels or spec decoding aren't deterministic; mention it | | `--thinking off, but the greedy replies contain reasoning` | thinking is still on in the server's chat template or flags. Fix the server, or declare what it does | @@ -213,7 +219,8 @@ during the benchmark if you want it. ## Developing `bench.sh` is generated: the sources are in [`dev/`](dev/), and `sh dev/build.sh` packs -them into the one file. Commit `dev/` and the rebuilt `bench.sh` together. +them into the one file. Commit `dev/` and the rebuilt `bench.sh` together. CI runs +shellcheck, checks that `bench.sh` is up to date, and runs `pytest dev/tests`. Bugs and ideas: open an issue on [GitHub](https://github.com/aneinander/benchmarks/issues). The GitHub repo is a mirror, updated automatically from the maintainers' source repo. diff --git a/bench.sh b/bench.sh index c4dd05d..20d646b 100755 --- a/bench.sh +++ b/bench.sh @@ -1,5 +1,5 @@ #!/bin/sh -# bench.sh - bench-standard 0.4.1, everything in one file: run ./bench.sh --help +# bench.sh - bench-standard 0.5.0, everything in one file: run ./bench.sh --help # Generated by dev/build.sh from dev/ - edit there and rebuild, not here. set -eu BENCH_HOME=${BENCH_HOME:-$(cd "$(dirname "$0")" && pwd)}; export BENCH_HOME @@ -123,6 +123,16 @@ sys.exit(not sys.argv[1] or v(sys.argv[1]) < v(sys.argv[2]))' "$have_ver" "$BETT die "BetterBench $BETTERBENCH_MIN_VERSION or newer required, found '${have_ver:-not installed}'" \ "(see https://github.com/GGZ14/BetterBench)" command -v curl >/dev/null || die "curl not found" +# The exact build: two installs can both say 0.6.1. pip records where it came +# from: a git commit, or a local checkout (then git describes it). +bb_build=$(bb=$(command -v betterbench) && py=$(sed -n '1s/^#!//p' "$(readlink -f "$bb")") && + $py -c 'import importlib.metadata as m, json +u = json.loads(m.distribution("betterbench").read_text("direct_url.json") or "{}") +c = (u.get("vcs_info") or {}).get("commit_id") +print(c[:12] if c else u.get("url", "")[7:] if u.get("url", "").startswith("file://") else "")' 2>/dev/null) || bb_build="" +if [ -d "$bb_build" ]; then + bb_build=$(git -c safe.directory='*' -C "$bb_build" describe --tags --always --dirty 2>/dev/null) || bb_build="" +fi missing="" for f in endpoint model tp pp quant kv spec thinking submitter; do @@ -233,7 +243,7 @@ fi [ -n "$pcie" ] && printf 'pcie=%s\n' "$pcie" [ -n "$special" ] && printf 'special_notes=%s\n' "$special" [ -n "$mem_bw" ] && printf 'mem_bw=%s\n' "$mem_bw" - printf 'betterbench=%s\n' "$have_ver" + printf 'betterbench=%s\nbetterbench_build=%s\n' "$have_ver" "$bb_build" printf 'bench_standard=%s\nrun_mode=%s\nconcurrency=%s\n' "$STANDARD_VERSION" \ "$([ $quick = 1 ] && echo quick || echo full)" "$([ $no_conc = 1 ] && echo off || echo on)" } > "$tmp/mandatory" @@ -264,201 +274,8 @@ fi # The notes are grouped for reading: one chip per topic, nothing twice. # The context size is left out - BetterBench shows it from --max-model-len. # launch.json: the settings parsed from the launch command, for meta.json. -python3 - "$tmp/mandatory" "$tmp/collected" "$tmp/measured" "$tmp/cmd.red" "$tmp/launch.json" \ - > "$tmp/notes" <<'PY' -import json, shlex, sys -def kv(path): - with open(path, encoding="utf-8") as f: - return dict(l.rstrip("\n").split("=", 1) for l in f if "=" in l) -m, c, meas = kv(sys.argv[1]), kv(sys.argv[2]), kv(sys.argv[3]) -cmd = open(sys.argv[4], encoding="utf-8").read().strip() -def g(k): - v = c.get(k, "") - return "" if v in ("", "unknown") else v -def join(*parts): - return " · ".join(p for p in parts if p) or "unknown" - -vendor = {"intel": "Intel", "nvidia": "NVIDIA", "amd": "AMD"}.get(g("gpu_vendor"), g("gpu_vendor")) -count = g("gpu_count") -gpu = join(" ".join(p for p in (count and count + "x", vendor if vendor != "none" else "", - g("gpu_model")) if p), - g("gpu_vram_gb") and g("gpu_vram_gb") + " GB", - g("gpu_driver") and "driver " + g("gpu_driver")) - -link, top = g("pcie_link"), g("pcie_max") -if m.get("pcie"): - pcie = m["pcie"] + " (declared)" -elif link and top and link != top: - pcie = f"{link} now, {top} max" # idle GPUs drop the link speed -else: - pcie = link or "unknown" -if g("rebar"): - pcie += " · ReBAR " + g("rebar") - -pl, det = m["power_limit"], g("gpu_power_limit_w") -if pl == "stock": - power = join("stock", det and det + " W") -else: - power = pl + " W" - if det and abs(float(det) - float(pl)) > 1: - power += f" (GPU reports {det} W)" - -virt = g("virt") -host = join(g("cpu_model"), g("ram_gb") and g("ram_gb") + " GB RAM", g("os"), - g("kernel") and "kernel " + g("kernel"), virt != "none" and virt and "VM " + virt) - -# Settings in the launch command that swing results but no API reports: -# batch sizes, flash attention, KV types, env flags. Flags left out of the -# command are the engine's defaults, which change between versions. -try: - words = shlex.split(cmd.replace("\\\n", " ")) -except ValueError: - words = cmd.split() -env, flags, prog = {}, {}, None -BOOL = {"--no-mmap", "--mlock", "--enforce-eager", "--enable-prefix-caching", - "--no-enable-prefix-caching", "--enable-chunked-prefill", - "--no-enable-chunked-prefill", "--cont-batching", "-cb", "--no-cont-batching", "-nocb", - "-cmoe", "--cpu-moe", "-rm", "--rm", "-d", "--detach", "-it", "-i", "--privileged"} -FA_VALUES = {"on", "off", "auto", "1", "0", "true", "false"} -i = 0 -while i < len(words): - w = words[i] - nxt = words[i + 1] if i + 1 < len(words) else None - if prog is None and "=" in w and not w.startswith("-") and w.split("=", 1)[0].isidentifier(): - k, v = w.split("=", 1); env[k] = v # FOO=1 cmd - elif prog is None and not w.startswith("-") and w != "env": - prog = w - elif w in ("-e", "--env") and nxt is not None and not nxt.startswith("-"): # docker -e K=V - k, _, v = nxt.partition("="); env[k] = v if _ else "(inherited)"; i += 1 - elif w.startswith("--env="): - k, _, v = w[6:].partition("="); env[k] = v if _ else "(inherited)" - elif w.startswith("-e") and len(w) > 2 and "=" in w and w[2:].split("=")[0].isidentifier(): - k, v = w[2:].split("=", 1); env[k] = v - elif w.startswith("-"): - if "=" in w and w.startswith("--"): - k, v = w.split("=", 1); flags[k] = v - elif w in ("-fa", "--flash-attn"): - if nxt is not None and nxt.lower() in FA_VALUES: - flags[w] = nxt; i += 1 - else: - flags[w] = "on" # older bare -fa - elif w in BOOL or nxt is None or nxt.startswith("-"): - flags[w] = True - else: - flags[w] = nxt; i += 1 - i += 1 - -def flag(*names): - for n in names: - if n in flags: - return flags[n] - return None - -LLAMA = [("b", ("-b", "--batch-size")), ("ub", ("-ub", "--ubatch-size")), - ("fa", ("-fa", "--flash-attn")), ("ctk", ("-ctk", "--cache-type-k")), - ("ctv", ("-ctv", "--cache-type-v")), ("ngl", ("-ngl", "--gpu-layers", "--n-gpu-layers")), - ("np", ("-np", "--parallel")), ("t", ("-t", "--threads")), - ("sm", ("-sm", "--split-mode")), ("ts", ("-ts", "--tensor-split")), - ("ot", ("-ot", "--override-tensor")), ("ncmoe", ("-ncmoe", "--n-cpu-moe")), - ("cmoe", ("-cmoe", "--cpu-moe")), ("no-mmap", ("--no-mmap",)), ("mlock", ("--mlock",)), - ("nocb", ("-nocb", "--no-cont-batching"))] -LLAMA_ALWAYS = {"b", "ub", "fa", "ctk", "ctv"} # shown as "default" when not set -VLLM = ["--max-num-batched-tokens", "--max-num-seqs", "--kv-cache-dtype", - "--gpu-memory-utilization", "--dtype", "--quantization", "--block-size", - "--enforce-eager", "--enable-chunked-prefill", "--no-enable-chunked-prefill", - "--enable-prefix-caching", "--no-enable-prefix-caching", "--attention-backend", - "--compilation-config", "-O", "--speculative-config"] -launch_kind = g("engine") -if launch_kind not in ("llama.cpp", "vllm"): - launch_kind = ("llama.cpp" if prog and "llama-server" in prog or flag("-ngl", "-ub", "-ctk") - else "vllm" if any(f in flags for f in VLLM) else "") -settings = {} -if launch_kind == "llama.cpp": - for name, al in LLAMA: - v = flag(*al) - if v is not None: - settings[name] = "on" if v is True else v - elif name in LLAMA_ALWAYS: - settings[name] = "default" -elif launch_kind == "vllm": - for f in VLLM: - if f in flags: - settings[f.lstrip("-")] = "on" if flags[f] is True else "".join(str(flags[f]).split()) -if not cmd: - launch = "unknown (pass --server-cmd-file)" -else: - launch = " · ".join(k if v == "on" and k in ("no-mmap", "mlock", "nocb", "cmoe") or - k.startswith(("enable-", "no-enable-", "enforce-")) else f"{k} {v}" - for k, v in settings.items()) or "no tuning flags" -# Offline switches and cache paths don't change the numbers. -QUIET = {"HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE", "HF_DATASETS_OFFLINE", "HF_HOME", - "VLLM_CACHE_ROOT", "PATH", "HOME", "TZ", "LANG", "LC_ALL"} -env_flags = (" · ".join(f"{k}={v}" for k, v in env.items() if k not in QUIET) or "none" - ) if cmd else "unknown" -json.dump({"engine": launch_kind or None, "settings": settings, "env": env, "flags": flags}, - open(sys.argv[5], "w", encoding="utf-8"), indent=2, default=str) - -# The declared --kv should be what the command sets. -kvset = [x for x in (settings.get("ctk"), settings.get("ctv"), settings.get("kv-cache-dtype")) - if x and x not in ("default", "auto")] -if kvset and m["kv"] not in kvset + ["/".join(kvset), "_".join(kvset)]: - print(f"bench.sh: warning: --kv {m['kv']} but the launch command sets " - f"{'/'.join(kvset)}", file=sys.stderr) - -mb = g("model_bytes") -model_file = join(g("model_file"), mb and f"{int(mb) / 1e9:.2f} GB") -mem_bw = join(g("gpu_mem_bw_gbs") and - f'{g("gpu_mem_bw_gbs")} GB/s measured ({g("gpu_mem_bw_tool") or "?"})', - m.get("mem_bw") and m["mem_bw"] + " GB/s declared") -if meas.get("greedy_check") == "identical": - greedy = f'identical {meas["greedy_runs"]}/{meas["greedy_runs"]} · {meas["greedy_hash"]}' -elif meas.get("greedy_check") == "differs": - greedy = f'differs: {meas["greedy_variants"]} variants in {meas["greedy_runs"]} · first {meas["greedy_hash"]}' -else: - greedy = "failed" - -# --thinking is declared, but the greedy replies show whether the model -# reasoned: check one against the other. -seen = meas.get("greedy_reasoning") -thinking = join(m["thinking"], {"yes": "reasoning seen", "no": "no reasoning seen", - "mixed": "reasoning in some replies"}.get(seen, "")) -if m["thinking"] == "off" and seen in ("yes", "mixed"): - print("bench.sh: warning: --thinking off, but the greedy replies contain reasoning;" - " check the server's chat template or reasoning flags", file=sys.stderr) -elif m["thinking"] in ("on", "low", "medium", "high") and seen == "no": - print(f"bench.sh: warning: --thinking {m['thinking']}, but the greedy replies contain no" - " reasoning; thinking may be off on the server", file=sys.stderr) - -eng = g("engine") -engine = join(" ".join(p for p in (eng, g("engine_version")) if p), - g("engine_slots") and g("engine_slots") + " slots", - g("engine_image") and "image " + g("engine_image"), - g("proxy") not in ("", "none") and "via " + g("proxy")) - -notes = [ - ("submitter", m["submitter"]), - ("gpu", gpu), - ("pcie", pcie), - ("power_limit", power), - ("host", host), - ("engine", engine), - ("model_file", model_file), - ("mem_bw", mem_bw), - ("parallel", f"tp {m['tp']} · pp {m['pp']}"), - ("precision", f"weights {m['quant']} · kv {m['kv']}"), - ("launch", launch), - ("env_flags", env_flags), - ("spec", m["spec"]), - ("thinking", thinking), - ("greedy_check", greedy), - ("run", join(m["run_mode"], "concurrency " + m["concurrency"], - "bench-standard " + m["bench_standard"], "betterbench " + m["betterbench"])), -] -if m.get("special_notes"): - notes.append(("special_notes", m["special_notes"])) -for k, v in notes: - print(f"{k}={v}") -PY +python3 "$here/notes.py" "$tmp/mandatory" "$tmp/collected" "$tmp/measured" "$tmp/cmd.red" \ + "$tmp/launch.json" "$here/models.tsv" > "$tmp/notes" engine=$(get engine) gpu=$(get gpu_model) count=$(get gpu_count) ctx=$(get ctx) [ "$engine" != unknown ] || echo "bench.sh: warning: engine not detected; result is hard to compare" >&2 @@ -535,8 +352,15 @@ echo "running betterbench -> $run_dir" >&2 t_start=$(date +%s.%N) # Full output always goes to betterbench.log; the terminal gets all of it # (--verbose) or the progress lines and anything that looks like trouble. +# timeline.tsv stamps each progress line, for the energy of each phase. { PYTHONUNBUFFERED=1 betterbench "$@" 2>&1 || echo $? > "$tmp/bb_rc"; } | tee "$run_dir/betterbench.log" | + python3 -uc 'import sys, time +tl = open(sys.argv[1], "w", encoding="utf-8") +for line in iter(sys.stdin.readline, ""): + if line.startswith("["): + tl.write(f"{time.time():.3f}\t{line}"); tl.flush() + sys.stdout.write(line); sys.stdout.flush()' "$run_dir/timeline.tsv" | if [ $verbose = 1 ]; then cat; else grep --line-buffered -E '^\[|^phases|warn|WARN|rror|Traceback' || true; fi >&2 if [ -s "$tmp/bb_rc" ]; then mv "$run_dir" "$run_dir.failed" 2>/dev/null || true @@ -548,104 +372,11 @@ if [ -n "$sampler" ]; then [ -s "$run_dir/power.csv" ] || rm -f "$run_dir/power.csv" fi -# Energy per token and decode as % of memory bandwidth, from what the run -# measured. They come after the run, so they go to meta.json ("post_run"), -# not into the notes of results.json. -T0=$t_start T1=$t_end python3 - "$run_dir" <<'PY' || echo "bench.sh: warning: post-run figures failed" >&2 -import json, os, statistics, sys -d = sys.argv[1] -res = json.load(open(f"{d}/results.json", encoding="utf-8")) -meta = json.load(open(f"{d}/meta.json", encoding="utf-8")) -c, m = meta["collected"], meta["mandatory"] -post = {"wall_s": round(float(os.environ["T1"]) - float(os.environ["T0"]), 1)} - -# Output tokens of the measured passes and the concurrency sweep; warm-up -# passes and prefill probes are not in results.json but draw power too. -single = [r for recs in (res.get("single_stream") or {}).values() for r in recs - if r.get("ok", True)] -tok = sum(r.get("completion_tokens") or 0 for r in single) -tok += sum(round(x.get("aggregate_tps", 0) * x.get("wall_s", 0)) - for x in res.get("concurrency") or []) - -rows = [] -if os.path.exists(f"{d}/power.csv"): - for line in open(f"{d}/power.csv"): - p = line.strip().split(",") - try: - rows.append((float(p[0]), float(p[1]), float(p[2]) if p[2] else None, - float(p[3]) if len(p) > 3 and p[3] else 0.0)) - except (ValueError, IndexError): - pass -if len(rows) >= 2: - span = rows[-1][0] - rows[0][0] - if rows[0][2] is not None and rows[-1][2] is not None and rows[-1][2] >= rows[0][2]: - joules, src = rows[-1][2] - rows[0][2], "energy counter" - else: - joules = sum((b[0] - a[0]) * (a[1] + b[1]) / 2 for a, b in zip(rows, rows[1:])) - src = "integrated power" - e = {"joules": round(joules), "source": src, "sampled_s": round(span, 1), - "avg_w": round(joules / span, 1) if span else None, - "peak_w": max(r[1] for r in rows), "output_tokens": tok, - "j_per_output_token": round(joules / tok, 3) if tok else None} - # A clock-gated idle GPU reads 0 MHz; average the samples where it runs. - clk = [r[3] for r in rows if r[3] > 0] - if clk: - e.update(avg_mhz=round(statistics.mean(clk)), min_mhz=round(min(clk)), - max_mhz=round(max(clk)), clock_samples=f"{len(clk)}/{len(rows)}") - post["energy"] = e - -# Batch-1 decode reads all weights once per token, so decode t/s x weight -# bytes is the bandwidth it achieves. Dense models only; spec decoding or MoE -# can go above 100%. -tps = [r["decode_tps"] for r in single if r.get("decode_tps")] -# measured where there is a figure: what the card really reaches -bw = c.get("gpu_mem_bw_gbs") if c.get("gpu_mem_bw_gbs") not in (None, "", "unknown") else m.get("mem_bw") -mb = c.get("model_bytes") -if tps and bw not in (None, "", "unknown") and mb not in (None, "", "unknown"): - med = statistics.median(tps) - eff = med * int(mb) / 1e9 - post["roofline"] = {"decode_tps_median": round(med, 2), "model_bytes": int(mb), - "mem_bw_gbs": float(bw), "effective_gbs": round(eff, 1), - "pct_of_mem_bw": round(100 * eff / float(bw), 1)} - -# The summary: headline numbers plus the setup that makes them comparable. -def med(xs): - xs = [x for x in xs if x] - return statistics.median(xs) if xs else None -def f(x, unit, d=0): - return "—" if x is None else f"{x:,.{d}f} {unit}" -notes = meta["notes"] -L = [f" {meta['model']} · {notes.get('engine', '?')}", - f" {notes.get('gpu', '?')} · {notes.get('power_limit', '?')} limit", - f" {notes.get('run', '?')} · greedy {notes.get('greedy_check', '?')}", - f" decode (batch 1) {f(med(tps), 't/s', 1)} TTFT p50 " - f"{f(med(r.get('ttft_ms') for r in single), 'ms')}"] -conc = res.get("concurrency") or [] -if conc: - L.append(" concurrency " + " ".join( - f"{x['level']}: {x.get('aggregate_tps', 0):,.0f} t/s" for x in conc)) -live = [p for p in res.get("prefill") or [] if not p.get("skipped")] -if live: - L.append(" prefill " + " ".join( - f"{p['target_depth'] // 1000}k: {f(med(p.get('pp_tps') or []), 't/s')}" for p in live)) -if "roofline" in post: - r = post["roofline"] - L.append(f" bandwidth {r['effective_gbs']:.0f} GB/s effective = " - f"{r['pct_of_mem_bw']:.0f}% of {r['mem_bw_gbs']:.0f} GB/s ({notes.get('mem_bw', '')})") -if "energy" in post: - e = post["energy"] - clock = (f" · clock avg {e['avg_mhz']} MHz ({e['min_mhz']}-{e['max_mhz']})" - if "avg_mhz" in e else "") - L.append(f" power avg {e['avg_w']} W, peak {e['peak_w']:.0f} W{clock}") - L.append(f" energy {e['joules'] / 1000:.1f} kJ, " - f"{e['j_per_output_token']} J per output token (whole run)") -print("\n" + "\n".join(L), file=sys.stderr) - -meta["post_run"] = post -with open(f"{d}/meta.json", "w", encoding="utf-8") as f: - json.dump(meta, f, indent=2) - f.write("\n") -PY +# Energy (whole run and per phase) and decode as % of memory bandwidth, from +# what the run measured. They come after the run, so they go to meta.json +# ("post_run"), not into the notes of results.json. +T0=$t_start T1=$t_end python3 "$here/postrun.py" "$run_dir" || + echo "bench.sh: warning: post-run figures failed" >&2 # BetterBench with GGZ14/BetterBench#4 fingerprints PCIe and BAR itself # (env.gpu.pci), on the machine BetterBench runs on. Say so when that is not @@ -685,7 +416,8 @@ cat > "$d/collect-env.sh" <<'__BENCH_STANDARD_EOF__' # --server-cmd-out behind llama-swap: write the model's launch command (raw) to FILE # --server-cmd-file the launch command when not behind llama-swap (finds the container) # env: BETTERBENCH_API_KEY, PROBE_TIMEOUT (s, default 10), LOAD_TIMEOUT (s, default 600), -# MEASURE_BW=0 (skip the bandwidth test), BW_PYTHON (python with torch for it) +# MEASURE_BW=0 (skip the bandwidth test), BW_PYTHON (python with torch for it), +# HASH_MODEL=0 (skip hashing the model file) set -u LC_ALL=C; export LC_ALL @@ -702,7 +434,7 @@ while [ $# -gt 0 ]; do --api-key) need $# "$1"; api_key=$2; shift 2 ;; --server-cmd-out) need $# "$1"; cmd_out=$2; shift 2 ;; --server-cmd-file) need $# "$1"; cmd_file=$2; shift 2 ;; - -h|--help) sed -n '2,13p' "$0"; exit 0 ;; + -h|--help) sed -n '2,14p' "$0"; exit 0 ;; *) echo "collect-env: unknown argument: $1" >&2; exit 2 ;; esac done @@ -925,7 +657,8 @@ PY fi # Weight bytes as stored: a single file, the parts of a split GGUF -# (-00001-of-0000N.gguf), or the *.safetensors of a model directory. +# (-00001-of-0000N.gguf), or the *.safetensors of a model directory, without +# an MTP head (*mtp*), which plain decoding doesn't read. model_bytes="" if [ -f "$model_file" ]; then case $model_file in @@ -934,7 +667,7 @@ if [ -f "$model_file" ]; then esac model_bytes=$(stat -c %s "$@" 2>/dev/null | awk '{s += $1} END {if (s) printf "%d", s}') elif [ -d "$model_file" ]; then - model_bytes=$(find "$model_file" -maxdepth 1 -name '*.safetensors' -exec stat -c %s {} + 2>/dev/null | + model_bytes=$(find "$model_file" -maxdepth 1 -name '*.safetensors' ! -name '*mtp*' -exec stat -c %s {} + 2>/dev/null | awk '{s += $1} END {if (s) printf "%d", s}') fi @@ -949,12 +682,28 @@ if [ -n "$container" ] && have docker && engine_image=$(printf '%s' "$i" | sed 's/@sha256:\(.\{12\}\).*/@\1/') fi +# vLLM logs what the weights take in GPU memory, per worker. That beats the +# stored size when it quantizes at load (fp8 from bf16 files reads half). +model_loaded_gib="" +if [ "$engine" = vllm ] && [ -n "$container" ] && have docker; then + model_loaded_gib=$(docker logs "$container" 2>&1 | sed -n 's/.*Model loading took \([0-9.]*\) GiB.*/\1/p' | tail -n1) +fi + +# The model's SHA256, checked against the standard models (README, Models). +# The first time takes a while for a big file, then it's cached. +# HASH_MODEL=0 skips it. +model_sha256="" +here=$(cd "$(dirname "$0")" && pwd) +if [ "${HASH_MODEL:-1}" != 0 ] && [ -e "$model_file" ] && have python3; then + echo "collect-env: hashing the model file (cached after the first time) ..." >&2 + model_sha256=$(python3 "$here/model_hash.py" "$model_file" 2>/dev/null) +fi + # Measured memory bandwidth, the base for "% of peak". mem-bw.py copies random # data with torch, inside the server's container (same GPU, env and torch), or # with $BW_PYTHON. Fallback: clpeak, whose test data may compress on Arc and # read high. A few seconds and 2 GiB of free VRAM; MEASURE_BW=0 skips it. gpu_mem_bw_gbs="" gpu_mem_bw_tool="" -here=$(cd "$(dirname "$0")" && pwd) if [ "${MEASURE_BW:-1}" != 0 ]; then if [ -n "${BW_PYTHON:-}" ]; then r=$(timeout 300 "$BW_PYTHON" "$here/mem-bw.py" 2>/dev/null) @@ -1004,6 +753,8 @@ kv engine_slots "$engine_slots" kv engine_image "$engine_image" kv model_file "$model_file" kv model_bytes "$model_bytes" +kv model_loaded_gib "$model_loaded_gib" +kv model_sha256 "$model_sha256" kv ctx "$ctx" exit 0 __BENCH_STANDARD_EOF__ @@ -1097,6 +848,563 @@ for _ in range(3): best = max(best, 20 * 2 * x.numel() * 4 / (time.perf_counter() - t) / 1e9) print(f"{best:.0f} {mib}") __BENCH_STANDARD_EOF__ +cat > "$d/model_hash.py" <<'__BENCH_STANDARD_EOF__' +"""model_hash.py - SHA256 of a model, as the README's Models section defines it. + +usage: model_hash.py PATH (prints the hash, or nothing when PATH can't be read) + +A file: its SHA256, like `sha256sum FILE`. A directory: the SHA256 over the +per-file hashes of its *.safetensors, in byte order of the names, exactly like +`sha256sum *.safetensors | LC_ALL=C sort -k2 | sha256sum`. + +Hashing a 16 GB file takes a while, so per-file hashes are cached in +~/.cache/bench-standard/sha256.tsv, keyed by path, size and mtime. +""" +import hashlib +import os +import sys + +CACHE = os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), + "bench-standard", "sha256.tsv") + + +def _load_cache(): + cache = {} + try: + with open(CACHE, encoding="utf-8") as f: + for line in f: + p = line.rstrip("\n").split("\t") + if len(p) == 4: + cache[(p[0], p[1], p[2])] = p[3] + except OSError: + pass + return cache + + +def _save_cache(cache): + try: + os.makedirs(os.path.dirname(CACHE), exist_ok=True) + tmp = CACHE + f".{os.getpid()}" + with open(tmp, "w", encoding="utf-8") as f: + for (path, size, mtime), h in sorted(cache.items()): + f.write(f"{path}\t{size}\t{mtime}\t{h}\n") + os.replace(tmp, CACHE) + except OSError: + pass + + +def file_sha256(path, cache): + st = os.stat(path) + key = (os.path.realpath(path), str(st.st_size), str(st.st_mtime_ns)) + if key not in cache: + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 22), b""): + h.update(block) + cache[key] = h.hexdigest() + return cache[key] + + +def model_sha256(path, cache=None): + cache = _load_cache() if cache is None else cache + if os.path.isdir(path): + names = sorted((n for n in os.listdir(path) if n.endswith(".safetensors")), + key=lambda n: n.encode()) + if not names: + return None + listing = "".join(f"{file_sha256(os.path.join(path, n), cache)} {n}\n" for n in names) + return hashlib.sha256(listing.encode()).hexdigest() + return file_sha256(path, cache) + + +if __name__ == "__main__": + try: + cache = _load_cache() + h = model_sha256(sys.argv[1], cache) + _save_cache(cache) + except (OSError, IndexError): + h = None + if h: + print(h) +__BENCH_STANDARD_EOF__ +cat > "$d/notes.py" <<'__BENCH_STANDARD_EOF__' +"""notes.py - the notes bench.sh hands BetterBench, one per topic. + +usage: notes.py MANDATORY COLLECTED MEASURED CMD LAUNCH_JSON MODELS_TSV > notes +The first three are key=value files (declared, detected by collect-env.sh, +measured by the greedy check), CMD the redacted launch command (may be +empty). Writes the parsed launch settings to LAUNCH_JSON and prints +key=value notes; warnings go to stderr. +""" +import json, shlex, sys +def kv(path): + with open(path, encoding="utf-8") as f: + return dict(l.rstrip("\n").split("=", 1) for l in f if "=" in l) +m, c, meas = kv(sys.argv[1]), kv(sys.argv[2]), kv(sys.argv[3]) +models = [l.rstrip("\n").split("\t") for l in open(sys.argv[6], encoding="utf-8") + if l.strip() and not l.startswith("#")] +cmd = open(sys.argv[4], encoding="utf-8").read().strip() +def g(k): + v = c.get(k, "") + return "" if v in ("", "unknown") else v +def join(*parts): + return " · ".join(p for p in parts if p) or "unknown" + +vendor = {"intel": "Intel", "nvidia": "NVIDIA", "amd": "AMD"}.get(g("gpu_vendor"), g("gpu_vendor")) +count = g("gpu_count") +gpu = join(" ".join(p for p in (count and count + "x", vendor if vendor != "none" else "", + g("gpu_model")) if p), + g("gpu_vram_gb") and g("gpu_vram_gb") + " GB", + g("gpu_driver") and "driver " + g("gpu_driver")) + +link, top = g("pcie_link"), g("pcie_max") +if m.get("pcie"): + pcie = m["pcie"] + " (declared)" +elif link and top and link != top: + pcie = f"{link} now, {top} max" # idle GPUs drop the link speed +else: + pcie = link or "unknown" +if g("rebar"): + pcie += " · ReBAR " + g("rebar") + +pl, det = m["power_limit"], g("gpu_power_limit_w") +if pl == "stock": + power = join("stock", det and det + " W") +else: + power = pl + " W" + if det and abs(float(det) - float(pl)) > 1: + power += f" (GPU reports {det} W)" + +virt = g("virt") +host = join(g("cpu_model"), g("ram_gb") and g("ram_gb") + " GB RAM", g("os"), + g("kernel") and "kernel " + g("kernel"), virt != "none" and virt and "VM " + virt) + +# Settings in the launch command that swing results but no API reports: +# batch sizes, flash attention, KV types, env flags. Flags left out of the +# command are the engine's defaults, which change between versions. +try: + words = shlex.split(cmd.replace("\\\n", " ")) +except ValueError: + words = cmd.split() +env, flags, prog = {}, {}, None +BOOL = {"--no-mmap", "--mlock", "--enforce-eager", "--enable-prefix-caching", + "--no-enable-prefix-caching", "--enable-chunked-prefill", + "--no-enable-chunked-prefill", "--cont-batching", "-cb", "--no-cont-batching", "-nocb", + "-cmoe", "--cpu-moe", "-rm", "--rm", "-d", "--detach", "-it", "-i", "--privileged"} +FA_VALUES = {"on", "off", "auto", "1", "0", "true", "false"} +i = 0 +while i < len(words): + w = words[i] + nxt = words[i + 1] if i + 1 < len(words) else None + if prog is None and "=" in w and not w.startswith("-") and w.split("=", 1)[0].isidentifier(): + k, v = w.split("=", 1); env[k] = v # FOO=1 cmd + elif prog is None and not w.startswith("-") and w != "env": + prog = w + elif w in ("-e", "--env") and nxt is not None and not nxt.startswith("-"): # docker -e K=V + k, _, v = nxt.partition("="); env[k] = v if _ else "(inherited)"; i += 1 + elif w.startswith("--env="): + k, _, v = w[6:].partition("="); env[k] = v if _ else "(inherited)" + elif w.startswith("-e") and len(w) > 2 and "=" in w and w[2:].split("=")[0].isidentifier(): + k, v = w[2:].split("=", 1); env[k] = v + elif w.startswith("-"): + if "=" in w and w.startswith("--"): + k, v = w.split("=", 1); flags[k] = v + elif w in ("-fa", "--flash-attn"): + if nxt is not None and nxt.lower() in FA_VALUES: + flags[w] = nxt; i += 1 + else: + flags[w] = "on" # older bare -fa + elif w in BOOL or nxt is None or nxt.startswith("-"): + flags[w] = True + else: + flags[w] = nxt; i += 1 + i += 1 + +def flag(*names): + for n in names: + if n in flags: + return flags[n] + return None + +LLAMA = [("b", ("-b", "--batch-size")), ("ub", ("-ub", "--ubatch-size")), + ("fa", ("-fa", "--flash-attn")), ("ctk", ("-ctk", "--cache-type-k")), + ("ctv", ("-ctv", "--cache-type-v")), ("ngl", ("-ngl", "--gpu-layers", "--n-gpu-layers")), + ("np", ("-np", "--parallel")), ("t", ("-t", "--threads")), + ("sm", ("-sm", "--split-mode")), ("ts", ("-ts", "--tensor-split")), + ("ot", ("-ot", "--override-tensor")), ("ncmoe", ("-ncmoe", "--n-cpu-moe")), + ("cmoe", ("-cmoe", "--cpu-moe")), ("no-mmap", ("--no-mmap",)), ("mlock", ("--mlock",)), + ("nocb", ("-nocb", "--no-cont-batching"))] +LLAMA_ALWAYS = {"b", "ub", "fa", "ctk", "ctv"} # shown as "default" when not set +VLLM = ["--max-num-batched-tokens", "--max-num-seqs", "--kv-cache-dtype", + "--gpu-memory-utilization", "--dtype", "--quantization", "--block-size", + "--enforce-eager", "--enable-chunked-prefill", "--no-enable-chunked-prefill", + "--enable-prefix-caching", "--no-enable-prefix-caching", "--attention-backend", + "--compilation-config", "-O", "--speculative-config"] +launch_kind = g("engine") +if launch_kind not in ("llama.cpp", "vllm"): + launch_kind = ("llama.cpp" if prog and "llama-server" in prog or flag("-ngl", "-ub", "-ctk") + else "vllm" if any(f in flags for f in VLLM) else "") +settings = {} +if launch_kind == "llama.cpp": + for name, al in LLAMA: + v = flag(*al) + if v is not None: + settings[name] = "on" if v is True else v + elif name in LLAMA_ALWAYS: + settings[name] = "default" +elif launch_kind == "vllm": + for f in VLLM: + if f in flags: + settings[f.lstrip("-")] = "on" if flags[f] is True else "".join(str(flags[f]).split()) +if not cmd: + launch = "unknown (pass --server-cmd-file)" +else: + launch = " · ".join(k if v == "on" and k in ("no-mmap", "mlock", "nocb", "cmoe") or + k.startswith(("enable-", "no-enable-", "enforce-")) else f"{k} {v}" + for k, v in settings.items()) or "no tuning flags" +# Offline switches and cache paths don't change the numbers. +QUIET = {"HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE", "HF_DATASETS_OFFLINE", "HF_HOME", + "VLLM_CACHE_ROOT", "PATH", "HOME", "TZ", "LANG", "LC_ALL"} +env_flags = (" · ".join(f"{k}={v}" for k, v in env.items() if k not in QUIET) or "none" + ) if cmd else "unknown" +json.dump({"engine": launch_kind or None, "settings": settings, "env": env, "flags": flags}, + open(sys.argv[5], "w", encoding="utf-8"), indent=2, default=str) + +# The declared --kv should be what the command sets. +kvset = [x for x in (settings.get("ctk"), settings.get("ctv"), settings.get("kv-cache-dtype")) + if x and x not in ("default", "auto")] +if kvset and m["kv"] not in kvset + ["/".join(kvset), "_".join(kvset)]: + print(f"bench.sh: warning: --kv {m['kv']} but the launch command sets " + f"{'/'.join(kvset)}", file=sys.stderr) + +# The model file against the standard models: results only count for those. +mb, sha = g("model_bytes"), g("model_sha256") +std = next((r for r in models if len(r) >= 4 and r[3] == sha), None) if sha else None +if std: + check = f"standard: {std[0]} {std[2]}" + if m["quant"] != std[2]: + print(f"bench.sh: warning: --quant {m['quant']}, but the file is the standard " + f"{std[0]} {std[2]}; declare --quant {std[2]}", file=sys.stderr) +elif sha: + check = f"not a standard model (sha256 {sha[:12]})" + print("bench.sh: warning: the model file is not one of the standard models " + "(README, Models), so the result won't count", file=sys.stderr) +else: + check = "hash not checked" +model_file = join(g("model_file"), mb and f"{int(mb) / 1e9:.2f} GB", check) +mem_bw = join(g("gpu_mem_bw_gbs") and + f'{g("gpu_mem_bw_gbs")} GB/s measured ({g("gpu_mem_bw_tool") or "?"})', + m.get("mem_bw") and m["mem_bw"] + " GB/s declared") +if meas.get("greedy_check") == "identical": + greedy = f'identical {meas["greedy_runs"]}/{meas["greedy_runs"]} · {meas["greedy_hash"]}' +elif meas.get("greedy_check") == "differs": + greedy = f'differs: {meas["greedy_variants"]} variants in {meas["greedy_runs"]} · first {meas["greedy_hash"]}' +else: + greedy = "failed" + +# --thinking is declared, but the greedy replies show whether the model +# reasoned: check one against the other. +seen = meas.get("greedy_reasoning") +thinking = join(m["thinking"], {"yes": "reasoning seen", "no": "no reasoning seen", + "mixed": "reasoning in some replies"}.get(seen, "")) +if m["thinking"] == "off" and seen in ("yes", "mixed"): + print("bench.sh: warning: --thinking off, but the greedy replies contain reasoning;" + " check the server's chat template or reasoning flags", file=sys.stderr) +elif m["thinking"] in ("on", "low", "medium", "high") and seen == "no": + print(f"bench.sh: warning: --thinking {m['thinking']}, but the greedy replies contain no" + " reasoning; thinking may be off on the server", file=sys.stderr) + +# The BetterBench build: a release tag says nothing more than the version, a +# commit or local changes do (two installs can share a version number). +build = m.get("betterbench_build", "") +betterbench = "betterbench " + m["betterbench"] +if build and build not in ("v" + m["betterbench"], m["betterbench"]): + betterbench += " @ " + build + +eng = g("engine") +engine = join(" ".join(p for p in (eng, g("engine_version")) if p), + g("engine_slots") and g("engine_slots") + " slots", + g("engine_image") and "image " + g("engine_image"), + g("proxy") not in ("", "none") and "via " + g("proxy")) + +notes = [ + ("submitter", m["submitter"]), + ("gpu", gpu), + ("pcie", pcie), + ("power_limit", power), + ("host", host), + ("engine", engine), + ("model_file", model_file), + ("mem_bw", mem_bw), + ("parallel", f"tp {m['tp']} · pp {m['pp']}"), + ("precision", f"weights {m['quant']} · kv {m['kv']}"), + ("launch", launch), + ("env_flags", env_flags), + ("spec", m["spec"]), + ("thinking", thinking), + ("greedy_check", greedy), + ("run", join(m["run_mode"], "concurrency " + m["concurrency"], + "bench-standard " + m["bench_standard"], betterbench)), +] +if m.get("special_notes"): + notes.append(("special_notes", m["special_notes"])) +for k, v in notes: + print(f"{k}={v}") +__BENCH_STANDARD_EOF__ +cat > "$d/postrun.py" <<'__BENCH_STANDARD_EOF__' +"""postrun.py - figures that need the finished run, and the summary. + +usage: T0=epoch T1=epoch postrun.py RUN_DIR + +Reads results.json, meta.json, power.csv (epoch_s,watts,joules,mhz) and +timeline.tsv (epochBetterBench progress line) from RUN_DIR. Writes +energy (whole run and per phase) and the bandwidth figure to meta.json under +"post_run", and prints the summary to stderr. +""" +import bisect +import json +import os +import re +import statistics +import sys + + +def read_power(path): + rows = [] + if os.path.exists(path): + for line in open(path): + p = line.strip().split(",") + try: + rows.append((float(p[0]), float(p[1]), float(p[2]) if p[2] else None, + float(p[3]) if len(p) > 3 and p[3] else 0.0)) + except (ValueError, IndexError): + pass + return rows + + +def energy_curve(rows): + """(times, cumulative joules): from the energy counter when every sample + has one, else integrated from the power samples.""" + ts = [r[0] for r in rows] + if all(r[2] is not None for r in rows) and rows[-1][2] >= rows[0][2]: + return ts, [r[2] - rows[0][2] for r in rows], "energy counter" + cum = [0.0] + for a, b in zip(rows, rows[1:]): + cum.append(cum[-1] + (b[0] - a[0]) * (a[1] + b[1]) / 2) + return ts, cum, "integrated power" + + +def joules_between(ts, cum, t0, t1): + """Energy between two moments, interpolating between samples.""" + def at(t): + if t <= ts[0]: + return cum[0] + if t >= ts[-1]: + return cum[-1] + i = bisect.bisect_right(ts, t) + f = (t - ts[i - 1]) / (ts[i] - ts[i - 1]) + return cum[i - 1] + f * (cum[i] - cum[i - 1]) + return max(0.0, at(t1) - at(t0)) + + +SEGMENT = re.compile(r"^\[(single|prefill|concurrency)\]\s+(.*)$") +WARMUP = re.compile(r"warmup (\d+) \+ (\d+)") + + +def segments(timeline, t_end): + """BetterBench prints a progress line when each piece of work starts; a + piece lasts until the next line. Yields (phase, key, warm-up factor, t0, t1).""" + marks = [] + for t, line in timeline: + m = SEGMENT.match(line) + if not m or "skip" in m.group(2): + continue + phase, rest = m.groups() + key = rest.split(":")[0].strip() + if phase == "concurrency": + key = re.sub(r"\D", "", key) + w = WARMUP.search(rest) + factor = (int(w.group(1)) + int(w.group(2))) / int(w.group(2)) if w and int(w.group(2)) else 1.0 + marks.append((t, phase, key, factor)) + for i, (t, phase, key, factor) in enumerate(marks): + yield phase, key, factor, t, marks[i + 1][0] if i + 1 < len(marks) else t_end + + +def phase_energy(res, rows, timeline, t_end): + """Joules and joules per token for decode, prefill and each concurrency + level. Warm-up passes draw power but aren't in results.json, so their + tokens are estimated from the measured passes of the same piece.""" + ts, cum, _ = energy_curve(rows) + single = res.get("single_stream") or {} + prefill = {str(p.get("target_depth")): p for p in res.get("prefill") or []} + conc = {str(x.get("level")): x for x in res.get("concurrency") or []} + out = {"decode": {"joules": 0.0, "seconds": 0.0, "tokens": 0.0}, + "prefill": {"joules": 0.0, "seconds": 0.0, "tokens": 0.0}, "concurrency": {}} + for phase, key, factor, t0, t1 in segments(timeline, t_end): + j = joules_between(ts, cum, t0, t1) + if phase == "single": + tok = sum(r.get("completion_tokens") or 0 for r in single.get(key, []) if r.get("ok", True)) + d = out["decode"] + elif phase == "prefill": + depth = re.sub(r"\D", "", key) + tok = sum(prefill.get(depth, {}).get("prompt_tokens") or []) + d = out["prefill"] + else: + x = conc.get(key, {}) + tok, factor = x.get("aggregate_tps", 0) * x.get("wall_s", 0), 1.0 + d = out["concurrency"].setdefault(key, {"joules": 0.0, "seconds": 0.0, "tokens": 0.0}) + d["joules"] += j + d["seconds"] += t1 - t0 + d["tokens"] += tok * factor + def finish(d, per=1): + return {"joules": round(d["joules"]), "avg_w": round(d["joules"] / d["seconds"], 1) if d["seconds"] else None, + "tokens_incl_warmup_est": round(d["tokens"]), + "j_per_token" if per == 1 else "j_per_1k_tokens": + round(d["joules"] / d["tokens"] * per, 3) if d["tokens"] else None} + result = {} + if out["decode"]["seconds"]: + result["decode"] = finish(out["decode"]) + if out["prefill"]["seconds"]: + result["prefill"] = finish(out["prefill"], per=1000) + if out["concurrency"]: + result["concurrency"] = {k: finish(v) for k, v in out["concurrency"].items()} + return result + + +def roofline(single, c, m): + """Batch-1 decode reads all weights once per token: decode t/s x weight + bytes is the bandwidth it reaches. The weights are what the engine loaded + (vLLM logs it per worker) or else what is stored; tensor parallelism + spreads them over tp GPUs, each with its own bandwidth.""" + def num(v): + try: + return float(v) + except (TypeError, ValueError): + return None + tps = [r["decode_tps"] for r in single if r.get("decode_tps")] + bw = num(c.get("gpu_mem_bw_gbs")) or num(m.get("mem_bw")) + tp = int(m.get("tp") or 1) + loaded, stored = num(c.get("model_loaded_gib")), num(c.get("model_bytes")) + if loaded: + nbytes, src = loaded * 2**30 * tp, "loaded (engine log)" + elif stored: + nbytes, src = stored, "stored files" + else: + return None + if not tps or not bw: + return None + med = statistics.median(tps) + eff = med * nbytes / 1e9 + return {"decode_tps_median": round(med, 2), "weight_bytes": int(nbytes), "weight_source": src, + "mem_bw_gbs": bw * tp, "gpus": tp, "effective_gbs": round(eff, 1), + "pct_of_mem_bw": round(100 * eff / (bw * tp), 1)} + + +def main(d): + res = json.load(open(f"{d}/results.json", encoding="utf-8")) + meta = json.load(open(f"{d}/meta.json", encoding="utf-8")) + c, m = meta["collected"], meta["mandatory"] + t0, t1 = float(os.environ["T0"]), float(os.environ["T1"]) + post = {"wall_s": round(t1 - t0, 1)} + + single = [r for recs in (res.get("single_stream") or {}).values() for r in recs + if r.get("ok", True)] + tok = sum(r.get("completion_tokens") or 0 for r in single) + tok += sum(round(x.get("aggregate_tps", 0) * x.get("wall_s", 0)) + for x in res.get("concurrency") or []) + + rows = read_power(f"{d}/power.csv") + timeline = [] + if os.path.exists(f"{d}/timeline.tsv"): + for line in open(f"{d}/timeline.tsv", encoding="utf-8"): + t, _, text = line.rstrip("\n").partition("\t") + try: + timeline.append((float(t), text)) + except ValueError: + pass + if len(rows) >= 2: + ts, cum, src = energy_curve(rows) + span = ts[-1] - ts[0] + joules = cum[-1] + e = {"joules": round(joules), "source": src, "sampled_s": round(span, 1), + "avg_w": round(joules / span, 1) if span else None, + "peak_w": max(r[1] for r in rows), "output_tokens": tok, + "j_per_output_token": round(joules / tok, 3) if tok else None} + # A clock-gated idle GPU reads 0 MHz; average the samples where it runs. + clk = [r[3] for r in rows if r[3] > 0] + if clk: + e.update(avg_mhz=round(statistics.mean(clk)), min_mhz=round(min(clk)), + max_mhz=round(max(clk)), clock_samples=f"{len(clk)}/{len(rows)}") + if timeline: + e["phases"] = phase_energy(res, rows, timeline, t1) + post["energy"] = e + + r = roofline(single, c, m) + if r: + post["roofline"] = r + + # The summary: headline numbers plus the setup that makes them comparable. + def med(xs): + xs = [x for x in xs if x] + return statistics.median(xs) if xs else None + def f(x, unit, dec=0): + return "—" if x is None else f"{x:,.{dec}f} {unit}" + notes = meta["notes"] + tps = [x["decode_tps"] for x in single if x.get("decode_tps")] + L = [f" {meta['model']} · {notes.get('engine', '?')}", + f" {notes.get('gpu', '?')} · {notes.get('power_limit', '?')} limit", + f" {notes.get('run', '?')} · greedy {notes.get('greedy_check', '?')}", + f" decode (batch 1) {f(med(tps), 't/s', 1)} TTFT p50 " + f"{f(med(x.get('ttft_ms') for x in single), 'ms')}"] + conc = res.get("concurrency") or [] + if conc: + L.append(" concurrency " + " ".join( + f"{x['level']}: {x.get('aggregate_tps', 0):,.0f} t/s" for x in conc)) + live = [p for p in res.get("prefill") or [] if not p.get("skipped")] + if live: + L.append(" prefill " + " ".join( + f"{p['target_depth'] // 1000}k: {f(med(p.get('pp_tps') or []), 't/s')}" for p in live)) + if r: + L.append(f" bandwidth {r['effective_gbs']:.0f} GB/s effective = " + f"{r['pct_of_mem_bw']:.0f}% of {r['mem_bw_gbs']:.0f} GB/s " + f"(weights {r['weight_bytes'] / 1e9:.2f} GB, {r['weight_source']})") + if "energy" in post: + e = post["energy"] + clock = (f" · clock avg {e['avg_mhz']} MHz ({e['min_mhz']}-{e['max_mhz']})" + if "avg_mhz" in e else "") + L.append(f" power avg {e['avg_w']} W, peak {e['peak_w']:.0f} W{clock}") + ph = e.get("phases") or {} + parts = [] + if ph.get("decode", {}).get("j_per_token") is not None: + parts.append(f"decode {ph['decode']['j_per_token']} J/tok at {ph['decode']['avg_w']} W") + if ph.get("prefill", {}).get("j_per_1k_tokens") is not None: + parts.append(f"prefill {ph['prefill']['j_per_1k_tokens']} J/1k tok") + if parts: + L.append(" energy " + " · ".join(parts)) + if ph.get("concurrency"): + L.append(" energy by conc. " + " ".join( + f"{k}: {v['j_per_token']} J/tok" for k, v in ph["concurrency"].items() + if v.get("j_per_token") is not None)) + L.append(f" energy (total) {e['joules'] / 1000:.1f} kJ, " + f"{e['j_per_output_token']} J per output token over the whole run") + print("\n" + "\n".join(L), file=sys.stderr) + + meta["post_run"] = post + with open(f"{d}/meta.json", "w", encoding="utf-8") as fh: + json.dump(meta, fh, indent=2) + fh.write("\n") + + +if __name__ == "__main__": + main(sys.argv[1]) +__BENCH_STANDARD_EOF__ +cat > "$d/models.tsv" <<'__BENCH_STANDARD_EOF__' +# name engine quant sha256 (a GGUF file, or a safetensors directory: README, Models) +Qwen3.5-9B llama.cpp Q4_K_M 03b74727a860a56338e042c4420bb3f04b2fec5734175f4cb9fa853daf52b7e8 +Qwen3.8-27B llama.cpp UD-Q4_K_M 322e194ff79741c7baa497c240f677f54b201b0efab44ca8e50f122b39123482 +Qwen3.5-9B vllm w4a16 cca16f9855b9f92eee5876ddc8656ed6397316ffc65b9f17ca1939a9549e4c26 +Qwen3.8-27B vllm w4a16 bffa6b23fa11be557fe9de4b122a8bb99f537ad7a1a4effa702f7d0c677778f7 +__BENCH_STANDARD_EOF__ cat > "$d/config.json" <<'__BENCH_STANDARD_EOF__' { "temperature": 0.7, @@ -1123,7 +1431,7 @@ __BENCH_STANDARD_EOF__ cat > "$d/standard.env" <<'__BENCH_STANDARD_EOF__' # Pins for this version of the group standard. Bump STANDARD_VERSION whenever # config.json, the minimum BetterBench or the mandatory fields change. -STANDARD_VERSION=0.4.1 +STANDARD_VERSION=0.5.0 # Oldest BetterBench that has everything bench.sh uses; newer ones run too, # and the version goes into the run note so compare shows a mismatch. BETTERBENCH_MIN_VERSION=0.6.1 diff --git a/dev/DETAILS.md b/dev/DETAILS.md index 9f4cda2..f82d045 100644 --- a/dev/DETAILS.md +++ b/dev/DETAILS.md @@ -22,6 +22,7 @@ What `bench.sh` records, how, and how it's built. For running it, see | `meta.json` | every raw value: `mandatory` (declared), `collected` (detected), `measured`, `launch`, `post_run` | | `server-cmd.txt` | the server launch command, secrets redacted | | `power.csv` | `epoch_s,watts,joules,mhz` during the run | +| `timeline.tsv` | when each BetterBench progress line appeared, for the energy per phase | | `betterbench.log` | BetterBench's full output | ## Notes @@ -37,7 +38,7 @@ can't be detected is left out or shows `unknown`. | `power_limit` | `200 W`, or `180 W (GPU reports 200 W)` | | `host` | `AMD EPYC 7282 16-Core Processor · 60 GB RAM · Ubuntu 26.04.1 LTS · kernel 7.0.0-38-generic · VM kvm` | | `engine` | `llama.cpp b11913-7aca0d2ea · 4 slots · image ghcr.io/ggml-org/llama.cpp:server-intel@1a2b3c4d5e6f · via llama-swap` | -| `model_file` | `/models/Qwen3.8-27B-Q4_0.gguf · 15.60 GB` (weights as stored) | +| `model_file` | `/models/Qwen3.8-27B-UD-Q4_K_M.gguf · 16.46 GB · standard: Qwen3.8-27B UD-Q4_K_M`, `... · not a standard model (sha256 4f58a79550e8)` | | `mem_bw` | `532 GB/s measured (torch copy, random, 1024 MiB) · 608 GB/s declared` | | `parallel` | `tp 1 · pp 1` | | `precision` | `weights Q4_0 · kv f16` | @@ -46,7 +47,7 @@ can't be detected is left out or shows `unknown`. | `spec` | `mtp:5`, `none` | | `thinking` | `default · reasoning seen`, `off · no reasoning seen` (declared · observed) | | `greedy_check` | `identical 3/3 · 1d5105fe09dc`, `differs: 2 variants in 3 · first ...` | -| `run` | `full · concurrency on · bench-standard 0.4.1 · betterbench 0.6.1` | +| `run` | `full · concurrency on · bench-standard 0.5.0 · betterbench 0.6.1`, or `... · betterbench 0.6.1 @ v0.6.1-3-gabc1234-dirty` for a build that isn't the release | | `special_notes` | only when given | The context size appears as BetterBench's own chip. @@ -76,6 +77,19 @@ launch command. For a docker server the image is recorded with its ID, because t put them in the command. - If `--kv` doesn't match the command, `bench.sh` warns. +**Model file:** the path comes from the launch command. `model_hash.py` hashes it the +way the README's Models section does (a GGUF file, or the `*.safetensors` of a +directory) and looks the hash up in `models.tsv`. Not a standard model, or a `--quant` +that differs from the table, gives a warning. Per-file hashes are cached in +`~/.cache/bench-standard/sha256.tsv` by path, size and mtime, so only the first run +waits (about a minute for 16 GB). `HASH_MODEL=0` skips it, and the note then reads +`hash not checked`. When the server runs in docker, the path is the one inside the +container. If that path doesn't exist on the host, the hash can't be checked either. + +**BetterBench build:** read from pip's record of where it was installed from: the git +commit for `pip install git+...`, or `git describe` of the checkout for an editable +install. A release tag adds nothing to the `run` note; a commit or `-dirty` does. + **Memory bandwidth:** `mem-bw.py` copies 1 GiB of random data with torch, inside the server's container (same GPU, env and torch), or with `$BW_PYTHON`. It uses random data because Arc compresses uniform buffers: zeros read 1627 GB/s on a B65 that really @@ -95,16 +109,23 @@ tags in the text. `bench.sh` warns when `--thinking off` meets reasoning, or whe These go to `meta.json` under `post_run` and the summary, not to the notes, which are fixed before BetterBench starts. -- **energy:** kJ, average and peak W, J per output token, and average, min and max clock. - The clock counts only samples where the GPU is running. The figures cover the - **whole run**, warm-up and prefill included, so compare only runs of the same mode. +- **energy:** kJ, average and peak W, J per output token over the whole run, and + average, min and max clock. The clock counts only samples where the GPU is running. Power is sampled only when BetterBench runs on the server. On a split setup, run `bench.sh power > power.csv` on the server yourself. +- **energy per phase** (`energy.phases`): each BetterBench progress line is stamped in + `timeline.tsv`, and a piece of work lasts until the next line. That gives joules and + average W for decode (J per output token), prefill (J per 1000 prompt tokens) and each + concurrency level (J per token). The warm-up passes draw power but aren't in + `results.json`, so their tokens are estimated from the measured passes of the same + piece (`tokens_incl_warmup_est`). These compare across quick and full runs; the + whole-run figure doesn't. - **roofline:** median batch-1 decode t/s × weight bytes ÷ memory bandwidth = % of - bandwidth. It holds for dense models. Spec decoding and MoE can exceed 100%. So - can models quantized at load (e.g. vLLM fp8 from bf16 files), because they read - fewer bytes than are stored. For safetensors the size includes every file, so the - RedHatAI models' MTP head adds about 5%. + bandwidth. The weight bytes are what vLLM logs as loaded ("Model loading took X GiB", + per GPU, × tp), which is right for models quantized at load (fp8 from bf16 files reads + half of what's stored). Otherwise the stored size, without `*mtp*` files, since plain + decoding doesn't read an MTP head. With tp > 1 the bandwidth is per GPU × tp. It holds + for dense models; spec decoding and MoE can exceed 100%. ## BetterBench with PR #4 @@ -117,8 +138,8 @@ mismatch between runs with and without the PR. ## Building People download only the root `bench.sh`. It's generated: `dev/build.sh` packs -`dev/bench.sh`, `collect-env.sh`, `gpu-power.sh`, `mem-bw.py`, `config.json` and -`standard.env` into it. At run time it unpacks them to a temp dir and runs +`dev/bench.sh`, `collect-env.sh`, `gpu-power.sh`, `mem-bw.py`, `model_hash.py`, +`notes.py`, `postrun.py`, `models.tsv`, `config.json` and `standard.env` into it. At run time it unpacks them to a temp dir and runs `dev/bench.sh` from there, with `BENCH_HOME` set to its own folder, so `results/` and `bench.local.env` stay next to the downloaded file. @@ -126,8 +147,12 @@ and `bench.local.env` stay next to the downloaded file. sh dev/build.sh # after any change in dev/; commit dev/ and bench.sh together sh dev/build.sh --check # fails if bench.sh is out of date sh dev/bench.sh --help # dev/bench.sh also runs directly, results in dev/results/ +pytest dev/tests # the notes, model hash and post-run figures ``` +CI (`.github/workflows/ci.yml`) runs shellcheck, `build.sh --check` and the tests. +A model added to the README's table goes into `dev/models.tsv` too. + BetterBench 0.6.1 is the oldest version that works (`BETTERBENCH_MIN_VERSION` in `standard.env`). Newer ones run too, and their version goes into the `run` note. Bump `STANDARD_VERSION` when `config.json`, the minimum BetterBench or the recorded diff --git a/dev/bench.sh b/dev/bench.sh index d24c95f..8135fc1 100755 --- a/dev/bench.sh +++ b/dev/bench.sh @@ -113,6 +113,16 @@ sys.exit(not sys.argv[1] or v(sys.argv[1]) < v(sys.argv[2]))' "$have_ver" "$BETT die "BetterBench $BETTERBENCH_MIN_VERSION or newer required, found '${have_ver:-not installed}'" \ "(see https://github.com/GGZ14/BetterBench)" command -v curl >/dev/null || die "curl not found" +# The exact build: two installs can both say 0.6.1. pip records where it came +# from: a git commit, or a local checkout (then git describes it). +bb_build=$(bb=$(command -v betterbench) && py=$(sed -n '1s/^#!//p' "$(readlink -f "$bb")") && + $py -c 'import importlib.metadata as m, json +u = json.loads(m.distribution("betterbench").read_text("direct_url.json") or "{}") +c = (u.get("vcs_info") or {}).get("commit_id") +print(c[:12] if c else u.get("url", "")[7:] if u.get("url", "").startswith("file://") else "")' 2>/dev/null) || bb_build="" +if [ -d "$bb_build" ]; then + bb_build=$(git -c safe.directory='*' -C "$bb_build" describe --tags --always --dirty 2>/dev/null) || bb_build="" +fi missing="" for f in endpoint model tp pp quant kv spec thinking submitter; do @@ -223,7 +233,7 @@ fi [ -n "$pcie" ] && printf 'pcie=%s\n' "$pcie" [ -n "$special" ] && printf 'special_notes=%s\n' "$special" [ -n "$mem_bw" ] && printf 'mem_bw=%s\n' "$mem_bw" - printf 'betterbench=%s\n' "$have_ver" + printf 'betterbench=%s\nbetterbench_build=%s\n' "$have_ver" "$bb_build" printf 'bench_standard=%s\nrun_mode=%s\nconcurrency=%s\n' "$STANDARD_VERSION" \ "$([ $quick = 1 ] && echo quick || echo full)" "$([ $no_conc = 1 ] && echo off || echo on)" } > "$tmp/mandatory" @@ -254,201 +264,8 @@ fi # The notes are grouped for reading: one chip per topic, nothing twice. # The context size is left out - BetterBench shows it from --max-model-len. # launch.json: the settings parsed from the launch command, for meta.json. -python3 - "$tmp/mandatory" "$tmp/collected" "$tmp/measured" "$tmp/cmd.red" "$tmp/launch.json" \ - > "$tmp/notes" <<'PY' -import json, shlex, sys -def kv(path): - with open(path, encoding="utf-8") as f: - return dict(l.rstrip("\n").split("=", 1) for l in f if "=" in l) -m, c, meas = kv(sys.argv[1]), kv(sys.argv[2]), kv(sys.argv[3]) -cmd = open(sys.argv[4], encoding="utf-8").read().strip() -def g(k): - v = c.get(k, "") - return "" if v in ("", "unknown") else v -def join(*parts): - return " · ".join(p for p in parts if p) or "unknown" - -vendor = {"intel": "Intel", "nvidia": "NVIDIA", "amd": "AMD"}.get(g("gpu_vendor"), g("gpu_vendor")) -count = g("gpu_count") -gpu = join(" ".join(p for p in (count and count + "x", vendor if vendor != "none" else "", - g("gpu_model")) if p), - g("gpu_vram_gb") and g("gpu_vram_gb") + " GB", - g("gpu_driver") and "driver " + g("gpu_driver")) - -link, top = g("pcie_link"), g("pcie_max") -if m.get("pcie"): - pcie = m["pcie"] + " (declared)" -elif link and top and link != top: - pcie = f"{link} now, {top} max" # idle GPUs drop the link speed -else: - pcie = link or "unknown" -if g("rebar"): - pcie += " · ReBAR " + g("rebar") - -pl, det = m["power_limit"], g("gpu_power_limit_w") -if pl == "stock": - power = join("stock", det and det + " W") -else: - power = pl + " W" - if det and abs(float(det) - float(pl)) > 1: - power += f" (GPU reports {det} W)" - -virt = g("virt") -host = join(g("cpu_model"), g("ram_gb") and g("ram_gb") + " GB RAM", g("os"), - g("kernel") and "kernel " + g("kernel"), virt != "none" and virt and "VM " + virt) - -# Settings in the launch command that swing results but no API reports: -# batch sizes, flash attention, KV types, env flags. Flags left out of the -# command are the engine's defaults, which change between versions. -try: - words = shlex.split(cmd.replace("\\\n", " ")) -except ValueError: - words = cmd.split() -env, flags, prog = {}, {}, None -BOOL = {"--no-mmap", "--mlock", "--enforce-eager", "--enable-prefix-caching", - "--no-enable-prefix-caching", "--enable-chunked-prefill", - "--no-enable-chunked-prefill", "--cont-batching", "-cb", "--no-cont-batching", "-nocb", - "-cmoe", "--cpu-moe", "-rm", "--rm", "-d", "--detach", "-it", "-i", "--privileged"} -FA_VALUES = {"on", "off", "auto", "1", "0", "true", "false"} -i = 0 -while i < len(words): - w = words[i] - nxt = words[i + 1] if i + 1 < len(words) else None - if prog is None and "=" in w and not w.startswith("-") and w.split("=", 1)[0].isidentifier(): - k, v = w.split("=", 1); env[k] = v # FOO=1 cmd - elif prog is None and not w.startswith("-") and w != "env": - prog = w - elif w in ("-e", "--env") and nxt is not None and not nxt.startswith("-"): # docker -e K=V - k, _, v = nxt.partition("="); env[k] = v if _ else "(inherited)"; i += 1 - elif w.startswith("--env="): - k, _, v = w[6:].partition("="); env[k] = v if _ else "(inherited)" - elif w.startswith("-e") and len(w) > 2 and "=" in w and w[2:].split("=")[0].isidentifier(): - k, v = w[2:].split("=", 1); env[k] = v - elif w.startswith("-"): - if "=" in w and w.startswith("--"): - k, v = w.split("=", 1); flags[k] = v - elif w in ("-fa", "--flash-attn"): - if nxt is not None and nxt.lower() in FA_VALUES: - flags[w] = nxt; i += 1 - else: - flags[w] = "on" # older bare -fa - elif w in BOOL or nxt is None or nxt.startswith("-"): - flags[w] = True - else: - flags[w] = nxt; i += 1 - i += 1 - -def flag(*names): - for n in names: - if n in flags: - return flags[n] - return None - -LLAMA = [("b", ("-b", "--batch-size")), ("ub", ("-ub", "--ubatch-size")), - ("fa", ("-fa", "--flash-attn")), ("ctk", ("-ctk", "--cache-type-k")), - ("ctv", ("-ctv", "--cache-type-v")), ("ngl", ("-ngl", "--gpu-layers", "--n-gpu-layers")), - ("np", ("-np", "--parallel")), ("t", ("-t", "--threads")), - ("sm", ("-sm", "--split-mode")), ("ts", ("-ts", "--tensor-split")), - ("ot", ("-ot", "--override-tensor")), ("ncmoe", ("-ncmoe", "--n-cpu-moe")), - ("cmoe", ("-cmoe", "--cpu-moe")), ("no-mmap", ("--no-mmap",)), ("mlock", ("--mlock",)), - ("nocb", ("-nocb", "--no-cont-batching"))] -LLAMA_ALWAYS = {"b", "ub", "fa", "ctk", "ctv"} # shown as "default" when not set -VLLM = ["--max-num-batched-tokens", "--max-num-seqs", "--kv-cache-dtype", - "--gpu-memory-utilization", "--dtype", "--quantization", "--block-size", - "--enforce-eager", "--enable-chunked-prefill", "--no-enable-chunked-prefill", - "--enable-prefix-caching", "--no-enable-prefix-caching", "--attention-backend", - "--compilation-config", "-O", "--speculative-config"] -launch_kind = g("engine") -if launch_kind not in ("llama.cpp", "vllm"): - launch_kind = ("llama.cpp" if prog and "llama-server" in prog or flag("-ngl", "-ub", "-ctk") - else "vllm" if any(f in flags for f in VLLM) else "") -settings = {} -if launch_kind == "llama.cpp": - for name, al in LLAMA: - v = flag(*al) - if v is not None: - settings[name] = "on" if v is True else v - elif name in LLAMA_ALWAYS: - settings[name] = "default" -elif launch_kind == "vllm": - for f in VLLM: - if f in flags: - settings[f.lstrip("-")] = "on" if flags[f] is True else "".join(str(flags[f]).split()) -if not cmd: - launch = "unknown (pass --server-cmd-file)" -else: - launch = " · ".join(k if v == "on" and k in ("no-mmap", "mlock", "nocb", "cmoe") or - k.startswith(("enable-", "no-enable-", "enforce-")) else f"{k} {v}" - for k, v in settings.items()) or "no tuning flags" -# Offline switches and cache paths don't change the numbers. -QUIET = {"HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE", "HF_DATASETS_OFFLINE", "HF_HOME", - "VLLM_CACHE_ROOT", "PATH", "HOME", "TZ", "LANG", "LC_ALL"} -env_flags = (" · ".join(f"{k}={v}" for k, v in env.items() if k not in QUIET) or "none" - ) if cmd else "unknown" -json.dump({"engine": launch_kind or None, "settings": settings, "env": env, "flags": flags}, - open(sys.argv[5], "w", encoding="utf-8"), indent=2, default=str) - -# The declared --kv should be what the command sets. -kvset = [x for x in (settings.get("ctk"), settings.get("ctv"), settings.get("kv-cache-dtype")) - if x and x not in ("default", "auto")] -if kvset and m["kv"] not in kvset + ["/".join(kvset), "_".join(kvset)]: - print(f"bench.sh: warning: --kv {m['kv']} but the launch command sets " - f"{'/'.join(kvset)}", file=sys.stderr) - -mb = g("model_bytes") -model_file = join(g("model_file"), mb and f"{int(mb) / 1e9:.2f} GB") -mem_bw = join(g("gpu_mem_bw_gbs") and - f'{g("gpu_mem_bw_gbs")} GB/s measured ({g("gpu_mem_bw_tool") or "?"})', - m.get("mem_bw") and m["mem_bw"] + " GB/s declared") -if meas.get("greedy_check") == "identical": - greedy = f'identical {meas["greedy_runs"]}/{meas["greedy_runs"]} · {meas["greedy_hash"]}' -elif meas.get("greedy_check") == "differs": - greedy = f'differs: {meas["greedy_variants"]} variants in {meas["greedy_runs"]} · first {meas["greedy_hash"]}' -else: - greedy = "failed" - -# --thinking is declared, but the greedy replies show whether the model -# reasoned: check one against the other. -seen = meas.get("greedy_reasoning") -thinking = join(m["thinking"], {"yes": "reasoning seen", "no": "no reasoning seen", - "mixed": "reasoning in some replies"}.get(seen, "")) -if m["thinking"] == "off" and seen in ("yes", "mixed"): - print("bench.sh: warning: --thinking off, but the greedy replies contain reasoning;" - " check the server's chat template or reasoning flags", file=sys.stderr) -elif m["thinking"] in ("on", "low", "medium", "high") and seen == "no": - print(f"bench.sh: warning: --thinking {m['thinking']}, but the greedy replies contain no" - " reasoning; thinking may be off on the server", file=sys.stderr) - -eng = g("engine") -engine = join(" ".join(p for p in (eng, g("engine_version")) if p), - g("engine_slots") and g("engine_slots") + " slots", - g("engine_image") and "image " + g("engine_image"), - g("proxy") not in ("", "none") and "via " + g("proxy")) - -notes = [ - ("submitter", m["submitter"]), - ("gpu", gpu), - ("pcie", pcie), - ("power_limit", power), - ("host", host), - ("engine", engine), - ("model_file", model_file), - ("mem_bw", mem_bw), - ("parallel", f"tp {m['tp']} · pp {m['pp']}"), - ("precision", f"weights {m['quant']} · kv {m['kv']}"), - ("launch", launch), - ("env_flags", env_flags), - ("spec", m["spec"]), - ("thinking", thinking), - ("greedy_check", greedy), - ("run", join(m["run_mode"], "concurrency " + m["concurrency"], - "bench-standard " + m["bench_standard"], "betterbench " + m["betterbench"])), -] -if m.get("special_notes"): - notes.append(("special_notes", m["special_notes"])) -for k, v in notes: - print(f"{k}={v}") -PY +python3 "$here/notes.py" "$tmp/mandatory" "$tmp/collected" "$tmp/measured" "$tmp/cmd.red" \ + "$tmp/launch.json" "$here/models.tsv" > "$tmp/notes" engine=$(get engine) gpu=$(get gpu_model) count=$(get gpu_count) ctx=$(get ctx) [ "$engine" != unknown ] || echo "bench.sh: warning: engine not detected; result is hard to compare" >&2 @@ -525,8 +342,15 @@ echo "running betterbench -> $run_dir" >&2 t_start=$(date +%s.%N) # Full output always goes to betterbench.log; the terminal gets all of it # (--verbose) or the progress lines and anything that looks like trouble. +# timeline.tsv stamps each progress line, for the energy of each phase. { PYTHONUNBUFFERED=1 betterbench "$@" 2>&1 || echo $? > "$tmp/bb_rc"; } | tee "$run_dir/betterbench.log" | + python3 -uc 'import sys, time +tl = open(sys.argv[1], "w", encoding="utf-8") +for line in iter(sys.stdin.readline, ""): + if line.startswith("["): + tl.write(f"{time.time():.3f}\t{line}"); tl.flush() + sys.stdout.write(line); sys.stdout.flush()' "$run_dir/timeline.tsv" | if [ $verbose = 1 ]; then cat; else grep --line-buffered -E '^\[|^phases|warn|WARN|rror|Traceback' || true; fi >&2 if [ -s "$tmp/bb_rc" ]; then mv "$run_dir" "$run_dir.failed" 2>/dev/null || true @@ -538,104 +362,11 @@ if [ -n "$sampler" ]; then [ -s "$run_dir/power.csv" ] || rm -f "$run_dir/power.csv" fi -# Energy per token and decode as % of memory bandwidth, from what the run -# measured. They come after the run, so they go to meta.json ("post_run"), -# not into the notes of results.json. -T0=$t_start T1=$t_end python3 - "$run_dir" <<'PY' || echo "bench.sh: warning: post-run figures failed" >&2 -import json, os, statistics, sys -d = sys.argv[1] -res = json.load(open(f"{d}/results.json", encoding="utf-8")) -meta = json.load(open(f"{d}/meta.json", encoding="utf-8")) -c, m = meta["collected"], meta["mandatory"] -post = {"wall_s": round(float(os.environ["T1"]) - float(os.environ["T0"]), 1)} - -# Output tokens of the measured passes and the concurrency sweep; warm-up -# passes and prefill probes are not in results.json but draw power too. -single = [r for recs in (res.get("single_stream") or {}).values() for r in recs - if r.get("ok", True)] -tok = sum(r.get("completion_tokens") or 0 for r in single) -tok += sum(round(x.get("aggregate_tps", 0) * x.get("wall_s", 0)) - for x in res.get("concurrency") or []) - -rows = [] -if os.path.exists(f"{d}/power.csv"): - for line in open(f"{d}/power.csv"): - p = line.strip().split(",") - try: - rows.append((float(p[0]), float(p[1]), float(p[2]) if p[2] else None, - float(p[3]) if len(p) > 3 and p[3] else 0.0)) - except (ValueError, IndexError): - pass -if len(rows) >= 2: - span = rows[-1][0] - rows[0][0] - if rows[0][2] is not None and rows[-1][2] is not None and rows[-1][2] >= rows[0][2]: - joules, src = rows[-1][2] - rows[0][2], "energy counter" - else: - joules = sum((b[0] - a[0]) * (a[1] + b[1]) / 2 for a, b in zip(rows, rows[1:])) - src = "integrated power" - e = {"joules": round(joules), "source": src, "sampled_s": round(span, 1), - "avg_w": round(joules / span, 1) if span else None, - "peak_w": max(r[1] for r in rows), "output_tokens": tok, - "j_per_output_token": round(joules / tok, 3) if tok else None} - # A clock-gated idle GPU reads 0 MHz; average the samples where it runs. - clk = [r[3] for r in rows if r[3] > 0] - if clk: - e.update(avg_mhz=round(statistics.mean(clk)), min_mhz=round(min(clk)), - max_mhz=round(max(clk)), clock_samples=f"{len(clk)}/{len(rows)}") - post["energy"] = e - -# Batch-1 decode reads all weights once per token, so decode t/s x weight -# bytes is the bandwidth it achieves. Dense models only; spec decoding or MoE -# can go above 100%. -tps = [r["decode_tps"] for r in single if r.get("decode_tps")] -# measured where there is a figure: what the card really reaches -bw = c.get("gpu_mem_bw_gbs") if c.get("gpu_mem_bw_gbs") not in (None, "", "unknown") else m.get("mem_bw") -mb = c.get("model_bytes") -if tps and bw not in (None, "", "unknown") and mb not in (None, "", "unknown"): - med = statistics.median(tps) - eff = med * int(mb) / 1e9 - post["roofline"] = {"decode_tps_median": round(med, 2), "model_bytes": int(mb), - "mem_bw_gbs": float(bw), "effective_gbs": round(eff, 1), - "pct_of_mem_bw": round(100 * eff / float(bw), 1)} - -# The summary: headline numbers plus the setup that makes them comparable. -def med(xs): - xs = [x for x in xs if x] - return statistics.median(xs) if xs else None -def f(x, unit, d=0): - return "—" if x is None else f"{x:,.{d}f} {unit}" -notes = meta["notes"] -L = [f" {meta['model']} · {notes.get('engine', '?')}", - f" {notes.get('gpu', '?')} · {notes.get('power_limit', '?')} limit", - f" {notes.get('run', '?')} · greedy {notes.get('greedy_check', '?')}", - f" decode (batch 1) {f(med(tps), 't/s', 1)} TTFT p50 " - f"{f(med(r.get('ttft_ms') for r in single), 'ms')}"] -conc = res.get("concurrency") or [] -if conc: - L.append(" concurrency " + " ".join( - f"{x['level']}: {x.get('aggregate_tps', 0):,.0f} t/s" for x in conc)) -live = [p for p in res.get("prefill") or [] if not p.get("skipped")] -if live: - L.append(" prefill " + " ".join( - f"{p['target_depth'] // 1000}k: {f(med(p.get('pp_tps') or []), 't/s')}" for p in live)) -if "roofline" in post: - r = post["roofline"] - L.append(f" bandwidth {r['effective_gbs']:.0f} GB/s effective = " - f"{r['pct_of_mem_bw']:.0f}% of {r['mem_bw_gbs']:.0f} GB/s ({notes.get('mem_bw', '')})") -if "energy" in post: - e = post["energy"] - clock = (f" · clock avg {e['avg_mhz']} MHz ({e['min_mhz']}-{e['max_mhz']})" - if "avg_mhz" in e else "") - L.append(f" power avg {e['avg_w']} W, peak {e['peak_w']:.0f} W{clock}") - L.append(f" energy {e['joules'] / 1000:.1f} kJ, " - f"{e['j_per_output_token']} J per output token (whole run)") -print("\n" + "\n".join(L), file=sys.stderr) - -meta["post_run"] = post -with open(f"{d}/meta.json", "w", encoding="utf-8") as f: - json.dump(meta, f, indent=2) - f.write("\n") -PY +# Energy (whole run and per phase) and decode as % of memory bandwidth, from +# what the run measured. They come after the run, so they go to meta.json +# ("post_run"), not into the notes of results.json. +T0=$t_start T1=$t_end python3 "$here/postrun.py" "$run_dir" || + echo "bench.sh: warning: post-run figures failed" >&2 # BetterBench with GGZ14/BetterBench#4 fingerprints PCIe and BAR itself # (env.gpu.pci), on the machine BetterBench runs on. Say so when that is not diff --git a/dev/build.sh b/dev/build.sh index 5863fd2..61ca699 100755 --- a/dev/build.sh +++ b/dev/build.sh @@ -9,7 +9,7 @@ set -eu dev=$(cd "$(dirname "$0")" && pwd) out="$dev/../bench.sh" -files="bench.sh collect-env.sh gpu-power.sh mem-bw.py config.json standard.env" +files="bench.sh collect-env.sh gpu-power.sh mem-bw.py model_hash.py notes.py postrun.py models.tsv config.json standard.env" eof=__BENCH_STANDARD_EOF__ . "$dev/standard.env" diff --git a/dev/collect-env.sh b/dev/collect-env.sh index 7703630..80cbab5 100755 --- a/dev/collect-env.sh +++ b/dev/collect-env.sh @@ -10,7 +10,8 @@ # --server-cmd-out behind llama-swap: write the model's launch command (raw) to FILE # --server-cmd-file the launch command when not behind llama-swap (finds the container) # env: BETTERBENCH_API_KEY, PROBE_TIMEOUT (s, default 10), LOAD_TIMEOUT (s, default 600), -# MEASURE_BW=0 (skip the bandwidth test), BW_PYTHON (python with torch for it) +# MEASURE_BW=0 (skip the bandwidth test), BW_PYTHON (python with torch for it), +# HASH_MODEL=0 (skip hashing the model file) set -u LC_ALL=C; export LC_ALL @@ -27,7 +28,7 @@ while [ $# -gt 0 ]; do --api-key) need $# "$1"; api_key=$2; shift 2 ;; --server-cmd-out) need $# "$1"; cmd_out=$2; shift 2 ;; --server-cmd-file) need $# "$1"; cmd_file=$2; shift 2 ;; - -h|--help) sed -n '2,13p' "$0"; exit 0 ;; + -h|--help) sed -n '2,14p' "$0"; exit 0 ;; *) echo "collect-env: unknown argument: $1" >&2; exit 2 ;; esac done @@ -250,7 +251,8 @@ PY fi # Weight bytes as stored: a single file, the parts of a split GGUF -# (-00001-of-0000N.gguf), or the *.safetensors of a model directory. +# (-00001-of-0000N.gguf), or the *.safetensors of a model directory, without +# an MTP head (*mtp*), which plain decoding doesn't read. model_bytes="" if [ -f "$model_file" ]; then case $model_file in @@ -259,7 +261,7 @@ if [ -f "$model_file" ]; then esac model_bytes=$(stat -c %s "$@" 2>/dev/null | awk '{s += $1} END {if (s) printf "%d", s}') elif [ -d "$model_file" ]; then - model_bytes=$(find "$model_file" -maxdepth 1 -name '*.safetensors' -exec stat -c %s {} + 2>/dev/null | + model_bytes=$(find "$model_file" -maxdepth 1 -name '*.safetensors' ! -name '*mtp*' -exec stat -c %s {} + 2>/dev/null | awk '{s += $1} END {if (s) printf "%d", s}') fi @@ -274,12 +276,28 @@ if [ -n "$container" ] && have docker && engine_image=$(printf '%s' "$i" | sed 's/@sha256:\(.\{12\}\).*/@\1/') fi +# vLLM logs what the weights take in GPU memory, per worker. That beats the +# stored size when it quantizes at load (fp8 from bf16 files reads half). +model_loaded_gib="" +if [ "$engine" = vllm ] && [ -n "$container" ] && have docker; then + model_loaded_gib=$(docker logs "$container" 2>&1 | sed -n 's/.*Model loading took \([0-9.]*\) GiB.*/\1/p' | tail -n1) +fi + +# The model's SHA256, checked against the standard models (README, Models). +# The first time takes a while for a big file, then it's cached. +# HASH_MODEL=0 skips it. +model_sha256="" +here=$(cd "$(dirname "$0")" && pwd) +if [ "${HASH_MODEL:-1}" != 0 ] && [ -e "$model_file" ] && have python3; then + echo "collect-env: hashing the model file (cached after the first time) ..." >&2 + model_sha256=$(python3 "$here/model_hash.py" "$model_file" 2>/dev/null) +fi + # Measured memory bandwidth, the base for "% of peak". mem-bw.py copies random # data with torch, inside the server's container (same GPU, env and torch), or # with $BW_PYTHON. Fallback: clpeak, whose test data may compress on Arc and # read high. A few seconds and 2 GiB of free VRAM; MEASURE_BW=0 skips it. gpu_mem_bw_gbs="" gpu_mem_bw_tool="" -here=$(cd "$(dirname "$0")" && pwd) if [ "${MEASURE_BW:-1}" != 0 ]; then if [ -n "${BW_PYTHON:-}" ]; then r=$(timeout 300 "$BW_PYTHON" "$here/mem-bw.py" 2>/dev/null) @@ -329,5 +347,7 @@ kv engine_slots "$engine_slots" kv engine_image "$engine_image" kv model_file "$model_file" kv model_bytes "$model_bytes" +kv model_loaded_gib "$model_loaded_gib" +kv model_sha256 "$model_sha256" kv ctx "$ctx" exit 0 diff --git a/dev/model_hash.py b/dev/model_hash.py new file mode 100644 index 0000000..2c5ca35 --- /dev/null +++ b/dev/model_hash.py @@ -0,0 +1,77 @@ +"""model_hash.py - SHA256 of a model, as the README's Models section defines it. + +usage: model_hash.py PATH (prints the hash, or nothing when PATH can't be read) + +A file: its SHA256, like `sha256sum FILE`. A directory: the SHA256 over the +per-file hashes of its *.safetensors, in byte order of the names, exactly like +`sha256sum *.safetensors | LC_ALL=C sort -k2 | sha256sum`. + +Hashing a 16 GB file takes a while, so per-file hashes are cached in +~/.cache/bench-standard/sha256.tsv, keyed by path, size and mtime. +""" +import hashlib +import os +import sys + +CACHE = os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), + "bench-standard", "sha256.tsv") + + +def _load_cache(): + cache = {} + try: + with open(CACHE, encoding="utf-8") as f: + for line in f: + p = line.rstrip("\n").split("\t") + if len(p) == 4: + cache[(p[0], p[1], p[2])] = p[3] + except OSError: + pass + return cache + + +def _save_cache(cache): + try: + os.makedirs(os.path.dirname(CACHE), exist_ok=True) + tmp = CACHE + f".{os.getpid()}" + with open(tmp, "w", encoding="utf-8") as f: + for (path, size, mtime), h in sorted(cache.items()): + f.write(f"{path}\t{size}\t{mtime}\t{h}\n") + os.replace(tmp, CACHE) + except OSError: + pass + + +def file_sha256(path, cache): + st = os.stat(path) + key = (os.path.realpath(path), str(st.st_size), str(st.st_mtime_ns)) + if key not in cache: + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 22), b""): + h.update(block) + cache[key] = h.hexdigest() + return cache[key] + + +def model_sha256(path, cache=None): + cache = _load_cache() if cache is None else cache + if os.path.isdir(path): + names = sorted((n for n in os.listdir(path) if n.endswith(".safetensors")), + key=lambda n: n.encode()) + if not names: + return None + listing = "".join(f"{file_sha256(os.path.join(path, n), cache)} {n}\n" for n in names) + return hashlib.sha256(listing.encode()).hexdigest() + return file_sha256(path, cache) + + +if __name__ == "__main__": + try: + cache = _load_cache() + h = model_sha256(sys.argv[1], cache) + _save_cache(cache) + except (OSError, IndexError): + h = None + if h: + print(h) diff --git a/dev/models.tsv b/dev/models.tsv new file mode 100644 index 0000000..e27011f --- /dev/null +++ b/dev/models.tsv @@ -0,0 +1,5 @@ +# name engine quant sha256 (a GGUF file, or a safetensors directory: README, Models) +Qwen3.5-9B llama.cpp Q4_K_M 03b74727a860a56338e042c4420bb3f04b2fec5734175f4cb9fa853daf52b7e8 +Qwen3.8-27B llama.cpp UD-Q4_K_M 322e194ff79741c7baa497c240f677f54b201b0efab44ca8e50f122b39123482 +Qwen3.5-9B vllm w4a16 cca16f9855b9f92eee5876ddc8656ed6397316ffc65b9f17ca1939a9549e4c26 +Qwen3.8-27B vllm w4a16 bffa6b23fa11be557fe9de4b122a8bb99f537ad7a1a4effa702f7d0c677778f7 diff --git a/dev/notes.py b/dev/notes.py new file mode 100644 index 0000000..c7df893 --- /dev/null +++ b/dev/notes.py @@ -0,0 +1,222 @@ +"""notes.py - the notes bench.sh hands BetterBench, one per topic. + +usage: notes.py MANDATORY COLLECTED MEASURED CMD LAUNCH_JSON MODELS_TSV > notes +The first three are key=value files (declared, detected by collect-env.sh, +measured by the greedy check), CMD the redacted launch command (may be +empty). Writes the parsed launch settings to LAUNCH_JSON and prints +key=value notes; warnings go to stderr. +""" +import json, shlex, sys +def kv(path): + with open(path, encoding="utf-8") as f: + return dict(l.rstrip("\n").split("=", 1) for l in f if "=" in l) +m, c, meas = kv(sys.argv[1]), kv(sys.argv[2]), kv(sys.argv[3]) +models = [l.rstrip("\n").split("\t") for l in open(sys.argv[6], encoding="utf-8") + if l.strip() and not l.startswith("#")] +cmd = open(sys.argv[4], encoding="utf-8").read().strip() +def g(k): + v = c.get(k, "") + return "" if v in ("", "unknown") else v +def join(*parts): + return " · ".join(p for p in parts if p) or "unknown" + +vendor = {"intel": "Intel", "nvidia": "NVIDIA", "amd": "AMD"}.get(g("gpu_vendor"), g("gpu_vendor")) +count = g("gpu_count") +gpu = join(" ".join(p for p in (count and count + "x", vendor if vendor != "none" else "", + g("gpu_model")) if p), + g("gpu_vram_gb") and g("gpu_vram_gb") + " GB", + g("gpu_driver") and "driver " + g("gpu_driver")) + +link, top = g("pcie_link"), g("pcie_max") +if m.get("pcie"): + pcie = m["pcie"] + " (declared)" +elif link and top and link != top: + pcie = f"{link} now, {top} max" # idle GPUs drop the link speed +else: + pcie = link or "unknown" +if g("rebar"): + pcie += " · ReBAR " + g("rebar") + +pl, det = m["power_limit"], g("gpu_power_limit_w") +if pl == "stock": + power = join("stock", det and det + " W") +else: + power = pl + " W" + if det and abs(float(det) - float(pl)) > 1: + power += f" (GPU reports {det} W)" + +virt = g("virt") +host = join(g("cpu_model"), g("ram_gb") and g("ram_gb") + " GB RAM", g("os"), + g("kernel") and "kernel " + g("kernel"), virt != "none" and virt and "VM " + virt) + +# Settings in the launch command that swing results but no API reports: +# batch sizes, flash attention, KV types, env flags. Flags left out of the +# command are the engine's defaults, which change between versions. +try: + words = shlex.split(cmd.replace("\\\n", " ")) +except ValueError: + words = cmd.split() +env, flags, prog = {}, {}, None +BOOL = {"--no-mmap", "--mlock", "--enforce-eager", "--enable-prefix-caching", + "--no-enable-prefix-caching", "--enable-chunked-prefill", + "--no-enable-chunked-prefill", "--cont-batching", "-cb", "--no-cont-batching", "-nocb", + "-cmoe", "--cpu-moe", "-rm", "--rm", "-d", "--detach", "-it", "-i", "--privileged"} +FA_VALUES = {"on", "off", "auto", "1", "0", "true", "false"} +i = 0 +while i < len(words): + w = words[i] + nxt = words[i + 1] if i + 1 < len(words) else None + if prog is None and "=" in w and not w.startswith("-") and w.split("=", 1)[0].isidentifier(): + k, v = w.split("=", 1); env[k] = v # FOO=1 cmd + elif prog is None and not w.startswith("-") and w != "env": + prog = w + elif w in ("-e", "--env") and nxt is not None and not nxt.startswith("-"): # docker -e K=V + k, _, v = nxt.partition("="); env[k] = v if _ else "(inherited)"; i += 1 + elif w.startswith("--env="): + k, _, v = w[6:].partition("="); env[k] = v if _ else "(inherited)" + elif w.startswith("-e") and len(w) > 2 and "=" in w and w[2:].split("=")[0].isidentifier(): + k, v = w[2:].split("=", 1); env[k] = v + elif w.startswith("-"): + if "=" in w and w.startswith("--"): + k, v = w.split("=", 1); flags[k] = v + elif w in ("-fa", "--flash-attn"): + if nxt is not None and nxt.lower() in FA_VALUES: + flags[w] = nxt; i += 1 + else: + flags[w] = "on" # older bare -fa + elif w in BOOL or nxt is None or nxt.startswith("-"): + flags[w] = True + else: + flags[w] = nxt; i += 1 + i += 1 + +def flag(*names): + for n in names: + if n in flags: + return flags[n] + return None + +LLAMA = [("b", ("-b", "--batch-size")), ("ub", ("-ub", "--ubatch-size")), + ("fa", ("-fa", "--flash-attn")), ("ctk", ("-ctk", "--cache-type-k")), + ("ctv", ("-ctv", "--cache-type-v")), ("ngl", ("-ngl", "--gpu-layers", "--n-gpu-layers")), + ("np", ("-np", "--parallel")), ("t", ("-t", "--threads")), + ("sm", ("-sm", "--split-mode")), ("ts", ("-ts", "--tensor-split")), + ("ot", ("-ot", "--override-tensor")), ("ncmoe", ("-ncmoe", "--n-cpu-moe")), + ("cmoe", ("-cmoe", "--cpu-moe")), ("no-mmap", ("--no-mmap",)), ("mlock", ("--mlock",)), + ("nocb", ("-nocb", "--no-cont-batching"))] +LLAMA_ALWAYS = {"b", "ub", "fa", "ctk", "ctv"} # shown as "default" when not set +VLLM = ["--max-num-batched-tokens", "--max-num-seqs", "--kv-cache-dtype", + "--gpu-memory-utilization", "--dtype", "--quantization", "--block-size", + "--enforce-eager", "--enable-chunked-prefill", "--no-enable-chunked-prefill", + "--enable-prefix-caching", "--no-enable-prefix-caching", "--attention-backend", + "--compilation-config", "-O", "--speculative-config"] +launch_kind = g("engine") +if launch_kind not in ("llama.cpp", "vllm"): + launch_kind = ("llama.cpp" if prog and "llama-server" in prog or flag("-ngl", "-ub", "-ctk") + else "vllm" if any(f in flags for f in VLLM) else "") +settings = {} +if launch_kind == "llama.cpp": + for name, al in LLAMA: + v = flag(*al) + if v is not None: + settings[name] = "on" if v is True else v + elif name in LLAMA_ALWAYS: + settings[name] = "default" +elif launch_kind == "vllm": + for f in VLLM: + if f in flags: + settings[f.lstrip("-")] = "on" if flags[f] is True else "".join(str(flags[f]).split()) +if not cmd: + launch = "unknown (pass --server-cmd-file)" +else: + launch = " · ".join(k if v == "on" and k in ("no-mmap", "mlock", "nocb", "cmoe") or + k.startswith(("enable-", "no-enable-", "enforce-")) else f"{k} {v}" + for k, v in settings.items()) or "no tuning flags" +# Offline switches and cache paths don't change the numbers. +QUIET = {"HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE", "HF_DATASETS_OFFLINE", "HF_HOME", + "VLLM_CACHE_ROOT", "PATH", "HOME", "TZ", "LANG", "LC_ALL"} +env_flags = (" · ".join(f"{k}={v}" for k, v in env.items() if k not in QUIET) or "none" + ) if cmd else "unknown" +json.dump({"engine": launch_kind or None, "settings": settings, "env": env, "flags": flags}, + open(sys.argv[5], "w", encoding="utf-8"), indent=2, default=str) + +# The declared --kv should be what the command sets. +kvset = [x for x in (settings.get("ctk"), settings.get("ctv"), settings.get("kv-cache-dtype")) + if x and x not in ("default", "auto")] +if kvset and m["kv"] not in kvset + ["/".join(kvset), "_".join(kvset)]: + print(f"bench.sh: warning: --kv {m['kv']} but the launch command sets " + f"{'/'.join(kvset)}", file=sys.stderr) + +# The model file against the standard models: results only count for those. +mb, sha = g("model_bytes"), g("model_sha256") +std = next((r for r in models if len(r) >= 4 and r[3] == sha), None) if sha else None +if std: + check = f"standard: {std[0]} {std[2]}" + if m["quant"] != std[2]: + print(f"bench.sh: warning: --quant {m['quant']}, but the file is the standard " + f"{std[0]} {std[2]}; declare --quant {std[2]}", file=sys.stderr) +elif sha: + check = f"not a standard model (sha256 {sha[:12]})" + print("bench.sh: warning: the model file is not one of the standard models " + "(README, Models), so the result won't count", file=sys.stderr) +else: + check = "hash not checked" +model_file = join(g("model_file"), mb and f"{int(mb) / 1e9:.2f} GB", check) +mem_bw = join(g("gpu_mem_bw_gbs") and + f'{g("gpu_mem_bw_gbs")} GB/s measured ({g("gpu_mem_bw_tool") or "?"})', + m.get("mem_bw") and m["mem_bw"] + " GB/s declared") +if meas.get("greedy_check") == "identical": + greedy = f'identical {meas["greedy_runs"]}/{meas["greedy_runs"]} · {meas["greedy_hash"]}' +elif meas.get("greedy_check") == "differs": + greedy = f'differs: {meas["greedy_variants"]} variants in {meas["greedy_runs"]} · first {meas["greedy_hash"]}' +else: + greedy = "failed" + +# --thinking is declared, but the greedy replies show whether the model +# reasoned: check one against the other. +seen = meas.get("greedy_reasoning") +thinking = join(m["thinking"], {"yes": "reasoning seen", "no": "no reasoning seen", + "mixed": "reasoning in some replies"}.get(seen, "")) +if m["thinking"] == "off" and seen in ("yes", "mixed"): + print("bench.sh: warning: --thinking off, but the greedy replies contain reasoning;" + " check the server's chat template or reasoning flags", file=sys.stderr) +elif m["thinking"] in ("on", "low", "medium", "high") and seen == "no": + print(f"bench.sh: warning: --thinking {m['thinking']}, but the greedy replies contain no" + " reasoning; thinking may be off on the server", file=sys.stderr) + +# The BetterBench build: a release tag says nothing more than the version, a +# commit or local changes do (two installs can share a version number). +build = m.get("betterbench_build", "") +betterbench = "betterbench " + m["betterbench"] +if build and build not in ("v" + m["betterbench"], m["betterbench"]): + betterbench += " @ " + build + +eng = g("engine") +engine = join(" ".join(p for p in (eng, g("engine_version")) if p), + g("engine_slots") and g("engine_slots") + " slots", + g("engine_image") and "image " + g("engine_image"), + g("proxy") not in ("", "none") and "via " + g("proxy")) + +notes = [ + ("submitter", m["submitter"]), + ("gpu", gpu), + ("pcie", pcie), + ("power_limit", power), + ("host", host), + ("engine", engine), + ("model_file", model_file), + ("mem_bw", mem_bw), + ("parallel", f"tp {m['tp']} · pp {m['pp']}"), + ("precision", f"weights {m['quant']} · kv {m['kv']}"), + ("launch", launch), + ("env_flags", env_flags), + ("spec", m["spec"]), + ("thinking", thinking), + ("greedy_check", greedy), + ("run", join(m["run_mode"], "concurrency " + m["concurrency"], + "bench-standard " + m["bench_standard"], betterbench)), +] +if m.get("special_notes"): + notes.append(("special_notes", m["special_notes"])) +for k, v in notes: + print(f"{k}={v}") diff --git a/dev/postrun.py b/dev/postrun.py new file mode 100644 index 0000000..b8eaaf2 --- /dev/null +++ b/dev/postrun.py @@ -0,0 +1,245 @@ +"""postrun.py - figures that need the finished run, and the summary. + +usage: T0=epoch T1=epoch postrun.py RUN_DIR + +Reads results.json, meta.json, power.csv (epoch_s,watts,joules,mhz) and +timeline.tsv (epochBetterBench progress line) from RUN_DIR. Writes +energy (whole run and per phase) and the bandwidth figure to meta.json under +"post_run", and prints the summary to stderr. +""" +import bisect +import json +import os +import re +import statistics +import sys + + +def read_power(path): + rows = [] + if os.path.exists(path): + for line in open(path): + p = line.strip().split(",") + try: + rows.append((float(p[0]), float(p[1]), float(p[2]) if p[2] else None, + float(p[3]) if len(p) > 3 and p[3] else 0.0)) + except (ValueError, IndexError): + pass + return rows + + +def energy_curve(rows): + """(times, cumulative joules): from the energy counter when every sample + has one, else integrated from the power samples.""" + ts = [r[0] for r in rows] + if all(r[2] is not None for r in rows) and rows[-1][2] >= rows[0][2]: + return ts, [r[2] - rows[0][2] for r in rows], "energy counter" + cum = [0.0] + for a, b in zip(rows, rows[1:]): + cum.append(cum[-1] + (b[0] - a[0]) * (a[1] + b[1]) / 2) + return ts, cum, "integrated power" + + +def joules_between(ts, cum, t0, t1): + """Energy between two moments, interpolating between samples.""" + def at(t): + if t <= ts[0]: + return cum[0] + if t >= ts[-1]: + return cum[-1] + i = bisect.bisect_right(ts, t) + f = (t - ts[i - 1]) / (ts[i] - ts[i - 1]) + return cum[i - 1] + f * (cum[i] - cum[i - 1]) + return max(0.0, at(t1) - at(t0)) + + +SEGMENT = re.compile(r"^\[(single|prefill|concurrency)\]\s+(.*)$") +WARMUP = re.compile(r"warmup (\d+) \+ (\d+)") + + +def segments(timeline, t_end): + """BetterBench prints a progress line when each piece of work starts; a + piece lasts until the next line. Yields (phase, key, warm-up factor, t0, t1).""" + marks = [] + for t, line in timeline: + m = SEGMENT.match(line) + if not m or "skip" in m.group(2): + continue + phase, rest = m.groups() + key = rest.split(":")[0].strip() + if phase == "concurrency": + key = re.sub(r"\D", "", key) + w = WARMUP.search(rest) + factor = (int(w.group(1)) + int(w.group(2))) / int(w.group(2)) if w and int(w.group(2)) else 1.0 + marks.append((t, phase, key, factor)) + for i, (t, phase, key, factor) in enumerate(marks): + yield phase, key, factor, t, marks[i + 1][0] if i + 1 < len(marks) else t_end + + +def phase_energy(res, rows, timeline, t_end): + """Joules and joules per token for decode, prefill and each concurrency + level. Warm-up passes draw power but aren't in results.json, so their + tokens are estimated from the measured passes of the same piece.""" + ts, cum, _ = energy_curve(rows) + single = res.get("single_stream") or {} + prefill = {str(p.get("target_depth")): p for p in res.get("prefill") or []} + conc = {str(x.get("level")): x for x in res.get("concurrency") or []} + out = {"decode": {"joules": 0.0, "seconds": 0.0, "tokens": 0.0}, + "prefill": {"joules": 0.0, "seconds": 0.0, "tokens": 0.0}, "concurrency": {}} + for phase, key, factor, t0, t1 in segments(timeline, t_end): + j = joules_between(ts, cum, t0, t1) + if phase == "single": + tok = sum(r.get("completion_tokens") or 0 for r in single.get(key, []) if r.get("ok", True)) + d = out["decode"] + elif phase == "prefill": + depth = re.sub(r"\D", "", key) + tok = sum(prefill.get(depth, {}).get("prompt_tokens") or []) + d = out["prefill"] + else: + x = conc.get(key, {}) + tok, factor = x.get("aggregate_tps", 0) * x.get("wall_s", 0), 1.0 + d = out["concurrency"].setdefault(key, {"joules": 0.0, "seconds": 0.0, "tokens": 0.0}) + d["joules"] += j + d["seconds"] += t1 - t0 + d["tokens"] += tok * factor + def finish(d, per=1): + return {"joules": round(d["joules"]), "avg_w": round(d["joules"] / d["seconds"], 1) if d["seconds"] else None, + "tokens_incl_warmup_est": round(d["tokens"]), + "j_per_token" if per == 1 else "j_per_1k_tokens": + round(d["joules"] / d["tokens"] * per, 3) if d["tokens"] else None} + result = {} + if out["decode"]["seconds"]: + result["decode"] = finish(out["decode"]) + if out["prefill"]["seconds"]: + result["prefill"] = finish(out["prefill"], per=1000) + if out["concurrency"]: + result["concurrency"] = {k: finish(v) for k, v in out["concurrency"].items()} + return result + + +def roofline(single, c, m): + """Batch-1 decode reads all weights once per token: decode t/s x weight + bytes is the bandwidth it reaches. The weights are what the engine loaded + (vLLM logs it per worker) or else what is stored; tensor parallelism + spreads them over tp GPUs, each with its own bandwidth.""" + def num(v): + try: + return float(v) + except (TypeError, ValueError): + return None + tps = [r["decode_tps"] for r in single if r.get("decode_tps")] + bw = num(c.get("gpu_mem_bw_gbs")) or num(m.get("mem_bw")) + tp = int(m.get("tp") or 1) + loaded, stored = num(c.get("model_loaded_gib")), num(c.get("model_bytes")) + if loaded: + nbytes, src = loaded * 2**30 * tp, "loaded (engine log)" + elif stored: + nbytes, src = stored, "stored files" + else: + return None + if not tps or not bw: + return None + med = statistics.median(tps) + eff = med * nbytes / 1e9 + return {"decode_tps_median": round(med, 2), "weight_bytes": int(nbytes), "weight_source": src, + "mem_bw_gbs": bw * tp, "gpus": tp, "effective_gbs": round(eff, 1), + "pct_of_mem_bw": round(100 * eff / (bw * tp), 1)} + + +def main(d): + res = json.load(open(f"{d}/results.json", encoding="utf-8")) + meta = json.load(open(f"{d}/meta.json", encoding="utf-8")) + c, m = meta["collected"], meta["mandatory"] + t0, t1 = float(os.environ["T0"]), float(os.environ["T1"]) + post = {"wall_s": round(t1 - t0, 1)} + + single = [r for recs in (res.get("single_stream") or {}).values() for r in recs + if r.get("ok", True)] + tok = sum(r.get("completion_tokens") or 0 for r in single) + tok += sum(round(x.get("aggregate_tps", 0) * x.get("wall_s", 0)) + for x in res.get("concurrency") or []) + + rows = read_power(f"{d}/power.csv") + timeline = [] + if os.path.exists(f"{d}/timeline.tsv"): + for line in open(f"{d}/timeline.tsv", encoding="utf-8"): + t, _, text = line.rstrip("\n").partition("\t") + try: + timeline.append((float(t), text)) + except ValueError: + pass + if len(rows) >= 2: + ts, cum, src = energy_curve(rows) + span = ts[-1] - ts[0] + joules = cum[-1] + e = {"joules": round(joules), "source": src, "sampled_s": round(span, 1), + "avg_w": round(joules / span, 1) if span else None, + "peak_w": max(r[1] for r in rows), "output_tokens": tok, + "j_per_output_token": round(joules / tok, 3) if tok else None} + # A clock-gated idle GPU reads 0 MHz; average the samples where it runs. + clk = [r[3] for r in rows if r[3] > 0] + if clk: + e.update(avg_mhz=round(statistics.mean(clk)), min_mhz=round(min(clk)), + max_mhz=round(max(clk)), clock_samples=f"{len(clk)}/{len(rows)}") + if timeline: + e["phases"] = phase_energy(res, rows, timeline, t1) + post["energy"] = e + + r = roofline(single, c, m) + if r: + post["roofline"] = r + + # The summary: headline numbers plus the setup that makes them comparable. + def med(xs): + xs = [x for x in xs if x] + return statistics.median(xs) if xs else None + def f(x, unit, dec=0): + return "—" if x is None else f"{x:,.{dec}f} {unit}" + notes = meta["notes"] + tps = [x["decode_tps"] for x in single if x.get("decode_tps")] + L = [f" {meta['model']} · {notes.get('engine', '?')}", + f" {notes.get('gpu', '?')} · {notes.get('power_limit', '?')} limit", + f" {notes.get('run', '?')} · greedy {notes.get('greedy_check', '?')}", + f" decode (batch 1) {f(med(tps), 't/s', 1)} TTFT p50 " + f"{f(med(x.get('ttft_ms') for x in single), 'ms')}"] + conc = res.get("concurrency") or [] + if conc: + L.append(" concurrency " + " ".join( + f"{x['level']}: {x.get('aggregate_tps', 0):,.0f} t/s" for x in conc)) + live = [p for p in res.get("prefill") or [] if not p.get("skipped")] + if live: + L.append(" prefill " + " ".join( + f"{p['target_depth'] // 1000}k: {f(med(p.get('pp_tps') or []), 't/s')}" for p in live)) + if r: + L.append(f" bandwidth {r['effective_gbs']:.0f} GB/s effective = " + f"{r['pct_of_mem_bw']:.0f}% of {r['mem_bw_gbs']:.0f} GB/s " + f"(weights {r['weight_bytes'] / 1e9:.2f} GB, {r['weight_source']})") + if "energy" in post: + e = post["energy"] + clock = (f" · clock avg {e['avg_mhz']} MHz ({e['min_mhz']}-{e['max_mhz']})" + if "avg_mhz" in e else "") + L.append(f" power avg {e['avg_w']} W, peak {e['peak_w']:.0f} W{clock}") + ph = e.get("phases") or {} + parts = [] + if ph.get("decode", {}).get("j_per_token") is not None: + parts.append(f"decode {ph['decode']['j_per_token']} J/tok at {ph['decode']['avg_w']} W") + if ph.get("prefill", {}).get("j_per_1k_tokens") is not None: + parts.append(f"prefill {ph['prefill']['j_per_1k_tokens']} J/1k tok") + if parts: + L.append(" energy " + " · ".join(parts)) + if ph.get("concurrency"): + L.append(" energy by conc. " + " ".join( + f"{k}: {v['j_per_token']} J/tok" for k, v in ph["concurrency"].items() + if v.get("j_per_token") is not None)) + L.append(f" energy (total) {e['joules'] / 1000:.1f} kJ, " + f"{e['j_per_output_token']} J per output token over the whole run") + print("\n" + "\n".join(L), file=sys.stderr) + + meta["post_run"] = post + with open(f"{d}/meta.json", "w", encoding="utf-8") as fh: + json.dump(meta, fh, indent=2) + fh.write("\n") + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/dev/standard.env b/dev/standard.env index d63ce1d..f005eeb 100644 --- a/dev/standard.env +++ b/dev/standard.env @@ -1,6 +1,6 @@ # Pins for this version of the group standard. Bump STANDARD_VERSION whenever # config.json, the minimum BetterBench or the mandatory fields change. -STANDARD_VERSION=0.4.1 +STANDARD_VERSION=0.5.0 # Oldest BetterBench that has everything bench.sh uses; newer ones run too, # and the version goes into the run note so compare shows a mismatch. BETTERBENCH_MIN_VERSION=0.6.1 diff --git a/dev/tests/test_model_hash.py b/dev/tests/test_model_hash.py new file mode 100644 index 0000000..804544f --- /dev/null +++ b/dev/tests/test_model_hash.py @@ -0,0 +1,31 @@ +"""model_hash.py must match the README's commands exactly.""" +import os +import subprocess +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import model_hash # noqa: E402 + + +def sh(cmd, cwd): + return subprocess.run(["sh", "-c", cmd], cwd=cwd, capture_output=True, text=True, + check=True).stdout.split()[0] + + +def test_directory_hash_matches_sha256sum(tmp_path): + # model_mtp sorts before model. in en_US but after it in C: the README pins C + (tmp_path / "model.safetensors").write_bytes(b"weights" * 1000) + (tmp_path / "model_mtp.safetensors").write_bytes(b"mtp head") + (tmp_path / "config.json").write_text("{}") + want = sh("sha256sum *.safetensors | LC_ALL=C sort -k2 | sha256sum", tmp_path) + assert model_hash.model_sha256(str(tmp_path), cache={}) == want + + +def test_file_hash_and_cache(tmp_path): + f = tmp_path / "m.gguf" + f.write_bytes(b"gguf" * 5000) + cache = {} + assert model_hash.model_sha256(str(f), cache) == sh("sha256sum m.gguf", tmp_path) + key = next(iter(cache)) + cache[key] = "cached" + assert model_hash.model_sha256(str(f), cache) == "cached" # same size and mtime: no rehash diff --git a/dev/tests/test_notes.py b/dev/tests/test_notes.py new file mode 100644 index 0000000..e220a34 --- /dev/null +++ b/dev/tests/test_notes.py @@ -0,0 +1,106 @@ +"""notes.py: launch parsing, the model check, the thinking check, the run note.""" +import json +import os +import subprocess +import sys + +DEV = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +STD_GGUF = "322e194ff79741c7baa497c240f677f54b201b0efab44ca8e50f122b39123482" + +MANDATORY = {"submitter": "pascal", "tp": "1", "pp": "1", "quant": "UD-Q4_K_M", "kv": "q8_0", + "spec": "none", "thinking": "default", "power_limit": "200", + "power_limit_source": "detected", "betterbench": "0.6.1", "betterbench_build": "v0.6.1", + "bench_standard": "0.4.1", "run_mode": "full", "concurrency": "on"} +COLLECTED = {"engine": "llama.cpp", "engine_version": "b11913-7aca0d2ea", "gpu_vendor": "intel", + "gpu_count": "1", "gpu_model": "Arc Pro B65", "model_file": "/models/x.gguf", + "model_bytes": "16464440224", "model_sha256": STD_GGUF} +MEASURED = {"greedy_check": "identical", "greedy_runs": "3", "greedy_variants": "1", + "greedy_hash": "1d5105fe09dc", "greedy_reasoning": "yes"} +LLAMA_CMD = ("GGML_SYCL_DISABLE_OPT=0 ZES_ENABLE_SYSMAN=1 HF_HUB_OFFLINE=1 /app/llama-server " + "-m /models/x.gguf -c 32768 -ngl 99 -fa on -b 4096 -ub 1024 -ctk q8_0 -ctv q8_0 " + "-np 4 --no-mmap --port 9000") +VLLM_CMD = ("docker run --rm --name v -e K8V4_PREFILL=onednn -e HF_TOKEN= img /model " + "--max-num-batched-tokens=4224 --max-num-seqs=4 --kv-cache-dtype=int8_k_int4_v " + "--no-enable-prefix-caching " + "'--compilation-config={\"cudagraph_mode\": \"FULL_DECODE_ONLY\"}'") + + +def run(tmp_path, cmd=LLAMA_CMD, **over): + files = {} + for name, base in (("m", MANDATORY), ("c", COLLECTED), ("x", MEASURED)): + d = {**base, **over.get(name, {})} + files[name] = tmp_path / name + files[name].write_text("".join(f"{k}={v}\n" for k, v in d.items())) + (tmp_path / "cmd").write_text(cmd) + p = subprocess.run([sys.executable, os.path.join(DEV, "notes.py"), files["m"], files["c"], + files["x"], tmp_path / "cmd", tmp_path / "launch.json", + os.path.join(DEV, "models.tsv")], capture_output=True, text=True, check=True) + notes = dict(line.split("=", 1) for line in p.stdout.splitlines()) + return notes, p.stderr, json.loads((tmp_path / "launch.json").read_text()) + + +def test_llama_launch_and_env(tmp_path): + notes, err, launch = run(tmp_path) + assert notes["launch"] == "b 4096 · ub 1024 · fa on · ctk q8_0 · ctv q8_0 · ngl 99 · np 4 · no-mmap" + assert notes["env_flags"] == "GGML_SYCL_DISABLE_OPT=0 · ZES_ENABLE_SYSMAN=1" # offline switch left out + assert launch["env"]["HF_HUB_OFFLINE"] == "1" # but kept in meta + assert "warning" not in err + + +def test_llama_defaults_shown(tmp_path): + notes, _, _ = run(tmp_path, cmd="llama-server -m /m.gguf -ngl 99 -fa", m={"kv": "f16"}) + assert notes["launch"] == "b default · ub default · fa on · ctk default · ctv default · ngl 99" + + +def test_vllm_launch_env_and_kv_warning(tmp_path): + notes, err, _ = run(tmp_path, cmd=VLLM_CMD, c={"engine": "vllm"}) + assert "max-num-batched-tokens 4224" in notes["launch"] + assert "no-enable-prefix-caching" in notes["launch"] + assert 'compilation-config {"cudagraph_mode":"FULL_DECODE_ONLY"}' in notes["launch"] + assert notes["env_flags"] == "K8V4_PREFILL=onednn · HF_TOKEN=" + assert "--kv q8_0 but the launch command sets int8_k_int4_v" in err + + +def test_no_command(tmp_path): + notes, _, _ = run(tmp_path, cmd="") + assert notes["launch"] == "unknown (pass --server-cmd-file)" + assert notes["env_flags"] == "unknown" + + +def test_standard_model(tmp_path): + notes, err, _ = run(tmp_path) + assert notes["model_file"].endswith("standard: Qwen3.8-27B UD-Q4_K_M") + assert "standard models" not in err + + +def test_standard_model_wrong_quant(tmp_path): + _, err, _ = run(tmp_path, m={"quant": "Q4_K_M"}) + assert "declare --quant UD-Q4_K_M" in err + + +def test_other_model(tmp_path): + notes, err, _ = run(tmp_path, c={"model_sha256": "ab" * 32}) + assert "not a standard model (sha256 abababababab)" in notes["model_file"] + assert "won't count" in err + + +def test_model_not_hashed(tmp_path): + notes, _, _ = run(tmp_path, c={"model_sha256": ""}) + assert notes["model_file"].endswith("hash not checked") + + +def test_thinking_checked_against_replies(tmp_path): + notes, err, _ = run(tmp_path, m={"thinking": "off"}) + assert notes["thinking"] == "off · reasoning seen" + assert "--thinking off, but the greedy replies contain reasoning" in err + notes, err, _ = run(tmp_path, m={"thinking": "high"}, x={"greedy_reasoning": "no"}) + assert "--thinking high, but the greedy replies contain no reasoning" in err + _, err, _ = run(tmp_path, m={"thinking": "default"}, x={"greedy_reasoning": "no"}) + assert "thinking" not in err + + +def test_run_note_betterbench_build(tmp_path): + notes, _, _ = run(tmp_path) + assert notes["run"] == "full · concurrency on · bench-standard 0.4.1 · betterbench 0.6.1" + notes, _, _ = run(tmp_path, m={"betterbench_build": "v0.6.1-3-gabc1234-dirty"}) + assert notes["run"].endswith("betterbench 0.6.1 @ v0.6.1-3-gabc1234-dirty") diff --git a/dev/tests/test_postrun.py b/dev/tests/test_postrun.py new file mode 100644 index 0000000..219641f --- /dev/null +++ b/dev/tests/test_postrun.py @@ -0,0 +1,58 @@ +"""postrun.py: energy per phase and the bandwidth figure.""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import postrun # noqa: E402 + + +def test_joules_between_interpolates(): + ts, cum = [0.0, 10.0, 20.0], [0.0, 1000.0, 3000.0] + assert postrun.joules_between(ts, cum, 5, 15) == 1500.0 + assert postrun.joules_between(ts, cum, -5, 30) == 3000.0 + + +def test_energy_curve_counter_or_integrated(): + rows = [(0, 100, 50.0, 0), (10, 100, 1050.0, 0)] + assert postrun.energy_curve(rows)[1] == [0.0, 1000.0] + rows = [(0, 100, None, 0), (10, 300, None, 0)] + ts, cum, src = postrun.energy_curve(rows) + assert cum == [0.0, 2000.0] and src == "integrated power" + + +def test_phase_energy_with_warmup_and_levels(): + # a steady 100 W, so energy = 100 J per second of each piece + rows = [(float(t), 100.0, 100.0 * t, 2000.0) for t in range(0, 101)] + timeline = [(0.0, "[single] chat: warmup 1 + 4 runs"), + (10.0, "[prefill] depth ~2000 tok: warmup 2 + 8"), + (20.0, "[prefill] skip depth ~64000: needs more"), + (30.0, "[concurrency] level 2: 48 requests")] + res = {"single_stream": {"chat": [{"ok": True, "completion_tokens": 100}] * 4}, + "prefill": [{"target_depth": 2000, "prompt_tokens": [1000] * 8}], + "concurrency": [{"level": 2, "aggregate_tps": 10.0, "wall_s": 50.0}]} + ph = postrun.phase_energy(res, rows, timeline, 80.0) + # decode: 10 s = 1000 J; 400 measured tokens, x 5/4 for the warm-up pass + assert ph["decode"] == {"joules": 1000, "avg_w": 100.0, "tokens_incl_warmup_est": 500, + "j_per_token": 2.0} + # prefill runs until the concurrency line (the skip line starts nothing): 20 s + assert ph["prefill"]["joules"] == 2000 + assert ph["prefill"]["j_per_1k_tokens"] == round(2000 / (8000 * 10 / 8) * 1000, 3) + # level 2: 50 s = 5000 J for 500 tokens + assert ph["concurrency"]["2"]["j_per_token"] == 10.0 + + +def test_roofline_prefers_loaded_weights_and_scales_with_tp(): + single = [{"decode_tps": 100.0}] + c = {"gpu_mem_bw_gbs": "500", "model_bytes": "4000000000", "model_loaded_gib": "1.0"} + r = postrun.roofline(single, c, {"tp": "2"}) + assert r["weight_source"] == "loaded (engine log)" + assert r["weight_bytes"] == 2 * 2**30 + assert r["mem_bw_gbs"] == 1000.0 + assert r["pct_of_mem_bw"] == round(100 * 100 * 2 * 2**30 / 1e9 / 1000, 1) + + +def test_roofline_falls_back_to_stored_and_declared_bw(): + r = postrun.roofline([{"decode_tps": 50.0}], {"model_bytes": "4000000000"}, + {"tp": "1", "mem_bw": "400"}) + assert r["weight_source"] == "stored files" and r["pct_of_mem_bw"] == 50.0 + assert postrun.roofline([{"decode_tps": 50.0}], {}, {"tp": "1", "mem_bw": "400"}) is None