bench-standard 0.3.0: ReBAR, memory bandwidth, launch flags, greedy check, energy

- collect-env.sh: ReBAR from the GPU's largest BAR (same rule as
  GGZ14/BetterBench#4), weight size of the model, docker image ID,
  memory bandwidth measured with mem-bw.py (torch copy of random data
  inside the server's container; clpeak as fallback)
- bench.sh: notes for mem_bw (measured + declared), launch settings
  (llama.cpp b/ub/fa/ctk/ctv/..., vLLM batching/KV/compilation),
  env_flags and a temp-0 greedy check with output hash
- gpu-power.sh: power, energy counter and clock during the run;
  post-run energy per token, avg clock/watts and % of memory bandwidth
  go to meta.json and a terminal summary
- short output by default, --verbose for BetterBench's full stream;
  full output always in betterbench.log
- cross-check BetterBench#4's own env.gpu.pci against collect-env.sh

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-10-29 12:37:22 +01:00
1 parent 279de33646
commit 82b65558ac
7 files changed
+605 -40

No files matched your search

+82 -7
View File
@@ -29,7 +29,12 @@ BetterBench itself is used unmodified, only through its CLI.
BetterBench can't send `chat_template_kwargs` / `reasoning_effort`, so the thinking
mode must be fixed in the server's chat template or launch flags and declared here.
5. **Results come from `bench.sh` only.** It adds everything it can detect itself
(GPU, driver, CPU, RAM, OS, engine and version, model file, context) as notes.
(GPU, driver, PCIe/ReBAR, memory bandwidth, CPU, RAM, OS, engine and version,
model file and size, launch flags and env flags, context) as notes.
6. **Memory bandwidth is measured** with `mem-bw.py`, a torch copy of random data run
inside the server's container (vLLM images have torch). Elsewhere set `BW_PYTHON`
to a python with GPU torch, or install `clpeak` as a fallback. Pass the card's
spec figure as `--mem-bw GBPS`; both are recorded.
## Running
@@ -47,23 +52,33 @@ Add `--full` for the run that counts; it takes much longer and occupies the GPU.
- `--full` - the complete, publishable run; recorded as `run=full · ...`.
- `--no-concurrency` - skip the concurrency sweep; recorded as `concurrency=off`.
- `--dry-run` - print the BetterBench command and exit.
- `--verbose` - stream BetterBench's full output and list the notes. By default you
see the progress lines and a summary at the end. The full output is in
`betterbench.log` either way, and what gets recorded is identical.
- `--pcie "Gen4 x16"` - declare the slot link where it can't be read (VMs).
- `--special-notes "..."` - free text for anything unusual about the run (custom
kernels, undervolt, patched engine). Recorded as `special_notes`.
- `--mem-bw GBPS` - the card's declared (spec sheet) memory bandwidth.
`MEASURE_BW=0` skips the measurement (a few seconds, 2 GiB of free VRAM).
- `--server-cmd-file FILE` - the server launch command; needed for the `launch` and
`env_flags` notes unless the server runs behind llama-swap.
- `--api-key KEY` or `$BETTERBENCH_API_KEY` - never stored.
- Each mandatory flag can also come from `BENCH_<NAME>` (e.g. `BENCH_SUBMITTER`).
- Results go to `results/` next to this file, or `--results-dir` / `$BENCH_RESULTS_DIR`.
Machine-local defaults can go in `bench.local.env` (sourced, not committed).
`bench.sh` first sends one warm-up request (through llama-swap the first request loads
the model, which takes minutes), then runs `collect-env.sh`, then BetterBench.
the model, which takes minutes), then the greedy check, then `collect-env.sh`, then
BetterBench while `gpu-power.sh` samples GPU power and clock.
**BetterBench on a different machine than the server:** run `./collect-env.sh --endpoint
http://localhost:PORT/v1 --model ID > env.txt` on the server and pass `--env-file env.txt`
to `bench.sh` on the client.
Each run produces `results/<timestamp>-<submitter>-<model>-<engine>-<gpu>/` with
`results.json`, `results.html`, `meta.json` and `server-cmd.txt`. See [`SUBMIT.md`](SUBMIT.md).
`results.json`, `results.html`, `meta.json`, `server-cmd.txt`, `power.csv` and
`betterbench.log`. See
[`SUBMIT.md`](SUBMIT.md).
## Recorded notes
@@ -73,15 +88,19 @@ The notes are grouped, one per topic, so the report and compare page stay readab
|---|---|
| `submitter` | `pascal` |
| `gpu` | `1x Intel Arc Pro B65 · 32 GB · driver 1.17.39395` (VRAM per GPU) |
| `pcie` | `Gen4 x16`, `Gen1 x16 now, Gen4 x16 max` (idle downclock), `Gen4 x16 (declared)` |
| `pcie` | `Gen4 x16 · ReBAR on`, `Gen1 x16 now, Gen4 x16 max · ReBAR on` (idle downclock), `Gen4 x16 (declared) · ReBAR off` |
| `power_limit` | `200 W`, or `180 W (GPU reports 200 W)` when they disagree |
| `host` | `AMD EPYC 7282 16-Core Processor · 60 GB RAM · Ubuntu 26.04.1 LTS · kernel 7.0.0-38-generic · VM kvm` |
| `engine` | `vllm 0.30.0 · via llama-swap`, `llama.cpp b11913-7aca0d2ea · 4 slots · via llama-swap` |
| `model_file` | `/models/Qwen3.8-27B-Q4_0.gguf` |
| `engine` | `vllm 0.32.0 · image lfm3-vllm-xpu:v0.32.0-lfm3-fp8fix@ad5083ed33a7 · via llama-swap`, `llama.cpp b11913-7aca0d2ea · 4 slots · image ghcr.io/ggml-org/llama.cpp:server-intel@1a2b3c4d5e6f` |
| `model_file` | `/models/Qwen3.8-27B-Q4_0.gguf · 15.60 GB` (weights as stored) |
| `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` |
| `launch` | llama.cpp: `b 4096 · ub 1024 · fa on · ctk q8_0 · ctv q8_0 · ngl 99 · np 4`; vLLM: `max-num-batched-tokens 4224 · max-num-seqs 4 · kv-cache-dtype int8_k_int4_v · ...` |
| `env_flags` | `GGML_SYCL_DISABLE_OPT=0 · ZES_ENABLE_SYSMAN=1`, `none` |
| `spec`, `thinking` | `mtp:5`, `default` |
| `run` | `full · concurrency on · bench-standard 0.2.0` |
| `greedy_check` | `identical 3/3 · 1d5105fe09dc`, `differs: 2 variants in 3 · first ...` |
| `run` | `full · concurrency on · bench-standard 0.3.0` |
| `special_notes` | only when given: free text from `--special-notes` |
The context size shows as BetterBench's own context chip. Parts that can't be detected
@@ -92,6 +111,62 @@ PCIe is the link into the slot. Cards with their own PCIe switch, like Intel Arc
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 "Gen4 x16"`.
ReBAR comes from the GPU's largest BAR: on when it's bigger than 256 MiB (roughly the
size of VRAM), off otherwise. This works inside a VM too, because passthrough keeps
the BAR sizes. The raw size is kept in `meta.json` as `gpu_bar_mib`.
**BetterBench with [#4](https://github.com/GGZ14/BetterBench/pull/4)** (Intel GPU,
PCIe and ReBAR detection; still reports version 0.6.1) also records its own probe in
`results.json` under `env.gpu` (`pci`, `xpu_smi_discovery`), and the report shows a
vendor chip such as `intel`. That probe describes the machine **BetterBench** runs
on, not necessarily the server, and inside a VM it reads the placeholder link. The
`gpu`/`pcie` notes are what counts. After the run, `bench.sh` checks that probe: it
prints a note if the probe lists a different GPU (expected with `--env-file`), and a
warning if the two disagree on ReBAR. Measurements are unaffected, but the vendor
chip makes a run with #4 show a `gpu` mismatch in `compare` against one without it.
**Launch settings.** Batch/ubatch, flash attention, KV types and env flags can swing
results by 10-50%, and no API reports them, so they are read from the launch command
(llama-swap's, or `--server-cmd-file`). Env flags are `VAR=x` prefixes, `env VAR=x`
and docker `-e VAR=x`. Settings in llama-swap's `env:` block, or set in the shell
that started the server, are invisible: put them in the command or the cmd file.
For llama.cpp, `b`, `ub`, `fa`, `ctk` and `ctv` show `default` when they aren't set,
because the defaults change between builds. Offline switches and cache paths
(`HF_HUB_OFFLINE`, `VLLM_CACHE_ROOT`, ...) are left out. `meta.json` keeps everything
parsed under `launch`. If `--kv` doesn't match the KV type the command sets,
`bench.sh` prints a warning.
**Greedy check.** Before the benchmark, the same prompt runs 3 times at temperature 0
(seed 0, 128 tokens). `identical` is expected. `differs` points to nondeterministic
kernels or batching, or a broken spec-decoding path. The hash makes the output
comparable across runs: the same model and quant should give the same hash on
another engine or card. A different hash isn't automatically wrong (kernels round
differently), but check spec decoding or a new kernel against a run without it.
**After the run** (in `meta.json` under `post_run`, printed at the end; these can't be
notes because the notes are fixed before BetterBench starts):
- `energy` - from `power.csv` (GPU power, energy counter and graphics clock every 2 s, via
`nvidia-smi` or `xpu-smi`): kJ, average/peak W, and J per output token. This
covers the **whole run** (warm-up passes and prefill included), so it is a gross
figure, comparable only between runs of the same mode. Only measured when
BetterBench runs on the server; on a split setup run `gpu-power.sh > power.csv` on
the server yourself.
Also average/min/max clock, counted only over samples where the GPU is running
(a clock-gated idle GPU reads 0 MHz).
- `roofline` - median batch-1 decode t/s × weight bytes ÷ measured `mem_bw` (else the
declared one) = % of memory
bandwidth. Valid for dense models whose stored weights are what the GPU reads.
Spec decoding and MoE can exceed 100%. A model quantized at load (e.g. vLLM
`--quantization fp8` from bf16 files) reads fewer bytes than are stored, so its
figure comes out too high.
**Why random data:** Arc compresses uniform buffers, so a test on zeros reads far too
high. On the B65 here zeros give 1627 GB/s and random data 532 GB/s, against 608
declared. A docker server's image is recorded with its ID, because tags like
llama.cpp's `server-intel` move daily. The llama.cpp build and commit are in the
`engine` note anyway (`b11913-7aca0d2ea`, from `/props`).
Engine detection: llama.cpp via `/props`, vLLM via `/version` + `/v1/models`; behind
llama-swap through `/upstream/<model>/...`, which also yields the launch command.
GPU detection: `nvidia-smi`, then `rocm-smi`, then `xpu-smi`.
+2
View File
@@ -8,6 +8,8 @@ Send the whole run directory `results/<timestamp>-<submitter>-<model>-<engine>-<
| `results.html` | the standalone report |
| `meta.json` | detected + declared setup, the exact BetterBench command |
| `server-cmd.txt` | the server launch command (from `--server-cmd-file`, or from llama-swap) |
| `power.csv` | GPU samples during the run (`epoch_s,watts,joules,mhz`), when measured |
| `betterbench.log` | BetterBench's full terminal output |
Only full runs count (`bench.sh --full`): the `run` note starts with `full`. Runs
without `--full` are quick smoke tests.
+342 -29
View File
@@ -6,7 +6,8 @@
# --thinking MODE --submitter NAME
# [--power-limit W|stock] [--api-key KEY] [--server-cmd-file FILE]
# [--env-file FILE] [--pcie GenN xW] [--special-notes TEXT]
# [--results-dir DIR] [--full] [--no-concurrency] [--dry-run]
# [--mem-bw GBPS] [--results-dir DIR] [--full] [--no-concurrency]
# [--verbose] [--dry-run]
#
# Default is a quick smoke run (BetterBench --quick); --full is the run that
# counts for submission.
@@ -17,6 +18,10 @@
# --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).
@@ -28,12 +33,13 @@ here=$(cd "$(dirname "$0")" && pwd)
[ -f "$here/bench.local.env" ] && . "$here/bench.local.env"
die() { echo "bench.sh: $*" >&2; exit 1; }
usage() { sed -n '2,22p' "$0"; exit "${1:-0}"; }
usage() { sed -n '2,27p' "$0"; exit "${1:-0}"; }
endpoint="" model="" server_cmd_file="" env_file="" quick=1 no_conc=0 dry=0
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}
need() { [ "$1" -ge 2 ] || die "$2 needs a value"; }
@@ -55,10 +61,12 @@ while [ $# -gt 0 ]; do
--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
@@ -90,6 +98,7 @@ matches "$thinking" 'off|on|low|medium|high|default' ||
[ -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
@@ -116,12 +125,47 @@ code=$(curl -s -m "${WARM_TIMEOUT:-900}" -o "$tmp/warm" -w '%{http_code}' -H @"$
-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
sh "$here/collect-env.sh" --endpoint "$endpoint" --model "$model" \
--server-cmd-out "$tmp/cmd.auto" > "$tmp/env"
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; }
@@ -140,6 +184,7 @@ fi
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 '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"
@@ -150,14 +195,34 @@ 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.
python3 - "$tmp/mandatory" "$tmp/collected" > "$tmp/notes" <<'PY'
import sys
# 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 = kv(sys.argv[1]), kv(sys.argv[2])
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
@@ -178,6 +243,8 @@ 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":
@@ -191,9 +258,120 @@ 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 = [
@@ -203,11 +381,15 @@ notes = [
("power_limit", power),
("host", host),
("engine", engine),
("model_file", g("model_file") or "unknown"),
("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"])),
]
@@ -241,29 +423,18 @@ 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'; printf ' %s' "$@"; echo
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"
# 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
if [ -n "$cmd_src" ]; then
python3 - "$tmp/cmd" "$run_dir/server-cmd.txt" <<'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
[ -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):
@@ -279,6 +450,8 @@ meta = {
"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:],
@@ -288,11 +461,151 @@ with open(sys.argv[3], "w", encoding="utf-8") as f:
f.write("\n")
PY
echo "running betterbench -> $run_dir" >&2
if ! betterbench "$@"; then
mv "$run_dir" "$run_dir.failed" 2>/dev/null || true
die "betterbench failed; partial output kept in $run_dir.failed"
# 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"
+92 -3
View File
@@ -4,15 +4,18 @@
# 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
# env: BETTERBENCH_API_KEY, PROBE_TIMEOUT (s, default 10), LOAD_TIMEOUT (s, default 600)
# --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=""
endpoint="" model="" api_key="${BETTERBENCH_API_KEY:-}" cmd_out="" cmd_file=""
PROBE_TIMEOUT=${PROBE_TIMEOUT:-10}
LOAD_TIMEOUT=${LOAD_TIMEOUT:-600}
@@ -23,7 +26,8 @@ while [ $# -gt 0 ]; do
--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 ;;
-h|--help) sed -n '2,10p' "$0"; exit 0 ;;
--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
@@ -152,6 +156,30 @@ 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)
@@ -221,6 +249,61 @@ PY
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"
@@ -230,6 +313,10 @@ 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"
@@ -239,6 +326,8 @@ 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
Executable
+43
View File
@@ -0,0 +1,43 @@
#!/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
+43
View File
@@ -0,0 +1,43 @@
"""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}")
+1 -1
View File
@@ -1,4 +1,4 @@
# 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.2.0
STANDARD_VERSION=0.3.0
BETTERBENCH_VERSION=0.6.1