0.6.0: GPU clocks and max context
ci / check (push) Successful in 1m30s

Record the max core and memory clocks, sample the memory clock during
the run, and add a max_ctx note: vLLM's KV cache size from its log, or
for llama.cpp an estimate from free VRAM and the GGUF's KV bytes per
token (dev/gguf_kv.py).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-11-01 18:23:50 +01:00
1 parent d6cf8777be
commit a677cdcb2a
12 files changed
+527 -54

No files matched your search

+9 -6
View File
@@ -132,30 +132,33 @@ file next to `bench.sh`.
identical. Its hash lets you compare setups: the same model and quant should give
the same text everywhere. The replies also show whether the model reasoned, and
`bench.sh` warns if that contradicts your `--thinking`.
3. **Detection:** GPU, driver, power limit, PCIe link and ReBAR, CPU, RAM, OS, the
3. **Detection:** GPU, driver, max clocks, power limit, PCIe link and ReBAR, CPU, RAM, OS, the
engine and its exact build, the docker image, the model file and size, launch and
env flags. **Memory bandwidth** is measured with random data inside the server's
container. Zeros compress on Arc and read about 3× too high.
container. Zeros compress on Arc and read about 3× too high. **Max context:** the
longest context the configuration holds in memory (from vLLM's log, estimated for
llama.cpp).
4. **BetterBench:** single-stream decode per category, a prefill sweep and a
concurrency sweep. GPU power, energy and clock are sampled throughout.
concurrency sweep. GPU power, energy, core and memory clock are sampled throughout.
5. **Summary:** decode t/s, TTFT, concurrency and prefill throughput, % of memory
bandwidth reached, average power and clock, and energy: J per token for decode and
bandwidth reached, average power and clocks, and energy: J per token for decode and
each concurrency level, J per 1000 tokens for prefill.
Everything is recorded as notes in the results `.json`, so it shows in the report and in
`compare`. Example notes:
```
gpu 1x Intel Arc Pro B65 · 32 GB · driver 1.17.39395
gpu 1x Intel Arc Pro B65 · 32 GB · driver 1.17.39395 · max 2800 MHz core
pcie Gen4 x16 · ReBAR on
engine llama.cpp b11913-7aca0d2ea · 4 slots · image ghcr.io/ggml-org/llama.cpp:server-intel@1a2b3c4d5e6f
model_file /models/Qwen3.8-27B-UD-Q4_K_M.gguf · 16.46 GB · standard: Qwen3.8-27B UD-Q4_K_M
launch b 4096 · ub 1024 · fa on · ctk q8_0 · ctv q8_0 · ngl 99 · np 4
max_ctx ≈ 181k tokens est. · 33k set · 9.1 GB free · 34 KiB/token
env_flags GGML_SYCL_DISABLE_OPT=0 · ZES_ENABLE_SYSMAN=1
mem_bw 532 GB/s measured (torch copy, random, 1024 MiB) · 608 GB/s declared
greedy_check identical 3/3 · 1d5105fe09dc
thinking default · reasoning seen
run full · concurrency on · bench-standard 0.5.0 · betterbench 0.6.1
run full · concurrency on · bench-standard 0.6.0 · betterbench 0.6.1
```
## Your result
+198 -21
View File
@@ -1,5 +1,5 @@
#!/bin/sh
# bench.sh - bench-standard 0.5.0, everything in one file: run ./bench.sh --help
# bench.sh - bench-standard 0.6.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
@@ -526,7 +526,10 @@ pcie_of() {
# ---------------------------------------------------------------- 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 \
# Max clocks of the first GPU. VRAM used and total over all GPUs, read with
# the model loaded (the warm-up ran), for the max context estimate.
gpu_max_core_mhz="" gpu_max_mem_mhz="" gpu_vram_used_mib="" gpu_vram_total_mib=""
if have nvidia-smi && q=$(nvidia-smi --query-gpu=name,memory.total,driver_version,power.limit,pci.bus_id,clocks.max.gr,clocks.max.mem,memory.used \
--format=csv,noheader,nounits 2>/dev/null) && [ -n "$q" ]; then
gpu_vendor=nvidia
gpu_count=$(printf '%s\n' "$q" | grep -c .)
@@ -537,6 +540,10 @@ if have nvidia-smi && q=$(nvidia-smi --query-gpu=name,memory.total,driver_versio
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/')
gpu_max_core_mhz=$(printf '%s' "$first" | cut -d, -f6 | awk '$1+0>0 {printf "%d", $1}')
gpu_max_mem_mhz=$(printf '%s' "$first" | cut -d, -f7 | awk '$1+0>0 {printf "%d", $1}')
gpu_vram_used_mib=$(printf '%s\n' "$q" | awk -F', *' '$8+0>0 {s += $8} END {if (s) printf "%d", s}')
gpu_vram_total_mib=$(printf '%s\n' "$q" | awk -F', *' '$2+0>0 {s += $2} END {if (s) printf "%d", s}')
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
@@ -548,6 +555,8 @@ elif have rocm-smi && rocm-smi --showproductname --json > "$tmp/rp" 2>/dev/null;
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_vram_used_mib=$(jget "$tmp/rm" 'sum(int(v["VRAM Total Used Memory (B)"]) for k, v in j.items() if k.startswith("card")) >> 20')
gpu_vram_total_mib=$(jget "$tmp/rm" 'sum(int(v["VRAM Total Memory (B)"]) for k, v in j.items() if k.startswith("card")) >> 20')
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
@@ -562,7 +571,24 @@ elif have xpu-smi && xpu-smi discovery -j > "$tmp/xl" 2>/dev/null; then
# 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}')
# The memory clock key differs between xpu-smi versions: take what looks
# like one. The core clock comes from sysfs below.
gpu_max_mem_mhz=$(jget "$tmp/xd" 'next(int(float(v)) for k, v in j.items() if "mem" in k.lower() and ("clock" in k.lower() or "freq" in k.lower()) and float(v) > 0)')
gpu_vram_total_mib=$(jget "$tmp/xd" 'int(j["memory_physical_size_byte"]) >> 20')
fi
case $gpu_count in [1-9]*) [ -n "$gpu_vram_total_mib" ] && gpu_vram_total_mib=$((gpu_vram_total_mib * gpu_count)) ;; esac
gpu_vram_used_mib=$(xpu-smi dump --device -1 --metrics memory.used --number 1 2>/dev/null |
awk -F', *' 'NR>1 && $3+0>0 {s += $3} END {if (s) printf "%d", s}')
fi
# The driver knows the hardware's max core clock: xe and i915 directly,
# amdgpu as its DPM levels (pp_dpm_*), which also list the memory clock.
if [ -n "$gpu_bdf" ]; then
dev=/sys/bus/pci/devices/$gpu_bdf
[ -n "$gpu_max_core_mhz" ] || gpu_max_core_mhz=$(cat "$dev"/tile0/gt0/freq0/rp0_freq \
"$dev"/drm/card*/gt_RP0_freq_mhz 2>/dev/null | awk '$1+0>0 {print $1+0; exit}')
dpm_max() { sed -n 's/^[0-9]*: *\([0-9]*\)[Mm][Hh]z.*/\1/p' "$1" 2>/dev/null | sort -n | tail -n1; }
[ -n "$gpu_max_core_mhz" ] || gpu_max_core_mhz=$(dpm_max "$dev/pp_dpm_sclk")
[ -n "$gpu_max_mem_mhz" ] || gpu_max_mem_mhz=$(dpm_max "$dev/pp_dpm_mclk")
fi
[ -n "$gpu_count" ] || gpu_count=unknown
@@ -695,9 +721,21 @@ fi
# vLLM logs what the weights take in GPU memory, per worker. That beats the
# stored size when it quantizes at load (fp8 from bf16 files reads half).
model_loaded_gib=""
# It also logs how many tokens its KV cache holds: the max context this
# configuration fits, over all requests together.
model_loaded_gib="" kv_cache_tokens=""
if [ "$engine" = vllm ] && [ -n "$container" ] && have docker; then
model_loaded_gib=$(docker logs "$container" 2>&1 | sed -n 's/.*Model loading took \([0-9.]*\) GiB.*/\1/p' | tail -n1)
docker logs "$container" > "$tmp/log" 2>&1
model_loaded_gib=$(sed -n 's/.*Model loading took \([0-9.]*\) GiB.*/\1/p' "$tmp/log" | tail -n1)
kv_cache_tokens=$(sed -n 's/.*GPU KV cache size: \([0-9,]*\) tokens.*/\1/p' "$tmp/log" | tail -n1 | tr -d ,)
fi
# llama.cpp allocates the KV cache for -c up front, so the max context is
# estimated: what's set, plus free VRAM over the KV bytes per token. The
# elements per token come from the GGUF header (notes.py applies -ctk/-ctv).
kv_elems_per_token=""
if [ "$engine" = llama.cpp ] && [ -f "$model_file" ] && have python3; then
kv_elems_per_token=$(python3 "$(cd "$(dirname "$0")" && pwd)/gguf_kv.py" "$model_file" 2>/dev/null)
fi
# The model's SHA256, checked against the standard models (README, Models).
@@ -746,6 +784,10 @@ 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 gpu_max_core_mhz "$gpu_max_core_mhz"
kv gpu_max_mem_mhz "$gpu_max_mem_mhz"
kv gpu_vram_used_mib "$gpu_vram_used_mib"
kv gpu_vram_total_mib "$gpu_vram_total_mib"
kv pcie_link "$pcie_link"
kv pcie_max "$pcie_max"
kv gpu_bar_mib "$gpu_bar_mib"
@@ -767,17 +809,20 @@ kv model_bytes "$model_bytes"
kv model_loaded_gib "$model_loaded_gib"
kv model_sha256 "$model_sha256"
kv ctx "$ctx"
kv kv_cache_tokens "$kv_cache_tokens"
kv kv_elems_per_token "$kv_elems_per_token"
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
# energy counter and the core and memory clocks of all GPUs until killed, one
# CSV line per sample:
# epoch_s,watts,joules,mhz,mem_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.
# mhz and mem_mhz are the mean graphics and memory clocks over the GPUs
# (mem_mhz empty where the tool doesn't report it).
# Prints nothing at all when no supported tool is found (nvidia-smi, xpu-smi).
#
# usage: gpu-power.sh [INTERVAL_S] (default 2)
@@ -790,18 +835,23 @@ 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 \
nvidia-smi --query-gpu=power.draw,total_energy_consumption,clocks.gr,clocks.mem \
--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}'
awk -F', *' '{w += $1; if ($2 + 0 > 0) j += $2 / 1000; else nj = 1; c += $3; m += $4}
END {if (NR) printf "%.2f,%s,%.0f,%.0f\n", w, nj ? "" : sprintf("%.3f", j), c / NR, m / NR}'
}
elif command -v xpu-smi >/dev/null 2>&1; then
# one call takes about a second
# One call takes about a second. Not every xpu-smi has the memory clock,
# and an unknown metric fails the whole call: try it once, else go without.
metrics=power.draw,energy.consumed,clocks.current.graphics
xpu-smi dump --device -1 --metrics "$metrics,clocks.current.memory" --number 1 2>/dev/null |
awk -F', *' 'NR > 1 && $6 + 0 > 0 {ok = 1} END {exit !ok}' && metrics="$metrics,clocks.current.memory"
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}'
xpu-smi dump --device -1 --metrics "$metrics" --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
if ($6 + 0 > 0) m += $6; else nm = 1}
END {if (n) printf "%.2f,%s,%.0f,%s\n", w, nj ? "" : sprintf("%.3f", j), c / n,
nm ? "" : sprintf("%.0f", m / n)}'
}
else
exit 0
@@ -814,6 +864,98 @@ while :; do
sleep "$interval"
done
__BENCH_STANDARD_EOF__
cat > "$d/gguf_kv.py" <<'__BENCH_STANDARD_EOF__'
"""gguf_kv.py - KV cache elements per token of a GGUF model, from its header.
usage: gguf_kv.py FILE (the first part of a split GGUF; prints nothing on failure)
Prints "K V SWA_K SWA_V": the K and V elements one token of context adds over
the layers whose cache grows with the context, and the same for sliding-window
layers, whose cache llama.cpp keeps at the window size (unless --swa-full).
Recurrent layers (Mamba, linear attention) keep a fixed state and count for
nothing. Bytes are elements x the size of the -ctk / -ctv type.
"""
import struct
import sys
# Sliding-window layouts llama.cpp sets in code when the GGUF doesn't say.
SWA_PATTERN = {"gemma2": 2, "gemma3": 6, "cohere2": 4, "gpt-oss": 2, "exaone4": 4}
SCALAR = {0: "B", 1: "b", 2: "H", 3: "h", 4: "I", 5: "i", 6: "f", 7: "?", 10: "Q", 11: "q", 12: "d"}
def read_meta(path):
"""The key/value header, without the tensor infos. Big arrays (the
tokenizer) are skipped, short ones kept."""
with open(path, "rb") as f:
def unpack(fmt):
fmt = "<" + fmt
return struct.unpack(fmt, f.read(struct.calcsize(fmt)))[0]
def string():
return f.read(unpack("Q")).decode("utf-8", "replace")
def value(t):
if t in SCALAR:
return unpack(SCALAR[t])
if t == 8:
return string()
if t == 9:
it, n = unpack("I"), unpack("Q")
if it in SCALAR and n > 4096:
f.seek(n * struct.calcsize("<" + SCALAR[it]), 1)
return None
items = [value(it) for _ in range(n)]
return items if n <= 4096 else None
raise ValueError(f"GGUF value type {t}")
if f.read(4) != b"GGUF" or unpack("I") < 2:
raise ValueError("not a GGUF v2+ file")
unpack("Q")
meta = {}
for _ in range(unpack("Q")):
k = string()
meta[k] = value(unpack("I"))
return meta
def kv_elems(meta):
arch = meta["general.architecture"]
a = lambda k, d=None: meta.get(f"{arch}.{k}", d)
n_layer = a("block_count")
per_layer = lambda v: v if isinstance(v, list) else [v] * n_layer
n_head = per_layer(a("attention.head_count"))
n_kv = per_layer(a("attention.head_count_kv", a("attention.head_count")))
embd = a("embedding_length")
k_len = a("attention.key_length") or embd // max(n_head)
v_len = a("attention.value_length") or embd // max(n_head)
if a("attention.kv_lora_rank") and not a("attention.key_length_mla"):
# older MLA files (DeepSeek): one latent head of rank + rope dims
rank = a("attention.kv_lora_rank")
n_kv, k_len, v_len = [1] * n_layer, rank + a("rope.dimension_count", 0), rank
interval = a("full_attention_interval")
swa = [False] * n_layer
if a("attention.sliding_window"):
pat = a("attention.sliding_window_pattern", SWA_PATTERN.get(arch))
if isinstance(pat, list):
swa = [bool(x) for x in pat]
elif pat:
swa = [il % pat < pat - 1 for il in range(n_layer)]
full, window = [0, 0], [0, 0]
for il in range(n_layer):
if not n_kv[il] or interval and (il + 1) % interval:
continue
d = window if swa[il] else full
d[0] += n_kv[il] * k_len
d[1] += n_kv[il] * v_len
return full + window
if __name__ == "__main__":
try:
print(*kv_elems(read_meta(sys.argv[1])))
except Exception:
pass
__BENCH_STANDARD_EOF__
cat > "$d/mem-bw.py" <<'__BENCH_STANDARD_EOF__'
"""mem-bw.py - measured GPU memory bandwidth with torch, printed as "GBPS MIB".
@@ -966,7 +1108,9 @@ 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"))
g("gpu_driver") and "driver " + g("gpu_driver"),
g("gpu_max_core_mhz") and "max " + g("gpu_max_core_mhz") + " MHz core",
g("gpu_max_mem_mhz") and g("gpu_max_mem_mhz") + " MHz mem")
link, top = g("pcie_link"), g("pcie_max")
if m.get("pcie"):
@@ -1106,6 +1250,30 @@ model_file = join(g("model_file"), mb and f"{int(mb) / 1e9:.2f} GB", check)
mem_bw = join(g("gpu_mem_bw_gbs") and
f'{g("gpu_mem_bw_gbs")} GB/s measured ({g("gpu_mem_bw_tool") or "?"})',
m.get("mem_bw") and m["mem_bw"] + " GB/s declared")
# The longest context this configuration holds. vLLM logs its KV cache in
# tokens. llama.cpp allocates the cache for -c up front, so estimate: what's
# set, plus the VRAM still free over the KV bytes per token of -ctk/-ctv.
# Sliding-window layers keep a fixed cache unless --swa-full.
KV_BYTES = {"f32": 4, "f16": 2, "bf16": 2, "q8_0": 34 / 32, "q5_1": 24 / 32, "q5_0": 22 / 32,
"q4_1": 20 / 32, "q4_0": 18 / 32, "iq4_nl": 18 / 32}
def kilo(n):
return f"{n / 1000:.0f}k" if n >= 10000 else f"{n:,}"
ctx = int(g("ctx")) if g("ctx").isdigit() else None
max_ctx = None
if g("kv_cache_tokens").isdigit():
max_ctx = join(kilo(int(g("kv_cache_tokens"))) + " tokens (engine KV cache)", ctx and kilo(ctx) + " set")
elif g("kv_elems_per_token") and ctx and g("gpu_vram_used_mib").isdigit() and g("gpu_vram_total_mib").isdigit():
ek, ev, sk, sv = (int(x) for x in g("kv_elems_per_token").split())
if "--swa-full" in flags:
ek, ev = ek + sk, ev + sv
bk = KV_BYTES.get(str(settings.get("ctk", "f16")).replace("default", "f16"))
bv = KV_BYTES.get(str(settings.get("ctv", "f16")).replace("default", "f16"))
free = (int(g("gpu_vram_total_mib")) - int(g("gpu_vram_used_mib"))) * 2**20
if bk and bv and ek + ev:
per = ek * bk + ev * bv
max_ctx = join("≈ " + kilo(ctx + int(max(free, 0) / per)) + " tokens est.", kilo(ctx) + " set",
f"{free / 1e9:.1f} GB free", f"{per / 1024:.0f} KiB/token")
if meas.get("greedy_check") == "identical":
greedy = f'identical {meas["greedy_runs"]}/{meas["greedy_runs"]} · {meas["greedy_hash"]}'
elif meas.get("greedy_check") == "differs":
@@ -1149,6 +1317,7 @@ notes = [
("mem_bw", mem_bw),
("parallel", f"tp {m['tp']} · pp {m['pp']}"),
("precision", f"weights {m['quant']} · kv {m['kv']}"),
("max_ctx", max_ctx),
("launch", launch),
("env_flags", env_flags),
("spec", m["spec"]),
@@ -1160,7 +1329,8 @@ notes = [
if m.get("special_notes"):
notes.append(("special_notes", m["special_notes"]))
for k, v in notes:
print(f"{k}={v}")
if v:
print(f"{k}={v}")
__BENCH_STANDARD_EOF__
cat > "$d/postrun.py" <<'__BENCH_STANDARD_EOF__'
"""postrun.py - figures that need the finished run, and the summary.
@@ -1168,7 +1338,7 @@ cat > "$d/postrun.py" <<'__BENCH_STANDARD_EOF__'
usage: T0=epoch T1=epoch postrun.py RUN_DIR [RESULTS_JSON]
Reads RESULTS_JSON (default RUN_DIR/results.json), and meta.json, power.csv
(epoch_s,watts,joules,mhz) and timeline.tsv (epoch<TAB>BetterBench progress
(epoch_s,watts,joules,mhz[,mem_mhz]) and timeline.tsv (epoch<TAB>BetterBench progress
line) from RUN_DIR. Writes
energy (whole run and per phase) and the bandwidth figure to meta.json under
"post_run", and prints the summary to stderr.
@@ -1188,7 +1358,8 @@ def read_power(path):
p = line.strip().split(",")
try:
rows.append((float(p[0]), float(p[1]), float(p[2]) if p[2] else None,
float(p[3]) if len(p) > 3 and p[3] else 0.0))
float(p[3]) if len(p) > 3 and p[3] else 0.0,
float(p[4]) if len(p) > 4 and p[4] else 0.0))
except (ValueError, IndexError):
pass
return rows
@@ -1347,6 +1518,10 @@ def main(d, results=None):
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)}")
mem = [r[4] for r in rows if r[4] > 0]
if mem:
e.update(avg_mem_mhz=round(statistics.mean(mem)), min_mem_mhz=round(min(mem)),
max_mem_mhz=round(max(mem)))
if timeline:
e["phases"] = phase_energy(res, rows, timeline, t1)
post["energy"] = e
@@ -1384,6 +1559,8 @@ def main(d, results=None):
e = post["energy"]
clock = (f" · clock avg {e['avg_mhz']} MHz ({e['min_mhz']}-{e['max_mhz']})"
if "avg_mhz" in e else "")
if "avg_mem_mhz" in e:
clock += f" · mem {e['avg_mem_mhz']} MHz ({e['min_mem_mhz']}-{e['max_mem_mhz']})"
L.append(f" power avg {e['avg_w']} W, peak {e['peak_w']:.0f} W{clock}")
ph = e.get("phases") or {}
parts = []
@@ -1443,7 +1620,7 @@ __BENCH_STANDARD_EOF__
cat > "$d/standard.env" <<'__BENCH_STANDARD_EOF__'
# Pins for this version of the group standard. Bump STANDARD_VERSION whenever
# config.json, the minimum BetterBench or the mandatory fields change.
STANDARD_VERSION=0.5.0
STANDARD_VERSION=0.6.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
+22 -6
View File
@@ -9,7 +9,7 @@ What `bench.sh` records, how, and how it's built. For running it, see
can take minutes.
2. **Greedy check:** the same prompt 3 times at temperature 0.
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.
4. BetterBench runs while `gpu-power.sh` (also `bench.sh power`) samples power, energy and the core and memory clocks every 2 s.
5. A summary prints. Energy and % of bandwidth are written to `meta.json`.
## Files in a run folder
@@ -24,7 +24,7 @@ with `N` = tp × pp; see the README.
| `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 |
| `power.csv` | `epoch_s,watts,joules,mhz,mem_mhz` during the run |
| `timeline.tsv` | when each BetterBench progress line appeared, for the energy per phase |
| `betterbench.log` | BetterBench's full output |
@@ -36,7 +36,7 @@ can't be detected is left out or shows `unknown`.
| note | example |
|---|---|
| `submitter` | `pascal` |
| `gpu` | `1x Intel Arc Pro B65 · 32 GB · driver 1.17.39395` (VRAM per GPU) |
| `gpu` | `1x Intel Arc Pro B65 · 32 GB · driver 1.17.39395 · max 2800 MHz core · 19000 MHz mem` (VRAM per GPU, max clocks of the first) |
| `pcie` | `Gen4 x16 · ReBAR on`, `Gen1 x16 now, Gen4 x16 max · ReBAR on`, `unknown (VM) · ReBAR on` |
| `power_limit` | `200 W`, or `180 W (GPU reports 200 W)` |
| `host` | `AMD EPYC 7282 16-Core Processor · 60 GB RAM · Ubuntu 26.04.1 LTS · kernel 7.0.0-38-generic · VM kvm` |
@@ -45,12 +45,13 @@ can't be detected is left out or shows `unknown`.
| `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` |
| `max_ctx` | `412k tokens (engine KV cache) · 262k set` (vLLM), `≈ 181k tokens est. · 32k set · 9.1 GB free · 64 KiB/token` (llama.cpp) |
| `launch` | `b 4096 · ub 1024 · fa on · ctk q8_0 · ctv q8_0 · ngl 99 · np 4` |
| `env_flags` | `GGML_SYCL_DISABLE_OPT=0 · ZES_ENABLE_SYSMAN=1`, or `none` |
| `spec` | `mtp:5`, `none` |
| `thinking` | `default · reasoning seen`, `off · no reasoning seen` (declared · observed) |
| `greedy_check` | `identical 3/3 · 1d5105fe09dc`, `differs: 2 variants in 3 · first ...` |
| `run` | `full · concurrency on · bench-standard 0.5.0 · betterbench 0.6.1`, or `... · betterbench 0.6.1 @ v0.6.1-3-gabc1234-dirty` for a build that isn't the release |
| `run` | `full · concurrency on · bench-standard 0.6.0 · betterbench 0.6.1`, or `... · betterbench 0.6.1 @ v0.6.1-3-gabc1234-dirty` for a build that isn't the release |
| `special_notes` | only when given |
The context size appears as BetterBench's own chip.
@@ -59,6 +60,21 @@ The context size appears as BetterBench's own chip.
**GPU:** `nvidia-smi`, then `rocm-smi`, then `xpu-smi`.
**Clocks:** the max core and memory clocks come from `nvidia-smi` (`clocks.max.*`), the
driver's sysfs (xe/i915 `RP0`, amdgpu `pp_dpm_sclk`/`pp_dpm_mclk`) or `xpu-smi discovery`.
The run samples the current ones. `xpu-smi` versions without a memory clock metric leave
`mem_mhz` empty, and the rest of the sampling still works.
**Max context** is the longest context this configuration holds in memory. vLLM logs its
KV cache size in tokens ("GPU KV cache size: N tokens"), shared by all requests running at
once. llama.cpp allocates the cache for `-c` when it loads, so this is an estimate: `-c`
plus the VRAM still free (read after the warm-up, over all GPUs) over the KV bytes per
token. Those come from the GGUF header and `-ctk`/`-ctv`: only layers whose cache grows
with the context count. Recurrent layers (Mamba, linear attention) don't, and neither do
sliding-window layers unless `--swa-full` is set. Compute buffers grow a little with the
context too, so treat it as an upper bound. The note is left out when the model file
can't be read on this machine.
**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
`bench.sh collect-env` on the hypervisor, or pass `--pcie`.
@@ -113,7 +129,7 @@ These go to `meta.json` under `post_run` and the summary, not to the notes, whic
fixed before BetterBench starts.
- **energy:** kJ, average and peak W, J per output token over the whole run, and
average, min and max clock. The clock counts only samples where the GPU is running.
average, min and max core and memory clock. The clock counts only samples where the GPU is running.
Power is sampled only when BetterBench runs on the server. On a split setup, run
`bench.sh power > power.csv` on the server yourself.
- **energy per phase** (`energy.phases`): each BetterBench progress line is stamped in
@@ -141,7 +157,7 @@ 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`, `model_hash.py`,
`dev/bench.sh`, `collect-env.sh`, `gpu-power.sh`, `gguf_kv.py`, `mem-bw.py`, `model_hash.py`,
`notes.py`, `postrun.py`, `models.tsv`, `config.json` and `standard.env` into it. At run time it unpacks them to a temp dir and runs
`dev/bench.sh` from there, with `BENCH_HOME` set to its own folder, so `results/`
and `bench.local.env` stay next to the downloaded file.
+1 -1
View File
@@ -9,7 +9,7 @@
set -eu
dev=$(cd "$(dirname "$0")" && pwd)
out="$dev/../bench.sh"
files="bench.sh collect-env.sh gpu-power.sh mem-bw.py model_hash.py notes.py postrun.py models.tsv config.json standard.env"
files="bench.sh collect-env.sh gpu-power.sh gguf_kv.py mem-bw.py model_hash.py notes.py postrun.py models.tsv config.json standard.env"
eof=__BENCH_STANDARD_EOF__
. "$dev/standard.env"
+47 -3
View File
@@ -109,7 +109,10 @@ pcie_of() {
# ---------------------------------------------------------------- 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 \
# Max clocks of the first GPU. VRAM used and total over all GPUs, read with
# the model loaded (the warm-up ran), for the max context estimate.
gpu_max_core_mhz="" gpu_max_mem_mhz="" gpu_vram_used_mib="" gpu_vram_total_mib=""
if have nvidia-smi && q=$(nvidia-smi --query-gpu=name,memory.total,driver_version,power.limit,pci.bus_id,clocks.max.gr,clocks.max.mem,memory.used \
--format=csv,noheader,nounits 2>/dev/null) && [ -n "$q" ]; then
gpu_vendor=nvidia
gpu_count=$(printf '%s\n' "$q" | grep -c .)
@@ -120,6 +123,10 @@ if have nvidia-smi && q=$(nvidia-smi --query-gpu=name,memory.total,driver_versio
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/')
gpu_max_core_mhz=$(printf '%s' "$first" | cut -d, -f6 | awk '$1+0>0 {printf "%d", $1}')
gpu_max_mem_mhz=$(printf '%s' "$first" | cut -d, -f7 | awk '$1+0>0 {printf "%d", $1}')
gpu_vram_used_mib=$(printf '%s\n' "$q" | awk -F', *' '$8+0>0 {s += $8} END {if (s) printf "%d", s}')
gpu_vram_total_mib=$(printf '%s\n' "$q" | awk -F', *' '$2+0>0 {s += $2} END {if (s) printf "%d", s}')
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
@@ -131,6 +138,8 @@ elif have rocm-smi && rocm-smi --showproductname --json > "$tmp/rp" 2>/dev/null;
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_vram_used_mib=$(jget "$tmp/rm" 'sum(int(v["VRAM Total Used Memory (B)"]) for k, v in j.items() if k.startswith("card")) >> 20')
gpu_vram_total_mib=$(jget "$tmp/rm" 'sum(int(v["VRAM Total Memory (B)"]) for k, v in j.items() if k.startswith("card")) >> 20')
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
@@ -145,7 +154,24 @@ elif have xpu-smi && xpu-smi discovery -j > "$tmp/xl" 2>/dev/null; then
# 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}')
# The memory clock key differs between xpu-smi versions: take what looks
# like one. The core clock comes from sysfs below.
gpu_max_mem_mhz=$(jget "$tmp/xd" 'next(int(float(v)) for k, v in j.items() if "mem" in k.lower() and ("clock" in k.lower() or "freq" in k.lower()) and float(v) > 0)')
gpu_vram_total_mib=$(jget "$tmp/xd" 'int(j["memory_physical_size_byte"]) >> 20')
fi
case $gpu_count in [1-9]*) [ -n "$gpu_vram_total_mib" ] && gpu_vram_total_mib=$((gpu_vram_total_mib * gpu_count)) ;; esac
gpu_vram_used_mib=$(xpu-smi dump --device -1 --metrics memory.used --number 1 2>/dev/null |
awk -F', *' 'NR>1 && $3+0>0 {s += $3} END {if (s) printf "%d", s}')
fi
# The driver knows the hardware's max core clock: xe and i915 directly,
# amdgpu as its DPM levels (pp_dpm_*), which also list the memory clock.
if [ -n "$gpu_bdf" ]; then
dev=/sys/bus/pci/devices/$gpu_bdf
[ -n "$gpu_max_core_mhz" ] || gpu_max_core_mhz=$(cat "$dev"/tile0/gt0/freq0/rp0_freq \
"$dev"/drm/card*/gt_RP0_freq_mhz 2>/dev/null | awk '$1+0>0 {print $1+0; exit}')
dpm_max() { sed -n 's/^[0-9]*: *\([0-9]*\)[Mm][Hh]z.*/\1/p' "$1" 2>/dev/null | sort -n | tail -n1; }
[ -n "$gpu_max_core_mhz" ] || gpu_max_core_mhz=$(dpm_max "$dev/pp_dpm_sclk")
[ -n "$gpu_max_mem_mhz" ] || gpu_max_mem_mhz=$(dpm_max "$dev/pp_dpm_mclk")
fi
[ -n "$gpu_count" ] || gpu_count=unknown
@@ -278,9 +304,21 @@ fi
# vLLM logs what the weights take in GPU memory, per worker. That beats the
# stored size when it quantizes at load (fp8 from bf16 files reads half).
model_loaded_gib=""
# It also logs how many tokens its KV cache holds: the max context this
# configuration fits, over all requests together.
model_loaded_gib="" kv_cache_tokens=""
if [ "$engine" = vllm ] && [ -n "$container" ] && have docker; then
model_loaded_gib=$(docker logs "$container" 2>&1 | sed -n 's/.*Model loading took \([0-9.]*\) GiB.*/\1/p' | tail -n1)
docker logs "$container" > "$tmp/log" 2>&1
model_loaded_gib=$(sed -n 's/.*Model loading took \([0-9.]*\) GiB.*/\1/p' "$tmp/log" | tail -n1)
kv_cache_tokens=$(sed -n 's/.*GPU KV cache size: \([0-9,]*\) tokens.*/\1/p' "$tmp/log" | tail -n1 | tr -d ,)
fi
# llama.cpp allocates the KV cache for -c up front, so the max context is
# estimated: what's set, plus free VRAM over the KV bytes per token. The
# elements per token come from the GGUF header (notes.py applies -ctk/-ctv).
kv_elems_per_token=""
if [ "$engine" = llama.cpp ] && [ -f "$model_file" ] && have python3; then
kv_elems_per_token=$(python3 "$(cd "$(dirname "$0")" && pwd)/gguf_kv.py" "$model_file" 2>/dev/null)
fi
# The model's SHA256, checked against the standard models (README, Models).
@@ -329,6 +367,10 @@ 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 gpu_max_core_mhz "$gpu_max_core_mhz"
kv gpu_max_mem_mhz "$gpu_max_mem_mhz"
kv gpu_vram_used_mib "$gpu_vram_used_mib"
kv gpu_vram_total_mib "$gpu_vram_total_mib"
kv pcie_link "$pcie_link"
kv pcie_max "$pcie_max"
kv gpu_bar_mib "$gpu_bar_mib"
@@ -350,4 +392,6 @@ kv model_bytes "$model_bytes"
kv model_loaded_gib "$model_loaded_gib"
kv model_sha256 "$model_sha256"
kv ctx "$ctx"
kv kv_cache_tokens "$kv_cache_tokens"
kv kv_elems_per_token "$kv_elems_per_token"
exit 0
+90
View File
@@ -0,0 +1,90 @@
"""gguf_kv.py - KV cache elements per token of a GGUF model, from its header.
usage: gguf_kv.py FILE (the first part of a split GGUF; prints nothing on failure)
Prints "K V SWA_K SWA_V": the K and V elements one token of context adds over
the layers whose cache grows with the context, and the same for sliding-window
layers, whose cache llama.cpp keeps at the window size (unless --swa-full).
Recurrent layers (Mamba, linear attention) keep a fixed state and count for
nothing. Bytes are elements x the size of the -ctk / -ctv type.
"""
import struct
import sys
# Sliding-window layouts llama.cpp sets in code when the GGUF doesn't say.
SWA_PATTERN = {"gemma2": 2, "gemma3": 6, "cohere2": 4, "gpt-oss": 2, "exaone4": 4}
SCALAR = {0: "B", 1: "b", 2: "H", 3: "h", 4: "I", 5: "i", 6: "f", 7: "?", 10: "Q", 11: "q", 12: "d"}
def read_meta(path):
"""The key/value header, without the tensor infos. Big arrays (the
tokenizer) are skipped, short ones kept."""
with open(path, "rb") as f:
def unpack(fmt):
fmt = "<" + fmt
return struct.unpack(fmt, f.read(struct.calcsize(fmt)))[0]
def string():
return f.read(unpack("Q")).decode("utf-8", "replace")
def value(t):
if t in SCALAR:
return unpack(SCALAR[t])
if t == 8:
return string()
if t == 9:
it, n = unpack("I"), unpack("Q")
if it in SCALAR and n > 4096:
f.seek(n * struct.calcsize("<" + SCALAR[it]), 1)
return None
items = [value(it) for _ in range(n)]
return items if n <= 4096 else None
raise ValueError(f"GGUF value type {t}")
if f.read(4) != b"GGUF" or unpack("I") < 2:
raise ValueError("not a GGUF v2+ file")
unpack("Q")
meta = {}
for _ in range(unpack("Q")):
k = string()
meta[k] = value(unpack("I"))
return meta
def kv_elems(meta):
arch = meta["general.architecture"]
a = lambda k, d=None: meta.get(f"{arch}.{k}", d)
n_layer = a("block_count")
per_layer = lambda v: v if isinstance(v, list) else [v] * n_layer
n_head = per_layer(a("attention.head_count"))
n_kv = per_layer(a("attention.head_count_kv", a("attention.head_count")))
embd = a("embedding_length")
k_len = a("attention.key_length") or embd // max(n_head)
v_len = a("attention.value_length") or embd // max(n_head)
if a("attention.kv_lora_rank") and not a("attention.key_length_mla"):
# older MLA files (DeepSeek): one latent head of rank + rope dims
rank = a("attention.kv_lora_rank")
n_kv, k_len, v_len = [1] * n_layer, rank + a("rope.dimension_count", 0), rank
interval = a("full_attention_interval")
swa = [False] * n_layer
if a("attention.sliding_window"):
pat = a("attention.sliding_window_pattern", SWA_PATTERN.get(arch))
if isinstance(pat, list):
swa = [bool(x) for x in pat]
elif pat:
swa = [il % pat < pat - 1 for il in range(n_layer)]
full, window = [0, 0], [0, 0]
for il in range(n_layer):
if not n_kv[il] or interval and (il + 1) % interval:
continue
d = window if swa[il] else full
d[0] += n_kv[il] * k_len
d[1] += n_kv[il] * v_len
return full + window
if __name__ == "__main__":
try:
print(*kv_elems(read_meta(sys.argv[1])))
except Exception:
pass
+18 -12
View File
@@ -1,11 +1,12 @@
#!/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
# energy counter and the core and memory clocks of all GPUs until killed, one
# CSV line per sample:
# epoch_s,watts,joules,mhz,mem_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.
# mhz and mem_mhz are the mean graphics and memory clocks over the GPUs
# (mem_mhz empty where the tool doesn't report it).
# Prints nothing at all when no supported tool is found (nvidia-smi, xpu-smi).
#
# usage: gpu-power.sh [INTERVAL_S] (default 2)
@@ -18,18 +19,23 @@ 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 \
nvidia-smi --query-gpu=power.draw,total_energy_consumption,clocks.gr,clocks.mem \
--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}'
awk -F', *' '{w += $1; if ($2 + 0 > 0) j += $2 / 1000; else nj = 1; c += $3; m += $4}
END {if (NR) printf "%.2f,%s,%.0f,%.0f\n", w, nj ? "" : sprintf("%.3f", j), c / NR, m / NR}'
}
elif command -v xpu-smi >/dev/null 2>&1; then
# one call takes about a second
# One call takes about a second. Not every xpu-smi has the memory clock,
# and an unknown metric fails the whole call: try it once, else go without.
metrics=power.draw,energy.consumed,clocks.current.graphics
xpu-smi dump --device -1 --metrics "$metrics,clocks.current.memory" --number 1 2>/dev/null |
awk -F', *' 'NR > 1 && $6 + 0 > 0 {ok = 1} END {exit !ok}' && metrics="$metrics,clocks.current.memory"
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}'
xpu-smi dump --device -1 --metrics "$metrics" --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
if ($6 + 0 > 0) m += $6; else nm = 1}
END {if (n) printf "%.2f,%s,%.0f,%s\n", w, nj ? "" : sprintf("%.3f", j), c / n,
nm ? "" : sprintf("%.0f", m / n)}'
}
else
exit 0
+30 -2
View File
@@ -25,7 +25,9 @@ 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"))
g("gpu_driver") and "driver " + g("gpu_driver"),
g("gpu_max_core_mhz") and "max " + g("gpu_max_core_mhz") + " MHz core",
g("gpu_max_mem_mhz") and g("gpu_max_mem_mhz") + " MHz mem")
link, top = g("pcie_link"), g("pcie_max")
if m.get("pcie"):
@@ -165,6 +167,30 @@ model_file = join(g("model_file"), mb and f"{int(mb) / 1e9:.2f} GB", check)
mem_bw = join(g("gpu_mem_bw_gbs") and
f'{g("gpu_mem_bw_gbs")} GB/s measured ({g("gpu_mem_bw_tool") or "?"})',
m.get("mem_bw") and m["mem_bw"] + " GB/s declared")
# The longest context this configuration holds. vLLM logs its KV cache in
# tokens. llama.cpp allocates the cache for -c up front, so estimate: what's
# set, plus the VRAM still free over the KV bytes per token of -ctk/-ctv.
# Sliding-window layers keep a fixed cache unless --swa-full.
KV_BYTES = {"f32": 4, "f16": 2, "bf16": 2, "q8_0": 34 / 32, "q5_1": 24 / 32, "q5_0": 22 / 32,
"q4_1": 20 / 32, "q4_0": 18 / 32, "iq4_nl": 18 / 32}
def kilo(n):
return f"{n / 1000:.0f}k" if n >= 10000 else f"{n:,}"
ctx = int(g("ctx")) if g("ctx").isdigit() else None
max_ctx = None
if g("kv_cache_tokens").isdigit():
max_ctx = join(kilo(int(g("kv_cache_tokens"))) + " tokens (engine KV cache)", ctx and kilo(ctx) + " set")
elif g("kv_elems_per_token") and ctx and g("gpu_vram_used_mib").isdigit() and g("gpu_vram_total_mib").isdigit():
ek, ev, sk, sv = (int(x) for x in g("kv_elems_per_token").split())
if "--swa-full" in flags:
ek, ev = ek + sk, ev + sv
bk = KV_BYTES.get(str(settings.get("ctk", "f16")).replace("default", "f16"))
bv = KV_BYTES.get(str(settings.get("ctv", "f16")).replace("default", "f16"))
free = (int(g("gpu_vram_total_mib")) - int(g("gpu_vram_used_mib"))) * 2**20
if bk and bv and ek + ev:
per = ek * bk + ev * bv
max_ctx = join("≈ " + kilo(ctx + int(max(free, 0) / per)) + " tokens est.", kilo(ctx) + " set",
f"{free / 1e9:.1f} GB free", f"{per / 1024:.0f} KiB/token")
if meas.get("greedy_check") == "identical":
greedy = f'identical {meas["greedy_runs"]}/{meas["greedy_runs"]} · {meas["greedy_hash"]}'
elif meas.get("greedy_check") == "differs":
@@ -208,6 +234,7 @@ notes = [
("mem_bw", mem_bw),
("parallel", f"tp {m['tp']} · pp {m['pp']}"),
("precision", f"weights {m['quant']} · kv {m['kv']}"),
("max_ctx", max_ctx),
("launch", launch),
("env_flags", env_flags),
("spec", m["spec"]),
@@ -219,4 +246,5 @@ notes = [
if m.get("special_notes"):
notes.append(("special_notes", m["special_notes"]))
for k, v in notes:
print(f"{k}={v}")
if v:
print(f"{k}={v}")
+9 -2
View File
@@ -3,7 +3,7 @@
usage: T0=epoch T1=epoch postrun.py RUN_DIR [RESULTS_JSON]
Reads RESULTS_JSON (default RUN_DIR/results.json), and meta.json, power.csv
(epoch_s,watts,joules,mhz) and timeline.tsv (epoch<TAB>BetterBench progress
(epoch_s,watts,joules,mhz[,mem_mhz]) and timeline.tsv (epoch<TAB>BetterBench progress
line) from RUN_DIR. Writes
energy (whole run and per phase) and the bandwidth figure to meta.json under
"post_run", and prints the summary to stderr.
@@ -23,7 +23,8 @@ def read_power(path):
p = line.strip().split(",")
try:
rows.append((float(p[0]), float(p[1]), float(p[2]) if p[2] else None,
float(p[3]) if len(p) > 3 and p[3] else 0.0))
float(p[3]) if len(p) > 3 and p[3] else 0.0,
float(p[4]) if len(p) > 4 and p[4] else 0.0))
except (ValueError, IndexError):
pass
return rows
@@ -182,6 +183,10 @@ def main(d, results=None):
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)}")
mem = [r[4] for r in rows if r[4] > 0]
if mem:
e.update(avg_mem_mhz=round(statistics.mean(mem)), min_mem_mhz=round(min(mem)),
max_mem_mhz=round(max(mem)))
if timeline:
e["phases"] = phase_energy(res, rows, timeline, t1)
post["energy"] = e
@@ -219,6 +224,8 @@ def main(d, results=None):
e = post["energy"]
clock = (f" · clock avg {e['avg_mhz']} MHz ({e['min_mhz']}-{e['max_mhz']})"
if "avg_mhz" in e else "")
if "avg_mem_mhz" in e:
clock += f" · mem {e['avg_mem_mhz']} MHz ({e['min_mem_mhz']}-{e['max_mem_mhz']})"
L.append(f" power avg {e['avg_w']} W, peak {e['peak_w']:.0f} W{clock}")
ph = e.get("phases") or {}
parts = []
+1 -1
View File
@@ -1,6 +1,6 @@
# Pins for this version of the group standard. Bump STANDARD_VERSION whenever
# config.json, the minimum BetterBench or the mandatory fields change.
STANDARD_VERSION=0.5.0
STANDARD_VERSION=0.6.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
+73
View File
@@ -0,0 +1,73 @@
"""gguf_kv.py: the header reader and the KV elements per token."""
import os
import struct
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import gguf_kv # noqa: E402
def write_gguf(path, meta):
def s(x):
b = x.encode()
return struct.pack("<Q", len(b)) + b
def val(v):
if isinstance(v, bool):
return struct.pack("<I?", 7, v)
if isinstance(v, int):
return struct.pack("<II", 4, v)
if isinstance(v, str):
return struct.pack("<I", 8) + s(v)
if isinstance(v, list) and v and isinstance(v[0], str):
return struct.pack("<IIQ", 9, 8, len(v)) + b"".join(s(x) for x in v)
if isinstance(v, list) and v and isinstance(v[0], bool):
return struct.pack("<IIQ", 9, 7, len(v)) + b"".join(struct.pack("<?", x) for x in v)
return struct.pack("<IIQ", 9, 4, len(v)) + b"".join(struct.pack("<I", x) for x in v)
body = b"".join(s(k) + val(v) for k, v in meta.items())
path.write_bytes(b"GGUF" + struct.pack("<IQQ", 3, 0, len(meta)) + body)
return str(path)
def test_dense(tmp_path):
p = write_gguf(tmp_path / "m.gguf", {
"general.architecture": "llama", "llama.block_count": 32, "llama.embedding_length": 4096,
"llama.attention.head_count": 32, "llama.attention.head_count_kv": 8,
"tokenizer.ggml.tokens": ["a"] * 5000}) # a big array is skipped
assert gguf_kv.kv_elems(gguf_kv.read_meta(p)) == [32 * 8 * 128, 32 * 8 * 128, 0, 0]
def test_hybrid_counts_only_attention_layers(tmp_path):
# qwen3next-style: every 4th layer is full attention, the rest linear
p = write_gguf(tmp_path / "m.gguf", {
"general.architecture": "qwen3next", "qwen3next.block_count": 8,
"qwen3next.embedding_length": 2048, "qwen3next.attention.head_count": 16,
"qwen3next.attention.head_count_kv": 2, "qwen3next.attention.key_length": 256,
"qwen3next.attention.value_length": 256, "qwen3next.full_attention_interval": 4})
assert gguf_kv.kv_elems(gguf_kv.read_meta(p)) == [2 * 2 * 256, 2 * 2 * 256, 0, 0]
# per-layer KV heads with 0 for recurrent layers (lfm2, granite hybrid, ...)
p = write_gguf(tmp_path / "h.gguf", {
"general.architecture": "lfm2", "lfm2.block_count": 4, "lfm2.embedding_length": 1024,
"lfm2.attention.head_count": 16, "lfm2.attention.head_count_kv": [0, 8, 0, 8]})
assert gguf_kv.kv_elems(gguf_kv.read_meta(p)) == [2 * 8 * 64, 2 * 8 * 64, 0, 0]
def test_sliding_window_split(tmp_path):
# gemma3: 5 of 6 layers are sliding-window (pattern set in code)
p = write_gguf(tmp_path / "m.gguf", {
"general.architecture": "gemma3", "gemma3.block_count": 12, "gemma3.embedding_length": 2560,
"gemma3.attention.head_count": 8, "gemma3.attention.head_count_kv": 4,
"gemma3.attention.key_length": 256, "gemma3.attention.value_length": 256,
"gemma3.attention.sliding_window": 1024})
assert gguf_kv.kv_elems(gguf_kv.read_meta(p)) == [2 * 4 * 256, 2 * 4 * 256, 10 * 4 * 256, 10 * 4 * 256]
def test_not_gguf(tmp_path):
(tmp_path / "x").write_bytes(b"nope")
try:
gguf_kv.read_meta(str(tmp_path / "x"))
except ValueError:
pass
else:
raise AssertionError
+29
View File
@@ -104,3 +104,32 @@ def test_run_note_betterbench_build(tmp_path):
assert notes["run"] == "full · concurrency on · bench-standard 0.4.1 · betterbench 0.6.1"
notes, _, _ = run(tmp_path, m={"betterbench_build": "v0.6.1-3-gabc1234-dirty"})
assert notes["run"].endswith("betterbench 0.6.1 @ v0.6.1-3-gabc1234-dirty")
def test_gpu_note_clocks(tmp_path):
notes, _, _ = run(tmp_path, c={"gpu_vram_gb": "32", "gpu_max_core_mhz": "2800",
"gpu_max_mem_mhz": "19000"})
assert notes["gpu"] == "1x Intel Arc Pro B65 · 32 GB · max 2800 MHz core · 19000 MHz mem"
def test_max_ctx_vllm_from_engine_log(tmp_path):
notes, _, _ = run(tmp_path, cmd=VLLM_CMD, m={"kv": "int8_k_int4_v"},
c={"engine": "vllm", "ctx": "262144", "kv_cache_tokens": "412416"})
assert notes["max_ctx"] == "412k tokens (engine KV cache) · 262k set"
def test_max_ctx_llama_estimate(tmp_path):
# 4 GiB free; q8_0 K and V, 16384 elements each per token = 34816 bytes
c = {"ctx": "32768", "kv_elems_per_token": "16384 16384 8192 8192",
"gpu_vram_total_mib": "32768", "gpu_vram_used_mib": "28672"}
notes, _, _ = run(tmp_path, c=c)
est = 32768 + 4 * 2**30 // 34816
assert notes["max_ctx"] == f"≈ {est / 1000:.0f}k tokens est. · 33k set · 4.3 GB free · 34 KiB/token"
# --swa-full keeps the sliding-window layers at full size too
notes, _, _ = run(tmp_path, cmd=LLAMA_CMD + " --swa-full", c=c)
assert notes["max_ctx"].endswith("51 KiB/token")
def test_max_ctx_left_out_without_data(tmp_path):
notes, _, _ = run(tmp_path)
assert "max_ctx" not in notes