bench-standard 0.5.0: fix silent exits and signals, check declared values, hash the model

Fixes:
- A run on a machine without nvidia-smi/xpu-smi (every AMD box) exited
  silently with status 1 after BetterBench: the power sampler had already
  exited, so `kill` failed under set -e. No summary, no post_run, no done.
- Ctrl-C or kill didn't stop the script: the INT/TERM traps cleaned up and
  carried on, so a partial run could print a summary and `done:`. Now
  BetterBench is stopped at once and the folder is renamed .interrupted. The
  one-file bench.sh exec's the real script, so kill PID reaches it.
- Redaction turned --max-num-batched-tokens=8192 into <redacted>, corrupting
  the launch note. Env-style secrets and user:pass@ in URLs are still redacted.
- The --kv check was inverted when only -ctk is set: it warned on the
  correct q8_0/f16 and accepted q8_0.
- Negative flag values (-t -1) were parsed as flags.
- Model sizes in the HF cache counted symlinks, not the weights.
- A failed greedy check was recorded without any message.

Improvements:
- The served model is hashed (cached) and checked against the README's table
  (dev/models.txt), with a --quant cross-check.
- --spec, --thinking and vLLM --tp/--pp are checked against the launch
  command, like --kv; warnings name the value to declare.
- Weights are found through docker -v/--mount for any launch command, not
  only llama-swap's, and vLLM repo ids through the HF cache.
- AMD power and clock are sampled from amdgpu's hwmon sysfs files.
- Warnings are repeated after the summary and in the dry run, and saved in
  meta.json; the summary is saved as summary.txt.
- dev/test.sh: 36 end-to-end tests with a fake server and fake BetterBench,
  no GPU; CI runs them under dash and bash, plus shellcheck and build --check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EooZ9aTJE7srSQEYUqdQio
This commit is contained in:
Claude committed 2026-11-01 20:05:40 +00:00
1 parent b892e7b14d
commit b36805d1cb
14 files changed
+1004 -206

No files matched your search

+27 -8
View File
@@ -19,7 +19,8 @@ What `bench.sh` records, how, and how it's built. For running it, see
| `results.json` | BetterBench results; the notes below are under `env.notes` |
| `results.html` | the standalone report |
| `config.json` | the BetterBench config the run used |
| `meta.json` | every raw value: `mandatory` (declared), `collected` (detected), `measured`, `launch`, `post_run` |
| `meta.json` | every raw value: `mandatory` (declared), `collected` (detected), `measured`, `launch`, `post_run`, `warnings` |
| `summary.txt` | the summary printed at the end, warnings included |
| `server-cmd.txt` | the server launch command, secrets redacted |
| `power.csv` | `epoch_s,watts,joules,mhz` during the run |
| `betterbench.log` | BetterBench's full output |
@@ -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.5-9B-Q4_K_M.gguf · 5.68 GB · sha256 03b74727a860 (standard: Qwen3.5-9B-Q4_K_M.gguf)` (weights as stored; `not a standard model` otherwise) |
| `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` |
| `special_notes` | only when given |
The context size appears as BetterBench's own chip.
@@ -67,6 +68,15 @@ This works in a VM too, because passthrough keeps BAR sizes.
launch command. For a docker server the image is recorded with its ID, because tags like
`server-intel` move daily.
**Model file:** the path the engine reports (`/props` `model_path`, vLLM's `root`). A path
inside a docker container is mapped back to the host through the command's `-v` and
`--mount` flags; a vLLM repo id is looked up in the Hugging Face cache (the container's
`HF_HOME` through its mounts, then this machine's). The size is that of the GGUF (all
parts of a split one) or of the `*.safetensors`. The hash is the one the README's table
lists (split GGUFs aren't hashed); it's cached in `~/.cache/bench-standard/` by path,
size and mtime. `dev/models.txt` holds the table; a hash not in it, or a `--quant` other
than the table's, gives a warning.
**Launch settings** come from the launch command, because no API reports them:
- llama.cpp: `b`, `ub`, `fa`, `ctk` and `ctv` always show, as `default` when not set,
because the defaults change between builds.
@@ -74,7 +84,12 @@ launch command. For a docker server the image is recorded with its ID, because t
- **Env flags** come from `VAR=x cmd`, `env VAR=x` and docker `-e VAR=x`. Settings in
llama-swap's `env:` block, or in the shell that started the server, aren't visible;
put them in the command.
- If `--kv` doesn't match the command, `bench.sh` warns.
- Declared values are checked against the command, and a contradiction is a warning
that names the value to declare: `--kv` (llama.cpp `-ctk`/`-ctv`, f16 when one is
unset; vLLM `--kv-cache-dtype`, or `--dtype` when that is `auto`), `--spec` (llama.cpp
`-md` with `--draft-max`, default 16; vLLM `--speculative-config`), `--thinking`
(`--reasoning-budget 0` or `enable_thinking: false` mean `off`) and, for vLLM, `--tp`
and `--pp`. Settings the command doesn't state aren't guessed.
**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
@@ -96,6 +111,8 @@ These go to `meta.json` under `post_run` and the summary, not to the notes, whic
fixed before BetterBench starts.
- **energy:** kJ, average and peak W, J per output token, and average, min and max clock.
Sampled with `nvidia-smi`, `xpu-smi`, or amdgpu's hwmon files in sysfs (power and
clock; no energy counter, so the power is integrated).
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.
Power is sampled only when BetterBench runs on the server. On a split setup, run
@@ -117,14 +134,16 @@ 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` from there, with `BENCH_HOME` set to its own folder, so `results/`
and `bench.local.env` stay next to the downloaded file.
`dev/bench.sh`, `collect-env.sh`, `gpu-power.sh`, `mem-bw.py`, `config.json`,
`standard.env` and `models.txt` into it. At run time it unpacks them to a temp dir and
exec's `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. `dev/bench.sh` removes the temp
dir when it exits (`BENCH_UNPACKED`).
```sh
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/test.sh # end-to-end tests: fake server, fake BetterBench, no GPU
sh dev/bench.sh --help # dev/bench.sh also runs directly, results in dev/results/
```
+205 -56
View File
@@ -59,9 +59,36 @@ home=${BENCH_HOME:-$here}
die() { echo "bench.sh: $*" >&2; exit 1; }
usage() { sed -n '2,/^$/p' "$0" | sed -e 's/^# \{0,1\}//' -e '$d'; exit "${1:-0}"; }
# Cleanup and signals. Long steps run in the background with `wait`, which a
# trapped signal interrupts at once (a foreground child would delay the trap
# until it finished). Background jobs ignore Ctrl-C, so the trap stops them.
# The one-file bench.sh hands its unpacked helpers over in BENCH_UNPACKED and
# exec's this script, so a kill of that pid lands here.
tmp="" child="" sampler="" run_dir_made=""
cleanup() {
for p in $child $sampler; do kill "$p" 2>/dev/null || true; done
[ -z "$tmp" ] || rm -rf "$tmp"
[ "${BENCH_UNPACKED:-}" != "$here" ] || rm -rf "$here"
}
on_signal() {
trap - INT TERM
for p in $child; do kill "$p" 2>/dev/null || true; wait "$p" 2>/dev/null || true; done
child=""
if [ -n "$run_dir_made" ] && [ -d "$run_dir_made" ]; then
mv "$run_dir_made" "$run_dir_made.interrupted" 2>/dev/null &&
echo "bench.sh: interrupted; partial output in $run_dir_made.interrupted (it doesn't count)" >&2
fi
exit "$1"
}
trap cleanup EXIT
trap 'on_signal 130' INT
trap 'on_signal 143' TERM
# bg CMD...: run CMD in the background, wait for it; its status in $rc.
bg() { "$@" & child=$!; rc=0; wait "$child" || rc=$?; child=""; }
case "${1:-}" in
collect-env) shift; exec sh "$here/collect-env.sh" "$@" ;;
power) shift; exec sh "$here/gpu-power.sh" "$@" ;;
collect-env) shift; rc=0; sh "$here/collect-env.sh" "$@" || rc=$?; exit "$rc" ;;
power) shift; bg sh "$here/gpu-power.sh" "$@"; exit "$rc" ;;
--version) echo "bench-standard $STANDARD_VERSION (BetterBench $BETTERBENCH_MIN_VERSION or newer)"; exit 0 ;;
esac
@@ -141,7 +168,12 @@ if [ -n "$server_cmd_file" ]; then [ -r "$server_cmd_file" ] || die "cannot read
if [ -n "$env_file" ]; then [ -r "$env_file" ] || die "cannot read $env_file"; fi
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT INT TERM
# Warnings print as they come and are repeated after the summary, so none
# scroll away during a long run; meta.json keeps them too.
warnings="$tmp/warnings"
: > "$warnings"
warn() { echo "bench.sh: warning: $*" >&2; printf '%s\n' "$*" >> "$warnings"; }
hdr="$tmp/hdr"
if [ -n "${BETTERBENCH_API_KEY:-}" ]; then printf 'Authorization: Bearer %s\n' "$BETTERBENCH_API_KEY" > "$hdr"
@@ -196,6 +228,9 @@ else:
print(f"greedy_variants={len(set(hashes))}\ngreedy_runs={len(hashes)}\ngreedy_hash={hashes[0]}")
print("greedy_reasoning=" + ("yes" if all(thought) else "no" if not any(thought) else "mixed"))
PY
if grep -q '^greedy_check=failed' "$tmp/measured"; then
warn "greedy check failed ($(sed -n 's/^greedy_error=//p' "$tmp/measured")); the result has no greedy hash"
fi
# ---------------------------------------------------------------- collect
if [ -n "$env_file" ]; then
@@ -245,8 +280,13 @@ if [ -n "$cmd_src" ]; then
python3 - "$tmp/cmd" "$tmp/cmd.red" <<'PY'
import re, sys
s = open(sys.argv[1], encoding="utf-8", errors="replace").read()
s = re.sub(r'(?i)\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY)[A-Z0-9_]*=)\S+', r'\1<redacted>', s)
s = re.sub(r'(?i)(--(?:api-key|hf-token|token)[= ])\S+', r'\1<redacted>', s)
# Env assignments (FOO_TOKEN=x, -e FOO_TOKEN=x, --env=FOO_TOKEN=x) - not
# flags like --max-num-batched-tokens=8192, hence no '-' right before.
s = re.sub(r'(?i)(?<![\w-])([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|ACCESS_KEY|CREDENTIAL)'
r'[A-Z0-9_]*=)\S+', r'\1<redacted>', s)
s = re.sub(r'(?i)((?<!\S)(?:--api-key|--hf-token|-hft|--token)[= ])\S+', r'\1<redacted>', s)
# user:password@ in URLs (proxies, registries)
s = re.sub(r'(?i)(\b[a-z][a-z0-9+.-]*://[^\s:/@]+:)[^\s@/]+@', r'\1<redacted>@', s)
open(sys.argv[2], "w", encoding="utf-8").write(s if s.endswith("\n") else s + "\n")
PY
fi
@@ -254,9 +294,14 @@ 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.
WARNINGS=$warnings MODELS=$here/models.txt \
python3 - "$tmp/mandatory" "$tmp/collected" "$tmp/measured" "$tmp/cmd.red" "$tmp/launch.json" \
> "$tmp/notes" <<'PY'
import json, shlex, sys
import json, os, re, shlex, sys
def warn(msg):
print("bench.sh: warning: " + msg, file=sys.stderr)
with open(os.environ["WARNINGS"], "a", encoding="utf-8") as f:
f.write(msg + "\n")
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)
@@ -269,7 +314,7 @@ 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")
count = g("gpu_count") if g("gpu_count") != "0" else "" # 0: nothing detected
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",
@@ -308,7 +353,11 @@ 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"}
"-cmoe", "--cpu-moe", "-rm", "--rm", "-d", "--detach", "-it", "-i", "--privileged",
"--init", "--jinja", "--no-webui", "--metrics", "--trust-remote-code",
"--enable-auto-tool-choice", "--disable-log-requests", "--disable-log-stats"}
def is_value(x): # the next word is this flag's value: not a flag, or a number
return x is not None and (not x.startswith("-") or re.fullmatch(r"-[0-9.]+", x))
FA_VALUES = {"on", "off", "auto", "1", "0", "true", "false"}
i = 0
while i < len(words):
@@ -332,7 +381,7 @@ while i < len(words):
flags[w] = nxt; i += 1
else:
flags[w] = "on" # older bare -fa
elif w in BOOL or nxt is None or nxt.startswith("-"):
elif w in BOOL or not is_value(nxt):
flags[w] = True
else:
flags[w] = nxt; i += 1
@@ -388,15 +437,92 @@ env_flags = (" · ".join(f"{k}={v}" for k, v in env.items() if k not in QUIET) o
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 declared values should be what the launch command sets (AGENTS.md
# step 4). Only what the command states is checked; defaults are assumed
# only where the standard defines them (llama.cpp KV f16, vLLM tp/pp 1).
def expect(name, declared, wanted, why):
if wanted is not None and declared != wanted:
warn(f"--{name} {declared} but the launch command sets {why}: declare --{name} {wanted}")
if cmd and launch_kind == "llama.cpp":
k, v = flag("-ctk", "--cache-type-k"), flag("-ctv", "--cache-type-v")
if k or v:
k, v = k or "f16", v or "f16"
expect("kv", m["kv"], k if k == v else f"{k}/{v}", f"K {k}, V {v}")
elif cmd and launch_kind == "vllm":
kvd, dt = flag("--kv-cache-dtype"), str(flag("--dtype") or "")
if kvd and kvd != "auto":
expect("kv", m["kv"], kvd, f"--kv-cache-dtype {kvd}")
elif dt in ("bfloat16", "float16", "half"):
expect("kv", m["kv"], "bf16" if dt == "bfloat16" else "f16",
f"--kv-cache-dtype {kvd or 'unset'} with --dtype {dt}")
# Speculative decoding.
spec_cmd = None
if cmd and launch_kind == "llama.cpp":
if flag("-md", "--model-draft", "-hfd", "-hfrd", "--hf-repo-draft"):
n = flag("--draft-max", "--draft", "--draft-n")
if n and str(n).isdigit():
spec_cmd = (f"draft:{n}", f"a draft model with --draft-max {n}")
elif not m["spec"].startswith("draft:"): # the default N varies between builds
warn(f"--spec {m['spec']} but the launch command loads a draft model (-md):"
" declare draft:N, N = the build's --draft-max default")
else:
spec_cmd = ("none", "no draft model")
elif cmd and launch_kind == "vllm":
sc, n = flag("--speculative-config"), flag("--num-speculative-tokens")
if sc not in (None, True):
try:
j = json.loads(sc)
except ValueError:
j = dict(re.findall(r'"?(method|num_speculative_tokens|model)"?\s*[:=]\s*"?([\w./-]+)', sc))
meth = str(j.get("method") or ("draft" if j.get("model") else ""))
meth = ("mtp" if "mtp" in meth else "draft" if meth.startswith("draft") else
meth if meth in ("eagle", "eagle3", "ngram") else None)
n = j.get("num_speculative_tokens") or n
if meth and n:
spec_cmd = (f"{meth}:{n}", f"--speculative-config {sc}")
elif not flag("--speculative-model"):
spec_cmd = ("none", "no --speculative-config")
if spec_cmd:
expect("spec", m["spec"], spec_cmd[0], spec_cmd[1])
if cmd and launch_kind == "vllm":
expect("tp", m["tp"], str(flag("--tensor-parallel-size", "-tp") or 1), "that tensor parallel size")
expect("pp", m["pp"], str(flag("--pipeline-parallel-size", "-pp") or 1), "that pipeline parallel size")
# Thinking switched off (or on) in the launch command.
think_cmd = None
if str(flag("--reasoning-budget")) == "0":
think_cmd = "--reasoning-budget 0"
et = re.search(r'enable_thinking"?\s*:\s*(true|false)', cmd, re.I)
if et:
think_cmd = think_cmd or f"enable_thinking: {et.group(1).lower()}"
if think_cmd and ("false" in think_cmd or "budget 0" in think_cmd):
expect("thinking", m["thinking"], "off", think_cmd)
elif think_cmd and m["thinking"] == "off":
warn(f"--thinking off but the launch command sets {think_cmd}")
# Results only count for the standard models (models.txt = the README's table).
std = {}
with open(os.environ["MODELS"], encoding="utf-8") as f:
for line in f:
p = line.split()
if len(p) == 3 and not p[0].startswith("#"):
std[p[0]] = (p[1], p[2])
sha = g("model_sha256")
if sha in std:
sha_note = f"sha256 {sha[:12]} (standard: {std[sha][1]})"
if m["quant"] != std[sha][0]:
warn(f"--quant {m['quant']} but the model file is {std[sha][1]}: declare --quant {std[sha][0]}")
elif sha:
sha_note = f"sha256 {sha[:12]} (not a standard model)"
warn(f"the model file (sha256 {sha[:12]}) is not one of the standard models in the README;"
" results only count for those files")
else:
sha_note = ""
mb = g("model_bytes")
model_file = join(g("model_file"), mb and f"{int(mb) / 1e9:.2f} GB")
model_file = join(g("model_file"), mb and f"{int(mb) / 1e9:.2f} GB", sha_note)
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")
@@ -413,11 +539,11 @@ 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)
warn("--thinking off, but the greedy replies contain reasoning;"
" check the server's chat template or reasoning flags")
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)
warn(f"--thinking {m['thinking']}, but the greedy replies contain no"
" reasoning; thinking may be off on the server")
eng = g("engine")
engine = join(" ".join(p for p in (eng, g("engine_version")) if p),
@@ -451,10 +577,10 @@ for k, v in notes:
PY
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
[ "$engine" != unknown ] || warn "engine not detected; result is hard to compare"
if [ "$power_src" = declared ] && [ "$power_limit" != stock ] && matches "$pl" '[0-9.]+' &&
[ "$(awk -v a="$pl" -v b="$power_limit" 'BEGIN{print (a-b>1||b-a>1)}')" = 1 ]; then
echo "bench.sh: warning: --power-limit $power_limit W but the GPU reports $pl W" >&2
warn "--power-limit $power_limit W but the GPU reports $pl W"
fi
matches "$count" '[2-9]|[1-9][0-9]+' && gpu="${count}x-$gpu"
slug() { tr 'A-Z' 'a-z' | sed -e 's/[^a-z0-9.]\{1,\}/-/g' -e 's/^-//' -e 's/-$//'; }
@@ -477,11 +603,16 @@ if [ $dry = 1 ]; then
printf ' betterbench'
for a; do case $a in *[[:space:]]*) printf " '%s'" "$a" ;; *) printf ' %s' "$a" ;; esac; done
echo
if [ -s "$warnings" ]; then
echo "$(wc -l < "$warnings") warning(s) - fix or explain them before the real run:"
sed 's/^/ - /' "$warnings"
fi
exit 0
fi
mkdir -p "$results_dir"
mkdir "$run_dir" || die "cannot create $run_dir"
run_dir_made=$run_dir
cp "$here/config.json" "$run_dir/config.json"
[ -n "$cmd_src" ] && cp "$tmp/cmd.red" "$run_dir/server-cmd.txt"
@@ -514,34 +645,66 @@ with open(sys.argv[3], "w", encoding="utf-8") as f:
PY
# Power is sampled where the GPU is: only when BetterBench runs on the server.
sampler=""
# The sampler exits at once when it finds nothing to read.
if [ -z "$env_file" ]; then
sh "$here/gpu-power.sh" 2 > "$run_dir/power.csv" 2>/dev/null &
sampler=$!
trap 'kill "$sampler" 2>/dev/null || true; rm -rf "$tmp"' EXIT INT TERM
fi
echo "running betterbench -> $run_dir" >&2
[ $verbose = 1 ] && sed 's/^/ note: /' "$tmp/notes" >&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.
{ PYTHONUNBUFFERED=1 betterbench "$@" 2>&1 || echo $? > "$tmp/bb_rc"; } |
tee "$run_dir/betterbench.log" |
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
die "betterbench failed (exit $(cat "$tmp/bb_rc")); output in $run_dir.failed/betterbench.log"
fi
# Full output always goes to betterbench.log; the terminal follows it: all of
# it (--verbose), or the progress lines and anything that looks like trouble.
: > "$run_dir/betterbench.log"
PYTHONUNBUFFERED=1 betterbench "$@" > "$run_dir/betterbench.log" 2>&1 &
child=$!
tail -n +1 -f --pid="$child" "$run_dir/betterbench.log" |
if [ $verbose = 1 ]; then cat; else grep --line-buffered -E '^\[|^phases|warn|WARN|rror|Traceback' || true; fi >&2 &
follower=$!
bb_rc=0
wait "$child" || bb_rc=$?
child=""
wait "$follower" 2>/dev/null || true
t_end=$(date +%s.%N)
if [ -n "$sampler" ]; then
kill "$sampler" 2>/dev/null; wait "$sampler" 2>/dev/null || true
kill "$sampler" 2>/dev/null || true
wait "$sampler" 2>/dev/null || true
sampler=""
[ -s "$run_dir/power.csv" ] || rm -f "$run_dir/power.csv"
fi
if [ "$bb_rc" != 0 ]; then
mv "$run_dir" "$run_dir.failed" 2>/dev/null || true
run_dir_made=""
die "betterbench failed (exit $bb_rc); output in $run_dir.failed/betterbench.log"
fi
# 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
# the benchmarked GPU, or when it disagrees with collect-env.sh.
ENV_FILE=$env_file WARNINGS=$warnings python3 - "$run_dir/results.json" "$tmp/collected" <<'PY' || true
import json, os, sys
pci = ((json.load(open(sys.argv[1], encoding="utf-8")).get("env") or {}).get("gpu") or {}).get("pci")
if not pci:
sys.exit()
with open(sys.argv[2], encoding="utf-8") as f:
c = dict(l.rstrip("\n").split("=", 1) for l in f if "=" in l)
bdf, rebar = c.get("gpu_bdf", "unknown"), c.get("rebar", "unknown")
mine = next((g for g in pci if g.get("pci_address") == bdf), None)
if mine is None:
where = "expected with --env-file" if os.environ["ENV_FILE"] else "different GPU or machine?"
print(f"bench.sh: note: BetterBench's own GPU fingerprint (env.gpu.pci) lists "
f"{', '.join(g.get('pci_address', '?') for g in pci)}, not the benchmarked GPU {bdf} "
f"({where}); the gpu/pcie notes describe the server", file=sys.stderr)
elif rebar != "unknown" and mine.get("resizable_bar", "").split()[-1:] != [rebar]:
msg = (f"ReBAR {rebar} per collect-env.sh, but BetterBench reads "
f"{mine.get('resizable_bar')} ({mine.get('largest_bar_mib')} MiB BAR)")
print("bench.sh: warning: " + msg, file=sys.stderr)
open(os.environ["WARNINGS"], "a", encoding="utf-8").write(msg + "\n")
PY
# 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
T0=$t_start T1=$t_end WARNINGS=$warnings python3 - "$run_dir" <<'PY' || warn "post-run figures failed"
import json, os, statistics, sys
d = sys.argv[1]
res = json.load(open(f"{d}/results.json", encoding="utf-8"))
@@ -629,35 +792,21 @@ if "energy" in post:
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)")
warnings = [w for w in open(os.environ["WARNINGS"], encoding="utf-8").read().splitlines() if w]
if warnings:
L.append(f" {len(warnings)} warning(s):")
L += [f" - {w}" for w in warnings]
print("\n" + "\n".join(L), file=sys.stderr)
with open(f"{d}/summary.txt", "w", encoding="utf-8") as f:
f.write("\n".join(x[2:] for x in L) + "\n")
meta["post_run"] = post
meta["warnings"] = warnings
with open(f"{d}/meta.json", "w", encoding="utf-8") as f:
json.dump(meta, f, indent=2)
f.write("\n")
PY
# 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
# the benchmarked GPU, or when it disagrees with collect-env.sh.
ENV_FILE=$env_file python3 - "$run_dir/results.json" "$tmp/collected" <<'PY' || true
import json, os, sys
pci = ((json.load(open(sys.argv[1], encoding="utf-8")).get("env") or {}).get("gpu") or {}).get("pci")
if not pci:
sys.exit()
with open(sys.argv[2], encoding="utf-8") as f:
c = dict(l.rstrip("\n").split("=", 1) for l in f if "=" in l)
bdf, rebar = c.get("gpu_bdf", "unknown"), c.get("rebar", "unknown")
mine = next((g for g in pci if g.get("pci_address") == bdf), None)
if mine is None:
where = "expected with --env-file" if os.environ["ENV_FILE"] else "different GPU or machine?"
print(f"bench.sh: note: BetterBench's own GPU fingerprint (env.gpu.pci) lists "
f"{', '.join(g.get('pci_address', '?') for g in pci)}, not the benchmarked GPU {bdf} "
f"({where}); the gpu/pcie notes describe the server", file=sys.stderr)
elif rebar != "unknown" and mine.get("resizable_bar", "").split()[-1:] != [rebar]:
print(f"bench.sh: warning: ReBAR {rebar} per collect-env.sh, but BetterBench reads "
f"{mine.get('resizable_bar')} ({mine.get('largest_bar_mib')} MiB BAR)", file=sys.stderr)
PY
echo
echo "done: $run_dir"
ls -1 "$run_dir"
+6 -4
View File
@@ -1,7 +1,8 @@
#!/bin/sh
# build.sh - pack dev/ into the one bench.sh at the repo root, which is all
# people download. It unpacks the helpers to a temp dir and runs dev's
# bench.sh from there, with results and bench.local.env next to itself.
# people download. It unpacks the helpers to a temp dir and exec's dev's
# bench.sh from there, with results and bench.local.env next to itself; that
# script removes the temp dir (BENCH_UNPACKED) when it exits.
#
# usage: dev/build.sh (then commit the root bench.sh with dev/)
# dev/build.sh --check (exit 1 if the root bench.sh is out of date)
@@ -9,7 +10,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 config.json standard.env models.txt"
eof=__BENCH_STANDARD_EOF__
. "$dev/standard.env"
@@ -36,7 +37,8 @@ EOF
cat "$dev/$f"
printf '%s\n' "$eof"
done
printf 'sh "$d/bench.sh" "$@"\n'
printf 'trap - EXIT INT TERM\n'
printf 'BENCH_UNPACKED=$d exec sh "$d/bench.sh" "$@"\n'
} > "$tmp"
if [ "${1:-}" = --check ]; then
+109 -30
View File
@@ -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; hashes are cached by size and mtime)
set -u
LC_ALL=C; export LC_ALL
@@ -27,13 +28,15 @@ 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
tmp=$(mktemp -d) || exit 1
trap 'rm -rf "$tmp"' EXIT INT TERM
trap 'rm -rf "$tmp"' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
# Header via a file so the key never shows up in `ps`.
if [ -n "$api_key" ]; then printf 'Authorization: Bearer %s\n' "$api_key" > "$tmp/hdr"
else printf 'Accept: application/json\n' > "$tmp/hdr"; fi
@@ -106,6 +109,44 @@ pcie_of() {
return 0
}
# hostpath PATH - the host path behind a path inside the server's container,
# from the -v / --mount flags of the launch command in $tmp/cmd; prints
# nothing when no bind mount covers it.
hostpath() {
[ -s "$tmp/cmd" ] && have python3 || return 0
python3 - "$tmp/cmd" "$1" <<'PY' 2>/dev/null
import os, re, sys
cmd, path = open(sys.argv[1], encoding="utf-8", errors="replace").read(), sys.argv[2]
maps = re.findall(r'(?:^|\s)(?:-v|--volume)[ =](\S+?):(/[^\s:]*)', cmd)
for m in re.finditer(r'--mount[ =](\S+)', cmd):
o = dict(p.split("=", 1) for p in m.group(1).split(",") if "=" in p)
src, dst = o.get("source") or o.get("src"), o.get("target") or o.get("destination") or o.get("dst")
if src and dst:
maps.append((src, dst))
best = None
for src, dst in maps:
dst = dst.rstrip("/") or "/"
src = os.path.expandvars(os.path.expanduser(src.strip("'\"")))
if src.startswith("/") and (path == dst or path.startswith(dst.rstrip("/") + "/")):
if best is None or len(dst) > len(best[1]): # the innermost mount wins
best = (src, dst)
if best:
print(best[0].rstrip("/") + path[len(best[1].rstrip("/")):])
PY
}
# hf_snapshot HF_HOME REPO_ID - the snapshot dir of a Hugging Face cache entry
hf_snapshot() {
r="$1/hub/models--$(printf '%s' "$2" | sed 's|/|--|g')"
[ -d "$r/snapshots" ] || return 1
if [ -f "$r/refs/main" ] && [ -d "$r/snapshots/$(cat "$r/refs/main")" ]; then
printf '%s\n' "$r/snapshots/$(cat "$r/refs/main")"
else
set -- "$r"/snapshots/*/
[ $# = 1 ] && [ -d "$1" ] && printf '%s\n' "${1%/}"
fi
}
# ---------------------------------------------------------------- GPU
gpu_vendor=none gpu_model="" gpu_count=0 gpu_vram_gb="" gpu_driver="" gpu_power_limit_w="" gpu_bdf=""
if have nvidia-smi && q=$(nvidia-smi --query-gpu=name,memory.total,driver_version,power.limit,pci.bus_id \
@@ -188,6 +229,7 @@ os=$( (. /etc/os-release 2>/dev/null && printf '%s' "${PRETTY_NAME:-}") )
kernel=$(uname -r 2>/dev/null)
# ---------------------------------------------------------------- engine
[ -n "$cmd_file" ] && cp "$cmd_file" "$tmp/cmd" 2>/dev/null
proxy=none engine=unknown engine_version="" model_file="" ctx="" engine_slots=""
if [ -n "$endpoint" ]; then
base=${endpoint%/}; base=${base%/v1}
@@ -227,43 +269,77 @@ if [ -n "$endpoint" ]; then
fi
fi
# Behind llama-swap the launch command is known: keep it, and map a
# container path (-v HOST:/model) back to the host path.
# Behind llama-swap the launch command is known: keep it (it wins over
# --server-cmd-file for finding the container and the mounts).
if [ "$proxy" = llama-swap ] && [ -n "$model" ] && fetch "$base/running" "$tmp/running"; then
export JARG="$model"
jget "$tmp/running" 'next((r.get("cmd") for r in j["running"] if r.get("model") == arg), "")' > "$tmp/cmd"
if [ -s "$tmp/cmd" ]; then
jget "$tmp/running" 'next((r.get("cmd") for r in j["running"] if r.get("model") == arg), "")' > "$tmp/cmd.swap"
if [ -s "$tmp/cmd.swap" ]; then
mv "$tmp/cmd.swap" "$tmp/cmd"
[ -n "$cmd_out" ] && cp "$tmp/cmd" "$cmd_out"
if [ -n "$model_file" ] && have python3; then
host=$(python3 - "$tmp/cmd" "$model_file" <<'PY' 2>/dev/null
import re, sys
cmd, path = open(sys.argv[1]).read(), sys.argv[2]
for src, dst in re.findall(r'(?:-v|--volume)[ =](\S+?):(/[^\s:]*)', cmd):
if path == dst or path.startswith(dst.rstrip("/") + "/"):
print(src + path[len(dst):]); break
PY
)
[ -n "$host" ] && model_file=$host
fi
fi
fi
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.
model_bytes=""
if [ -f "$model_file" ]; then
case $model_file in
*-00001-of-[0-9]*.gguf) set -- "${model_file%-00001-of-*}"-[0-9]*-of-[0-9]*.gguf ;;
*) set -- "$model_file" ;;
# model_path: where the weights are on this machine. The engine reports its
# own view: a path inside its container (mapped back through -v / --mount),
# or, for vLLM, often a Hugging Face repo id (looked up in the HF cache, the
# container's and this machine's).
model_path=""
if [ -n "$model_file" ]; then
model_path=$(hostpath "$model_file")
[ -n "$model_path" ] && [ -e "$model_path" ] || model_path=$model_file
case $model_path in
/*|.*) ;;
*/*) if [ ! -e "$model_path" ]; then
cenv=$( [ -s "$tmp/cmd" ] && tr '\n' ' ' < "$tmp/cmd" | sed -n 's/.*[ =]HF_HOME=\([^ ]*\).*/\1/p')
for root in $(hostpath "${cenv:-/root/.cache/huggingface}") $cenv \
"${HF_HOME:-$HOME/.cache/huggingface}"; do
snap=$(hf_snapshot "$root" "$model_file") && { model_path=$snap; break; }
done
fi ;;
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 |
awk '{s += $1} END {if (s) printf "%d", s}')
[ -e "$model_path" ] || model_path=""
fi
[ -s "$tmp/cmd" ] || { [ -n "$cmd_file" ] && cp "$cmd_file" "$tmp/cmd" 2>/dev/null; }
# Weight bytes as stored: a single file, the parts of a split GGUF
# (-00001-of-0000N.gguf), or the *.safetensors of a model directory. stat -L:
# the HF cache keeps files as symlinks into blobs/.
model_bytes="" model_sha256=""
set --
if [ -f "$model_path" ]; then
case $model_path in
*-00001-of-[0-9]*.gguf) set -- "${model_path%-00001-of-*}"-[0-9]*-of-[0-9]*.gguf ;;
*) set -- "$model_path" ;;
esac
elif [ -d "$model_path" ]; then
set -- "$model_path"/*.safetensors
[ -e "$1" ] || set --
fi
[ $# -gt 0 ] && model_bytes=$(stat -L -c %s "$@" 2>/dev/null | awk '{s += $1} END {if (s) printf "%d", s}')
# The hash the README's model table lists: sha256 of the GGUF, or of a repo's
# per-file *.safetensors hashes in name order. Split GGUFs aren't hashed.
# Cached by path, size and mtime, since hashing 15 GB takes a while.
case $model_path in *-00001-of-[0-9]*.gguf) split=1 ;; *) split=0 ;; esac
if [ "${HASH_MODEL:-1}" != 0 ] && [ -n "$model_bytes" ] && [ $split = 0 ] && have sha256sum; then
sig=$(stat -L -c '%n %s %Y' "$@" 2>/dev/null | cksum | cut -d' ' -f1)
cache="${XDG_CACHE_HOME:-$HOME/.cache}/bench-standard/model-sha256"
model_sha256=$(awk -v s="$sig" -v p="$model_path" -F '\t' '$1 == s && $2 == p {print $3; exit}' "$cache" 2>/dev/null)
if [ -z "$model_sha256" ]; then
echo "collect-env: hashing $model_path ($((model_bytes / 1000000000)) GB; once, it's cached; HASH_MODEL=0 skips) ..." >&2
if [ -f "$model_path" ]; then
model_sha256=$(sha256sum "$model_path" | cut -c1-64)
else
model_sha256=$(cd "$model_path" && sha256sum -- *.safetensors | sort -k2 | sha256sum | cut -c1-64)
fi
case $model_sha256 in
[0-9a-f]*) mkdir -p "${cache%/*}" 2>/dev/null &&
printf '%s\t%s\t%s\n' "$sig" "$model_path" "$model_sha256" >> "$cache" 2>/dev/null ;;
*) model_sha256="" ;;
esac
fi
fi
# A docker server: the exact image, since tags like llama.cpp's server-intel
# move daily (the llama.cpp build itself is in engine_version).
container="" engine_image=""
@@ -288,6 +364,7 @@ if [ "${MEASURE_BW:-1}" != 0 ]; then
else
r=""
fi
case $r in [0-9]*' '[0-9]*) ;; *) r="" ;; esac # "GBPS MIB", or nothing usable
if [ -n "$r" ]; then
gpu_mem_bw_gbs=${r% *} gpu_mem_bw_tool="torch copy, random, ${r#* } MiB"
elif have clpeak && [ -n "$gpu_model" ]; then
@@ -328,6 +405,8 @@ kv engine_version "$engine_version"
kv engine_slots "$engine_slots"
kv engine_image "$engine_image"
kv model_file "$model_file"
kv model_path "$model_path"
kv model_bytes "$model_bytes"
kv model_sha256 "$model_sha256"
kv ctx "$ctx"
exit 0
+18 -2
View File
@@ -6,9 +6,11 @@
# watts is the sum over all GPUs; joules is the sum of the cards' cumulative
# energy counters (empty where the card has none, then integrate the watts);
# mhz is the mean graphics clock over the GPUs.
# Prints nothing at all when no supported tool is found (nvidia-smi, xpu-smi).
# Prints nothing at all when no supported tool is found (nvidia-smi, xpu-smi,
# or amdgpu's hwmon files in sysfs, which have no energy counter).
#
# usage: gpu-power.sh [INTERVAL_S] (default 2)
# GPU_POWER_SYSFS=DIR: the sysfs root for the amdgpu lookup (tests)
set -u
LC_ALL=C; export LC_ALL
@@ -32,7 +34,21 @@ elif command -v xpu-smi >/dev/null 2>&1; then
END {if (n) printf "%.2f,%s,%.0f\n", w, nj ? "" : sprintf("%.3f", j), c / n}'
}
else
exit 0
# amdgpu: power1_average (older kernels) or power1_input, in microwatts;
# freq1_input is the graphics clock in Hz.
amd=""
for h in "${GPU_POWER_SYSFS:-/sys}"/bus/pci/drivers/amdgpu/*:*/hwmon/hwmon*; do
{ [ -r "$h/power1_average" ] || [ -r "$h/power1_input" ]; } && amd="$amd $h"
done
[ -n "$amd" ] || exit 0
sample() {
for h in $amd; do
p=$(cat "$h/power1_average" 2>/dev/null || cat "$h/power1_input" 2>/dev/null)
f=$(cat "$h/freq1_input" 2>/dev/null)
echo "${p:-0} ${f:-0}"
done | awk '$1 > 0 {w += $1 / 1e6; c += $2 / 1e6; n++}
END {if (n) printf "%.2f,,%.0f\n", w, c / n}'
}
fi
while :; do
+7
View File
@@ -0,0 +1,7 @@
# The standard models: results only count for these files. Same as the
# README's model table; change both together and bump STANDARD_VERSION.
# sha256 (a GGUF file, or a repo's *.safetensors as in the README) --quant name
03b74727a860a56338e042c4420bb3f04b2fec5734175f4cb9fa853daf52b7e8 Q4_K_M Qwen3.5-9B-Q4_K_M.gguf
322e194ff79741c7baa497c240f677f54b201b0efab44ca8e50f122b39123482 UD-Q4_K_M Qwen3.8-27B-UD-Q4_K_M.gguf
cca16f9855b9f92eee5876ddc8656ed6397316ffc65b9f17ca1939a9549e4c26 w4a16 RedHatAI/Qwen3.5-9B-quantized.w4a16
bffa6b23fa11be557fe9de4b122a8bb99f537ad7a1a4effa702f7d0c677778f7 w4a16 RedHatAI/Qwen3.8-27B-INT4
+2 -2
View File
@@ -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
# config.json, models.txt, the minimum BetterBench or the recorded fields change.
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
+149
View File
@@ -0,0 +1,149 @@
#!/bin/sh
# shellcheck disable=SC2034 # variables are read inside the eval'd check strings
# test.sh - end-to-end tests of the one-file bench.sh, without a GPU: a fake
# OpenAI-compatible server (dev/test/fake_server.py) and a fake betterbench
# (dev/test/betterbench) stand in for the real ones.
#
# usage: sh dev/test.sh (needs python3, curl; rebuilds nothing, checks the build)
set -u
dev=$(cd "$(dirname "$0")" && pwd)
root=$(cd "$dev/.." && pwd)
t=$(mktemp -d)
pids=""
trap 'for p in $pids; do kill "$p" 2>/dev/null; done; rm -rf "$t"' EXIT
pass=0 fail=0
ok() { pass=$((pass + 1)); printf 'ok %s\n' "$1"; }
bad() { fail=$((fail + 1)); printf 'FAIL %s\n' "$1"; [ -f "$t/out" ] && sed 's/^/ | /' "$t/out" | tail -n 25; }
check() { if (eval "$2"); then ok "$1"; else bad "$1"; fi; } # check NAME SHELL-TEST
PATH="$dev/test:$PATH"; export PATH
MEASURE_BW=0 XDG_CACHE_HOME="$t/cache" BENCH_HOME="$t/home"; export MEASURE_BW XDG_CACHE_HOME BENCH_HOME
unset BETTERBENCH_API_KEY BENCH_SUBMITTER BENCH_QUANT BENCH_KV BENCH_SPEC BENCH_THINKING 2>/dev/null || true
mkdir -p "$t/home" "$t/models" "$t/tmpdir"
printf 'fake gguf weights\n' > "$t/models/test.gguf"
# serve PORT ENGINE REASONING MODEL_PATH
serve() {
python3 "$dev/test/fake_server.py" "$@" & pids="$pids $!"
i=0; until curl -s "http://127.0.0.1:$1/v1/models" >/dev/null || [ $i -gt 50 ]; do sleep 0.1; i=$((i + 1)); done
}
serve 18431 llama.cpp 0 "$t/models/test.gguf"
serve 18432 vllm 0 "Org/Repo"
serve 18433 llama.cpp 1 "/models/test.gguf"
LL=http://127.0.0.1:18431/v1 VL=http://127.0.0.1:18432/v1 LR=http://127.0.0.1:18433/v1
# bench ENDPOINT CMDFILE ARGS... - the one-file bench.sh with the declared values
bench() {
e=$1 c=$2; shift 2
TMPDIR="$t/tmpdir" sh "$root/bench.sh" --endpoint "$e" --model test-model --tp 1 --pp 1 \
--quant Q4_K_M --kv f16 --spec none --thinking default --submitter tester --power-limit 200 \
--results-dir "$t/res" ${c:+--server-cmd-file "$c"} "$@" > "$t/out" 2>&1
}
note() { sed -n "s/^$1=//p" "$t/notes"; }
# dry-run notes: the --note values the dry run would pass
dry_notes() { bench "$@" --dry-run; python3 - "$t/out" > "$t/notes" <<'PY'
import shlex, sys
line = next(l for l in open(sys.argv[1]) if l.startswith(" betterbench"))
w = shlex.split(line)
print("\n".join(w[i + 1] for i, x in enumerate(w) if x == "--note"))
PY
}
# ------------------------------------------------------------------ build
check "bench.sh is built from dev/" 'sh "$dev/build.sh" --check >/dev/null 2>&1'
check "shell syntax" 'for f in "$root/bench.sh" "$dev"/*.sh; do sh -n "$f" || exit 1; done'
# ------------------------------------------------------------------ argument checks
bench "$LL" "" --spec bogus; check "rejects a bad --spec" 'grep -q "spec must be" "$t/out"'
TMPDIR="$t/tmpdir" sh "$root/bench.sh" --endpoint "$LL" > "$t/out" 2>&1
check "lists missing mandatory values" 'grep -q "missing mandatory value(s): --model --tp" "$t/out"'
bench "$LL" "" --temperature 0; check "refuses BetterBench flags" 'grep -q "not allowed" "$t/out"'
# ------------------------------------------------------------------ a quick run
printf 'llama-server -m %s -ngl 99 -fa on -b 4096 -t -1 -e HF_TOKEN=hf_secret\n' "$t/models/test.gguf" > "$t/cmd1"
bench "$LL" "$t/cmd1"; rc=$?
run=$(sed -n 's/^done: //p' "$t/out")
check "quick run finishes (no GPU, the sampler exits at once)" '[ $rc = 0 ] && [ -d "$run" ]'
check "run folder has every file" 'for f in results.json results.html meta.json config.json server-cmd.txt summary.txt betterbench.log; do [ -s "$run/$f" ] || exit 1; done'
check "no empty power.csv without a GPU" '[ ! -e "$run/power.csv" ]'
check "summary printed" 'grep -q "decode (batch 1) 52.0 t/s" "$t/out"'
check "meta.json has post-run figures and warnings" 'python3 -c "import json,sys; m=json.load(open(sys.argv[1])); assert \"post_run\" in m and \"warnings\" in m" "$run/meta.json"'
check "secrets redacted" '! grep -q hf_secret "$run/server-cmd.txt" && grep -q "HF_TOKEN=<redacted>" "$run/server-cmd.txt"'
check "results in --results-dir, helpers cleaned up" '[ -z "$(ls -A "$t/tmpdir")" ] && [ ! -e "$t/home/results" ]'
check "model hashed, flagged as non-standard" 'grep -q "not one of the standard models" "$t/out"'
check "model hash is cached" 'bench "$LL" "$t/cmd1" --dry-run; ! grep -q "collect-env: hashing" "$t/out"'
# ------------------------------------------------------------------ launch flags and cross-checks
dry_notes "$LL" "$t/cmd1"
check "launch note parsed (negative values stay values)" '[ "$(note launch)" = "b 4096 · ub default · fa on · ctk default · ctv default · ngl 99 · t -1" ]'
check "model_file note has size and hash" 'note model_file | grep -q "0.00 GB · sha256 [0-9a-f]\{12\} (not a standard model)"'
printf 'llama-server -m /m.gguf -ctk q8_0\n' > "$t/cmd2"
bench "$LL" "$t/cmd2" --kv q8_0 --dry-run
check "--kv: K set, V default -> q8_0/f16" 'grep -q "declare --kv q8_0/f16" "$t/out"'
bench "$LL" "$t/cmd2" --kv q8_0/f16 --dry-run
check "--kv q8_0/f16 accepted" '! grep -q "warning: --kv" "$t/out"'
printf 'llama-server -m /m.gguf -md /d.gguf --draft-max 8 --reasoning-budget 0\n' > "$t/cmd3"
bench "$LL" "$t/cmd3" --dry-run
check "--spec checked against a draft model" 'grep -q "declare --spec draft:8" "$t/out"'
check "--thinking checked against --reasoning-budget 0" 'grep -q "declare --thinking off" "$t/out"'
check "dry run recaps warnings" 'grep -q "warning(s) - fix or explain" "$t/out"'
cat > "$t/cmd4" <<'EOF'
VLLM_USE_V1=1 vllm serve Org/Repo -tp 2 --max-num-batched-tokens=8192 \
--speculative-config '{"method": "mtp", "num_speculative_tokens": 5}' --api-key sk-secret
EOF
bench "$VL" "$t/cmd4" --dry-run
check "vllm: --spec from --speculative-config" 'grep -q "declare --spec mtp:5" "$t/out"'
check "vllm: --tp from -tp" 'grep -q "declare --tp 2" "$t/out"'
dry_notes "$VL" "$t/cmd4" --spec mtp:5 --tp 2
check "vllm: matching values give no warning" '! grep -q "warning: --" "$t/out"'
check "vllm: --max-num-batched-tokens=N not redacted" 'note launch | grep -q "max-num-batched-tokens 8192"'
check "vllm: env flags recorded" '[ "$(note env_flags)" = "VLLM_USE_V1=1" ]'
bench "$LR" "" --thinking off --dry-run
check "--thinking off vs reasoning in the replies" 'grep -q "thinking off, but the greedy replies contain reasoning" "$t/out"'
# ------------------------------------------------------------------ finding the weights
# docker without llama-swap: the container path maps back through -v
printf 'docker run --rm -v %s:/models img -m /models/test.gguf\n' "$t/models" > "$t/cmd5"
dry_notes "$LR" "$t/cmd5"
check "docker -v mapping without llama-swap" 'note model_file | grep -q "^/models/test.gguf · 0.00 GB · sha256"'
# vLLM repo id -> HF cache snapshot, safetensors as symlinks into blobs/
hf="$t/hf/hub/models--Org--Repo"; mkdir -p "$hf/blobs" "$hf/refs" "$hf/snapshots/abc123"
printf 'A%.0s' $(seq 1000) > "$hf/blobs/b1"; printf 'B%.0s' $(seq 2000) > "$hf/blobs/b2"
ln -s ../../blobs/b1 "$hf/snapshots/abc123/model-00001-of-00002.safetensors"
ln -s ../../blobs/b2 "$hf/snapshots/abc123/model-00002-of-00002.safetensors"
printf 'abc123' > "$hf/refs/main"
HF_HOME="$t/hf" sh "$root/bench.sh" collect-env --endpoint "$VL" --model test-model > "$t/env" 2>/dev/null
want=$(cd "$hf/snapshots/abc123" && sha256sum *.safetensors | LC_ALL=C sort -k2 | sha256sum | cut -c1-64)
check "HF repo id resolved, symlink sizes followed" 'grep -qx "model_bytes=3000" "$t/env"'
check "repo hash equals the README recipe" 'grep -qx "model_sha256=$want" "$t/env"'
# ------------------------------------------------------------------ failures and signals
FAKE_BB_FAIL=3 bench "$LL" "$t/cmd1"; rc=$?
check "betterbench failure -> .failed folder, exit 1" '[ $rc = 1 ] && grep -q "betterbench failed (exit 3)" "$t/out" && ls -d "$t"/res/*.failed >/dev/null 2>&1'
FAKE_BB_SLEEP=60 TMPDIR="$t/tmpdir" sh "$root/bench.sh" --endpoint "$LL" --model test-model --tp 1 --pp 1 \
--quant Q4_K_M --kv f16 --spec none --thinking default --submitter tester --power-limit 200 \
--results-dir "$t/res2" > "$t/out" 2>&1 &
p=$!
i=0; until grep -q "running betterbench" "$t/out" || [ $i -gt 100 ]; do sleep 0.1; i=$((i + 1)); done
sleep 0.5; s0=$(date +%s); kill -TERM "$p"; wait "$p"; rc=$?; s1=$(date +%s)
check "TERM stops a run at once, exit 143" '[ $rc = 143 ] && [ $((s1 - s0)) -lt 5 ]'
check "interrupted run folder marked, no done:" 'ls -d "$t"/res2/*.interrupted >/dev/null 2>&1 && ! grep -q "^done:" "$t/out"'
check "no betterbench left running" '! pgrep -f "FAKE_BB_SLEEP|dev/test/betterbench run" >/dev/null 2>&1'
check "helpers cleaned up after a signal" '[ -z "$(ls -A "$t/tmpdir")" ]'
# ------------------------------------------------------------------ power sampling
f="$t/sys/bus/pci/drivers/amdgpu/0000:03:00.0/hwmon/hwmon1"; mkdir -p "$f"
echo 150000000 > "$f/power1_input"; echo 2100000000 > "$f/freq1_input"
GPU_POWER_SYSFS="$t/sys" timeout 2 sh "$dev/gpu-power.sh" 1 > "$t/power" 2>/dev/null
check "amdgpu power via sysfs" 'grep -q "^[0-9.]*,150.00,,2100$" "$t/power"'
echo
echo "$pass passed, $fail failed"
[ $fail = 0 ]
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env python3
"""A fake betterbench for dev/test.sh: writes a plausible results.json.
FAKE_BB_SLEEP=S sleeps S seconds first; FAKE_BB_FAIL=N exits N."""
import json, os, sys, time
a = sys.argv[1:]
if a[:1] == ["--version"]:
print("betterbench " + os.environ.get("FAKE_BB_VERSION", "0.6.1")); sys.exit()
print("[1/3] single stream"); sys.stdout.flush()
time.sleep(float(os.environ.get("FAKE_BB_SLEEP", "0")))
if os.environ.get("FAKE_BB_FAIL"):
print("Traceback: boom"); sys.exit(int(os.environ["FAKE_BB_FAIL"]))
out = a[a.index("--out") + 1]
rec = [{"ok": True, "completion_tokens": 256, "decode_tps": 50.0 + i, "ttft_ms": 120 + i} for i in range(5)]
res = {"single_stream": {"code": rec},
"concurrency": [{"level": 1, "aggregate_tps": 50, "wall_s": 10},
{"level": 4, "aggregate_tps": 160, "wall_s": 10}],
"prefill": [{"target_depth": 4000, "pp_tps": [1500, 1600]}, {"target_depth": 64000, "skipped": True}],
"env": {}, "argv": a}
json.dump(res, open(out, "w"))
open(out.replace(".json", ".html"), "w").write("<html></html>")
print("[3/3] done")
+53
View File
@@ -0,0 +1,53 @@
"""fake_server.py - a stand-in OpenAI-compatible server for dev/test.sh.
usage: fake_server.py PORT ENGINE [REASONING] [MODEL_PATH]
ENGINE llama.cpp | vllm
REASONING 1: replies carry reasoning_content
MODEL_PATH what /props or /v1/models reports as the model file
"""
import json
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
port, engine = int(sys.argv[1]), sys.argv[2]
reasoning = len(sys.argv) > 3 and sys.argv[3] == "1"
model_path = sys.argv[4] if len(sys.argv) > 4 else "/models/test.gguf"
class H(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def send(self, obj, code=200):
b = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def do_GET(self):
p = self.path.rstrip("/")
if engine == "llama.cpp" and p == "/props":
self.send({"build_info": "b9999-abcdef0", "model_path": model_path,
"total_slots": 4, "default_generation_settings": {"n_ctx": 32768}})
elif engine == "vllm" and p == "/version":
self.send({"version": "0.99.0"})
elif p == "/v1/models":
self.send({"data": [{"id": "test-model", "owned_by": engine.replace(".cpp", ""),
"root": model_path, "max_model_len": 32768}]})
else:
self.send({"error": "not found"}, 404)
def do_POST(self):
n = int(self.headers.get("Content-Length", 0))
req = json.loads(self.rfile.read(n) or b"{}")
if req.get("model") != "test-model":
return self.send({"error": "unknown model"}, 404)
msg = {"role": "assistant", "content": "2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37."}
if reasoning:
msg["reasoning_content"] = "Let me think about primes."
self.send({"choices": [{"message": msg, "finish_reason": "stop"}]})
ThreadingHTTPServer(("127.0.0.1", port), H).serve_forever()