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

+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