One-file bench.sh, sources in dev/, BetterBench 0.6.1 or newer

- bench.sh at the root is generated by dev/build.sh and holds everything;
  people download just that file. It unpacks its helpers to a temp dir;
  results and bench.local.env stay next to it
- collect-env and the power sampler are subcommands (bench.sh collect-env,
  bench.sh power); --help is the manual, --version prints the versions
- BetterBench: minimum 0.6.1 instead of exactly 0.6.1; the version is
  recorded in the run note. Standard bumped to 0.4.0
- each run folder gets a copy of config.json
- AGENTS.md carries the install, the models with hashes and the agent
  procedure; README is a pointer; DETAILS.md moved to dev/

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-10-29 12:58:02 +01:00
1 parent 9400c074bd
commit 1f4ea0b225
13 files changed
+1330 -209

No files matched your search

+64 -39
View File
@@ -1,8 +1,19 @@
# AGENTS.md
# bench-standard
Instructions for a coding agent that helps someone benchmark their LLM server with
this repo. The human-facing docs are [`README.md`](README.md) and
[`DETAILS.md`](DETAILS.md).
Benchmark your LLM server the way everyone in the group does. You need one file:
```sh
pip install git+https://github.com/GGZ14/BetterBench # BetterBench 0.6.1 or newer
curl -O https://git.linxweiler.xyz/miga/benchmarks/raw/branch/main/bench.sh && chmod +x bench.sh
./bench.sh --help
```
**Humans:** `./bench.sh --help` has everything. Serve one of the [models](#models) below,
run it, and send in the `results/<run>/` folder of a `--full` run.
**Agents:** the rest of this file is for you.
---
Your job: get one correct, comparable result folder out of `bench.sh`, and tell your
human what it says. A wrong declared value makes the result worthless, and a skipped
@@ -12,32 +23,50 @@ one makes the run fail. Correct is more important than fast.
- **Run benchmarks only through `./bench.sh`.** Never call `betterbench run` directly,
and never add BetterBench flags. `bench.sh` refuses them.
- **Don't change the standard to make a run pass.** Leave `config.json`,
`standard.env`, `bench.sh`, `collect-env.sh`, `gpu-power.sh` and `mem-bw.py` alone. If one
of them seems wrong, tell your human instead.
- **Don't edit `bench.sh`** to make a run pass. If it seems wrong, tell your human.
- **Never edit anything in a results folder.**
- **Never guess a declared value silently.** Derive it from the launch command (below),
- **Never guess a declared value silently.** Derive it from the launch command (step 4),
show your human what you derived, and ask when the command doesn't say.
`--submitter` always comes from the human.
- **Ask before `--full`.** It takes much longer than the quick run, and the GPU is busy
the whole time.
- **Don't restart, reconfigure or stop the inference server** without asking. Don't
start other GPU work while a benchmark runs.
- **API keys** go in `$BETTERBENCH_API_KEY`, never into files or committed commands.
- **Don't commit results.** `results/` and `bench.local.env` are git-ignored on purpose.
- **API keys** go in `$BETTERBENCH_API_KEY`, never into files or commands that get saved.
## Models
Results only count for these files. Check the hash before benchmarking. On a mismatch,
tell your human.
| model | engine | Hugging Face repo | file | `--quant` | SHA256 |
|---|---|---|---|---|---|
| Qwen3.5-9B | llama.cpp | `unsloth/Qwen3.5-9B-GGUF` | `Qwen3.5-9B-Q4_K_M.gguf` | `Q4_K_M` | `03b74727a860a56338e042c4420bb3f04b2fec5734175f4cb9fa853daf52b7e8` |
| Qwen3.8-27B | llama.cpp | `unsloth/Qwen3.8-27B-GGUF` | `Qwen3.8-27B-UD-Q4_K_M.gguf` | `UD-Q4_K_M` | `322e194ff79741c7baa497c240f677f54b201b0efab44ca8e50f122b39123482` |
| Qwen3.5-9B | vLLM & co. | `RedHatAI/Qwen3.5-9B-quantized.w4a16` | the repo | `w4a16` | `cca16f9855b9f92eee5876ddc8656ed6397316ffc65b9f17ca1939a9549e4c26` |
| Qwen3.8-27B | vLLM & co. | `RedHatAI/Qwen3.8-27B-INT4` | the repo | `w4a16` | `bffa6b23fa11be557fe9de4b122a8bb99f537ad7a1a4effa702f7d0c677778f7` |
```sh
sha256sum Qwen3.5-9B-Q4_K_M.gguf # a GGUF
cd MODEL_DIR && sha256sum *.safetensors | LC_ALL=C sort -k2 | sha256sum # a repo
```
`LC_ALL=C` matters: other locales sort the files differently and give another hash.
The RedHatAI repos include an MTP head for `--spec mtp:N`. The 27B GGUF repo has no plain
Q4_K_M, only Unsloth's `UD-Q4_K_M`. Hashes are as of 2026-10-29.
## Procedure
### 1. Check the tools
```sh
betterbench --version # must print 0.6.1
python3 --version # 3.10+
./bench.sh --version # bench-standard version and the BetterBench it needs
betterbench --version # 0.6.1 or newer
python3 --version # 3.10+
```
If BetterBench is missing or a different version, install it as the README shows
(`git checkout v0.6.1 && pip install -e .`). If an existing install has a different
version, ask before touching it.
If BetterBench is missing, install it (see the top). If an older one is installed, ask
before upgrading it.
### 2. Find the endpoint and the model id
@@ -52,33 +81,26 @@ curl -s http://localhost:8080/running # llama-swap only: loaded models + l
- **Behind llama-swap** (`/running` answers): nothing to do, `bench.sh` reads it.
- **Otherwise:** write the exact command the server was started with into
`server-cmd.txt`, including any `VAR=value` env prefixes and docker `-e` flags. Pass it
with `--server-cmd-file server-cmd.txt`. Get the command from your human, a
launch script, `docker inspect`, or `ps -o args= -p PID`.
`server-cmd.txt`, including `VAR=value` env prefixes and docker `-e` flags. Pass it
with `--server-cmd-file server-cmd.txt`. Get the command from your human, a launch
script, `docker inspect`, or `ps -o args= -p PID`.
Without it, the `launch` and `env_flags` notes read `unknown`, and those settings
swing results by 10-50%.
### 4. Check the model, derive the declared values
### 4. Derive the declared values
Results only count for the models in [`models.md`](models.md). Check the served file's
SHA256 against that table, with the commands at its end. On a mismatch, tell your
human before benchmarking. For those models, `--quant` is listed in `models.md`.
For the rest, use the launch command and confirm with your human:
`--quant` comes from the model table. For the rest, use the launch command and confirm
with your human:
| flag | llama.cpp | vLLM |
|---|---|---|
| `--quant` | quant in the GGUF filename (`Q4_K_M`, `Q8_0`, ...) | `--quantization`, or the checkpoint's format (`gptq-int4`, `awq`, `fp8`); `bf16`/`fp16` when unquantized |
| `--kv` | `-ctk`/`-ctv`; `f16` when unset; `q8_0/q4_0` when K and V differ | `--kv-cache-dtype`; with `auto` (or unset), the model dtype (`bf16`) |
| `--tp` / `--pp` | `1` / `1` on one GPU; multi-GPU: ask | `--tensor-parallel-size` / `--pipeline-parallel-size`; default `1` |
| `--spec` | `-md`/`--model-draft` with `--draft-max N` → `draft:N`; otherwise `none` | `--speculative-config` method and `num_speculative_tokens` → e.g. `mtp:5`, `eagle3:4`, `ngram:4`; otherwise `none` |
| `--thinking` | `--reasoning-budget 0` or `enable_thinking: false` in the template kwargs → `off`; unclear → ask | `enable_thinking`/effort in the chat template or default kwargs; nothing set → `default`; unclear → ask |
| `--submitter` | ask | ask |
`--spec` methods are `mtp`, `eagle`, `eagle3`, `ngram` and `draft`. `--thinking` values are
`off`, `on`, `low`, `medium`, `high` and `default`.
### 5. Dry run
```sh
@@ -86,8 +108,8 @@ For the rest, use the launch command and confirm with your human:
--spec none --thinking default --submitter NAME [--server-cmd-file server-cmd.txt] --dry-run
```
This sends the warm-up and the greedy check, detects everything, prints the notes it
would record, and stops. Read the notes:
This sends the warm-up and the greedy check, detects everything, prints what it would
run, and stops. Check the `--note` values in that output:
- `unknown` values should have a reason (VM PCIe, no cmd file, ...).
- Any `bench.sh: warning:` line needs fixing or explaining before the real run.
@@ -95,10 +117,8 @@ would record, and stops. Read the notes:
Run the same command without `--dry-run`. This is a quick check of a few minutes,
ending in a summary. If it looks sane, ask your human, then run again with `--full`.
That is the result that counts.
For long runs, use a terminal multiplexer or a background job, so a dropped
session doesn't kill the benchmark.
That is the result that counts. For long runs, use a terminal multiplexer or a
background job, so a dropped session doesn't kill the benchmark.
### 7. Report back
@@ -107,13 +127,13 @@ Tell your human:
- the summary block: decode t/s, TTFT, concurrency, prefill, bandwidth %, power, energy
- 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
anything private first (tokens, keys and passwords are already redacted)
## When something goes wrong
| message | what to do |
|---|---|
| `BetterBench 0.6.1 required, found ...` | install 0.6.1 (step 1) |
| `BetterBench 0.6.1 or newer required` | install or upgrade BetterBench (step 1) |
| `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` |
@@ -122,7 +142,12 @@ Tell your human:
| `mem_bw` has no measured figure | no torch in the server container. Set `BW_PYTHON` to a python with GPU torch, or install `clpeak`, or leave it |
| `launch=unknown (pass --server-cmd-file)` | step 3 |
| `betterbench failed (exit N)` | read `betterbench.log` in the `.failed` folder. Usually the server crashed or ran out of memory |
| `ReBAR ... but BetterBench reads ...` | BetterBench runs on another machine than the GPU. Use `--env-file` (see README) |
| `ReBAR ... but BetterBench reads ...` | BetterBench runs on another machine than the GPU. Use `--env-file` (below) |
BetterBench on a different machine than the GPU: run `collect-env.sh` on the GPU
machine and pass its output with `--env-file` (README, "More").
**BetterBench on another machine than the GPU:** run
`./bench.sh collect-env --endpoint URL --model ID > env.txt` on the GPU machine, then
add `--env-file env.txt` on the BetterBench machine. Power isn't sampled then. Run
`./bench.sh power > power.csv` on the GPU machine during the run if your human wants it.
What each recorded value means, and how it's detected:
[`dev/DETAILS.md`](dev/DETAILS.md).
+6 -86
View File
@@ -1,92 +1,12 @@
# bench-standard
One script so everyone in the group benchmarks LLM servers the same way, with
[BetterBench](https://github.com/GGZ14/BetterBench). Every result records the setup it was
measured on: GPU, PCIe, engine, launch flags and more. Results stay comparable that way.
Using a coding agent? Point it at [`AGENTS.md`](AGENTS.md).
## 1. Install
On the machine with the GPU and the inference server (Linux, Python 3.10+):
Benchmark your LLM server the way everyone in the group does. One file:
```sh
git clone https://github.com/GGZ14/BetterBench && cd BetterBench
git checkout v0.6.1 && pip install -e . && cd ..
git clone https://git.linxweiler.xyz/miga/benchmarks bench-standard
pip install git+https://github.com/GGZ14/BetterBench # BetterBench 0.6.1 or newer
curl -O https://git.linxweiler.xyz/miga/benchmarks/raw/branch/main/bench.sh && chmod +x bench.sh
./bench.sh --help
```
## 2. Run
Serve one of the models in [`models.md`](models.md), Qwen3.5-9B or Qwen3.8-27B as
GGUF or w4a16, and check its SHA256. Any OpenAI-compatible server works (llama.cpp,
vLLM, ...). Then:
```sh
cd bench-standard
./bench.sh --endpoint http://localhost:8080/v1 --model MODEL_ID \
--tp 1 --pp 1 --quant Q4_K_M --kv f16 --spec none --thinking default \
--submitter YOUR_NAME --server-cmd-file server-cmd.txt
```
That's a quick check run of a few minutes. When it looks right, add `--full` for the
run that counts. It takes much longer and uses the GPU the whole time.
**You declare** what the script can't detect:
| flag | what | examples |
|---|---|---|
| `--tp` / `--pp` | tensor / pipeline parallel size | `1` / `1` |
| `--quant` | weight quantization | `Q4_K_M`, `gptq-int4`, `bf16` |
| `--kv` | KV cache type | `f16`, `q8_0` |
| `--spec` | speculative decoding | `none`, `mtp:5`, `eagle3:4`, `draft:8` |
| `--thinking` | thinking mode set **on the server** | `default`, `off`, `on`, `low`, `high` |
| `--submitter` | your name | `pascal` |
`--server-cmd-file` is a text file with the command you started the server with. Behind
llama-swap you can leave it out, because it's read automatically.
**Everything else is detected.** That includes the GPU, driver, power limit,
PCIe and ReBAR, measured memory bandwidth, CPU, OS, the engine and its exact
version, the model file, and launch and env flags. A temperature-0 output check
runs too. During the run it records power, clock and energy.
Optional flags:
| flag | for |
|---|---|
| `--full` | the real run (default is a quick check) |
| `--verbose` | show everything BetterBench prints |
| `--dry-run` | print what would run, then stop |
| `--mem-bw 608` | the card's spec memory bandwidth in GB/s |
| `--power-limit 250` | when the power limit can't be read |
| `--pcie "Gen4 x16"` | inside a VM, where the PCIe link can't be read |
| `--special-notes "..."` | anything unusual: custom kernels, undervolt, patched engine |
| `--api-key KEY` | if the server needs one (never stored) |
## 3. Send your result
Each run makes a folder `results/<date>-<you>-<model>-<engine>-<gpu>/`. Send the whole
folder. Open `results.html` in a browser to see the report.
- Only `--full` runs count.
- Check `server-cmd.txt` for anything private first. Tokens, keys and passwords
are already redacted.
To compare two runs: `betterbench compare A/results.json B/results.json`
## Rules
- BetterBench **0.6.1** exactly, with the settings in `config.json`. `bench.sh` refuses
any other version, and other BetterBench flags aren't allowed.
- Results come from `bench.sh` only. Don't edit them.
## More
- **BetterBench on another machine than the GPU:** run
`./collect-env.sh --endpoint URL --model ID > env.txt` on the server, then add
`--env-file env.txt` on the other machine.
- The declared values can also be set as `BENCH_<NAME>`, e.g. `BENCH_SUBMITTER=pascal`.
Results go to `results/` (or `--results-dir`). Machine-local defaults like these
go in `bench.local.env`.
- What each recorded field means and how it's detected: [`DETAILS.md`](DETAILS.md).
The models to use, and a step-by-step guide you can hand to a coding agent:
[`AGENTS.md`](AGENTS.md).
+534 -32
View File
@@ -1,46 +1,86 @@
#!/bin/sh
# bench.sh - the single entry point for a standardized BetterBench run (see README.md).
# bench.sh - bench-standard 0.4.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
d=$(mktemp -d)
trap 'rm -rf "$d"' EXIT
trap 'rm -rf "$d"; exit 130' INT
trap 'rm -rf "$d"; exit 143' TERM
cat > "$d/bench.sh" <<'__BENCH_STANDARD_EOF__'
#!/bin/sh
# bench.sh - bench-standard: benchmark an LLM server the way everyone in the
# group does, with BetterBench 0.6.1+. Every result records its setup (GPU,
# PCIe, engine, launch flags, ...), so results stay comparable.
#
# usage: bench.sh --endpoint URL --model ID
# --tp N --pp N --quant Q --kv KV --spec none|METHOD:N
# --thinking MODE --submitter NAME
# [--power-limit W|stock] [--api-key KEY] [--server-cmd-file FILE]
# [--env-file FILE] [--pcie GenN xW] [--special-notes TEXT]
# [--mem-bw GBPS] [--results-dir DIR] [--full] [--no-concurrency]
# [--verbose] [--dry-run]
# A quick check (a few minutes), then the same with --full for the real run:
# ./bench.sh --endpoint http://localhost:8080/v1 --model MODEL_ID \
# --tp 1 --pp 1 --quant Q4_K_M --kv f16 --spec none --thinking default \
# --submitter YOUR_NAME --server-cmd-file server-cmd.txt
#
# Default is a quick smoke run (BetterBench --quick); --full is the run that
# counts for submission.
# Mandatory values may also come from the environment: BENCH_TP, BENCH_PP,
# BENCH_QUANT, BENCH_KV, BENCH_SPEC, BENCH_THINKING, BENCH_SUBMITTER.
# --power-limit (or BENCH_POWER_LIMIT): read from the GPU when omitted; required
# only where it can't be detected. API key: --api-key or $BETTERBENCH_API_KEY.
# --pcie (or BENCH_PCIE): declare the slot link where it can't be read (VMs).
# --special-notes (or BENCH_SPECIAL_NOTES): free text for anything unusual
# about this run, e.g. "custom k8v4 kernels" or "undervolted".
# --mem-bw (or BENCH_MEM_BW): the card's declared (spec sheet) memory
# bandwidth in GB/s, recorded next to the one collect-env.sh measures.
# --verbose: stream BetterBench's full output (default: progress lines and a
# summary; the full output is in betterbench.log either way).
# --env-file: output of collect-env.sh run on the server, when BetterBench
# runs on another machine (default: run collect-env.sh here).
# You declare (these can't be detected):
# --tp N / --pp N tensor / pipeline parallel size
# --quant Q weight quantization: Q4_K_M, UD-Q4_K_M, w4a16, bf16
# --kv KV KV cache type: f16, bf16, q8_0
# --spec S speculative decoding: none, or METHOD:N with METHOD
# mtp, eagle, eagle3, ngram or draft (e.g. mtp:5)
# --thinking T thinking mode set on the server: off, on, low, medium,
# high or default
# --submitter NAME you
# --server-cmd-file F the command that started the server (not needed
# behind llama-swap, which reports it)
#
# Options:
# --full the run that counts (default: a quick check)
# --verbose show all of BetterBench's output
# --dry-run detect everything, print what would run, stop
# --mem-bw GBPS the card's spec memory bandwidth (measured anyway)
# --power-limit W when it can't be read from the GPU, or 'stock'
# --pcie "Gen4 x16" inside a VM, where the link can't be read
# --special-notes TXT anything unusual: custom kernels, undervolt, ...
# --api-key KEY or $BETTERBENCH_API_KEY; never stored
# --no-concurrency skip the concurrency sweep
# --results-dir DIR default: results/ next to bench.sh
# --env-file FILE when BetterBench runs on another machine than the GPU:
# the output of 'bench.sh collect-env' run on the GPU box
#
# Other commands:
# bench.sh collect-env --endpoint URL --model ID print the detected setup
# bench.sh power [SECONDS] sample GPU power, energy and clock until killed
# bench.sh --version
#
# Values can also come from the environment: BENCH_TP, BENCH_PP, BENCH_QUANT,
# BENCH_KV, BENCH_SPEC, BENCH_THINKING, BENCH_SUBMITTER, BENCH_POWER_LIMIT,
# BENCH_PCIE, BENCH_MEM_BW, BENCH_SPECIAL_NOTES, BENCH_RESULTS_DIR. Machine-
# local defaults like these go in bench.local.env next to bench.sh.
# Send the whole results/<run>/ folder. Only --full runs count.
# The standard models, their hashes and step-by-step help: AGENTS.md.
set -eu
umask 002
# here: the helper files. home: where results and bench.local.env go - next to
# the bench.sh people run, which unpacks the helpers to a temp dir.
here=$(cd "$(dirname "$0")" && pwd)
home=${BENCH_HOME:-$here}
. "$here/standard.env"
# Machine-local defaults (e.g. BENCH_RESULTS_DIR), not part of the standard.
[ -f "$here/bench.local.env" ] && . "$here/bench.local.env"
[ -f "$home/bench.local.env" ] && . "$home/bench.local.env"
die() { echo "bench.sh: $*" >&2; exit 1; }
usage() { sed -n '2,27p' "$0"; exit "${1:-0}"; }
usage() { sed -n '2,/^$/p' "$0" | sed -e 's/^# \{0,1\}//' -e '$d'; exit "${1:-0}"; }
case "${1:-}" in
collect-env) shift; exec sh "$here/collect-env.sh" "$@" ;;
power) shift; exec sh "$here/gpu-power.sh" "$@" ;;
--version) echo "bench-standard $STANDARD_VERSION (BetterBench $BETTERBENCH_MIN_VERSION or newer)"; exit 0 ;;
esac
endpoint="" model="" server_cmd_file="" env_file="" quick=1 no_conc=0 dry=0 verbose=0
tp=${BENCH_TP:-} pp=${BENCH_PP:-} quant=${BENCH_QUANT:-} kv=${BENCH_KV:-}
spec=${BENCH_SPEC:-} thinking=${BENCH_THINKING:-} power_limit=${BENCH_POWER_LIMIT:-}
submitter=${BENCH_SUBMITTER:-} pcie=${BENCH_PCIE:-} special=${BENCH_SPECIAL_NOTES:-}
mem_bw=${BENCH_MEM_BW:-}
results_dir=${BENCH_RESULTS_DIR:-$here/results}
results_dir=${BENCH_RESULTS_DIR:-$home/results}
need() { [ "$1" -ge 2 ] || die "$2 needs a value"; }
while [ $# -gt 0 ]; do
@@ -75,11 +115,13 @@ done
# ---------------------------------------------------------------- checks
matches() { printf '%s\n' "$1" | grep -Eqx "$2"; }
have_ver=$(betterbench --version 2>/dev/null | awk '{print $NF}') || have_ver=""
[ "$have_ver" = "$BETTERBENCH_VERSION" ] ||
die "BetterBench $BETTERBENCH_VERSION required, found '${have_ver:-not installed}'" \
"(git checkout v$BETTERBENCH_VERSION && pip install -e .)"
command -v python3 >/dev/null || die "python3 not found"
have_ver=$(betterbench --version 2>/dev/null | awk '{print $NF}') || have_ver=""
python3 -c 'import re, sys
v = lambda s: tuple(int(x) for x in re.findall(r"\d+", s)[:3])
sys.exit(not sys.argv[1] or v(sys.argv[1]) < v(sys.argv[2]))' "$have_ver" "$BETTERBENCH_MIN_VERSION" ||
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"
missing=""
@@ -185,6 +227,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 '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"
@@ -391,7 +434,7 @@ notes = [
("thinking", m["thinking"]),
("greedy_check", greedy),
("run", join(m["run_mode"], "concurrency " + m["concurrency"],
"bench-standard " + m["bench_standard"])),
"bench-standard " + m["bench_standard"], "betterbench " + m["betterbench"])),
]
if m.get("special_notes"):
notes.append(("special_notes", m["special_notes"]))
@@ -413,7 +456,7 @@ run_dir="$results_dir/$(date +%Y%m%d-%H%M%S)-$(printf '%s' "$submitter" | slug)-
# ---------------------------------------------------------------- run
set -- run --no-update-check --endpoint "$endpoint" --model "$model" \
--config "$here/config.json" --name "$name" --out "$run_dir/results.json"
--config "$run_dir/config.json" --name "$name" --out "$run_dir/results.json"
[ $quick = 1 ] && set -- "$@" --quick
[ $no_conc = 1 ] && set -- "$@" --no-concurrency
# Through a proxy /v1/models often lacks the context size; hand over what the
@@ -431,6 +474,7 @@ fi
mkdir -p "$results_dir"
mkdir "$run_dir" || die "cannot create $run_dir"
cp "$here/config.json" "$run_dir/config.json"
[ -n "$cmd_src" ] && cp "$tmp/cmd.red" "$run_dir/server-cmd.txt"
STANDARD_VERSION=$STANDARD_VERSION CMD_SRC=$cmd_src ENDPOINT=$endpoint MODEL=$model NAME=$name NOTES=$tmp/notes \
@@ -609,3 +653,461 @@ PY
echo
echo "done: $run_dir"
ls -1 "$run_dir"
__BENCH_STANDARD_EOF__
cat > "$d/collect-env.sh" <<'__BENCH_STANDARD_EOF__'
#!/bin/sh
# collect-env.sh - run ON THE INFERENCE SERVER. Prints a flat key=value list
# describing the hardware and the inference engine behind an endpoint.
# Never aborts on detection: anything it cannot find is reported as "unknown".
#
# usage: collect-env.sh [--endpoint URL] [--model ID] [--api-key KEY] [--server-cmd-out FILE]
# [--server-cmd-file FILE]
# --endpoint OpenAI-compatible base, e.g. http://localhost:8080/v1 (omit: hardware only)
# --model model id as sent to the endpoint (needed behind llama-swap)
# --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)
set -u
LC_ALL=C; export LC_ALL
endpoint="" model="" api_key="${BETTERBENCH_API_KEY:-}" cmd_out="" cmd_file=""
PROBE_TIMEOUT=${PROBE_TIMEOUT:-10}
LOAD_TIMEOUT=${LOAD_TIMEOUT:-600}
need() { [ "$1" -ge 2 ] || { echo "collect-env: $2 needs a value" >&2; exit 2; }; }
while [ $# -gt 0 ]; do
case "$1" in
--endpoint) need $# "$1"; endpoint=$2; shift 2 ;;
--model) need $# "$1"; model=$2; shift 2 ;;
--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 ;;
*) echo "collect-env: unknown argument: $1" >&2; exit 2 ;;
esac
done
tmp=$(mktemp -d) || exit 1
trap 'rm -rf "$tmp"' EXIT INT 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
have() { command -v "$1" >/dev/null 2>&1; }
# jget FILE EXPR - evaluate a python expression over the parsed JSON `j`
# (and `arg` = $JARG); prints nothing on any failure. Tolerates junk before
# the JSON (xpu-smi prints "[Error] ..." lines on stdout).
jget() {
have python3 || return 0
python3 - "$1" "$2" <<'PY' 2>/dev/null
import json, os, sys
try:
raw = open(sys.argv[1], encoding="utf-8", errors="replace").read()
try:
j = json.loads(raw)
except ValueError:
j = json.loads(raw[raw.index("{"):])
v = eval(sys.argv[2], {"j": j, "arg": os.environ.get("JARG", "")})
if v is not None and v != "":
print(" ".join(str(v).split()))
except Exception:
pass
PY
}
# fetch URL OUTFILE [TIMEOUT] - succeeds only on HTTP 2xx.
fetch() {
have curl || return 1
code=$(curl -s -m "${3:-$PROBE_TIMEOUT}" -o "$2" -w '%{http_code}' -H @"$tmp/hdr" "$1" 2>/dev/null) || code=000
case "$code" in 2*) return 0 ;; *) return 1 ;; esac
}
# Strip vendor boilerplate so the same card reads the same everywhere.
norm_gpu() {
sed -e 's/([RT]M*)//g' -e 's/^ *Intel *//' -e 's/^ *NVIDIA *//' -e 's/^ *AMD *//' \
-e 's/ Graphics *$//' -e 's/ */ /g' -e 's/^ //' -e 's/ $//'
}
kv() { printf '%s=%s\n' "$1" "$(printf '%s' "${2:-unknown}" | tr '\n\r' ' ')"; }
# "16.0 GT/s PCIe" -> 4
pcie_gen() {
case "$1" in
2.5*) echo 1 ;; 5.0*|5\ *) echo 2 ;; 8.0*|8\ *) echo 3 ;; 16.0*|16\ *) echo 4 ;;
32.0*|32\ *) echo 5 ;; 64.0*|64\ *) echo 6 ;; *) echo "" ;;
esac
}
# pcie_of BDF - sets pcie_link (negotiated now) and pcie_max (what card and slot
# both support) for the link into the slot. Cards with their own PCIe switch
# (Intel Arc, some AMD) expose an internal link on the GPU function itself, so
# walk up through bridges of the GPU's vendor to the switch's upstream port.
pcie_of() {
d=$(readlink -f "/sys/bus/pci/devices/$1" 2>/dev/null) && [ -f "$d/vendor" ] || return 0
vendor=$(cat "$d/vendor")
while p=${d%/*}; [ -f "$p/class" ] && [ "$(cat "$p/vendor")" = "$vendor" ]; do
case $(cat "$p/class") in 0x0604*) d=$p ;; *) break ;; esac
done
p=${d%/*}
g=$(pcie_gen "$(cat "$d/current_link_speed" 2>/dev/null)") w=$(cat "$d/current_link_width" 2>/dev/null)
[ -n "$g" ] && [ -n "$w" ] && pcie_link="Gen$g x$w"
g=$(pcie_gen "$(cat "$d/max_link_speed" 2>/dev/null)") w=$(cat "$d/max_link_width" 2>/dev/null)
if [ -f "$p/max_link_speed" ]; then
pg=$(pcie_gen "$(cat "$p/max_link_speed")") pw=$(cat "$p/max_link_width" 2>/dev/null)
[ -n "$pg" ] && [ "$pg" -lt "${g:-99}" ] && g=$pg
[ -n "$pw" ] && [ "$pw" -lt "${w:-99}" ] && w=$pw
fi
[ -n "$g" ] && [ -n "$w" ] && pcie_max="Gen$g x$w"
return 0
}
# ---------------------------------------------------------------- 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 \
--format=csv,noheader,nounits 2>/dev/null) && [ -n "$q" ]; then
gpu_vendor=nvidia
gpu_count=$(printf '%s\n' "$q" | grep -c .)
gpu_model=$(printf '%s\n' "$q" | cut -d, -f1 | norm_gpu | sort -u | paste -sd+ -)
first=$(printf '%s\n' "$q" | head -n1)
gpu_vram_gb=$(printf '%s' "$first" | cut -d, -f2 | awk '$1+0>0 {printf "%d", $1/1024+0.5}')
gpu_driver=$(printf '%s' "$first" | cut -d, -f3 | tr -d ' ')
gpu_power_limit_w=$(printf '%s' "$first" | cut -d, -f4 | awk '$1+0>0 {printf "%g", $1}')
# 00000000:01:00.0 -> 0000:01:00.0
gpu_bdf=$(printf '%s' "$first" | cut -d, -f5 | tr -d ' ' | tr 'A-F' 'a-f' | sed 's/^[0-9a-f]*\([0-9a-f]\{4\}:\)/\1/')
elif have rocm-smi && rocm-smi --showproductname --json > "$tmp/rp" 2>/dev/null; then
gpu_vendor=amd
rocm-smi --showmeminfo vram --json > "$tmp/rm" 2>/dev/null
rocm-smi --showdriverversion --json > "$tmp/rd" 2>/dev/null
rocm-smi --showmaxpower --json > "$tmp/rw" 2>/dev/null
rocm-smi --showbus --json > "$tmp/rb" 2>/dev/null
gpu_bdf=$(jget "$tmp/rb" 'next(v["PCI Bus"] for k, v in j.items() if k.startswith("card")).lower()')
gpu_count=$(jget "$tmp/rp" 'len([k for k in j if k.startswith("card")])')
gpu_model=$(jget "$tmp/rp" '"+".join(sorted({v.get("Card Series") or v.get("Card series") or v.get("Card model", "") for k, v in j.items() if k.startswith("card")}))' | norm_gpu)
gpu_vram_gb=$(jget "$tmp/rm" 'round(int(next(v["VRAM Total Memory (B)"] for k, v in j.items() if k.startswith("card"))) / 2**30)')
gpu_driver=$(jget "$tmp/rd" 'j["system"]["Driver version"]')
gpu_power_limit_w=$(jget "$tmp/rw" '"%g" % float(next(v for k, v in next(c for n, c in j.items() if n.startswith("card")).items() if "Power" in k))')
elif have xpu-smi && xpu-smi discovery -j > "$tmp/xl" 2>/dev/null; then
gpu_vendor=intel
gpu_count=$(jget "$tmp/xl" 'len(j["device_list"])')
gpu_model=$(jget "$tmp/xl" '"+".join(sorted({d["device_name"] for d in j["device_list"]}))' | norm_gpu)
dev0=$(jget "$tmp/xl" 'j["device_list"][0]["device_id"]')
gpu_bdf=$(jget "$tmp/xl" 'j["device_list"][0]["pci_bdf_address"].lower()')
if [ -n "$dev0" ]; then
xpu-smi discovery -d "$dev0" -j > "$tmp/xd" 2>/dev/null
gpu_vram_gb=$(jget "$tmp/xd" 'round(int(j["memory_physical_size_byte"]) / 2**30)')
gpu_driver=$(jget "$tmp/xd" 'j["driver_version"]')
# Newer xpu-smi takes named metrics; the old numeric -m syntax is gone.
gpu_power_limit_w=$(xpu-smi dump --device "$dev0" --metrics power.limit --number 1 2>/dev/null \
| awk -F', *' 'NR>1 && $3+0>0 {printf "%g", $3; exit}')
fi
fi
[ -n "$gpu_count" ] || gpu_count=unknown
# ---------------------------------------------------------------- host
# In a VM the GPU hangs off a virtual root port whose link figures are made
# up, so PCIe is only measured on bare metal.
virt=$(systemd-detect-virt --vm 2>/dev/null) || virt=none
pcie_link="" pcie_max=""
if [ "$virt" = none ] && [ -n "$gpu_bdf" ]; then pcie_of "$gpu_bdf"
elif [ "$virt" != none ]; then pcie_link="unknown (VM)" pcie_max="unknown (VM)"; fi
# Largest BAR of the GPU function: about VRAM-sized with Resizable BAR on,
# 256 MiB or less when off - the rule BetterBench's own fingerprint uses
# (GGZ14/BetterBench#4). Passthrough keeps BAR sizes, so this holds in a VM too.
gpu_bar_mib="" rebar=""
if [ -n "$gpu_bdf" ] && [ -r "/sys/bus/pci/devices/$gpu_bdf/resource" ] && have python3; then
gpu_bar_mib=$(python3 - "/sys/bus/pci/devices/$gpu_bdf/resource" <<'PY' 2>/dev/null
import sys
bars = []
for line in open(sys.argv[1]):
try:
start, end, _ = (int(x, 16) for x in line.split())
except ValueError:
continue
if end > start:
bars.append((end - start + 1) >> 20)
if bars:
print(max(bars))
PY
)
if [ -n "$gpu_bar_mib" ]; then
if [ "$gpu_bar_mib" -gt 256 ]; then rebar=on; else rebar=off; fi
fi
fi
cpu_model=$(lscpu 2>/dev/null | sed -n 's/^Model name: *//p' | head -n1)
[ -n "$cpu_model" ] || cpu_model=$(sed -n 's/^model name[[:space:]]*: *//p' /proc/cpuinfo 2>/dev/null | head -n1)
ram_gb=$(awk '/^MemTotal:/ {printf "%d", $2/1048576+0.5}' /proc/meminfo 2>/dev/null)
os=$( (. /etc/os-release 2>/dev/null && printf '%s' "${PRETTY_NAME:-}") )
[ -n "$os" ] || os=$(uname -s 2>/dev/null)
kernel=$(uname -r 2>/dev/null)
# ---------------------------------------------------------------- engine
proxy=none engine=unknown engine_version="" model_file="" ctx="" engine_slots=""
if [ -n "$endpoint" ]; then
base=${endpoint%/}; base=${base%/v1}
prefix=$base
t1=$PROBE_TIMEOUT
if fetch "$base/running" "$tmp/running" && [ -n "$(jget "$tmp/running" '"running" in j and "y"')" ]; then
proxy=llama-swap
if [ -n "$model" ]; then
prefix="$base/upstream/$model"
export JARG="$model"
state=$(jget "$tmp/running" 'next((r.get("state") for r in j["running"] if r.get("model") == arg), "")')
if [ "$state" != ready ]; then
echo "collect-env: $model is not loaded; llama-swap loads it on this probe (up to ${LOAD_TIMEOUT}s)" >&2
t1=$LOAD_TIMEOUT
fi
fi
fi
if fetch "$prefix/props" "$tmp/props" "$t1" \
&& [ -n "$(jget "$tmp/props" '("build_info" in j or "default_generation_settings" in j) and "y"')" ]; then
engine=llama.cpp
engine_version=$(jget "$tmp/props" 'j.get("build_info")')
model_file=$(jget "$tmp/props" 'j.get("model_path")')
ctx=$(jget "$tmp/props" '(j.get("default_generation_settings") or {}).get("n_ctx") or j.get("n_ctx")')
engine_slots=$(jget "$tmp/props" 'j.get("total_slots")')
elif fetch "$prefix/version" "$tmp/version" "$t1" \
&& v=$(jget "$tmp/version" 'j.get("version")') && [ -n "$v" ]; then
engine_version=$v
if fetch "$prefix/v1/models" "$tmp/models"; then
export JARG="$model"
# Behind a proxy the served name differs from the routed id, so a single
# entry is taken as is.
pick='next((m for m in j["data"] if m.get("id") == arg), j["data"][0] if len(j["data"]) == 1 else {})'
[ "$(jget "$tmp/models" "($pick).get('owned_by')")" = vllm ] && engine=vllm
ctx=$(jget "$tmp/models" "($pick).get('max_model_len')")
model_file=$(jget "$tmp/models" "($pick).get('root')")
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.
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
[ -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" ;;
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}')
fi
[ -s "$tmp/cmd" ] || { [ -n "$cmd_file" ] && cp "$cmd_file" "$tmp/cmd" 2>/dev/null; }
# 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=""
[ -s "$tmp/cmd" ] && container=$(tr '\n' ' ' < "$tmp/cmd" |
sed -n 's/.*docker *\(run\|create\) .*--name[= ]\([^ ]*\).*/\2/p')
if [ -n "$container" ] && have docker &&
i=$(docker inspect -f '{{.Config.Image}}@{{.Image}}' "$container" 2>/dev/null); then
engine_image=$(printf '%s' "$i" | sed 's/@sha256:\(.\{12\}\).*/@\1/')
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)
elif [ -n "$engine_image" ]; then
r=$(timeout 300 docker exec -i "$container" python3 - < "$here/mem-bw.py" 2>/dev/null)
else
r=""
fi
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
echo "collect-env: measuring memory bandwidth with clpeak (MEASURE_BW=0 skips) ..." >&2
timeout 300 clpeak --global-bandwidth > "$tmp/clpeak" 2>/dev/null
# Pick the device whose name holds the detected model; take the best width.
gpu_mem_bw_gbs=$(awk -v want="$gpu_model" '
/^ *Device:/ { sub(/^ *Device: */, ""); gsub(/\([RT]M*\)/, ""); gsub(/ +/, " "); dev = $0; next }
/Global memory bandwidth/ { inbw = index(dev, want) > 0; next }
inbw && /^ *float[0-9]* *:/ { v = $NF + 0; if (v > best) best = v; next }
inbw && !/^ *float/ { inbw = 0 }
END { if (best > 0) printf "%.0f", best }' "$tmp/clpeak")
[ -n "$gpu_mem_bw_gbs" ] && gpu_mem_bw_tool=clpeak
fi
fi
kv gpu_vendor "$gpu_vendor"
kv gpu_model "$gpu_model"
kv gpu_count "$gpu_count"
kv gpu_vram_gb "$gpu_vram_gb"
kv gpu_driver "$gpu_driver"
kv gpu_power_limit_w "$gpu_power_limit_w"
kv gpu_bdf "$gpu_bdf"
kv pcie_link "$pcie_link"
kv pcie_max "$pcie_max"
kv gpu_bar_mib "$gpu_bar_mib"
kv rebar "$rebar"
kv gpu_mem_bw_gbs "$gpu_mem_bw_gbs"
kv gpu_mem_bw_tool "$gpu_mem_bw_tool"
kv cpu_model "$cpu_model"
kv ram_gb "$ram_gb"
kv os "$os"
kv kernel "$kernel"
kv virt "$virt"
kv proxy "$proxy"
kv engine "$engine"
kv engine_version "$engine_version"
kv engine_slots "$engine_slots"
kv engine_image "$engine_image"
kv model_file "$model_file"
kv model_bytes "$model_bytes"
kv ctx "$ctx"
exit 0
__BENCH_STANDARD_EOF__
cat > "$d/gpu-power.sh" <<'__BENCH_STANDARD_EOF__'
#!/bin/sh
# gpu-power.sh - run ON THE INFERENCE SERVER. Samples the power draw and the
# energy counter and the core clock of all GPUs until killed, one CSV line
# per sample:
# epoch_s,watts,joules,mhz
# 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).
#
# usage: gpu-power.sh [INTERVAL_S] (default 2)
set -u
LC_ALL=C; export LC_ALL
interval=${1:-2}
if command -v nvidia-smi >/dev/null 2>&1 &&
nvidia-smi --query-gpu=power.draw --format=csv,noheader >/dev/null 2>&1; then
# total_energy_consumption is in mJ since the driver loaded
sample() {
nvidia-smi --query-gpu=power.draw,total_energy_consumption,clocks.gr \
--format=csv,noheader,nounits 2>/dev/null |
awk -F', *' '{w += $1; if ($2 + 0 > 0) j += $2 / 1000; else nj = 1; c += $3}
END {if (NR) printf "%.2f,%s,%.0f\n", w, nj ? "" : sprintf("%.3f", j), c / NR}'
}
elif command -v xpu-smi >/dev/null 2>&1; then
# one call takes about a second
sample() {
xpu-smi dump --device -1 --metrics power.draw,energy.consumed,clocks.current.graphics \
--number 1 2>/dev/null |
awk -F', *' 'NR > 1 && $3 + 0 > 0 {w += $3; n++; if ($4 + 0 > 0) j += $4; else nj = 1; c += $5}
END {if (n) printf "%.2f,%s,%.0f\n", w, nj ? "" : sprintf("%.3f", j), c / n}'
}
else
exit 0
fi
while :; do
t=$(date +%s.%N)
s=$(sample)
[ -n "$s" ] && printf '%s,%s\n' "$t" "$s"
sleep "$interval"
done
__BENCH_STANDARD_EOF__
cat > "$d/mem-bw.py" <<'__BENCH_STANDARD_EOF__'
"""mem-bw.py - measured GPU memory bandwidth with torch, printed as "GBPS MIB".
Copies a buffer of random floats 20 times and counts read + write. Random
data on purpose: Arc compresses uniform buffers, so a zero-filled test reads
far too high (1227 GB/s with zeros vs 533 GB/s real on a B70). Best of three
rounds. Tries 1 GiB, then smaller buffers when the inference server has taken
most of the VRAM. Prints nothing when there is no usable GPU.
Runs with any python that has torch for the GPU: collect-env.sh runs it inside
the server's own container (docker exec), or with $BW_PYTHON.
"""
import sys
import time
import torch
if hasattr(torch, "xpu") and torch.xpu.is_available():
dev, sync = "xpu", torch.xpu.synchronize
elif torch.cuda.is_available(): # NVIDIA, and AMD through ROCm
dev, sync = "cuda", torch.cuda.synchronize
else:
sys.exit(0)
for mib in (1024, 512, 256):
try:
x = torch.rand(mib * 2**20 // 4, device=dev)
y = torch.empty_like(x)
break
except RuntimeError: # out of memory
continue
else:
sys.exit(0)
y.copy_(x)
sync()
best = 0.0
for _ in range(3):
t = time.perf_counter()
for _ in range(20):
y.copy_(x)
sync()
best = max(best, 20 * 2 * x.numel() * 4 / (time.perf_counter() - t) / 1e9)
print(f"{best:.0f} {mib}")
__BENCH_STANDARD_EOF__
cat > "$d/config.json" <<'__BENCH_STANDARD_EOF__'
{
"temperature": 0.7,
"top_p": 0.95,
"top_k": 20,
"greedy": false,
"warmup": 3,
"runs_per_category": 20,
"unique_nonce": true,
"run_concurrency": true,
"concurrency_levels": [1, 2, 4, 8],
"concurrency_requests": 48,
"weights": {
"code": 0.30, "reasoning": 0.20, "prose": 0.15,
"json": 0.15, "file_edit": 0.10, "summarization": 0.10
},
"conf": 0.95,
"target_mde_pct": 1.0,
"ab_max_pairs": 200,
"ab_min_pairs": 12,
"timeout_s": 600.0
}
__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.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
__BENCH_STANDARD_EOF__
sh "$d/bench.sh" "$@"
+27 -6
View File
@@ -1,14 +1,15 @@
# Details
What `bench.sh` records, and how. For running it, see [`README.md`](README.md).
What `bench.sh` records, how, and how it's built. For running it, see
[`AGENTS.md`](../AGENTS.md) or `./bench.sh --help`.
## What a run does
1. One warm-up request. Behind llama-swap the first request loads the model, which
can take minutes.
2. **Greedy check:** the same prompt 3 times at temperature 0.
3. `collect-env.sh` detects the hardware and the engine, and measures memory bandwidth.
4. BetterBench runs while `gpu-power.sh` samples power, energy and clock every 2 s.
3. `collect-env.sh` (also `bench.sh collect-env`) detects the hardware and the engine, and measures memory bandwidth.
4. BetterBench runs while `gpu-power.sh` (also `bench.sh power`) samples power, energy and clock every 2 s.
5. A summary prints. Energy and % of bandwidth are written to `meta.json`.
## Files in a run folder
@@ -17,6 +18,7 @@ What `bench.sh` records, and how. For running it, see [`README.md`](README.md).
|---|---|
| `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` |
| `server-cmd.txt` | the server launch command, secrets redacted |
| `power.csv` | `epoch_s,watts,joules,mhz` during the run |
@@ -43,7 +45,7 @@ can't be detected is left out or shows `unknown`.
| `env_flags` | `GGML_SYCL_DISABLE_OPT=0 · ZES_ENABLE_SYSMAN=1`, or `none` |
| `spec`, `thinking` | `mtp:5`, `default` |
| `greedy_check` | `identical 3/3 · 1d5105fe09dc`, `differs: 2 variants in 3 · first ...` |
| `run` | `full · concurrency on · bench-standard 0.3.0` |
| `run` | `full · concurrency on · bench-standard 0.4.0 · betterbench 0.6.1` |
| `special_notes` | only when given |
The context size appears as BetterBench's own chip.
@@ -54,7 +56,7 @@ The context size appears as BetterBench's own chip.
**PCIe** is the link into the slot. Cards with their own PCIe switch (Intel Arc, some AMD)
are read at the switch's upstream port. Inside a VM the link can't be read: run
`collect-env.sh` on the hypervisor, or pass `--pcie`.
`bench.sh collect-env` on the hypervisor, or pass `--pcie`.
**ReBAR** is on when the GPU's largest BAR is bigger than 256 MiB (about the size of VRAM).
This works in a VM too, because passthrough keeps BAR sizes.
@@ -93,7 +95,7 @@ fixed before BetterBench starts.
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
`gpu-power.sh > power.csv` on the server yourself.
`bench.sh power > power.csv` on the server yourself.
- **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
@@ -107,3 +109,22 @@ own GPU/PCIe/ReBAR probe under `env.gpu` (still version 0.6.1). That probe descr
machine BetterBench runs on, so the notes above are what count. `bench.sh` warns when
the two disagree. The probe adds an `intel`-style chip, so `compare` shows a `gpu`
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.
```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/bench.sh --help # dev/bench.sh also runs directly, results in dev/results/
```
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
fields change.
Executable
+645
View File
@@ -0,0 +1,645 @@
#!/bin/sh
# bench.sh - bench-standard: benchmark an LLM server the way everyone in the
# group does, with BetterBench 0.6.1+. Every result records its setup (GPU,
# PCIe, engine, launch flags, ...), so results stay comparable.
#
# A quick check (a few minutes), then the same with --full for the real run:
# ./bench.sh --endpoint http://localhost:8080/v1 --model MODEL_ID \
# --tp 1 --pp 1 --quant Q4_K_M --kv f16 --spec none --thinking default \
# --submitter YOUR_NAME --server-cmd-file server-cmd.txt
#
# You declare (these can't be detected):
# --tp N / --pp N tensor / pipeline parallel size
# --quant Q weight quantization: Q4_K_M, UD-Q4_K_M, w4a16, bf16
# --kv KV KV cache type: f16, bf16, q8_0
# --spec S speculative decoding: none, or METHOD:N with METHOD
# mtp, eagle, eagle3, ngram or draft (e.g. mtp:5)
# --thinking T thinking mode set on the server: off, on, low, medium,
# high or default
# --submitter NAME you
# --server-cmd-file F the command that started the server (not needed
# behind llama-swap, which reports it)
#
# Options:
# --full the run that counts (default: a quick check)
# --verbose show all of BetterBench's output
# --dry-run detect everything, print what would run, stop
# --mem-bw GBPS the card's spec memory bandwidth (measured anyway)
# --power-limit W when it can't be read from the GPU, or 'stock'
# --pcie "Gen4 x16" inside a VM, where the link can't be read
# --special-notes TXT anything unusual: custom kernels, undervolt, ...
# --api-key KEY or $BETTERBENCH_API_KEY; never stored
# --no-concurrency skip the concurrency sweep
# --results-dir DIR default: results/ next to bench.sh
# --env-file FILE when BetterBench runs on another machine than the GPU:
# the output of 'bench.sh collect-env' run on the GPU box
#
# Other commands:
# bench.sh collect-env --endpoint URL --model ID print the detected setup
# bench.sh power [SECONDS] sample GPU power, energy and clock until killed
# bench.sh --version
#
# Values can also come from the environment: BENCH_TP, BENCH_PP, BENCH_QUANT,
# BENCH_KV, BENCH_SPEC, BENCH_THINKING, BENCH_SUBMITTER, BENCH_POWER_LIMIT,
# BENCH_PCIE, BENCH_MEM_BW, BENCH_SPECIAL_NOTES, BENCH_RESULTS_DIR. Machine-
# local defaults like these go in bench.local.env next to bench.sh.
# Send the whole results/<run>/ folder. Only --full runs count.
# The standard models, their hashes and step-by-step help: AGENTS.md.
set -eu
umask 002
# here: the helper files. home: where results and bench.local.env go - next to
# the bench.sh people run, which unpacks the helpers to a temp dir.
here=$(cd "$(dirname "$0")" && pwd)
home=${BENCH_HOME:-$here}
. "$here/standard.env"
# Machine-local defaults (e.g. BENCH_RESULTS_DIR), not part of the standard.
[ -f "$home/bench.local.env" ] && . "$home/bench.local.env"
die() { echo "bench.sh: $*" >&2; exit 1; }
usage() { sed -n '2,/^$/p' "$0" | sed -e 's/^# \{0,1\}//' -e '$d'; exit "${1:-0}"; }
case "${1:-}" in
collect-env) shift; exec sh "$here/collect-env.sh" "$@" ;;
power) shift; exec sh "$here/gpu-power.sh" "$@" ;;
--version) echo "bench-standard $STANDARD_VERSION (BetterBench $BETTERBENCH_MIN_VERSION or newer)"; exit 0 ;;
esac
endpoint="" model="" server_cmd_file="" env_file="" quick=1 no_conc=0 dry=0 verbose=0
tp=${BENCH_TP:-} pp=${BENCH_PP:-} quant=${BENCH_QUANT:-} kv=${BENCH_KV:-}
spec=${BENCH_SPEC:-} thinking=${BENCH_THINKING:-} power_limit=${BENCH_POWER_LIMIT:-}
submitter=${BENCH_SUBMITTER:-} pcie=${BENCH_PCIE:-} special=${BENCH_SPECIAL_NOTES:-}
mem_bw=${BENCH_MEM_BW:-}
results_dir=${BENCH_RESULTS_DIR:-$home/results}
need() { [ "$1" -ge 2 ] || die "$2 needs a value"; }
while [ $# -gt 0 ]; do
case "$1" in
--endpoint) need $# "$1"; endpoint=$2; shift 2 ;;
--model) need $# "$1"; model=$2; shift 2 ;;
--api-key) need $# "$1"; BETTERBENCH_API_KEY=$2; export BETTERBENCH_API_KEY; shift 2 ;;
--server-cmd-file) need $# "$1"; server_cmd_file=$2; shift 2 ;;
--env-file) need $# "$1"; env_file=$2; shift 2 ;;
--results-dir) need $# "$1"; results_dir=$2; shift 2 ;;
--tp) need $# "$1"; tp=$2; shift 2 ;;
--pp) need $# "$1"; pp=$2; shift 2 ;;
--quant) need $# "$1"; quant=$2; shift 2 ;;
--kv) need $# "$1"; kv=$2; shift 2 ;;
--spec) need $# "$1"; spec=$2; shift 2 ;;
--thinking) need $# "$1"; thinking=$2; shift 2 ;;
--power-limit) need $# "$1"; power_limit=$2; shift 2 ;;
--submitter) need $# "$1"; submitter=$2; shift 2 ;;
--pcie) need $# "$1"; pcie=$2; shift 2 ;;
--special-notes) need $# "$1"; special=$2; shift 2 ;;
--mem-bw) need $# "$1"; mem_bw=$2; shift 2 ;;
--quick) quick=1; shift ;;
--full) quick=0; shift ;;
--no-concurrency) no_conc=1; shift ;;
--dry-run) dry=1; shift ;;
--verbose) verbose=1; shift ;;
-h|--help) usage 0 ;;
*) echo "bench.sh: unknown argument: $1 (other BetterBench flags are not allowed)" >&2; usage 2 ;;
esac
done
# ---------------------------------------------------------------- checks
matches() { printf '%s\n' "$1" | grep -Eqx "$2"; }
command -v python3 >/dev/null || die "python3 not found"
have_ver=$(betterbench --version 2>/dev/null | awk '{print $NF}') || have_ver=""
python3 -c 'import re, sys
v = lambda s: tuple(int(x) for x in re.findall(r"\d+", s)[:3])
sys.exit(not sys.argv[1] or v(sys.argv[1]) < v(sys.argv[2]))' "$have_ver" "$BETTERBENCH_MIN_VERSION" ||
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"
missing=""
for f in endpoint model tp pp quant kv spec thinking submitter; do
eval "v=\${$f}"
[ -n "$v" ] || missing="$missing --$(printf '%s' "$f" | tr _ -)"
done
[ -z "$missing" ] || die "missing mandatory value(s):$missing"
matches "$tp" '[1-9][0-9]*' || die "--tp must be a positive integer"
matches "$pp" '[1-9][0-9]*' || die "--pp must be a positive integer"
matches "$spec" 'none|(mtp|eagle|eagle3|ngram|draft):[1-9][0-9]*' ||
die "--spec must be none or METHOD:N (mtp|eagle|eagle3|ngram|draft), e.g. mtp:5"
matches "$thinking" 'off|on|low|medium|high|default' ||
die "--thinking must be off|on|low|medium|high|default (the server-side mode)"
[ -z "$power_limit" ] || matches "$power_limit" 'stock|[0-9]+(\.[0-9]+)?' ||
die "--power-limit must be watts or 'stock'"
[ -z "$pcie" ] || matches "$pcie" 'Gen[1-6] x(1|2|4|8|16|32)' || die "--pcie must look like 'Gen4 x16'"
[ -z "$mem_bw" ] || matches "$mem_bw" '[1-9][0-9]*(\.[0-9]+)?' || die "--mem-bw must be GB/s, e.g. 456"
case "$special" in *"
"*) die "--special-notes must be a single line" ;; esac
for f in quant kv submitter; do
eval "v=\${$f}"
matches "$v" '[^[:space:]=]+' || die "--$f must be one word without '='"
done
if [ -n "$server_cmd_file" ]; then [ -r "$server_cmd_file" ] || die "cannot read $server_cmd_file"; fi
if [ -n "$env_file" ]; then [ -r "$env_file" ] || die "cannot read $env_file"; fi
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT INT TERM
hdr="$tmp/hdr"
if [ -n "${BETTERBENCH_API_KEY:-}" ]; then printf 'Authorization: Bearer %s\n' "$BETTERBENCH_API_KEY" > "$hdr"
else printf 'Accept: application/json\n' > "$hdr"; fi
# ---------------------------------------------------------------- warm up
# The first request through llama-swap loads the model (minutes); it must not
# land inside a timed pass, and the engine probe needs it loaded anyway.
echo "warming up $model (a cold model behind llama-swap takes minutes to load) ..." >&2
body=$(python3 -c 'import json, sys; print(json.dumps({"model": sys.argv[1], "max_tokens": 1,
"messages": [{"role": "user", "content": "hi"}]}))' "$model")
code=$(curl -s -m "${WARM_TIMEOUT:-900}" -o "$tmp/warm" -w '%{http_code}' -H @"$hdr" \
-H 'Content-Type: application/json' -d "$body" "${endpoint%/}/chat/completions") || code=000
case "$code" in 2*) ;; *) die "warm-up request failed (HTTP $code): $(head -c 300 "$tmp/warm" 2>/dev/null)" ;; esac
# ---------------------------------------------------------------- greedy check
# The same prompt three times at temperature 0 must give the same text. The
# hash of that text also lets two setups of the same model be compared: a
# different hash means different numerics (quant, kernels, spec decoding bug).
echo "greedy check: 3 requests at temperature 0 ..." >&2
ENDPOINT=$endpoint MODEL=$model python3 - > "$tmp/measured" <<'PY'
import hashlib, json, os, urllib.request
PROMPT = ("List the first twelve prime numbers, then explain in three sentences "
"why there are infinitely many primes.")
body = json.dumps({"model": os.environ["MODEL"], "temperature": 0, "seed": 0,
"max_tokens": 128, "stream": False,
"messages": [{"role": "user", "content": PROMPT}]}).encode()
hdr = {"Content-Type": "application/json"}
if os.environ.get("BETTERBENCH_API_KEY"):
hdr["Authorization"] = "Bearer " + os.environ["BETTERBENCH_API_KEY"]
outs = []
try:
for _ in range(3):
req = urllib.request.Request(os.environ["ENDPOINT"].rstrip("/") + "/chat/completions",
body, hdr)
with urllib.request.urlopen(req, timeout=600) as r:
msg = json.load(r)["choices"][0]["message"]
# thinking models may spend all 128 tokens on reasoning
outs.append((msg.get("reasoning_content") or msg.get("reasoning") or "") +
"\0" + (msg.get("content") or ""))
except Exception as e:
print("greedy_check=failed")
print("greedy_error=" + " ".join(str(e).split())[:200])
else:
hashes = [hashlib.sha256(o.encode()).hexdigest()[:12] for o in outs]
print("greedy_check=" + ("identical" if len(set(hashes)) == 1 else "differs"))
print(f"greedy_variants={len(set(hashes))}\ngreedy_runs={len(hashes)}\ngreedy_hash={hashes[0]}")
PY
# ---------------------------------------------------------------- collect
if [ -n "$env_file" ]; then
cp "$env_file" "$tmp/env"
else
set -- --endpoint "$endpoint" --model "$model" --server-cmd-out "$tmp/cmd.auto"
[ -n "$server_cmd_file" ] && set -- "$@" --server-cmd-file "$server_cmd_file"
sh "$here/collect-env.sh" "$@" > "$tmp/env"
fi
get() { sed -n "s/^$1=//p" "$tmp/env" | head -n1; }
pl=$(get gpu_power_limit_w)
power_src=declared
if [ -z "$power_limit" ]; then
matches "$pl" '[0-9]+(\.[0-9]+)?' ||
die "GPU power limit not detected here; pass --power-limit W (or 'stock')"
power_limit=$pl power_src=detected
fi
# Raw declared values; meta.json keeps these and the collected ones as is.
{
printf 'submitter=%s\ntp=%s\npp=%s\nquant=%s\nkv=%s\nspec=%s\nthinking=%s\npower_limit=%s\n' \
"$submitter" "$tp" "$pp" "$quant" "$kv" "$spec" "$thinking" "$power_limit"
printf 'power_limit_source=%s\n' "$power_src"
[ -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 '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"
grep -Ev '^[[:space:]]*(#|$)' "$tmp/env" > "$tmp/collected" || true
if grep -Evq '^[a-z0-9_]+=' "$tmp/collected"; then
die "malformed line in collected env (want key=value, lowercase keys)"
fi
for k in $(cut -d= -f1 "$tmp/mandatory"); do
if grep -q "^$k=" "$tmp/collected"; then die "collected env must not set mandatory key '$k'"; fi
done
# Launch command: the user's file wins, else what llama-swap reports.
# Secrets in env vars / flags are redacted either way.
cmd_src=""
if [ -n "$server_cmd_file" ]; then cmd_src="file:$(basename "$server_cmd_file")"; cp "$server_cmd_file" "$tmp/cmd"
elif [ -s "$tmp/cmd.auto" ]; then cmd_src="llama-swap /running"; cp "$tmp/cmd.auto" "$tmp/cmd"; fi
: > "$tmp/cmd.red"
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)
open(sys.argv[2], "w", encoding="utf-8").write(s if s.endswith("\n") else s + "\n")
PY
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"
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", m["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
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
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
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/-$//'; }
name=$(printf '%s-%s-%s' "$model" "$engine" "$gpu" | slug)
run_dir="$results_dir/$(date +%Y%m%d-%H%M%S)-$(printf '%s' "$submitter" | slug)-$name"
# ---------------------------------------------------------------- run
set -- run --no-update-check --endpoint "$endpoint" --model "$model" \
--config "$run_dir/config.json" --name "$name" --out "$run_dir/results.json"
[ $quick = 1 ] && set -- "$@" --quick
[ $no_conc = 1 ] && set -- "$@" --no-concurrency
# Through a proxy /v1/models often lacks the context size; hand over what the
# engine itself reported so prefill depths that don't fit are skipped cleanly.
matches "$ctx" '[1-9][0-9]*' && set -- "$@" --max-model-len "$ctx"
while IFS= read -r line; do set -- "$@" --note "$line"; done < "$tmp/notes"
if [ $dry = 1 ]; then
echo "dry run - would write $run_dir/ and run:"
printf ' betterbench'
for a; do case $a in *[[:space:]]*) printf " '%s'" "$a" ;; *) printf ' %s' "$a" ;; esac; done
echo
exit 0
fi
mkdir -p "$results_dir"
mkdir "$run_dir" || die "cannot create $run_dir"
cp "$here/config.json" "$run_dir/config.json"
[ -n "$cmd_src" ] && cp "$tmp/cmd.red" "$run_dir/server-cmd.txt"
STANDARD_VERSION=$STANDARD_VERSION CMD_SRC=$cmd_src ENDPOINT=$endpoint MODEL=$model NAME=$name NOTES=$tmp/notes \
MEASURED=$tmp/measured LAUNCH=$tmp/launch.json \
python3 - "$tmp/mandatory" "$tmp/collected" "$run_dir/meta.json" "$@" <<'PY'
import json, os, sys, time
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)
src = os.environ["CMD_SRC"]
meta = {
"bench_standard": os.environ["STANDARD_VERSION"],
"created": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
"endpoint": os.environ["ENDPOINT"],
"model": os.environ["MODEL"],
"name": os.environ["NAME"],
"notes": kv(os.environ["NOTES"]),
"mandatory": kv(sys.argv[1]),
"collected": kv(sys.argv[2]),
"measured": kv(os.environ["MEASURED"]),
"launch": json.load(open(os.environ["LAUNCH"], encoding="utf-8")),
"server_cmd_file": "server-cmd.txt" if src else None,
"server_cmd_source": src or None,
"betterbench_argv": ["betterbench"] + sys.argv[4:],
}
with open(sys.argv[3], "w", encoding="utf-8") as f:
json.dump(meta, f, indent=2)
f.write("\n")
PY
# Power is sampled where the GPU is: only when BetterBench runs on the server.
sampler=""
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
t_end=$(date +%s.%N)
if [ -n "$sampler" ]; then
kill "$sampler" 2>/dev/null; wait "$sampler" 2>/dev/null || true
[ -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
# 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"
Executable
+48
View File
@@ -0,0 +1,48 @@
#!/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.
#
# 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)
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"
eof=__BENCH_STANDARD_EOF__
. "$dev/standard.env"
for f in $files; do
if grep -q "$eof" "$dev/$f"; then echo "build.sh: $f contains $eof" >&2; exit 1; fi
done
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT
{
cat <<EOF
#!/bin/sh
# bench.sh - bench-standard $STANDARD_VERSION, 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
d=\$(mktemp -d)
trap 'rm -rf "\$d"' EXIT
trap 'rm -rf "\$d"; exit 130' INT
trap 'rm -rf "\$d"; exit 143' TERM
EOF
for f in $files; do
printf "cat > \"\$d/%s\" <<'%s'\n" "$f" "$eof"
cat "$dev/$f"
printf '%s\n' "$eof"
done
printf 'sh "$d/bench.sh" "$@"\n'
} > "$tmp"
if [ "${1:-}" = --check ]; then
cmp -s "$tmp" "$out" || { echo "build.sh: bench.sh is out of date, run dev/build.sh" >&2; exit 1; }
echo "bench.sh is up to date"
else
cp "$tmp" "$out" && chmod +x "$out"
echo "built $(cd "$dev/.." && pwd)/bench.sh ($(wc -c < "$out") bytes)"
fi
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
+6
View File
@@ -0,0 +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.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
-42
View File
@@ -1,42 +0,0 @@
# Models
Benchmark only these files, and check the hash first. A different file is a different
benchmark.
| model | engine | Hugging Face repo | file(s) | `--quant` |
|---|---|---|---|---|
| Qwen3.5-9B | vLLM & co. | [`RedHatAI/Qwen3.5-9B-quantized.w4a16`](https://huggingface.co/RedHatAI/Qwen3.5-9B-quantized.w4a16) | the repo (`model.safetensors`, `model_mtp.safetensors`) | `w4a16` |
| Qwen3.8-27B | vLLM & co. | [`RedHatAI/Qwen3.8-27B-INT4`](https://huggingface.co/RedHatAI/Qwen3.8-27B-INT4) | the repo (`model.safetensors`, `model_mtp.safetensors`) | `w4a16` |
| Qwen3.5-9B | llama.cpp | [`unsloth/Qwen3.5-9B-GGUF`](https://huggingface.co/unsloth/Qwen3.5-9B-GGUF) | `Qwen3.5-9B-Q4_K_M.gguf` | `Q4_K_M` |
| Qwen3.8-27B | llama.cpp | [`unsloth/Qwen3.8-27B-GGUF`](https://huggingface.co/unsloth/Qwen3.8-27B-GGUF) | `Qwen3.8-27B-UD-Q4_K_M.gguf` | `UD-Q4_K_M` |
Both RedHatAI checkpoints are int4 weights with 16-bit activations (compressed-tensors),
and they include an MTP head (`model_mtp.safetensors`) for `--spec mtp:N`. The 27B GGUF
repo has no plain Q4_K_M, only Unsloth's dynamic `UD-Q4_K_M`.
## SHA256
| file | SHA256 |
|---|---|
| `Qwen3.5-9B-Q4_K_M.gguf` | `03b74727a860a56338e042c4420bb3f04b2fec5734175f4cb9fa853daf52b7e8` |
| `Qwen3.8-27B-UD-Q4_K_M.gguf` | `322e194ff79741c7baa497c240f677f54b201b0efab44ca8e50f122b39123482` |
| `RedHatAI/Qwen3.5-9B-quantized.w4a16` (directory) | `cca16f9855b9f92eee5876ddc8656ed6397316ffc65b9f17ca1939a9549e4c26` |
| `RedHatAI/Qwen3.8-27B-INT4` (directory) | `bffa6b23fa11be557fe9de4b122a8bb99f537ad7a1a4effa702f7d0c677778f7` |
The hashes are from the Hugging Face repos as of 2026-10-29 (revisions `3885219`,
`4ca7207`, `a398088`, `91bd022`). If a repo changes its files, this table gets updated.
## Check
A GGUF file:
```sh
sha256sum Qwen3.5-9B-Q4_K_M.gguf
```
A safetensors directory: one hash over the per-file hashes, in name order. `LC_ALL=C`
matters, because other locales sort `model_mtp` before `model.` and give a different hash.
```sh
cd /path/to/model-dir && sha256sum *.safetensors | LC_ALL=C sort -k2 | sha256sum
```
-4
View File
@@ -1,4 +0,0 @@
# Pins for this version of the group standard. Bump STANDARD_VERSION whenever
# config.json, the pinned BetterBench or the mandatory fields change.
STANDARD_VERSION=0.3.0
BETTERBENCH_VERSION=0.6.1