diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index 515c3b3..0000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,17 +0,0 @@ -name: ci -on: [push, pull_request] -jobs: - check: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: "3.10" - - run: pip install pytest shellcheck-py - - name: shellcheck - run: shellcheck -s sh -S warning dev/*.sh bench.sh - - name: bench.sh is built from dev/ - run: sh dev/build.sh --check - - name: tests - run: pytest -q dev/tests diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..dfe5103 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,17 @@ +name: test +on: [push, pull_request] +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: bench.sh is built from dev/ + run: sh dev/build.sh --check + - name: shellcheck + run: shellcheck -s sh -S warning bench.sh dev/*.sh + - name: end-to-end tests (dash) + run: sh dev/test.sh + - name: end-to-end tests (bash as sh) + run: | + mkdir -p "$RUNNER_TEMP/bashsh" && ln -s "$(command -v bash)" "$RUNNER_TEMP/bashsh/sh" + PATH="$RUNNER_TEMP/bashsh:$PATH" bash dev/test.sh diff --git a/AGENTS.md b/AGENTS.md index 2622124..fac362c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,32 +10,87 @@ one makes the run fail. Correct is more important than fast. ## Rules +- **Ask in the three rounds below**, not one question at a time: round 1 before you + start, round 2 after detecting, round 3 before `--full`. A round is one batch, + asked before you do anything else, never spread across turns. Number the questions, + and fill in what you already know as a default they only have to confirm. "Don't + know, find it" is always a valid answer. + - **With a question tool** (e.g. `ask_user_question` in Pi, `AskUserQuestion` in + Claude Code), use it for each round. If a round has more questions than one call + allows, split it into consecutive calls of the tool's maximum, in the original + order, and keep the numbers: with 4 per call, round 1 is 1-4, 5-8, 9-10. Make the + bracketed default the first option, marked as recommended. Leave the free-text + answer ("Other") open for anything that needs typing: a name, a URL, a launch + command, watts. A free-text question (1, 3, 5) has no real choices, so give it the + default and "find it" as options. + - **Without one,** ask in one numbered message, answered as `1: pascal, 2: yes, ...`. + - **Round 2's table is always a plain message**, so it stays readable. Only its + confirmation ("ok", or correct line N) may go through the tool. - **Run benchmarks only through `./bench.sh`.** Never call `betterbench run` directly, and never add BetterBench flags. `bench.sh` refuses them. - **Don't edit `bench.sh`** to make a run pass. If it seems wrong, tell your human. - **Never edit anything in a results folder.** -- **Never guess a declared value silently.** Derive it from the launch command (step 4), - show your human what you derived, and ask when the command doesn't say. - `--submitter` always comes from the human. -- **Ask before `--full`.** It takes much longer than the quick run, and the GPU is busy - the whole time. +- **Never guess a declared value silently.** Derive it from the launch command, show + it in round 2, and ask when the command doesn't say. `--submitter` always comes from + the human. +- **Ask before `--full`** (round 3). It takes much longer than the quick run, and the + GPU is busy the whole time. - **Don't restart, reconfigure or stop the inference server** without asking. Don't start other GPU work while a benchmark runs. -- **API keys** go in `$BETTERBENCH_API_KEY`, never into files or commands that get saved. +- **API keys** go in `$BETTERBENCH_API_KEY`, never into files, saved commands or the + chat. Ask your human to set it themselves in the shell you use. ## Models Results only count for the files in the [README's model table](README.md#models). -`bench.sh` hashes the served file during the dry run and warns on a non-standard file -or a wrong `--quant`. The `model_file` note then says `standard: ...` or -`not a standard model`. On a mismatch, tell your human before benchmarking. If it says -`hash not checked` (the path from the launch command doesn't exist on this machine, -e.g. inside a container), check by hand with the commands below the table. -`--quant` for each model is in that table. +`bench.sh` hashes the served file when it can find it on this machine (the `model_file` +note in the dry run shows `sha256 ... (standard: NAME)`), and warns when it isn't a +standard model or `--quant` doesn't match. When the note has no hash (BetterBench on +another machine, weights it can't locate), check the SHA256 yourself with the commands +below the table. On a mismatch, tell your human before benchmarking. `--quant` for each +model is in that table. ## Procedure -### 1. Check the tools +### 1. Round 1: the setup questions + +Ask these as one batch before running anything: with a question tool, in calls of its +maximum (1-4, 5-8, 9-10 with 4 per call); without one, in one message like this. Put the +default in brackets. + +```text +Before I start, a few questions. Answer by number; "find it" is fine for any of them. + +1. Your name for the results (--submitter): +2. Is this the machine with the GPU and the inference server? [yes] +3. The server's address [http://localhost:8080/v1]: +4. Does the server need an API key? [no] + If yes, don't paste it here: run export BETTERBENCH_API_KEY=... in the + terminal I work in, and tell me when it's set. +5. How was the server started? llama-swap / docker / a script / a command. + Paste the command or the script's path if you have it [find it]: +6. Which model from the README table is loaded? [find it] +7. How many GPUs does the server use? [1] +8. Is the GPU power limit changed from stock? [stock / watts / don't know] +9. Anything unusual? A VM, undervolt, custom kernels, a patched engine [no] +10. May I install BetterBench if it's missing? [yes; I'll ask before upgrading one] +``` + +If `bench.local.env` exists next to `bench.sh` (your human saved values with +`./bench.sh init`), read it first and put its values in as the defaults. It never holds +the API key, so it's safe to read. Still ask every question; a saved value can be stale. + +What the answers mean: +- **2 = no:** BetterBench runs elsewhere. Use `--env-file` ([below](#when-something-goes-wrong)). +- **4 = yes:** wait until they say it's set. Check with `[ -n "$BETTERBENCH_API_KEY" ]`, + never by printing it. +- **5:** a pasted command goes into `server-cmd.txt` exactly as given (step 3). +- **7 > 1 with llama.cpp:** ask how the model is split (`-sm`, `-ts`) for `--tp`/`--pp`. +- **8:** watts → `--power-limit W`. `stock` or "don't know" → let `bench.sh` read it. +- **9:** a VM → ask for the PCIe link if they know it (`--pcie "Gen4 x16"`). + Anything else → `--special-notes "..."`. + +### 2. Check the tools ```sh ./bench.sh --version # bench-standard version and the BetterBench it needs @@ -43,10 +98,12 @@ betterbench --version # 0.6.1 or newer python3 --version # 3.10+ ``` -If something is missing, install it as the README's quick start shows. If an older one is installed, ask -before upgrading it. +If something is missing, install it as the README's quick start shows (if answer 10 +allows it). If an older one is installed, ask before upgrading it. -### 2. Find the endpoint and the model id +### 3. Find the endpoint, the model id and the launch command + +Start from the answers to 3, 5 and 6, and verify them: ```sh curl -s http://localhost:8080/v1/models # ids the server accepts @@ -54,22 +111,22 @@ curl -s http://localhost:8080/running # llama-swap only: loaded models + l ``` `--endpoint` is the base URL ending in `/v1`. `--model` is the id exactly as listed. +Nothing answers: look for listening ports (`ss -ltnp`) and containers (`docker ps`). -### 3. Get the launch command - +The launch command: - **Behind llama-swap** (`/running` answers): nothing to do, `bench.sh` reads it. - **Otherwise:** write the exact command the server was started with into `server-cmd.txt`, including `VAR=value` env prefixes and docker `-e` flags. Pass it - with `--server-cmd-file server-cmd.txt`. Get the command from your human, a launch - script, `docker inspect`, or `ps -o args= -p PID`. + with `--server-cmd-file server-cmd.txt`. Get it from answer 5, a launch script, + `docker inspect`, or `ps -o args= -p PID`. Env vars set in llama-swap's `env:` block + or in the shell that started the server aren't in any of these: ask. Without it, the `launch` and `env_flags` notes read `unknown`, and those settings swing results by 10-50%. ### 4. Derive the declared values -`--quant` comes from the README's model table. For the rest, use the launch command and confirm -with your human: +`--quant` comes from the README's model table. The rest comes from the launch command: | flag | llama.cpp | vLLM | |---|---|---| @@ -77,7 +134,7 @@ with your human: | `--tp` / `--pp` | `1` / `1` on one GPU; multi-GPU: ask | `--tensor-parallel-size` / `--pipeline-parallel-size`; default `1` | | `--spec` | `-md`/`--model-draft` with `--draft-max N` → `draft:N`; otherwise `none` | `--speculative-config` method and `num_speculative_tokens` → e.g. `mtp:5`, `eagle3:4`, `ngram:4`; otherwise `none` | | `--thinking` | `--reasoning-budget 0` or `enable_thinking: false` in the template kwargs → `off`; unclear → ask | `enable_thinking`/effort in the chat template or default kwargs; nothing set → `default`; unclear → ask | -| `--submitter` | ask | ask | +| `--submitter` | answer 1 | answer 1 | ### 5. Dry run @@ -87,23 +144,68 @@ with your human: ``` This sends the warm-up and the greedy check, detects everything, prints what it would -run, and stops. Check the `--note` values in that output: -- `unknown` values should have a reason (VM PCIe, no cmd file, ...). -- Any `bench.sh: warning:` line needs fixing or explaining before the real run. +run, and stops. `bench.sh` checks `--kv`, `--spec`, `--thinking` (and `--tp`/`--pp` for +vLLM) against the launch command and the model file against the README's table, and +lists every warning at the end. -### 6. Quick run, then full run +### 6. Round 2: confirm the values + +Show your human one table with every declared value, where it came from, and what the +dry run found, then ask them to confirm or correct it: + +```text +Here is what I'll declare. Reply "ok", or correct a line by number. + + # flag value from + 1 --endpoint http://localhost:8080/v1 your answer, /v1/models answers + 2 --model qwen3.5-9b /v1/models + 3 --quant Q4_K_M README table; hash matches Qwen3.5-9B-Q4_K_M.gguf + 4 --kv q8_0/f16 -ctk q8_0, no -ctv (V defaults to f16) + 5 --tp / --pp 1 / 1 one GPU + 6 --spec none no -md in the launch command + 7 --thinking default nothing in the command; greedy replies show reasoning + 8 --submitter pascal your answer + 9 --power-limit (detected) GPU reports 250 W + 10 launch b 4096 · ub 1024 · fa on · ... server-cmd.txt + +Warnings from the dry run: + - ... (each one, with what you think it means) + +Notes that read unknown, and why: + - ... +``` + +Every `bench.sh: warning:` needs fixing or an explanation before the real run. For +`--X A but the launch command sets ...: declare --X B`, don't just switch to B: show it +here and let your human decide. Rerun the dry run after any change. + +Once the values are confirmed, offer to save them, so the next run needs no typing: +`./bench.sh init` writes `bench.local.env` (it refuses to overwrite one), then fill in +the confirmed values. Ask before changing an existing file. After that the run is +just `./bench.sh` plus `--dry-run` or `--full`. + +### 7. Quick run Run the same command without `--dry-run`. This is a quick check of a few minutes, -ending in a summary. If it looks sane, ask your human, then run again with `--full`. -That is the result that counts. For long runs, use a terminal multiplexer or a -background job, so a dropped session doesn't kill the benchmark. +ending in a summary (also saved as `summary.txt` in the result folder). -### 7. Report back +### 8. Round 3: before the full run + +```text +The quick run finished: decode X t/s, TTFT Y ms, N warnings (listed below). + +1. Start the --full run now? It takes much longer and keeps the GPU busy. [yes] +2. Run it in tmux/screen or in the background, so a dropped session doesn't stop it? [yes] +3. Is anything else using the GPU right now that should be stopped first? [no] +``` + +### 9. Report back Tell your human: - the result folder (printed after `done:`) -- the summary block: decode t/s, TTFT, concurrency, prefill, bandwidth %, power, energy per phase -- every warning, and whether the greedy check was `identical` +- the summary block: decode t/s, TTFT, concurrency, prefill, bandwidth %, power, energy +- every warning (listed at the end of the summary), and whether the greedy check was + `identical` - that the folder is what they send in, and that they should check `server-cmd.txt` for anything private first (tokens, keys and passwords are already redacted) @@ -111,18 +213,20 @@ Tell your human: | message | what to do | |---|---| -| `BetterBench 0.6.1 or newer required` | install or upgrade BetterBench (step 1) | -| `warm-up request failed (HTTP ...)` | server not up, or wrong `--endpoint`/`--model` (step 2). Behind llama-swap the first load can take minutes; `WARM_TIMEOUT=1800` gives it longer | +| `BetterBench 0.6.1 or newer required` | install or upgrade BetterBench (step 2) | +| `warm-up request failed (HTTP ...)` | server not up, or wrong `--endpoint`/`--model` (step 3). HTTP 401/403: the server needs an API key (round 1, question 4). Behind llama-swap the first load can take minutes; `WARM_TIMEOUT=1800` gives it longer | | `missing mandatory value(s)` | pass the listed flags (step 4) | | `GPU power limit not detected here` | ask for the limit, pass `--power-limit W` or `stock` | -| `the model file is not one of the standard models` | the server serves a different file. Tell your human; results with it won't count | -| `--quant X, but the file is the standard ...` | declare the `--quant` the warning names | -| `--kv X but the launch command sets Y` | the declared `--kv` is wrong. Use what the command sets | +| `--X A but the launch command sets ...: declare --X B` | the declared value contradicts the launch command. Confirm with your human (round 2), then use B | +| `not one of the standard models` | the served file's hash isn't in the README's table: wrong file or quant. Tell your human | +| `--quant X but the model file is NAME` | use the `--quant` the table lists for that file | +| `greedy check failed (...)` | the server rejected or timed out the temperature-0 requests; read the error | | `greedy_check=differs` | not a failure, but report it. It means nondeterministic kernels or a broken spec-decoding path | | `--thinking X, but the greedy replies ...` | the declared thinking mode doesn't match what the server does. Ask your human which is right; never change the server yourself | | `mem_bw` has no measured figure | no torch in the server container. Set `BW_PYTHON` to a python with GPU torch, or install `clpeak`, or leave it | | `launch=unknown (pass --server-cmd-file)` | step 3 | | `betterbench failed (exit N)` | read `betterbench.log` in the `.failed` folder. Usually the server crashed or ran out of memory | +| `interrupted; partial output in ....interrupted` | the run was stopped (Ctrl-C, kill, dropped session). It doesn't count; run again | | `ReBAR ... but BetterBench reads ...` | BetterBench runs on another machine than the GPU. Use `--env-file` (below) | **BetterBench on another machine than the GPU:** run diff --git a/README.md b/README.md index 0285d85..0ca2ea7 100644 --- a/README.md +++ b/README.md @@ -15,14 +15,25 @@ machine with your GPU: Help me benchmark my LLM server with bench-standard. Read these two files first: https://raw.githubusercontent.com/aneinander/benchmarks/main/AGENTS.md https://raw.githubusercontent.com/aneinander/benchmarks/main/README.md -Then follow AGENTS.md step by step: install what's missing, find my server and model, -check the model hash, work out the values to declare from my server's launch command, -and do a dry run and a quick run. Ask me for anything you can't find out yourself, -and ask me before the --full run. +Then follow AGENTS.md step by step. Start with its round 1 questions, all in one +numbered message, before you run anything. Install what's missing, find my server and +model, check the model hash, work out the values to declare from my server's launch +command, and do a dry run. Show me the round 2 table of values to confirm, then do a +quick run, and ask me the round 3 questions before the --full run. ``` The agent follows [`AGENTS.md`](AGENTS.md), a step-by-step procedure with rules that keep -the result valid. Without an agent, do it yourself as described below. +the result valid. It asks you three rounds of numbered questions with defaults already +filled in, so you mostly confirm: + +1. **Before it starts:** your name, the server's address, whether it needs an API key + (you set that yourself, it never goes in the chat), how the server was started, the + model, the number of GPUs, the power limit, anything unusual. +2. **After the dry run:** a table of every value it will declare and where each came + from, plus every warning. +3. **Before the full run:** whether to start it, and in tmux or the background. + +Without an agent, do it yourself as described below. ## Quick start @@ -34,15 +45,62 @@ curl -O https://raw.githubusercontent.com/aneinander/benchmarks/main/bench.sh && ``` Serve one of the [models](#models) with any OpenAI-compatible server (llama.cpp, vLLM, -...), then: +...). Then copy this into a text editor, fill in the top part, and paste it into the +terminal in the folder with `bench.sh`. [What you declare](#what-you-declare) explains +how to read each value off your server's launch command. ```sh -./bench.sh --endpoint http://localhost:8080/v1 --model MODEL_ID \ - --tp 1 --pp 1 --quant Q4_K_M --kv f16 --spec none --thinking default \ - --submitter YOUR_NAME --server-cmd-file server-cmd.txt +# ─── fill these in ────────────────────────────────────────────────────────── +SUBMITTER=your-name # you +ENDPOINT=http://localhost:8080/v1 # the server's base URL, ending in /v1 +MODEL=MODEL_ID # the id exactly as `curl $ENDPOINT/models` lists it +QUANT=Q4_K_M # from the model table: Q4_K_M, UD-Q4_K_M or w4a16 +KV=f16 # KV cache type: f16, q8_0, q8_0/f16 (K/V), bf16, fp8 +TP=1 # tensor parallel size (1 on one GPU) +PP=1 # pipeline parallel size (1 on one GPU) +SPEC=none # speculative decoding: none, mtp:5, draft:8, ... +THINKING=default # set on the server: default, off, on, low, medium, high +SERVER_CMD=server-cmd.txt # file with the command that started the server; + # leave empty behind llama-swap +# export BETTERBENCH_API_KEY=... # only if the server needs a key; never saved +# ─── then run (add --full for the run that counts) ────────────────────────── +./bench.sh --submitter "$SUBMITTER" --endpoint "$ENDPOINT" --model "$MODEL" \ + --quant "$QUANT" --kv "$KV" --tp "$TP" --pp "$PP" --spec "$SPEC" --thinking "$THINKING" \ + ${SERVER_CMD:+--server-cmd-file "$SERVER_CMD"} ``` -That's a **quick check** of a few minutes. If the summary at the end looks right, +Add `--dry-run` first to see what it detects and every warning without running the +benchmark. To write the launch command into `server-cmd.txt`, paste it into the file +exactly as you typed it, env vars and docker `-e` flags included, or for a running +process: + +```sh +ps -o args= -p "$(pgrep -f 'llama-server|vllm' | head -n1)" > server-cmd.txt +``` + +### Save your values + +So you don't fill these in every time, save them once: + +```sh +./bench.sh init # writes bench.local.env next to bench.sh, every value explained +nano bench.local.env # fill in the empty ones +./bench.sh --dry-run # then just this; --full for the run that counts +``` + +`bench.local.env` holds one `BENCH_...=value` per line (`BENCH_SUBMITTER`, +`BENCH_ENDPOINT`, `BENCH_MODEL`, `BENCH_SERVER_CMD_FILE`, `BENCH_QUANT`, `BENCH_KV`, +`BENCH_TP`, `BENCH_PP`, `BENCH_SPEC`, `BENCH_THINKING`, and optional ones like +`BENCH_POWER_LIMIT`). It's read as plain values, never run as a script. Relative paths +in it are relative to the file. A flag on the command line wins over an environment +variable, which wins over the file. Every run prints which values came from the file. +For a second server or model, keep a second file and pass `--settings other.env`. +The API key never goes in it: `bench.sh` refuses `BETTERBENCH_API_KEY` there. Export +it in your shell. + +### The run + +Without `--full`, that's a **quick check** of a few minutes. If the summary at the end looks right, run the same command with `--full`. That's the result that counts. It takes much longer and keeps the GPU busy the whole time. @@ -50,10 +108,8 @@ longer and keeps the GPU busy the whole time. ## Models -Results only count for these files: a different file is a different benchmark. -`bench.sh` hashes the served file and warns when it isn't one of these, or when -`--quant` doesn't match. The first run takes about a minute for a big file, then the -hash is cached. To check by hand before downloading everything into place: +Results only count for these files. Check the hash before you benchmark: a +different file is a different benchmark. | model | engine | Hugging Face repo | file | `--quant` | |---|---|---|---|---| @@ -77,6 +133,11 @@ cd MODEL_DIR && sha256sum *.safetensors | LC_ALL=C sort -k2 | sha256sum # a rep For a repo, the hash is over the per-file hashes in name order. Keep `LC_ALL=C`: other locales sort the files differently and give a different hash. +`bench.sh` does this for you when it finds the weights on the machine (also through +docker `-v` mounts and the Hugging Face cache). It records the hash in the `model_file` +note and warns when the file isn't in this table or `--quant` doesn't match. The hash is +cached, so only the first run spends time on it; `HASH_MODEL=0` skips it. + - The RedHatAI checkpoints are int4 weights with 16-bit activations (compressed-tensors). They include an MTP head, so `--spec mtp:N` works. - The 27B GGUF repo has no plain Q4_K_M, only Unsloth's dynamic `UD-Q4_K_M`. @@ -101,6 +162,9 @@ can be read off the command you started the server with: `off`, `on`, `low`, `medium`, `high` and `default`. BetterBench can't switch thinking on or off per request, so it has to be set in the server's chat template or launch flags. +`bench.sh` checks `--kv`, `--spec`, `--thinking` and, for vLLM, `--tp`/`--pp` against the +launch command, and warns with the value the command implies. + **`--server-cmd-file`** is a text file with the exact command that started your server, including env vars (`VAR=x ...`, docker `-e VAR=x`). It's how batch sizes, flash attention and env flags get recorded, and those swing results by 10-50%. Behind @@ -121,9 +185,9 @@ llama-swap you can leave it out, because the command is read automatically. | `--no-concurrency` | skip the concurrency sweep | | `--results-dir DIR` | where run folders go (default `results/` next to `bench.sh`) | -The declared values can also come from the environment (`BENCH_SUBMITTER=pascal`, -`BENCH_QUANT=...`, ...). Machine-local defaults like these go in a `bench.local.env` -file next to `bench.sh`. +| `--settings FILE` | read saved values from FILE instead of `bench.local.env` | + +Every value can also be saved, see [Save your values](#save-your-values). ## What a run does @@ -132,56 +196,46 @@ 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, 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. **Max context:** the - longest context the configuration holds in memory (from vLLM's log, estimated for - llama.cpp). +3. **Detection:** GPU, driver, power limit, PCIe link and ReBAR, CPU, RAM, OS, the + engine and its exact build, the docker image, the model file, its size and hash, + 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. 4. **BetterBench:** single-stream decode per category, a prefill sweep and a - concurrency sweep. GPU power, energy, core and memory clock are sampled throughout. + concurrency sweep. GPU power, energy and clock are sampled throughout. 5. **Summary:** decode t/s, TTFT, concurrency and prefill throughput, % of memory - bandwidth reached, average power and clocks, and energy: J per token for decode and - each concurrency level, J per 1000 tokens for prefill. + bandwidth reached, average power and clock, J per token, and every warning again. -Everything is recorded as notes in the results `.json`, so it shows in the report and in +Ctrl-C or a `kill` stops the run at once; the folder is renamed `.interrupted` and +doesn't count. + +Everything is recorded as notes in `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 · max 2800 MHz core +gpu 1x Intel Arc Pro B65 · 32 GB · driver 1.17.39395 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 +model_file /models/Qwen3.5-9B-Q4_K_M.gguf · 5.68 GB · sha256 03b74727a860 (standard: Qwen3.5-9B-Q4_K_M.gguf) 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.6.0 · betterbench 0.6.1 +run full · concurrency on · bench-standard 0.5.0 · betterbench 0.6.1 ``` ## Your result -Each run makes a folder `results//`, and the report and results inside it carry the -same name, so they still say what they are when sent on their own: - -```text -____x-[_quick][_2] -261029_pascal_qwen3.5-9b_llama.cpp_1x-intel-arc-pro-b65 -``` - -`N` is the number of GPUs the model runs on (`--tp` × `--pp`). Fields are separated by -`_`, words within a field by `-`. Quick runs end in `_quick`. Another run of the same -setup on the same day gets `_2`, `_3`, ... +Each run makes a folder `results/----/`: | file | what | |---|---| -| `.html` | the report; open it in a browser | -| `.json` | the results, with all notes | -| `meta.json` | every raw value, plus energy and % of bandwidth | +| `results.html` | the report; open it in a browser | +| `results.json` | the results, with all notes | +| `meta.json` | every raw value, plus energy, % of bandwidth and the warnings | +| `summary.txt` | the summary printed at the end | | `server-cmd.txt` | your server's launch command, secrets redacted | -| `config.json`, `power.csv`, `timeline.tsv`, `betterbench.log` | the config used, power samples, when each phase ran, the full output | +| `config.json`, `power.csv`, `betterbench.log` | the config used, power samples, the full output | **Send the whole folder of a `--full` run.** Check `server-cmd.txt` for anything private first. Tokens, keys and passwords are redacted automatically. @@ -189,7 +243,7 @@ first. Tokens, keys and passwords are redacted automatically. Compare two runs: ```sh -betterbench compare A/A.json B/B.json +betterbench compare A/results.json B/results.json ``` Every recorded difference shows up as a mismatch chip, so you can see exactly what @@ -215,13 +269,14 @@ during the benchmark if you want it. | `warm-up request failed` | is the server up? Are `--endpoint` and `--model` right? `curl URL/models` lists the ids. For a slow first load, try `WARM_TIMEOUT=1800` | | `missing mandatory value(s)` | pass the listed flags | | `GPU power limit not detected` | pass `--power-limit W` (or `stock`) | -| `the model file is not one of the standard models` | you're serving a different file. Download the one from the [table](#models) | -| `--quant X, but the file is the standard ...` | declare the `--quant` the warning names | -| `--kv X but the launch command sets Y` | your `--kv` is wrong; use what the command sets | +| `--X A but the launch command sets ...: declare --X B` | the declared value contradicts the server's launch command; check it and use B | +| `not one of the standard models` | the served file's hash isn't in the [table](#models): wrong file or quant | +| `greedy check failed` | the temperature-0 requests failed; the error is in the message | | `greedy_check=differs` | not fatal. Kernels or spec decoding aren't deterministic; mention it | | `--thinking off, but the greedy replies contain reasoning` | thinking is still on in the server's chat template or flags. Fix the server, or declare what it does | | `launch=unknown` | pass `--server-cmd-file` | | `betterbench failed` | see `betterbench.log` in the `.failed` folder, usually a server crash or OOM | +| `interrupted` | the run was stopped; the `.interrupted` folder doesn't count, run again | ## Rules @@ -232,8 +287,8 @@ during the benchmark if you want it. ## Developing `bench.sh` is generated: the sources are in [`dev/`](dev/), and `sh dev/build.sh` packs -them into the one file. Commit `dev/` and the rebuilt `bench.sh` together. CI runs -shellcheck, checks that `bench.sh` is up to date, and runs `pytest dev/tests`. +them into the one file. Commit `dev/` and the rebuilt `bench.sh` together. `sh dev/test.sh` +runs the end-to-end tests against a fake server and a fake BetterBench, no GPU needed. Bugs and ideas: open an issue on [GitHub](https://github.com/aneinander/benchmarks/issues). The GitHub repo is a mirror, updated automatically from the maintainers' source repo. diff --git a/bench.sh b/bench.sh index c29ad96..c55a6a8 100755 --- a/bench.sh +++ b/bench.sh @@ -1,5 +1,5 @@ #!/bin/sh -# bench.sh - bench-standard 0.6.0, everything in one file: run ./bench.sh --help +# bench.sh - bench-standard 0.5.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 @@ -43,16 +43,22 @@ cat > "$d/bench.sh" <<'__BENCH_STANDARD_EOF__' # --results-dir DIR default: results/ next to bench.sh # --env-file FILE when BetterBench runs on another machine than the GPU: # the output of 'bench.sh collect-env' run on the GPU box +# --settings FILE your saved values (default: bench.local.env next to +# bench.sh, if it exists) # # Other commands: +# bench.sh init [FILE] write a settings file to fill in once, so you +# don't type the values every time # bench.sh collect-env --endpoint URL --model ID print the detected setup # bench.sh power [SECONDS] sample GPU power, energy and clock until killed # bench.sh --version # -# Values can also come from the environment: BENCH_TP, BENCH_PP, BENCH_QUANT, -# BENCH_KV, BENCH_SPEC, BENCH_THINKING, BENCH_SUBMITTER, BENCH_POWER_LIMIT, -# BENCH_PCIE, BENCH_MEM_BW, BENCH_SPECIAL_NOTES, BENCH_RESULTS_DIR. Machine- -# local defaults like these go in bench.local.env next to bench.sh. +# Saved values: bench.local.env (see 'bench.sh init') or the environment, as +# BENCH_SUBMITTER, BENCH_ENDPOINT, BENCH_MODEL, BENCH_SERVER_CMD_FILE, +# BENCH_TP, BENCH_PP, BENCH_QUANT, BENCH_KV, BENCH_SPEC, BENCH_THINKING, +# BENCH_POWER_LIMIT, BENCH_PCIE, BENCH_MEM_BW, BENCH_SPECIAL_NOTES, +# BENCH_RESULTS_DIR, BENCH_ENV_FILE. Flags win over the environment, which +# wins over the file. # Send the whole results// folder. Only --full runs count. # The standard models and their hashes: README.md. For agents: AGENTS.md. @@ -63,19 +69,130 @@ umask 002 here=$(cd "$(dirname "$0")" && pwd) home=${BENCH_HOME:-$here} . "$here/standard.env" -# Machine-local defaults (e.g. BENCH_RESULTS_DIR), not part of the standard. -[ -f "$home/bench.local.env" ] && . "$home/bench.local.env" die() { echo "bench.sh: $*" >&2; exit 1; } usage() { sed -n '2,/^$/p' "$0" | sed -e 's/^# \{0,1\}//' -e '$d'; exit "${1:-0}"; } +# Cleanup and signals. Long steps run in the background with `wait`, which a +# trapped signal interrupts at once (a foreground child would delay the trap +# until it finished). Background jobs ignore Ctrl-C, so the trap stops them. +# The one-file bench.sh hands its unpacked helpers over in BENCH_UNPACKED and +# exec's this script, so a kill of that pid lands here. +tmp="" child="" sampler="" run_dir_made="" +cleanup() { + for p in $child $sampler; do kill "$p" 2>/dev/null || true; done + [ -z "$tmp" ] || rm -rf "$tmp" + [ "${BENCH_UNPACKED:-}" != "$here" ] || rm -rf "$here" +} +on_signal() { + trap - INT TERM + for p in $child; do kill "$p" 2>/dev/null || true; wait "$p" 2>/dev/null || true; done + child="" + if [ -n "$run_dir_made" ] && [ -d "$run_dir_made" ]; then + mv "$run_dir_made" "$run_dir_made.interrupted" 2>/dev/null && + echo "bench.sh: interrupted; partial output in $run_dir_made.interrupted (it doesn't count)" >&2 + fi + exit "$1" +} +trap cleanup EXIT +trap 'on_signal 130' INT +trap 'on_signal 143' TERM +# bg CMD...: run CMD in the background, wait for it; its status in $rc. +bg() { "$@" & child=$!; rc=0; wait "$child" || rc=$?; child=""; } + +# The settings file people fill in once (bench.sh init writes it). +settings_template() { + cat <<'EOF' +# bench.local.env - your values for ./bench.sh, so you don't type them every +# time. Fill in what's empty, then run just: ./bench.sh (or --dry-run, --full) +# +# One KEY=value per line; '#' starts a comment; quote values with spaces. +# Relative paths are relative to this file. Flags on the command line win over +# the environment, which wins over this file. Never put the API key here: +# export BETTERBENCH_API_KEY in your shell instead. + +# --- you and your server ------------------------------------------------- +BENCH_SUBMITTER= # your name +BENCH_ENDPOINT=http://localhost:8080/v1 # the server's base URL, ending in /v1 +BENCH_MODEL= # the id exactly as /v1/models lists it +BENCH_SERVER_CMD_FILE= # file with the server's launch command, + # e.g. server-cmd.txt; empty behind llama-swap + +# --- what you declare (README: "What you declare") ----------------------- +BENCH_QUANT= # from the model table: Q4_K_M, UD-Q4_K_M or w4a16 +BENCH_KV=f16 # f16, q8_0, q8_0/f16 (K/V differ), bf16, fp8 +BENCH_TP=1 # tensor parallel size +BENCH_PP=1 # pipeline parallel size +BENCH_SPEC=none # none, mtp:5, eagle3:4, ngram:4, draft:8 +BENCH_THINKING=default # set on the server: default, off, on, low, medium, high + +# --- only when needed ---------------------------------------------------- +# BENCH_POWER_LIMIT=250 # when the GPU can't report it, or: stock +# BENCH_PCIE="Gen4 x16" # inside a VM +# BENCH_MEM_BW=608 # the card's spec memory bandwidth, GB/s +# BENCH_SPECIAL_NOTES="undervolted" # anything unusual +# BENCH_RESULTS_DIR=results # where run folders go +# WARM_TIMEOUT=1800 # a slow first model load behind llama-swap +EOF +} + +# load_settings FILE - set each KEY=value the environment doesn't set already. +# Read as data, not run as shell code. +loaded="" +load_settings() { + sdir=$(cd "$(dirname "$1")" && pwd) n=0 + while IFS= read -r line || [ -n "$line" ]; do + n=$((n + 1)) + line=${line#"${line%%[![:space:]]*}"} + case $line in ''|'#'*) continue ;; esac + line=${line#export } + case $line in *=*) ;; *) die "$1 line $n: want KEY=value" ;; esac + key=${line%%=*} val=${line#*=} + case $key in ''|[0-9]*|*[!A-Z0-9_]*) die "$1 line $n: '$key' is not a variable name" ;; esac + [ "$key" != BETTERBENCH_API_KEY ] || + die "$1 line $n: keep the API key out of files; export BETTERBENCH_API_KEY in your shell" + case $val in + \"*) val=${val#\"}; case $val in *\"*) val=${val%%\"*} ;; *) die "$1 line $n: missing closing quote" ;; esac ;; + \'*) val=${val#\'}; case $val in *\'*) val=${val%%\'*} ;; *) die "$1 line $n: missing closing quote" ;; esac ;; + *) val=${val%%[[:space:]]#*}; val=${val%"${val##*[![:space:]]}"} ;; + esac + # shellcheck disable=SC2088 # a literal ~/ in the file, expanded here + case $val in '~/'*) val=$HOME/${val#'~/'} ;; '$HOME/'*) val=$HOME/${val#'$HOME/'} ;; esac + case $key in *_FILE|*_DIR) case $val in /*|'') ;; *) val=$sdir/$val ;; esac ;; esac + eval "isset=\${$key+y}" + if [ -z "$isset" ]; then + eval "$key=\$val"; export "${key?}" + [ -z "$val" ] || loaded="$loaded $key" + fi + done < "$1" +} + case "${1:-}" in - collect-env) shift; exec sh "$here/collect-env.sh" "$@" ;; - power) shift; exec sh "$here/gpu-power.sh" "$@" ;; + init) + out=${2:-$home/bench.local.env} + [ ! -e "$out" ] || die "$out exists; edit it, or remove it first" + settings_template > "$out" || die "cannot write $out" + echo "wrote $out - fill in the empty values, then run ./bench.sh --dry-run" + exit 0 ;; + collect-env) shift; rc=0; sh "$here/collect-env.sh" "$@" || rc=$?; exit "$rc" ;; + power) shift; bg sh "$here/gpu-power.sh" "$@"; exit "$rc" ;; --version) echo "bench-standard $STANDARD_VERSION (BetterBench $BETTERBENCH_MIN_VERSION or newer)"; exit 0 ;; esac -endpoint="" model="" server_cmd_file="" env_file="" quick=1 no_conc=0 dry=0 verbose=0 +# --settings is read before the other flags, so that they win over it. +settings="" prev="" +for a; do [ "$prev" = --settings ] && settings=$a; prev=$a; done +if [ -n "$settings" ]; then + [ -f "$settings" ] && [ -r "$settings" ] || die "cannot read settings file $settings" + load_settings "$settings" +elif [ -f "$home/bench.local.env" ]; then + settings=$home/bench.local.env + load_settings "$settings" +fi +[ -z "$loaded" ] || echo "settings from $settings:$loaded" >&2 + +endpoint=${BENCH_ENDPOINT:-} model=${BENCH_MODEL:-} server_cmd_file=${BENCH_SERVER_CMD_FILE:-} +env_file=${BENCH_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:-} @@ -91,6 +208,7 @@ while [ $# -gt 0 ]; do --server-cmd-file) need $# "$1"; server_cmd_file=$2; shift 2 ;; --env-file) need $# "$1"; env_file=$2; shift 2 ;; --results-dir) need $# "$1"; results_dir=$2; shift 2 ;; + --settings) need $# "$1"; shift 2 ;; --tp) need $# "$1"; tp=$2; shift 2 ;; --pp) need $# "$1"; pp=$2; shift 2 ;; --quant) need $# "$1"; quant=$2; shift 2 ;; @@ -123,23 +241,14 @@ sys.exit(not sys.argv[1] or v(sys.argv[1]) < v(sys.argv[2]))' "$have_ver" "$BETT die "BetterBench $BETTERBENCH_MIN_VERSION or newer required, found '${have_ver:-not installed}'" \ "(see https://github.com/GGZ14/BetterBench)" command -v curl >/dev/null || die "curl not found" -# The exact build: two installs can both say 0.6.1. pip records where it came -# from: a git commit, or a local checkout (then git describes it). -bb_build=$(bb=$(command -v betterbench) && py=$(sed -n '1s/^#!//p' "$(readlink -f "$bb")") && - $py -c 'import importlib.metadata as m, json -u = json.loads(m.distribution("betterbench").read_text("direct_url.json") or "{}") -c = (u.get("vcs_info") or {}).get("commit_id") -print(c[:12] if c else u.get("url", "")[7:] if u.get("url", "").startswith("file://") else "")' 2>/dev/null) || bb_build="" -if [ -d "$bb_build" ]; then - bb_build=$(git -c safe.directory='*' -C "$bb_build" describe --tags --always --dirty 2>/dev/null) || bb_build="" -fi missing="" for f in endpoint model tp pp quant kv spec thinking submitter; do eval "v=\${$f}" [ -n "$v" ] || missing="$missing --$(printf '%s' "$f" | tr _ -)" done -[ -z "$missing" ] || die "missing mandatory value(s):$missing" +[ -z "$missing" ] || die "missing mandatory value(s):$missing" \ + "(as flags, or saved in ${settings:-bench.local.env}; './bench.sh init' writes one to fill in)" matches "$tp" '[1-9][0-9]*' || die "--tp must be a positive integer" matches "$pp" '[1-9][0-9]*' || die "--pp must be a positive integer" @@ -161,7 +270,12 @@ if [ -n "$server_cmd_file" ]; then [ -r "$server_cmd_file" ] || die "cannot read if [ -n "$env_file" ]; then [ -r "$env_file" ] || die "cannot read $env_file"; fi tmp=$(mktemp -d) -trap 'rm -rf "$tmp"' EXIT INT TERM + +# Warnings print as they come and are repeated after the summary, so none +# scroll away during a long run; meta.json keeps them too. +warnings="$tmp/warnings" +: > "$warnings" +warn() { echo "bench.sh: warning: $*" >&2; printf '%s\n' "$*" >> "$warnings"; } hdr="$tmp/hdr" if [ -n "${BETTERBENCH_API_KEY:-}" ]; then printf 'Authorization: Bearer %s\n' "$BETTERBENCH_API_KEY" > "$hdr" @@ -216,6 +330,9 @@ else: print(f"greedy_variants={len(set(hashes))}\ngreedy_runs={len(hashes)}\ngreedy_hash={hashes[0]}") print("greedy_reasoning=" + ("yes" if all(thought) else "no" if not any(thought) else "mixed")) PY +if grep -q '^greedy_check=failed' "$tmp/measured"; then + warn "greedy check failed ($(sed -n 's/^greedy_error=//p' "$tmp/measured")); the result has no greedy hash" +fi # ---------------------------------------------------------------- collect if [ -n "$env_file" ]; then @@ -243,7 +360,7 @@ fi [ -n "$pcie" ] && printf 'pcie=%s\n' "$pcie" [ -n "$special" ] && printf 'special_notes=%s\n' "$special" [ -n "$mem_bw" ] && printf 'mem_bw=%s\n' "$mem_bw" - printf 'betterbench=%s\nbetterbench_build=%s\n' "$have_ver" "$bb_build" + printf 'betterbench=%s\n' "$have_ver" printf 'bench_standard=%s\nrun_mode=%s\nconcurrency=%s\n' "$STANDARD_VERSION" \ "$([ $quick = 1 ] && echo quick || echo full)" "$([ $no_conc = 1 ] && echo off || echo on)" } > "$tmp/mandatory" @@ -265,8 +382,13 @@ if [ -n "$cmd_src" ]; then python3 - "$tmp/cmd" "$tmp/cmd.red" <<'PY' import re, sys s = open(sys.argv[1], encoding="utf-8", errors="replace").read() -s = re.sub(r'(?i)\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY)[A-Z0-9_]*=)\S+', r'\1', s) -s = re.sub(r'(?i)(--(?:api-key|hf-token|token)[= ])\S+', r'\1', s) +# Env assignments (FOO_TOKEN=x, -e FOO_TOKEN=x, --env=FOO_TOKEN=x) - not +# flags like --max-num-batched-tokens=8192, hence no '-' right before. +s = re.sub(r'(?i)(?', s) +s = re.sub(r'(?i)((?', s) +# user:password@ in URLs (proxies, registries) +s = re.sub(r'(?i)(\b[a-z][a-z0-9+.-]*://[^\s:/@]+:)[^\s@/]+@', r'\1@', s) open(sys.argv[2], "w", encoding="utf-8").write(s if s.endswith("\n") else s + "\n") PY fi @@ -274,35 +396,303 @@ fi # The notes are grouped for reading: one chip per topic, nothing twice. # The context size is left out - BetterBench shows it from --max-model-len. # launch.json: the settings parsed from the launch command, for meta.json. -python3 "$here/notes.py" "$tmp/mandatory" "$tmp/collected" "$tmp/measured" "$tmp/cmd.red" \ - "$tmp/launch.json" "$here/models.tsv" > "$tmp/notes" +WARNINGS=$warnings MODELS=$here/models.txt \ +python3 - "$tmp/mandatory" "$tmp/collected" "$tmp/measured" "$tmp/cmd.red" "$tmp/launch.json" \ + > "$tmp/notes" <<'PY' +import json, os, re, shlex, sys +def warn(msg): + print("bench.sh: warning: " + msg, file=sys.stderr) + with open(os.environ["WARNINGS"], "a", encoding="utf-8") as f: + f.write(msg + "\n") +def kv(path): + with open(path, encoding="utf-8") as f: + return dict(l.rstrip("\n").split("=", 1) for l in f if "=" in l) +m, c, meas = kv(sys.argv[1]), kv(sys.argv[2]), kv(sys.argv[3]) +cmd = open(sys.argv[4], encoding="utf-8").read().strip() +def g(k): + v = c.get(k, "") + return "" if v in ("", "unknown") else v +def join(*parts): + return " · ".join(p for p in parts if p) or "unknown" -engine=$(get engine) gpu=$(get gpu_model) ctx=$(get ctx) -[ "$engine" != unknown ] || echo "bench.sh: warning: engine not detected; result is hard to compare" >&2 +vendor = {"intel": "Intel", "nvidia": "NVIDIA", "amd": "AMD"}.get(g("gpu_vendor"), g("gpu_vendor")) +count = g("gpu_count") if g("gpu_count") != "0" else "" # 0: nothing detected +gpu = join(" ".join(p for p in (count and count + "x", vendor if vendor != "none" else "", + g("gpu_model")) if p), + g("gpu_vram_gb") and g("gpu_vram_gb") + " GB", + g("gpu_driver") and "driver " + g("gpu_driver")) + +link, top = g("pcie_link"), g("pcie_max") +if m.get("pcie"): + pcie = m["pcie"] + " (declared)" +elif link and top and link != top: + pcie = f"{link} now, {top} max" # idle GPUs drop the link speed +else: + pcie = link or "unknown" +if g("rebar"): + pcie += " · ReBAR " + g("rebar") + +pl, det = m["power_limit"], g("gpu_power_limit_w") +if pl == "stock": + power = join("stock", det and det + " W") +else: + power = pl + " W" + if det and abs(float(det) - float(pl)) > 1: + power += f" (GPU reports {det} W)" + +virt = g("virt") +host = join(g("cpu_model"), g("ram_gb") and g("ram_gb") + " GB RAM", g("os"), + g("kernel") and "kernel " + g("kernel"), virt != "none" and virt and "VM " + virt) + +# Settings in the launch command that swing results but no API reports: +# batch sizes, flash attention, KV types, env flags. Flags left out of the +# command are the engine's defaults, which change between versions. +try: + words = shlex.split(cmd.replace("\\\n", " ")) +except ValueError: + words = cmd.split() +env, flags, prog = {}, {}, None +BOOL = {"--no-mmap", "--mlock", "--enforce-eager", "--enable-prefix-caching", + "--no-enable-prefix-caching", "--enable-chunked-prefill", + "--no-enable-chunked-prefill", "--cont-batching", "-cb", "--no-cont-batching", "-nocb", + "-cmoe", "--cpu-moe", "-rm", "--rm", "-d", "--detach", "-it", "-i", "--privileged", + "--init", "--jinja", "--no-webui", "--metrics", "--trust-remote-code", + "--enable-auto-tool-choice", "--disable-log-requests", "--disable-log-stats"} +def is_value(x): # the next word is this flag's value: not a flag, or a number + return x is not None and (not x.startswith("-") or re.fullmatch(r"-[0-9.]+", x)) +FA_VALUES = {"on", "off", "auto", "1", "0", "true", "false"} +i = 0 +while i < len(words): + 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 not is_value(nxt): + 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 values should be what the launch command sets (AGENTS.md +# step 4). Only what the command states is checked; defaults are assumed +# only where the standard defines them (llama.cpp KV f16, vLLM tp/pp 1). +def expect(name, declared, wanted, why): + if wanted is not None and declared != wanted: + warn(f"--{name} {declared} but the launch command sets {why}: declare --{name} {wanted}") + +if cmd and launch_kind == "llama.cpp": + k, v = flag("-ctk", "--cache-type-k"), flag("-ctv", "--cache-type-v") + if k or v: + k, v = k or "f16", v or "f16" + expect("kv", m["kv"], k if k == v else f"{k}/{v}", f"K {k}, V {v}") +elif cmd and launch_kind == "vllm": + kvd, dt = flag("--kv-cache-dtype"), str(flag("--dtype") or "") + if kvd and kvd != "auto": + expect("kv", m["kv"], kvd, f"--kv-cache-dtype {kvd}") + elif dt in ("bfloat16", "float16", "half"): + expect("kv", m["kv"], "bf16" if dt == "bfloat16" else "f16", + f"--kv-cache-dtype {kvd or 'unset'} with --dtype {dt}") + +# Speculative decoding. +spec_cmd = None +if cmd and launch_kind == "llama.cpp": + if flag("-md", "--model-draft", "-hfd", "-hfrd", "--hf-repo-draft"): + n = flag("--draft-max", "--draft", "--draft-n") + if n and str(n).isdigit(): + spec_cmd = (f"draft:{n}", f"a draft model with --draft-max {n}") + elif not m["spec"].startswith("draft:"): # the default N varies between builds + warn(f"--spec {m['spec']} but the launch command loads a draft model (-md):" + " declare draft:N, N = the build's --draft-max default") + else: + spec_cmd = ("none", "no draft model") +elif cmd and launch_kind == "vllm": + sc, n = flag("--speculative-config"), flag("--num-speculative-tokens") + if sc not in (None, True): + try: + j = json.loads(sc) + except ValueError: + j = dict(re.findall(r'"?(method|num_speculative_tokens|model)"?\s*[:=]\s*"?([\w./-]+)', sc)) + meth = str(j.get("method") or ("draft" if j.get("model") else "")) + meth = ("mtp" if "mtp" in meth else "draft" if meth.startswith("draft") else + meth if meth in ("eagle", "eagle3", "ngram") else None) + n = j.get("num_speculative_tokens") or n + if meth and n: + spec_cmd = (f"{meth}:{n}", f"--speculative-config {sc}") + elif not flag("--speculative-model"): + spec_cmd = ("none", "no --speculative-config") +if spec_cmd: + expect("spec", m["spec"], spec_cmd[0], spec_cmd[1]) + +if cmd and launch_kind == "vllm": + expect("tp", m["tp"], str(flag("--tensor-parallel-size", "-tp") or 1), "that tensor parallel size") + expect("pp", m["pp"], str(flag("--pipeline-parallel-size", "-pp") or 1), "that pipeline parallel size") + +# Thinking switched off (or on) in the launch command. +think_cmd = None +if str(flag("--reasoning-budget")) == "0": + think_cmd = "--reasoning-budget 0" +et = re.search(r'enable_thinking"?\s*:\s*(true|false)', cmd, re.I) +if et: + think_cmd = think_cmd or f"enable_thinking: {et.group(1).lower()}" +if think_cmd and ("false" in think_cmd or "budget 0" in think_cmd): + expect("thinking", m["thinking"], "off", think_cmd) +elif think_cmd and m["thinking"] == "off": + warn(f"--thinking off but the launch command sets {think_cmd}") + +# Results only count for the standard models (models.txt = the README's table). +std = {} +with open(os.environ["MODELS"], encoding="utf-8") as f: + for line in f: + p = line.split() + if len(p) == 3 and not p[0].startswith("#"): + std[p[0]] = (p[1], p[2]) +sha = g("model_sha256") +if sha in std: + sha_note = f"sha256 {sha[:12]} (standard: {std[sha][1]})" + if m["quant"] != std[sha][0]: + warn(f"--quant {m['quant']} but the model file is {std[sha][1]}: declare --quant {std[sha][0]}") +elif sha: + sha_note = f"sha256 {sha[:12]} (not a standard model)" + warn(f"the model file (sha256 {sha[:12]}) is not one of the standard models in the README;" + " results only count for those files") +else: + sha_note = "" +mb = g("model_bytes") +model_file = join(g("model_file"), mb and f"{int(mb) / 1e9:.2f} GB", sha_note) +mem_bw = join(g("gpu_mem_bw_gbs") and + f'{g("gpu_mem_bw_gbs")} GB/s measured ({g("gpu_mem_bw_tool") or "?"})', + m.get("mem_bw") and m["mem_bw"] + " GB/s declared") +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" + +# --thinking is declared, but the greedy replies show whether the model +# reasoned: check one against the other. +seen = meas.get("greedy_reasoning") +thinking = join(m["thinking"], {"yes": "reasoning seen", "no": "no reasoning seen", + "mixed": "reasoning in some replies"}.get(seen, "")) +if m["thinking"] == "off" and seen in ("yes", "mixed"): + warn("--thinking off, but the greedy replies contain reasoning;" + " check the server's chat template or reasoning flags") +elif m["thinking"] in ("on", "low", "medium", "high") and seen == "no": + warn(f"--thinking {m['thinking']}, but the greedy replies contain no" + " reasoning; thinking may be off on the server") + +eng = g("engine") +engine = join(" ".join(p for p in (eng, g("engine_version")) if p), + g("engine_slots") and g("engine_slots") + " slots", + g("engine_image") and "image " + g("engine_image"), + g("proxy") not in ("", "none") and "via " + g("proxy")) + +notes = [ + ("submitter", m["submitter"]), + ("gpu", gpu), + ("pcie", pcie), + ("power_limit", power), + ("host", host), + ("engine", engine), + ("model_file", model_file), + ("mem_bw", mem_bw), + ("parallel", f"tp {m['tp']} · pp {m['pp']}"), + ("precision", f"weights {m['quant']} · kv {m['kv']}"), + ("launch", launch), + ("env_flags", env_flags), + ("spec", m["spec"]), + ("thinking", thinking), + ("greedy_check", greedy), + ("run", join(m["run_mode"], "concurrency " + m["concurrency"], + "bench-standard " + m["bench_standard"], "betterbench " + m["betterbench"])), +] +if m.get("special_notes"): + notes.append(("special_notes", m["special_notes"])) +for k, v in notes: + print(f"{k}={v}") +PY + +engine=$(get engine) gpu=$(get gpu_model) count=$(get gpu_count) ctx=$(get ctx) +[ "$engine" != unknown ] || warn "engine not detected; result is hard to compare" if [ "$power_src" = declared ] && [ "$power_limit" != stock ] && matches "$pl" '[0-9.]+' && [ "$(awk -v a="$pl" -v b="$power_limit" 'BEGIN{print (a-b>1||b-a>1)}')" = 1 ]; then - echo "bench.sh: warning: --power-limit $power_limit W but the GPU reports $pl W" >&2 + warn "--power-limit $power_limit W but the GPU reports $pl W" fi -# File names: ____x-[_quick][_2], -# with N the GPUs the model runs on (tp x pp); _2, _3, ... for another run of -# the same setup on the same day. Fields are joined with _ since -# model names have dashes. The run folder and the exported results.json/.html -# are named alike, so a file sent on its own still says what it is. +matches "$count" '[2-9]|[1-9][0-9]+' && gpu="${count}x-$gpu" slug() { tr 'A-Z' 'a-z' | sed -e 's/[^a-z0-9.]\{1,\}/-/g' -e 's/^-//' -e 's/-$//'; } -gpu=$(printf '%s' "$gpu" | slug) -name="$(printf '%s' "$model" | slug)_$(printf '%s' "$engine" | slug)_$((tp * pp))x-${gpu:-unknown}" -run_id="$(date +%y%m%d)_$(printf '%s' "$submitter" | slug)_$name" -[ $quick = 1 ] && run_id="${run_id}_quick" -base=$run_id i=1 -while [ -e "$results_dir/$run_id" ] || [ -e "$results_dir/$run_id.failed" ]; do - i=$((i + 1)); run_id="${base}_$i" -done -run_dir="$results_dir/$run_id" -results="$run_dir/$run_id.json" +name=$(printf '%s-%s-%s' "$model" "$engine" "$gpu" | slug) + +run_dir="$results_dir/$(date +%Y%m%d-%H%M%S)-$(printf '%s' "$submitter" | slug)-$name" # ---------------------------------------------------------------- run set -- run --no-update-check --endpoint "$endpoint" --model "$model" \ - --config "$run_dir/config.json" --name "$name" --out "$results" + --config "$run_dir/config.json" --name "$name" --out "$run_dir/results.json" [ $quick = 1 ] && set -- "$@" --quick [ $no_conc = 1 ] && set -- "$@" --no-concurrency # Through a proxy /v1/models often lacks the context size; hand over what the @@ -315,11 +705,16 @@ if [ $dry = 1 ]; then printf ' betterbench' for a; do case $a in *[[:space:]]*) printf " '%s'" "$a" ;; *) printf ' %s' "$a" ;; esac; done echo + if [ -s "$warnings" ]; then + echo "$(wc -l < "$warnings") warning(s) - fix or explain them before the real run:" + sed 's/^/ - /' "$warnings" + fi exit 0 fi mkdir -p "$results_dir" mkdir "$run_dir" || die "cannot create $run_dir" +run_dir_made=$run_dir cp "$here/config.json" "$run_dir/config.json" [ -n "$cmd_src" ] && cp "$tmp/cmd.red" "$run_dir/server-cmd.txt" @@ -352,47 +747,43 @@ with open(sys.argv[3], "w", encoding="utf-8") as f: PY # Power is sampled where the GPU is: only when BetterBench runs on the server. -sampler="" +# The sampler exits at once when it finds nothing to read. if [ -z "$env_file" ]; then sh "$here/gpu-power.sh" 2 > "$run_dir/power.csv" 2>/dev/null & sampler=$! - trap 'kill "$sampler" 2>/dev/null || true; rm -rf "$tmp"' EXIT INT TERM fi echo "running betterbench -> $run_dir" >&2 [ $verbose = 1 ] && sed 's/^/ note: /' "$tmp/notes" >&2 t_start=$(date +%s.%N) -# Full output always goes to betterbench.log; the terminal gets all of it -# (--verbose) or the progress lines and anything that looks like trouble. -# timeline.tsv stamps each progress line, for the energy of each phase. -{ PYTHONUNBUFFERED=1 betterbench "$@" 2>&1 || echo $? > "$tmp/bb_rc"; } | - tee "$run_dir/betterbench.log" | - python3 -uc 'import sys, time -tl = open(sys.argv[1], "w", encoding="utf-8") -for line in iter(sys.stdin.readline, ""): - if line.startswith("["): - tl.write(f"{time.time():.3f}\t{line}"); tl.flush() - sys.stdout.write(line); sys.stdout.flush()' "$run_dir/timeline.tsv" | - if [ $verbose = 1 ]; then cat; else grep --line-buffered -E '^\[|^phases|warn|WARN|rror|Traceback' || true; fi >&2 -if [ -s "$tmp/bb_rc" ]; then - mv "$run_dir" "$run_dir.failed" 2>/dev/null || true - die "betterbench failed (exit $(cat "$tmp/bb_rc")); output in $run_dir.failed/betterbench.log" -fi +# Full output always goes to betterbench.log; the terminal follows it: all of +# it (--verbose), or the progress lines and anything that looks like trouble. +: > "$run_dir/betterbench.log" +PYTHONUNBUFFERED=1 betterbench "$@" > "$run_dir/betterbench.log" 2>&1 & +child=$! +tail -n +1 -f --pid="$child" "$run_dir/betterbench.log" | + if [ $verbose = 1 ]; then cat; else grep --line-buffered -E '^\[|^phases|warn|WARN|rror|Traceback' || true; fi >&2 & +follower=$! +bb_rc=0 +wait "$child" || bb_rc=$? +child="" +wait "$follower" 2>/dev/null || true t_end=$(date +%s.%N) if [ -n "$sampler" ]; then - kill "$sampler" 2>/dev/null; wait "$sampler" 2>/dev/null || true + kill "$sampler" 2>/dev/null || true + wait "$sampler" 2>/dev/null || true + sampler="" [ -s "$run_dir/power.csv" ] || rm -f "$run_dir/power.csv" fi - -# Energy (whole run and per phase) 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 the results file. -T0=$t_start T1=$t_end python3 "$here/postrun.py" "$run_dir" "$results" || - echo "bench.sh: warning: post-run figures failed" >&2 +if [ "$bb_rc" != 0 ]; then + mv "$run_dir" "$run_dir.failed" 2>/dev/null || true + run_dir_made="" + die "betterbench failed (exit $bb_rc); output in $run_dir.failed/betterbench.log" +fi # BetterBench with GGZ14/BetterBench#4 fingerprints PCIe and BAR itself # (env.gpu.pci), on the machine BetterBench runs on. Say so when that is not # the benchmarked GPU, or when it disagrees with collect-env.sh. -ENV_FILE=$env_file python3 - "$results" "$tmp/collected" <<'PY' || true +ENV_FILE=$env_file WARNINGS=$warnings python3 - "$run_dir/results.json" "$tmp/collected" <<'PY' || true import json, os, sys pci = ((json.load(open(sys.argv[1], encoding="utf-8")).get("env") or {}).get("gpu") or {}).get("pci") if not pci: @@ -407,9 +798,117 @@ if mine is None: 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) + msg = (f"ReBAR {rebar} per collect-env.sh, but BetterBench reads " + f"{mine.get('resizable_bar')} ({mine.get('largest_bar_mib')} MiB BAR)") + print("bench.sh: warning: " + msg, file=sys.stderr) + open(os.environ["WARNINGS"], "a", encoding="utf-8").write(msg + "\n") PY +# Energy per token and decode as % of memory bandwidth, from what the run +# measured. They come after the run, so they go to meta.json ("post_run"), +# not into the notes of results.json. +T0=$t_start T1=$t_end WARNINGS=$warnings python3 - "$run_dir" <<'PY' || warn "post-run figures failed" +import json, os, statistics, sys +d = sys.argv[1] +res = json.load(open(f"{d}/results.json", encoding="utf-8")) +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)") +warnings = [w for w in open(os.environ["WARNINGS"], encoding="utf-8").read().splitlines() if w] +if warnings: + L.append(f" {len(warnings)} warning(s):") + L += [f" - {w}" for w in warnings] +print("\n" + "\n".join(L), file=sys.stderr) +with open(f"{d}/summary.txt", "w", encoding="utf-8") as f: + f.write("\n".join(x[2:] for x in L) + "\n") + +meta["post_run"] = post +meta["warnings"] = warnings +with open(f"{d}/meta.json", "w", encoding="utf-8") as f: + json.dump(meta, f, indent=2) + f.write("\n") +PY + echo echo "done: $run_dir" ls -1 "$run_dir" @@ -428,7 +927,7 @@ cat > "$d/collect-env.sh" <<'__BENCH_STANDARD_EOF__' # --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), -# HASH_MODEL=0 (skip hashing the model file) +# HASH_MODEL=0 (skip hashing the model file; hashes are cached by size and mtime) set -u LC_ALL=C; export LC_ALL @@ -451,7 +950,9 @@ while [ $# -gt 0 ]; do done tmp=$(mktemp -d) || exit 1 -trap 'rm -rf "$tmp"' EXIT INT TERM +trap 'rm -rf "$tmp"' EXIT +trap 'exit 130' INT +trap 'exit 143' TERM # Header via a file so the key never shows up in `ps`. if [ -n "$api_key" ]; then printf 'Authorization: Bearer %s\n' "$api_key" > "$tmp/hdr" else printf 'Accept: application/json\n' > "$tmp/hdr"; fi @@ -524,12 +1025,47 @@ pcie_of() { return 0 } +# hostpath PATH - the host path behind a path inside the server's container, +# from the -v / --mount flags of the launch command in $tmp/cmd; prints +# nothing when no bind mount covers it. +hostpath() { + [ -s "$tmp/cmd" ] && have python3 || return 0 + python3 - "$tmp/cmd" "$1" <<'PY' 2>/dev/null +import os, re, sys +cmd, path = open(sys.argv[1], encoding="utf-8", errors="replace").read(), sys.argv[2] +maps = re.findall(r'(?:^|\s)(?:-v|--volume)[ =](\S+?):(/[^\s:]*)', cmd) +for m in re.finditer(r'--mount[ =](\S+)', cmd): + o = dict(p.split("=", 1) for p in m.group(1).split(",") if "=" in p) + src, dst = o.get("source") or o.get("src"), o.get("target") or o.get("destination") or o.get("dst") + if src and dst: + maps.append((src, dst)) +best = None +for src, dst in maps: + dst = dst.rstrip("/") or "/" + src = os.path.expandvars(os.path.expanduser(src.strip("'\""))) + if src.startswith("/") and (path == dst or path.startswith(dst.rstrip("/") + "/")): + if best is None or len(dst) > len(best[1]): # the innermost mount wins + best = (src, dst) +if best: + print(best[0].rstrip("/") + path[len(best[1].rstrip("/")):]) +PY +} + +# hf_snapshot HF_HOME REPO_ID - the snapshot dir of a Hugging Face cache entry +hf_snapshot() { + r="$1/hub/models--$(printf '%s' "$2" | sed 's|/|--|g')" + [ -d "$r/snapshots" ] || return 1 + if [ -f "$r/refs/main" ] && [ -d "$r/snapshots/$(cat "$r/refs/main")" ]; then + printf '%s\n' "$r/snapshots/$(cat "$r/refs/main")" + else + set -- "$r"/snapshots/*/ + [ $# = 1 ] && [ -d "$1" ] && printf '%s\n' "${1%/}" + fi +} + # ---------------------------------------------------------------- GPU gpu_vendor=none gpu_model="" gpu_count=0 gpu_vram_gb="" gpu_driver="" gpu_power_limit_w="" gpu_bdf="" -# 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 \ +if have nvidia-smi && q=$(nvidia-smi --query-gpu=name,memory.total,driver_version,power.limit,pci.bus_id \ --format=csv,noheader,nounits 2>/dev/null) && [ -n "$q" ]; then gpu_vendor=nvidia gpu_count=$(printf '%s\n' "$q" | grep -c .) @@ -540,10 +1076,6 @@ 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 @@ -555,8 +1087,6 @@ 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 @@ -571,24 +1101,7 @@ 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 @@ -632,6 +1145,7 @@ os=$( (. /etc/os-release 2>/dev/null && printf '%s' "${PRETTY_NAME:-}") ) kernel=$(uname -r 2>/dev/null) # ---------------------------------------------------------------- engine +[ -n "$cmd_file" ] && cp "$cmd_file" "$tmp/cmd" 2>/dev/null proxy=none engine=unknown engine_version="" model_file="" ctx="" engine_slots="" if [ -n "$endpoint" ]; then base=${endpoint%/}; base=${base%/v1} @@ -671,44 +1185,77 @@ if [ -n "$endpoint" ]; then fi fi - # Behind llama-swap the launch command is known: keep it, and map a - # container path (-v HOST:/model) back to the host path. + # Behind llama-swap the launch command is known: keep it (it wins over + # --server-cmd-file for finding the container and the mounts). if [ "$proxy" = llama-swap ] && [ -n "$model" ] && fetch "$base/running" "$tmp/running"; then export JARG="$model" - jget "$tmp/running" 'next((r.get("cmd") for r in j["running"] if r.get("model") == arg), "")' > "$tmp/cmd" - if [ -s "$tmp/cmd" ]; then + jget "$tmp/running" 'next((r.get("cmd") for r in j["running"] if r.get("model") == arg), "")' > "$tmp/cmd.swap" + if [ -s "$tmp/cmd.swap" ]; then + mv "$tmp/cmd.swap" "$tmp/cmd" [ -n "$cmd_out" ] && cp "$tmp/cmd" "$cmd_out" - if [ -n "$model_file" ] && have python3; then - host=$(python3 - "$tmp/cmd" "$model_file" <<'PY' 2>/dev/null -import re, sys -cmd, path = open(sys.argv[1]).read(), sys.argv[2] -for src, dst in re.findall(r'(?:-v|--volume)[ =](\S+?):(/[^\s:]*)', cmd): - if path == dst or path.startswith(dst.rstrip("/") + "/"): - print(src + path[len(dst):]); break -PY -) - [ -n "$host" ] && model_file=$host - fi fi fi fi -# Weight bytes as stored: a single file, the parts of a split GGUF -# (-00001-of-0000N.gguf), or the *.safetensors of a model directory, without -# an MTP head (*mtp*), which plain decoding doesn't read. -model_bytes="" -if [ -f "$model_file" ]; then - case $model_file in - *-00001-of-[0-9]*.gguf) set -- "${model_file%-00001-of-*}"-[0-9]*-of-[0-9]*.gguf ;; - *) set -- "$model_file" ;; +# model_path: where the weights are on this machine. The engine reports its +# own view: a path inside its container (mapped back through -v / --mount), +# or, for vLLM, often a Hugging Face repo id (looked up in the HF cache, the +# container's and this machine's). +model_path="" +if [ -n "$model_file" ]; then + model_path=$(hostpath "$model_file") + [ -n "$model_path" ] && [ -e "$model_path" ] || model_path=$model_file + case $model_path in + /*|.*) ;; + */*) if [ ! -e "$model_path" ]; then + cenv=$( [ -s "$tmp/cmd" ] && tr '\n' ' ' < "$tmp/cmd" | sed -n 's/.*[ =]HF_HOME=\([^ ]*\).*/\1/p') + for root in $(hostpath "${cenv:-/root/.cache/huggingface}") $cenv \ + "${HF_HOME:-$HOME/.cache/huggingface}"; do + snap=$(hf_snapshot "$root" "$model_file") && { model_path=$snap; break; } + done + fi ;; esac - model_bytes=$(stat -c %s "$@" 2>/dev/null | awk '{s += $1} END {if (s) printf "%d", s}') -elif [ -d "$model_file" ]; then - model_bytes=$(find "$model_file" -maxdepth 1 -name '*.safetensors' ! -name '*mtp*' -exec stat -c %s {} + 2>/dev/null | - awk '{s += $1} END {if (s) printf "%d", s}') + [ -e "$model_path" ] || model_path="" fi -[ -s "$tmp/cmd" ] || { [ -n "$cmd_file" ] && cp "$cmd_file" "$tmp/cmd" 2>/dev/null; } +# Weight bytes as stored: a single file, the parts of a split GGUF +# (-00001-of-0000N.gguf), or the *.safetensors of a model directory. stat -L: +# the HF cache keeps files as symlinks into blobs/. +model_bytes="" model_sha256="" +set -- +if [ -f "$model_path" ]; then + case $model_path in + *-00001-of-[0-9]*.gguf) set -- "${model_path%-00001-of-*}"-[0-9]*-of-[0-9]*.gguf ;; + *) set -- "$model_path" ;; + esac +elif [ -d "$model_path" ]; then + set -- "$model_path"/*.safetensors + [ -e "$1" ] || set -- +fi +[ $# -gt 0 ] && model_bytes=$(stat -L -c %s "$@" 2>/dev/null | awk '{s += $1} END {if (s) printf "%d", s}') + +# The hash the README's model table lists: sha256 of the GGUF, or of a repo's +# per-file *.safetensors hashes in name order. Split GGUFs aren't hashed. +# Cached by path, size and mtime, since hashing 15 GB takes a while. +case $model_path in *-00001-of-[0-9]*.gguf) split=1 ;; *) split=0 ;; esac +if [ "${HASH_MODEL:-1}" != 0 ] && [ -n "$model_bytes" ] && [ $split = 0 ] && have sha256sum; then + sig=$(stat -L -c '%n %s %Y' "$@" 2>/dev/null | cksum | cut -d' ' -f1) + cache="${XDG_CACHE_HOME:-$HOME/.cache}/bench-standard/model-sha256" + model_sha256=$(awk -v s="$sig" -v p="$model_path" -F '\t' '$1 == s && $2 == p {print $3; exit}' "$cache" 2>/dev/null) + if [ -z "$model_sha256" ]; then + echo "collect-env: hashing $model_path ($((model_bytes / 1000000000)) GB; once, it's cached; HASH_MODEL=0 skips) ..." >&2 + if [ -f "$model_path" ]; then + model_sha256=$(sha256sum "$model_path" | cut -c1-64) + else + model_sha256=$(cd "$model_path" && sha256sum -- *.safetensors | sort -k2 | sha256sum | cut -c1-64) + fi + case $model_sha256 in + [0-9a-f]*) mkdir -p "${cache%/*}" 2>/dev/null && + printf '%s\t%s\t%s\n' "$sig" "$model_path" "$model_sha256" >> "$cache" 2>/dev/null ;; + *) model_sha256="" ;; + esac + fi +fi # A docker server: the exact image, since tags like llama.cpp's server-intel # move daily (the llama.cpp build itself is in engine_version). container="" engine_image="" @@ -719,40 +1266,12 @@ if [ -n "$container" ] && have docker && engine_image=$(printf '%s' "$i" | sed 's/@sha256:\(.\{12\}\).*/@\1/') 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). -# 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 - 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). -# The first time takes a while for a big file, then it's cached. -# HASH_MODEL=0 skips it. -model_sha256="" -here=$(cd "$(dirname "$0")" && pwd) -if [ "${HASH_MODEL:-1}" != 0 ] && [ -e "$model_file" ] && have python3; then - echo "collect-env: hashing the model file (cached after the first time) ..." >&2 - model_sha256=$(python3 "$here/model_hash.py" "$model_file" 2>/dev/null) -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) @@ -761,6 +1280,7 @@ if [ "${MEASURE_BW:-1}" != 0 ]; then else r="" fi + case $r in [0-9]*' '[0-9]*) ;; *) r="" ;; esac # "GBPS MIB", or nothing usable if [ -n "$r" ]; then gpu_mem_bw_gbs=${r% *} gpu_mem_bw_tool="torch copy, random, ${r#* } MiB" elif have clpeak && [ -n "$gpu_model" ]; then @@ -784,10 +1304,6 @@ 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" @@ -805,27 +1321,26 @@ kv engine_version "$engine_version" kv engine_slots "$engine_slots" kv engine_image "$engine_image" kv model_file "$model_file" +kv model_path "$model_path" kv model_bytes "$model_bytes" -kv model_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 and memory clocks of all GPUs until killed, one -# CSV line per sample: -# epoch_s,watts,joules,mhz,mem_mhz +# 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 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). +# mhz is the mean graphics clock over the GPUs. +# Prints nothing at all when no supported tool is found (nvidia-smi, xpu-smi, +# or amdgpu's hwmon files in sysfs, which have no energy counter). # # usage: gpu-power.sh [INTERVAL_S] (default 2) +# GPU_POWER_SYSFS=DIR: the sysfs root for the amdgpu lookup (tests) set -u LC_ALL=C; export LC_ALL @@ -835,26 +1350,35 @@ 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,clocks.mem \ + 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; m += $4} - END {if (NR) printf "%.2f,%s,%.0f,%.0f\n", w, nj ? "" : sprintf("%.3f", j), c / NR, m / NR}' + 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. 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" + # one call takes about a second sample() { - 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)}' + 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 + # amdgpu: power1_average (older kernels) or power1_input, in microwatts; + # freq1_input is the graphics clock in Hz. + amd="" + for h in "${GPU_POWER_SYSFS:-/sys}"/bus/pci/drivers/amdgpu/*:*/hwmon/hwmon*; do + { [ -r "$h/power1_average" ] || [ -r "$h/power1_input" ]; } && amd="$amd $h" + done + [ -n "$amd" ] || exit 0 + sample() { + for h in $amd; do + p=$(cat "$h/power1_average" 2>/dev/null || cat "$h/power1_input" 2>/dev/null) + f=$(cat "$h/freq1_input" 2>/dev/null) + echo "${p:-0} ${f:-0}" + done | awk '$1 > 0 {w += $1 / 1e6; c += $2 / 1e6; n++} + END {if (n) printf "%.2f,,%.0f\n", w, c / n}' + } fi while :; do @@ -864,98 +1388,6 @@ 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". @@ -1001,599 +1433,6 @@ for _ in range(3): best = max(best, 20 * 2 * x.numel() * 4 / (time.perf_counter() - t) / 1e9) print(f"{best:.0f} {mib}") __BENCH_STANDARD_EOF__ -cat > "$d/model_hash.py" <<'__BENCH_STANDARD_EOF__' -"""model_hash.py - SHA256 of a model, as the README's Models section defines it. - -usage: model_hash.py PATH (prints the hash, or nothing when PATH can't be read) - -A file: its SHA256, like `sha256sum FILE`. A directory: the SHA256 over the -per-file hashes of its *.safetensors, in byte order of the names, exactly like -`sha256sum *.safetensors | LC_ALL=C sort -k2 | sha256sum`. - -Hashing a 16 GB file takes a while, so per-file hashes are cached in -~/.cache/bench-standard/sha256.tsv, keyed by path, size and mtime. -""" -import hashlib -import os -import sys - -CACHE = os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), - "bench-standard", "sha256.tsv") - - -def _load_cache(): - cache = {} - try: - with open(CACHE, encoding="utf-8") as f: - for line in f: - p = line.rstrip("\n").split("\t") - if len(p) == 4: - cache[(p[0], p[1], p[2])] = p[3] - except OSError: - pass - return cache - - -def _save_cache(cache): - try: - os.makedirs(os.path.dirname(CACHE), exist_ok=True) - tmp = CACHE + f".{os.getpid()}" - with open(tmp, "w", encoding="utf-8") as f: - for (path, size, mtime), h in sorted(cache.items()): - f.write(f"{path}\t{size}\t{mtime}\t{h}\n") - os.replace(tmp, CACHE) - except OSError: - pass - - -def file_sha256(path, cache): - st = os.stat(path) - key = (os.path.realpath(path), str(st.st_size), str(st.st_mtime_ns)) - if key not in cache: - h = hashlib.sha256() - with open(path, "rb") as f: - for block in iter(lambda: f.read(1 << 22), b""): - h.update(block) - cache[key] = h.hexdigest() - return cache[key] - - -def model_sha256(path, cache=None): - cache = _load_cache() if cache is None else cache - if os.path.isdir(path): - names = sorted((n for n in os.listdir(path) if n.endswith(".safetensors")), - key=lambda n: n.encode()) - if not names: - return None - listing = "".join(f"{file_sha256(os.path.join(path, n), cache)} {n}\n" for n in names) - return hashlib.sha256(listing.encode()).hexdigest() - return file_sha256(path, cache) - - -if __name__ == "__main__": - try: - cache = _load_cache() - h = model_sha256(sys.argv[1], cache) - _save_cache(cache) - except (OSError, IndexError): - h = None - if h: - print(h) -__BENCH_STANDARD_EOF__ -cat > "$d/notes.py" <<'__BENCH_STANDARD_EOF__' -"""notes.py - the notes bench.sh hands BetterBench, one per topic. - -usage: notes.py MANDATORY COLLECTED MEASURED CMD LAUNCH_JSON MODELS_TSV > notes -The first three are key=value files (declared, detected by collect-env.sh, -measured by the greedy check), CMD the redacted launch command (may be -empty). Writes the parsed launch settings to LAUNCH_JSON and prints -key=value notes; warnings go to stderr. -""" -import json, shlex, sys -def kv(path): - with open(path, encoding="utf-8") as f: - return dict(l.rstrip("\n").split("=", 1) for l in f if "=" in l) -m, c, meas = kv(sys.argv[1]), kv(sys.argv[2]), kv(sys.argv[3]) -models = [l.rstrip("\n").split("\t") for l in open(sys.argv[6], encoding="utf-8") - if l.strip() and not l.startswith("#")] -cmd = open(sys.argv[4], encoding="utf-8").read().strip() -def g(k): - v = c.get(k, "") - return "" if v in ("", "unknown") else v -def join(*parts): - return " · ".join(p for p in parts if p) or "unknown" - -vendor = {"intel": "Intel", "nvidia": "NVIDIA", "amd": "AMD"}.get(g("gpu_vendor"), g("gpu_vendor")) -count = g("gpu_count") -gpu = join(" ".join(p for p in (count and count + "x", vendor if vendor != "none" else "", - g("gpu_model")) if p), - g("gpu_vram_gb") and g("gpu_vram_gb") + " GB", - g("gpu_driver") and "driver " + g("gpu_driver"), - 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"): - pcie = m["pcie"] + " (declared)" -elif link and top and link != top: - pcie = f"{link} now, {top} max" # idle GPUs drop the link speed -else: - pcie = link or "unknown" -if g("rebar"): - pcie += " · ReBAR " + g("rebar") - -pl, det = m["power_limit"], g("gpu_power_limit_w") -if pl == "stock": - power = join("stock", det and det + " W") -else: - power = pl + " W" - if det and abs(float(det) - float(pl)) > 1: - power += f" (GPU reports {det} W)" - -virt = g("virt") -host = join(g("cpu_model"), g("ram_gb") and g("ram_gb") + " GB RAM", g("os"), - g("kernel") and "kernel " + g("kernel"), virt != "none" and virt and "VM " + virt) - -# Settings in the launch command that swing results but no API reports: -# batch sizes, flash attention, KV types, env flags. Flags left out of the -# command are the engine's defaults, which change between versions. -try: - words = shlex.split(cmd.replace("\\\n", " ")) -except ValueError: - words = cmd.split() -env, flags, prog = {}, {}, None -BOOL = {"--no-mmap", "--mlock", "--enforce-eager", "--enable-prefix-caching", - "--no-enable-prefix-caching", "--enable-chunked-prefill", - "--no-enable-chunked-prefill", "--cont-batching", "-cb", "--no-cont-batching", "-nocb", - "-cmoe", "--cpu-moe", "-rm", "--rm", "-d", "--detach", "-it", "-i", "--privileged"} -FA_VALUES = {"on", "off", "auto", "1", "0", "true", "false"} -i = 0 -while i < len(words): - w = words[i] - nxt = words[i + 1] if i + 1 < len(words) else None - if prog is None and "=" in w and not w.startswith("-") and w.split("=", 1)[0].isidentifier(): - k, v = w.split("=", 1); env[k] = v # FOO=1 cmd - elif prog is None and not w.startswith("-") and w != "env": - prog = w - elif w in ("-e", "--env") and nxt is not None and not nxt.startswith("-"): # docker -e K=V - k, _, v = nxt.partition("="); env[k] = v if _ else "(inherited)"; i += 1 - elif w.startswith("--env="): - k, _, v = w[6:].partition("="); env[k] = v if _ else "(inherited)" - elif w.startswith("-e") and len(w) > 2 and "=" in w and w[2:].split("=")[0].isidentifier(): - k, v = w[2:].split("=", 1); env[k] = v - elif w.startswith("-"): - if "=" in w and w.startswith("--"): - k, v = w.split("=", 1); flags[k] = v - elif w in ("-fa", "--flash-attn"): - if nxt is not None and nxt.lower() in FA_VALUES: - flags[w] = nxt; i += 1 - else: - flags[w] = "on" # older bare -fa - elif w in BOOL or nxt is None or nxt.startswith("-"): - flags[w] = True - else: - flags[w] = nxt; i += 1 - i += 1 - -def flag(*names): - for n in names: - if n in flags: - return flags[n] - return None - -LLAMA = [("b", ("-b", "--batch-size")), ("ub", ("-ub", "--ubatch-size")), - ("fa", ("-fa", "--flash-attn")), ("ctk", ("-ctk", "--cache-type-k")), - ("ctv", ("-ctv", "--cache-type-v")), ("ngl", ("-ngl", "--gpu-layers", "--n-gpu-layers")), - ("np", ("-np", "--parallel")), ("t", ("-t", "--threads")), - ("sm", ("-sm", "--split-mode")), ("ts", ("-ts", "--tensor-split")), - ("ot", ("-ot", "--override-tensor")), ("ncmoe", ("-ncmoe", "--n-cpu-moe")), - ("cmoe", ("-cmoe", "--cpu-moe")), ("no-mmap", ("--no-mmap",)), ("mlock", ("--mlock",)), - ("nocb", ("-nocb", "--no-cont-batching"))] -LLAMA_ALWAYS = {"b", "ub", "fa", "ctk", "ctv"} # shown as "default" when not set -VLLM = ["--max-num-batched-tokens", "--max-num-seqs", "--kv-cache-dtype", - "--gpu-memory-utilization", "--dtype", "--quantization", "--block-size", - "--enforce-eager", "--enable-chunked-prefill", "--no-enable-chunked-prefill", - "--enable-prefix-caching", "--no-enable-prefix-caching", "--attention-backend", - "--compilation-config", "-O", "--speculative-config"] -launch_kind = g("engine") -if launch_kind not in ("llama.cpp", "vllm"): - launch_kind = ("llama.cpp" if prog and "llama-server" in prog or flag("-ngl", "-ub", "-ctk") - else "vllm" if any(f in flags for f in VLLM) else "") -settings = {} -if launch_kind == "llama.cpp": - for name, al in LLAMA: - v = flag(*al) - if v is not None: - settings[name] = "on" if v is True else v - elif name in LLAMA_ALWAYS: - settings[name] = "default" -elif launch_kind == "vllm": - for f in VLLM: - if f in flags: - settings[f.lstrip("-")] = "on" if flags[f] is True else "".join(str(flags[f]).split()) -if not cmd: - launch = "unknown (pass --server-cmd-file)" -else: - launch = " · ".join(k if v == "on" and k in ("no-mmap", "mlock", "nocb", "cmoe") or - k.startswith(("enable-", "no-enable-", "enforce-")) else f"{k} {v}" - for k, v in settings.items()) or "no tuning flags" -# Offline switches and cache paths don't change the numbers. -QUIET = {"HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE", "HF_DATASETS_OFFLINE", "HF_HOME", - "VLLM_CACHE_ROOT", "PATH", "HOME", "TZ", "LANG", "LC_ALL"} -env_flags = (" · ".join(f"{k}={v}" for k, v in env.items() if k not in QUIET) or "none" - ) if cmd else "unknown" -json.dump({"engine": launch_kind or None, "settings": settings, "env": env, "flags": flags}, - open(sys.argv[5], "w", encoding="utf-8"), indent=2, default=str) - -# The declared --kv should be what the command sets. -kvset = [x for x in (settings.get("ctk"), settings.get("ctv"), settings.get("kv-cache-dtype")) - if x and x not in ("default", "auto")] -if kvset and m["kv"] not in kvset + ["/".join(kvset), "_".join(kvset)]: - print(f"bench.sh: warning: --kv {m['kv']} but the launch command sets " - f"{'/'.join(kvset)}", file=sys.stderr) - -# The model file against the standard models: results only count for those. -mb, sha = g("model_bytes"), g("model_sha256") -std = next((r for r in models if len(r) >= 4 and r[3] == sha), None) if sha else None -if std: - check = f"standard: {std[0]} {std[2]}" - if m["quant"] != std[2]: - print(f"bench.sh: warning: --quant {m['quant']}, but the file is the standard " - f"{std[0]} {std[2]}; declare --quant {std[2]}", file=sys.stderr) -elif sha: - check = f"not a standard model (sha256 {sha[:12]})" - print("bench.sh: warning: the model file is not one of the standard models " - "(README, Models), so the result won't count", file=sys.stderr) -else: - check = "hash not checked" -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": - greedy = f'differs: {meas["greedy_variants"]} variants in {meas["greedy_runs"]} · first {meas["greedy_hash"]}' -else: - greedy = "failed" - -# --thinking is declared, but the greedy replies show whether the model -# reasoned: check one against the other. -seen = meas.get("greedy_reasoning") -thinking = join(m["thinking"], {"yes": "reasoning seen", "no": "no reasoning seen", - "mixed": "reasoning in some replies"}.get(seen, "")) -if m["thinking"] == "off" and seen in ("yes", "mixed"): - print("bench.sh: warning: --thinking off, but the greedy replies contain reasoning;" - " check the server's chat template or reasoning flags", file=sys.stderr) -elif m["thinking"] in ("on", "low", "medium", "high") and seen == "no": - print(f"bench.sh: warning: --thinking {m['thinking']}, but the greedy replies contain no" - " reasoning; thinking may be off on the server", file=sys.stderr) - -# The BetterBench build: a release tag says nothing more than the version, a -# commit or local changes do (two installs can share a version number). -build = m.get("betterbench_build", "") -betterbench = "betterbench " + m["betterbench"] -if build and build not in ("v" + m["betterbench"], m["betterbench"]): - betterbench += " @ " + build - -eng = g("engine") -engine = join(" ".join(p for p in (eng, g("engine_version")) if p), - g("engine_slots") and g("engine_slots") + " slots", - g("engine_image") and "image " + g("engine_image"), - g("proxy") not in ("", "none") and "via " + g("proxy")) - -notes = [ - ("submitter", m["submitter"]), - ("gpu", gpu), - ("pcie", pcie), - ("power_limit", power), - ("host", host), - ("engine", engine), - ("model_file", model_file), - ("mem_bw", mem_bw), - ("parallel", f"tp {m['tp']} · pp {m['pp']}"), - ("precision", f"weights {m['quant']} · kv {m['kv']}"), - ("max_ctx", max_ctx), - ("launch", launch), - ("env_flags", env_flags), - ("spec", m["spec"]), - ("thinking", thinking), - ("greedy_check", greedy), - ("run", join(m["run_mode"], "concurrency " + m["concurrency"], - "bench-standard " + m["bench_standard"], betterbench)), -] -if m.get("special_notes"): - notes.append(("special_notes", m["special_notes"])) -for k, v in notes: - 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. - -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[,mem_mhz]) and timeline.tsv (epochBetterBench 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. -""" -import bisect -import json -import os -import re -import statistics -import sys - - -def read_power(path): - rows = [] - if os.path.exists(path): - for line in open(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[4]) if len(p) > 4 and p[4] else 0.0)) - except (ValueError, IndexError): - pass - return rows - - -def energy_curve(rows): - """(times, cumulative joules): from the energy counter when every sample - has one, else integrated from the power samples.""" - ts = [r[0] for r in rows] - if all(r[2] is not None for r in rows) and rows[-1][2] >= rows[0][2]: - return ts, [r[2] - rows[0][2] for r in rows], "energy counter" - cum = [0.0] - for a, b in zip(rows, rows[1:]): - cum.append(cum[-1] + (b[0] - a[0]) * (a[1] + b[1]) / 2) - return ts, cum, "integrated power" - - -def joules_between(ts, cum, t0, t1): - """Energy between two moments, interpolating between samples.""" - def at(t): - if t <= ts[0]: - return cum[0] - if t >= ts[-1]: - return cum[-1] - i = bisect.bisect_right(ts, t) - f = (t - ts[i - 1]) / (ts[i] - ts[i - 1]) - return cum[i - 1] + f * (cum[i] - cum[i - 1]) - return max(0.0, at(t1) - at(t0)) - - -SEGMENT = re.compile(r"^\[(single|prefill|concurrency)\]\s+(.*)$") -WARMUP = re.compile(r"warmup (\d+) \+ (\d+)") - - -def segments(timeline, t_end): - """BetterBench prints a progress line when each piece of work starts; a - piece lasts until the next line. Yields (phase, key, warm-up factor, t0, t1).""" - marks = [] - for t, line in timeline: - m = SEGMENT.match(line) - if not m or "skip" in m.group(2): - continue - phase, rest = m.groups() - key = rest.split(":")[0].strip() - if phase == "concurrency": - key = re.sub(r"\D", "", key) - w = WARMUP.search(rest) - factor = (int(w.group(1)) + int(w.group(2))) / int(w.group(2)) if w and int(w.group(2)) else 1.0 - marks.append((t, phase, key, factor)) - for i, (t, phase, key, factor) in enumerate(marks): - yield phase, key, factor, t, marks[i + 1][0] if i + 1 < len(marks) else t_end - - -def phase_energy(res, rows, timeline, t_end): - """Joules and joules per token for decode, prefill and each concurrency - level. Warm-up passes draw power but aren't in the results, so their - tokens are estimated from the measured passes of the same piece.""" - ts, cum, _ = energy_curve(rows) - single = res.get("single_stream") or {} - prefill = {str(p.get("target_depth")): p for p in res.get("prefill") or []} - conc = {str(x.get("level")): x for x in res.get("concurrency") or []} - out = {"decode": {"joules": 0.0, "seconds": 0.0, "tokens": 0.0}, - "prefill": {"joules": 0.0, "seconds": 0.0, "tokens": 0.0}, "concurrency": {}} - for phase, key, factor, t0, t1 in segments(timeline, t_end): - j = joules_between(ts, cum, t0, t1) - if phase == "single": - tok = sum(r.get("completion_tokens") or 0 for r in single.get(key, []) if r.get("ok", True)) - d = out["decode"] - elif phase == "prefill": - depth = re.sub(r"\D", "", key) - tok = sum(prefill.get(depth, {}).get("prompt_tokens") or []) - d = out["prefill"] - else: - x = conc.get(key, {}) - tok, factor = x.get("aggregate_tps", 0) * x.get("wall_s", 0), 1.0 - d = out["concurrency"].setdefault(key, {"joules": 0.0, "seconds": 0.0, "tokens": 0.0}) - d["joules"] += j - d["seconds"] += t1 - t0 - d["tokens"] += tok * factor - def finish(d, per=1): - return {"joules": round(d["joules"]), "avg_w": round(d["joules"] / d["seconds"], 1) if d["seconds"] else None, - "tokens_incl_warmup_est": round(d["tokens"]), - "j_per_token" if per == 1 else "j_per_1k_tokens": - round(d["joules"] / d["tokens"] * per, 3) if d["tokens"] else None} - result = {} - if out["decode"]["seconds"]: - result["decode"] = finish(out["decode"]) - if out["prefill"]["seconds"]: - result["prefill"] = finish(out["prefill"], per=1000) - if out["concurrency"]: - result["concurrency"] = {k: finish(v) for k, v in out["concurrency"].items()} - return result - - -def roofline(single, c, m): - """Batch-1 decode reads all weights once per token: decode t/s x weight - bytes is the bandwidth it reaches. The weights are what the engine loaded - (vLLM logs it per worker) or else what is stored; tensor parallelism - spreads them over tp GPUs, each with its own bandwidth.""" - def num(v): - try: - return float(v) - except (TypeError, ValueError): - return None - tps = [r["decode_tps"] for r in single if r.get("decode_tps")] - bw = num(c.get("gpu_mem_bw_gbs")) or num(m.get("mem_bw")) - tp = int(m.get("tp") or 1) - loaded, stored = num(c.get("model_loaded_gib")), num(c.get("model_bytes")) - if loaded: - nbytes, src = loaded * 2**30 * tp, "loaded (engine log)" - elif stored: - nbytes, src = stored, "stored files" - else: - return None - if not tps or not bw: - return None - med = statistics.median(tps) - eff = med * nbytes / 1e9 - return {"decode_tps_median": round(med, 2), "weight_bytes": int(nbytes), "weight_source": src, - "mem_bw_gbs": bw * tp, "gpus": tp, "effective_gbs": round(eff, 1), - "pct_of_mem_bw": round(100 * eff / (bw * tp), 1)} - - -def main(d, results=None): - res = json.load(open(results or f"{d}/results.json", encoding="utf-8")) - meta = json.load(open(f"{d}/meta.json", encoding="utf-8")) - c, m = meta["collected"], meta["mandatory"] - t0, t1 = float(os.environ["T0"]), float(os.environ["T1"]) - post = {"wall_s": round(t1 - t0, 1)} - - 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 = read_power(f"{d}/power.csv") - timeline = [] - if os.path.exists(f"{d}/timeline.tsv"): - for line in open(f"{d}/timeline.tsv", encoding="utf-8"): - t, _, text = line.rstrip("\n").partition("\t") - try: - timeline.append((float(t), text)) - except ValueError: - pass - if len(rows) >= 2: - ts, cum, src = energy_curve(rows) - span = ts[-1] - ts[0] - joules = cum[-1] - 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)}") - 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 - - r = roofline(single, c, m) - if r: - post["roofline"] = r - - # 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, dec=0): - return "—" if x is None else f"{x:,.{dec}f} {unit}" - notes = meta["notes"] - tps = [x["decode_tps"] for x in single if x.get("decode_tps")] - 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(x.get('ttft_ms') for x 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 r: - 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 " - f"(weights {r['weight_bytes'] / 1e9:.2f} GB, {r['weight_source']})") - 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 "") - 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 = [] - if ph.get("decode", {}).get("j_per_token") is not None: - parts.append(f"decode {ph['decode']['j_per_token']} J/tok at {ph['decode']['avg_w']} W") - if ph.get("prefill", {}).get("j_per_1k_tokens") is not None: - parts.append(f"prefill {ph['prefill']['j_per_1k_tokens']} J/1k tok") - if parts: - L.append(" energy " + " · ".join(parts)) - if ph.get("concurrency"): - L.append(" energy by conc. " + " ".join( - f"{k}: {v['j_per_token']} J/tok" for k, v in ph["concurrency"].items() - if v.get("j_per_token") is not None)) - L.append(f" energy (total) {e['joules'] / 1000:.1f} kJ, " - f"{e['j_per_output_token']} J per output token over the 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 fh: - json.dump(meta, fh, indent=2) - fh.write("\n") - - -if __name__ == "__main__": - main(*sys.argv[1:3]) -__BENCH_STANDARD_EOF__ -cat > "$d/models.tsv" <<'__BENCH_STANDARD_EOF__' -# name engine quant sha256 (a GGUF file, or a safetensors directory: README, Models) -Qwen3.5-9B llama.cpp Q4_K_M 03b74727a860a56338e042c4420bb3f04b2fec5734175f4cb9fa853daf52b7e8 -Qwen3.8-27B llama.cpp UD-Q4_K_M 322e194ff79741c7baa497c240f677f54b201b0efab44ca8e50f122b39123482 -Qwen3.5-9B vllm w4a16 cca16f9855b9f92eee5876ddc8656ed6397316ffc65b9f17ca1939a9549e4c26 -Qwen3.8-27B vllm w4a16 bffa6b23fa11be557fe9de4b122a8bb99f537ad7a1a4effa702f7d0c677778f7 -__BENCH_STANDARD_EOF__ cat > "$d/config.json" <<'__BENCH_STANDARD_EOF__' { "temperature": 0.7, @@ -1619,10 +1458,20 @@ cat > "$d/config.json" <<'__BENCH_STANDARD_EOF__' __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.6.0 +# config.json, models.txt, the minimum BetterBench or the recorded fields change. +STANDARD_VERSION=0.5.0 # Oldest BetterBench that has everything bench.sh uses; newer ones run too, # and the version goes into the run note so compare shows a mismatch. BETTERBENCH_MIN_VERSION=0.6.1 __BENCH_STANDARD_EOF__ -sh "$d/bench.sh" "$@" +cat > "$d/models.txt" <<'__BENCH_STANDARD_EOF__' +# The standard models: results only count for these files. Same as the +# README's model table; change both together and bump STANDARD_VERSION. +# sha256 (a GGUF file, or a repo's *.safetensors as in the README) --quant name +03b74727a860a56338e042c4420bb3f04b2fec5734175f4cb9fa853daf52b7e8 Q4_K_M Qwen3.5-9B-Q4_K_M.gguf +322e194ff79741c7baa497c240f677f54b201b0efab44ca8e50f122b39123482 UD-Q4_K_M Qwen3.8-27B-UD-Q4_K_M.gguf +cca16f9855b9f92eee5876ddc8656ed6397316ffc65b9f17ca1939a9549e4c26 w4a16 RedHatAI/Qwen3.5-9B-quantized.w4a16 +bffa6b23fa11be557fe9de4b122a8bb99f537ad7a1a4effa702f7d0c677778f7 w4a16 RedHatAI/Qwen3.8-27B-INT4 +__BENCH_STANDARD_EOF__ +trap - EXIT INT TERM +BENCH_UNPACKED=$d exec sh "$d/bench.sh" "$@" diff --git a/dev/DETAILS.md b/dev/DETAILS.md index d74fc34..5135dcc 100644 --- a/dev/DETAILS.md +++ b/dev/DETAILS.md @@ -9,23 +9,20 @@ 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 the core and memory clocks every 2 s. +4. BetterBench runs while `gpu-power.sh` (also `bench.sh power`) samples power, energy and clock every 2 s. 5. A summary prints. Energy and % of bandwidth are written to `meta.json`. ## Files in a run folder -`` is the folder's name, `____x-[_quick][_2]` -with `N` = tp × pp; see the README. - | file | what | |---|---| -| `.json` | BetterBench results; the notes below are under `env.notes` | -| `.html` | the standalone report | +| `results.json` | BetterBench results; the notes below are under `env.notes` | +| `results.html` | the standalone report | | `config.json` | the BetterBench config the run used | -| `meta.json` | every raw value: `mandatory` (declared), `collected` (detected), `measured`, `launch`, `post_run` | +| `meta.json` | every raw value: `mandatory` (declared), `collected` (detected), `measured`, `launch`, `post_run`, `warnings` | +| `summary.txt` | the summary printed at the end, warnings included | | `server-cmd.txt` | the server launch command, secrets redacted | -| `power.csv` | `epoch_s,watts,joules,mhz,mem_mhz` during the run | -| `timeline.tsv` | when each BetterBench progress line appeared, for the energy per phase | +| `power.csv` | `epoch_s,watts,joules,mhz` during the run | | `betterbench.log` | BetterBench's full output | ## Notes @@ -36,22 +33,21 @@ 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 · max 2800 MHz core · 19000 MHz mem` (VRAM per GPU, max clocks of the first) | +| `gpu` | `1x Intel Arc Pro B65 · 32 GB · driver 1.17.39395` (VRAM per GPU) | | `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` | | `engine` | `llama.cpp b11913-7aca0d2ea · 4 slots · image ghcr.io/ggml-org/llama.cpp:server-intel@1a2b3c4d5e6f · via llama-swap` | -| `model_file` | `/models/Qwen3.8-27B-UD-Q4_K_M.gguf · 16.46 GB · standard: Qwen3.8-27B UD-Q4_K_M`, `... · not a standard model (sha256 4f58a79550e8)` | +| `model_file` | `/models/Qwen3.5-9B-Q4_K_M.gguf · 5.68 GB · sha256 03b74727a860 (standard: Qwen3.5-9B-Q4_K_M.gguf)` (weights as stored; `not a standard model` otherwise) | | `mem_bw` | `532 GB/s measured (torch copy, random, 1024 MiB) · 608 GB/s declared` | | `parallel` | `tp 1 · pp 1` | | `precision` | `weights Q4_0 · kv f16` | -| `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.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 | +| `run` | `full · concurrency on · bench-standard 0.5.0 · betterbench 0.6.1` | | `special_notes` | only when given | The context size appears as BetterBench's own chip. @@ -60,21 +56,6 @@ 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`. @@ -87,6 +68,15 @@ This works in a VM too, because passthrough keeps BAR sizes. launch command. For a docker server the image is recorded with its ID, because tags like `server-intel` move daily. +**Model file:** the path the engine reports (`/props` `model_path`, vLLM's `root`). A path +inside a docker container is mapped back to the host through the command's `-v` and +`--mount` flags; a vLLM repo id is looked up in the Hugging Face cache (the container's +`HF_HOME` through its mounts, then this machine's). The size is that of the GGUF (all +parts of a split one) or of the `*.safetensors`. The hash is the one the README's table +lists (split GGUFs aren't hashed); it's cached in `~/.cache/bench-standard/` by path, +size and mtime. `dev/models.txt` holds the table; a hash not in it, or a `--quant` other +than the table's, gives a warning. + **Launch settings** come from the launch command, because no API reports them: - llama.cpp: `b`, `ub`, `fa`, `ctk` and `ctv` always show, as `default` when not set, because the defaults change between builds. @@ -94,20 +84,12 @@ launch command. For a docker server the image is recorded with its ID, because t - **Env flags** come from `VAR=x cmd`, `env VAR=x` and docker `-e VAR=x`. Settings in llama-swap's `env:` block, or in the shell that started the server, aren't visible; put them in the command. -- If `--kv` doesn't match the command, `bench.sh` warns. - -**Model file:** the path comes from the launch command. `model_hash.py` hashes it the -way the README's Models section does (a GGUF file, or the `*.safetensors` of a -directory) and looks the hash up in `models.tsv`. Not a standard model, or a `--quant` -that differs from the table, gives a warning. Per-file hashes are cached in -`~/.cache/bench-standard/sha256.tsv` by path, size and mtime, so only the first run -waits (about a minute for 16 GB). `HASH_MODEL=0` skips it, and the note then reads -`hash not checked`. When the server runs in docker, the path is the one inside the -container. If that path doesn't exist on the host, the hash can't be checked either. - -**BetterBench build:** read from pip's record of where it was installed from: the git -commit for `pip install git+...`, or `git describe` of the checkout for an editable -install. A release tag adds nothing to the `run` note; a commit or `-dirty` does. +- Declared values are checked against the command, and a contradiction is a warning + that names the value to declare: `--kv` (llama.cpp `-ctk`/`-ctv`, f16 when one is + unset; vLLM `--kv-cache-dtype`, or `--dtype` when that is `auto`), `--spec` (llama.cpp + `-md` with `--draft-max`, default 16; vLLM `--speculative-config`), `--thinking` + (`--reasoning-budget 0` or `enable_thinking: false` mean `off`) and, for vLLM, `--tp` + and `--pp`. Settings the command doesn't state aren't guessed. **Memory bandwidth:** `mem-bw.py` copies 1 GiB of random data with torch, inside the server's container (same GPU, env and torch), or with `$BW_PYTHON`. It uses random @@ -128,23 +110,18 @@ tags in the text. `bench.sh` warns when `--thinking off` meets reasoning, or whe These go to `meta.json` under `post_run` and the summary, not to the notes, which are fixed before BetterBench starts. -- **energy:** kJ, average and peak W, J per output token over the whole run, and - average, min and max core and memory clock. The clock counts only samples where the GPU is running. +- **energy:** kJ, average and peak W, J per output token, and average, min and max clock. + Sampled with `nvidia-smi`, `xpu-smi`, or amdgpu's hwmon files in sysfs (power and + clock; no energy counter, so the power is integrated). + The clock counts only samples where the GPU is running. The figures cover the + **whole run**, warm-up and prefill included, so compare only runs of the same mode. Power is sampled only when BetterBench runs on the server. On a split setup, run `bench.sh power > power.csv` on the server yourself. -- **energy per phase** (`energy.phases`): each BetterBench progress line is stamped in - `timeline.tsv`, and a piece of work lasts until the next line. That gives joules and - average W for decode (J per output token), prefill (J per 1000 prompt tokens) and each - concurrency level (J per token). The warm-up passes draw power but aren't in - the results, so their tokens are estimated from the measured passes of the same - piece (`tokens_incl_warmup_est`). These compare across quick and full runs; the - whole-run figure doesn't. - **roofline:** median batch-1 decode t/s × weight bytes ÷ memory bandwidth = % of - bandwidth. The weight bytes are what vLLM logs as loaded ("Model loading took X GiB", - per GPU, × tp), which is right for models quantized at load (fp8 from bf16 files reads - half of what's stored). Otherwise the stored size, without `*mtp*` files, since plain - decoding doesn't read an MTP head. With tp > 1 the bandwidth is per GPU × tp. It holds - for dense models; spec decoding and MoE can exceed 100%. + bandwidth. It holds for dense models. Spec decoding and MoE can exceed 100%. So + can models quantized at load (e.g. vLLM fp8 from bf16 files), because they read + fewer bytes than are stored. For safetensors the size includes every file, so the + RedHatAI models' MTP head adds about 5%. ## BetterBench with PR #4 @@ -157,21 +134,19 @@ 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`, `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. +`dev/bench.sh`, `collect-env.sh`, `gpu-power.sh`, `mem-bw.py`, `config.json`, +`standard.env` and `models.txt` into it. At run time it unpacks them to a temp dir and +exec's `dev/bench.sh` from there, with `BENCH_HOME` set to its own folder, so `results/` +and `bench.local.env` stay next to the downloaded file. `dev/bench.sh` removes the temp +dir when it exits (`BENCH_UNPACKED`). ```sh sh dev/build.sh # after any change in dev/; commit dev/ and bench.sh together sh dev/build.sh --check # fails if bench.sh is out of date +sh dev/test.sh # end-to-end tests: fake server, fake BetterBench, no GPU sh dev/bench.sh --help # dev/bench.sh also runs directly, results in dev/results/ -pytest dev/tests # the notes, model hash and post-run figures ``` -CI (`.github/workflows/ci.yml`) runs shellcheck, `build.sh --check` and the tests. -A model added to the README's table goes into `dev/models.tsv` too. - BetterBench 0.6.1 is the oldest version that works (`BETTERBENCH_MIN_VERSION` in `standard.env`). Newer ones run too, and their version goes into the `run` note. Bump `STANDARD_VERSION` when `config.json`, the minimum BetterBench or the recorded diff --git a/dev/bench.sh b/dev/bench.sh index c9594b5..98ffde8 100755 --- a/dev/bench.sh +++ b/dev/bench.sh @@ -33,16 +33,22 @@ # --results-dir DIR default: results/ next to bench.sh # --env-file FILE when BetterBench runs on another machine than the GPU: # the output of 'bench.sh collect-env' run on the GPU box +# --settings FILE your saved values (default: bench.local.env next to +# bench.sh, if it exists) # # Other commands: +# bench.sh init [FILE] write a settings file to fill in once, so you +# don't type the values every time # bench.sh collect-env --endpoint URL --model ID print the detected setup # bench.sh power [SECONDS] sample GPU power, energy and clock until killed # bench.sh --version # -# Values can also come from the environment: BENCH_TP, BENCH_PP, BENCH_QUANT, -# BENCH_KV, BENCH_SPEC, BENCH_THINKING, BENCH_SUBMITTER, BENCH_POWER_LIMIT, -# BENCH_PCIE, BENCH_MEM_BW, BENCH_SPECIAL_NOTES, BENCH_RESULTS_DIR. Machine- -# local defaults like these go in bench.local.env next to bench.sh. +# Saved values: bench.local.env (see 'bench.sh init') or the environment, as +# BENCH_SUBMITTER, BENCH_ENDPOINT, BENCH_MODEL, BENCH_SERVER_CMD_FILE, +# BENCH_TP, BENCH_PP, BENCH_QUANT, BENCH_KV, BENCH_SPEC, BENCH_THINKING, +# BENCH_POWER_LIMIT, BENCH_PCIE, BENCH_MEM_BW, BENCH_SPECIAL_NOTES, +# BENCH_RESULTS_DIR, BENCH_ENV_FILE. Flags win over the environment, which +# wins over the file. # Send the whole results// folder. Only --full runs count. # The standard models and their hashes: README.md. For agents: AGENTS.md. @@ -53,19 +59,130 @@ umask 002 here=$(cd "$(dirname "$0")" && pwd) home=${BENCH_HOME:-$here} . "$here/standard.env" -# Machine-local defaults (e.g. BENCH_RESULTS_DIR), not part of the standard. -[ -f "$home/bench.local.env" ] && . "$home/bench.local.env" die() { echo "bench.sh: $*" >&2; exit 1; } usage() { sed -n '2,/^$/p' "$0" | sed -e 's/^# \{0,1\}//' -e '$d'; exit "${1:-0}"; } +# Cleanup and signals. Long steps run in the background with `wait`, which a +# trapped signal interrupts at once (a foreground child would delay the trap +# until it finished). Background jobs ignore Ctrl-C, so the trap stops them. +# The one-file bench.sh hands its unpacked helpers over in BENCH_UNPACKED and +# exec's this script, so a kill of that pid lands here. +tmp="" child="" sampler="" run_dir_made="" +cleanup() { + for p in $child $sampler; do kill "$p" 2>/dev/null || true; done + [ -z "$tmp" ] || rm -rf "$tmp" + [ "${BENCH_UNPACKED:-}" != "$here" ] || rm -rf "$here" +} +on_signal() { + trap - INT TERM + for p in $child; do kill "$p" 2>/dev/null || true; wait "$p" 2>/dev/null || true; done + child="" + if [ -n "$run_dir_made" ] && [ -d "$run_dir_made" ]; then + mv "$run_dir_made" "$run_dir_made.interrupted" 2>/dev/null && + echo "bench.sh: interrupted; partial output in $run_dir_made.interrupted (it doesn't count)" >&2 + fi + exit "$1" +} +trap cleanup EXIT +trap 'on_signal 130' INT +trap 'on_signal 143' TERM +# bg CMD...: run CMD in the background, wait for it; its status in $rc. +bg() { "$@" & child=$!; rc=0; wait "$child" || rc=$?; child=""; } + +# The settings file people fill in once (bench.sh init writes it). +settings_template() { + cat <<'EOF' +# bench.local.env - your values for ./bench.sh, so you don't type them every +# time. Fill in what's empty, then run just: ./bench.sh (or --dry-run, --full) +# +# One KEY=value per line; '#' starts a comment; quote values with spaces. +# Relative paths are relative to this file. Flags on the command line win over +# the environment, which wins over this file. Never put the API key here: +# export BETTERBENCH_API_KEY in your shell instead. + +# --- you and your server ------------------------------------------------- +BENCH_SUBMITTER= # your name +BENCH_ENDPOINT=http://localhost:8080/v1 # the server's base URL, ending in /v1 +BENCH_MODEL= # the id exactly as /v1/models lists it +BENCH_SERVER_CMD_FILE= # file with the server's launch command, + # e.g. server-cmd.txt; empty behind llama-swap + +# --- what you declare (README: "What you declare") ----------------------- +BENCH_QUANT= # from the model table: Q4_K_M, UD-Q4_K_M or w4a16 +BENCH_KV=f16 # f16, q8_0, q8_0/f16 (K/V differ), bf16, fp8 +BENCH_TP=1 # tensor parallel size +BENCH_PP=1 # pipeline parallel size +BENCH_SPEC=none # none, mtp:5, eagle3:4, ngram:4, draft:8 +BENCH_THINKING=default # set on the server: default, off, on, low, medium, high + +# --- only when needed ---------------------------------------------------- +# BENCH_POWER_LIMIT=250 # when the GPU can't report it, or: stock +# BENCH_PCIE="Gen4 x16" # inside a VM +# BENCH_MEM_BW=608 # the card's spec memory bandwidth, GB/s +# BENCH_SPECIAL_NOTES="undervolted" # anything unusual +# BENCH_RESULTS_DIR=results # where run folders go +# WARM_TIMEOUT=1800 # a slow first model load behind llama-swap +EOF +} + +# load_settings FILE - set each KEY=value the environment doesn't set already. +# Read as data, not run as shell code. +loaded="" +load_settings() { + sdir=$(cd "$(dirname "$1")" && pwd) n=0 + while IFS= read -r line || [ -n "$line" ]; do + n=$((n + 1)) + line=${line#"${line%%[![:space:]]*}"} + case $line in ''|'#'*) continue ;; esac + line=${line#export } + case $line in *=*) ;; *) die "$1 line $n: want KEY=value" ;; esac + key=${line%%=*} val=${line#*=} + case $key in ''|[0-9]*|*[!A-Z0-9_]*) die "$1 line $n: '$key' is not a variable name" ;; esac + [ "$key" != BETTERBENCH_API_KEY ] || + die "$1 line $n: keep the API key out of files; export BETTERBENCH_API_KEY in your shell" + case $val in + \"*) val=${val#\"}; case $val in *\"*) val=${val%%\"*} ;; *) die "$1 line $n: missing closing quote" ;; esac ;; + \'*) val=${val#\'}; case $val in *\'*) val=${val%%\'*} ;; *) die "$1 line $n: missing closing quote" ;; esac ;; + *) val=${val%%[[:space:]]#*}; val=${val%"${val##*[![:space:]]}"} ;; + esac + # shellcheck disable=SC2088 # a literal ~/ in the file, expanded here + case $val in '~/'*) val=$HOME/${val#'~/'} ;; '$HOME/'*) val=$HOME/${val#'$HOME/'} ;; esac + case $key in *_FILE|*_DIR) case $val in /*|'') ;; *) val=$sdir/$val ;; esac ;; esac + eval "isset=\${$key+y}" + if [ -z "$isset" ]; then + eval "$key=\$val"; export "${key?}" + [ -z "$val" ] || loaded="$loaded $key" + fi + done < "$1" +} + case "${1:-}" in - collect-env) shift; exec sh "$here/collect-env.sh" "$@" ;; - power) shift; exec sh "$here/gpu-power.sh" "$@" ;; + init) + out=${2:-$home/bench.local.env} + [ ! -e "$out" ] || die "$out exists; edit it, or remove it first" + settings_template > "$out" || die "cannot write $out" + echo "wrote $out - fill in the empty values, then run ./bench.sh --dry-run" + exit 0 ;; + collect-env) shift; rc=0; sh "$here/collect-env.sh" "$@" || rc=$?; exit "$rc" ;; + power) shift; bg sh "$here/gpu-power.sh" "$@"; exit "$rc" ;; --version) echo "bench-standard $STANDARD_VERSION (BetterBench $BETTERBENCH_MIN_VERSION or newer)"; exit 0 ;; esac -endpoint="" model="" server_cmd_file="" env_file="" quick=1 no_conc=0 dry=0 verbose=0 +# --settings is read before the other flags, so that they win over it. +settings="" prev="" +for a; do [ "$prev" = --settings ] && settings=$a; prev=$a; done +if [ -n "$settings" ]; then + [ -f "$settings" ] && [ -r "$settings" ] || die "cannot read settings file $settings" + load_settings "$settings" +elif [ -f "$home/bench.local.env" ]; then + settings=$home/bench.local.env + load_settings "$settings" +fi +[ -z "$loaded" ] || echo "settings from $settings:$loaded" >&2 + +endpoint=${BENCH_ENDPOINT:-} model=${BENCH_MODEL:-} server_cmd_file=${BENCH_SERVER_CMD_FILE:-} +env_file=${BENCH_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:-} @@ -81,6 +198,7 @@ while [ $# -gt 0 ]; do --server-cmd-file) need $# "$1"; server_cmd_file=$2; shift 2 ;; --env-file) need $# "$1"; env_file=$2; shift 2 ;; --results-dir) need $# "$1"; results_dir=$2; shift 2 ;; + --settings) need $# "$1"; shift 2 ;; --tp) need $# "$1"; tp=$2; shift 2 ;; --pp) need $# "$1"; pp=$2; shift 2 ;; --quant) need $# "$1"; quant=$2; shift 2 ;; @@ -113,23 +231,14 @@ sys.exit(not sys.argv[1] or v(sys.argv[1]) < v(sys.argv[2]))' "$have_ver" "$BETT die "BetterBench $BETTERBENCH_MIN_VERSION or newer required, found '${have_ver:-not installed}'" \ "(see https://github.com/GGZ14/BetterBench)" command -v curl >/dev/null || die "curl not found" -# The exact build: two installs can both say 0.6.1. pip records where it came -# from: a git commit, or a local checkout (then git describes it). -bb_build=$(bb=$(command -v betterbench) && py=$(sed -n '1s/^#!//p' "$(readlink -f "$bb")") && - $py -c 'import importlib.metadata as m, json -u = json.loads(m.distribution("betterbench").read_text("direct_url.json") or "{}") -c = (u.get("vcs_info") or {}).get("commit_id") -print(c[:12] if c else u.get("url", "")[7:] if u.get("url", "").startswith("file://") else "")' 2>/dev/null) || bb_build="" -if [ -d "$bb_build" ]; then - bb_build=$(git -c safe.directory='*' -C "$bb_build" describe --tags --always --dirty 2>/dev/null) || bb_build="" -fi missing="" for f in endpoint model tp pp quant kv spec thinking submitter; do eval "v=\${$f}" [ -n "$v" ] || missing="$missing --$(printf '%s' "$f" | tr _ -)" done -[ -z "$missing" ] || die "missing mandatory value(s):$missing" +[ -z "$missing" ] || die "missing mandatory value(s):$missing" \ + "(as flags, or saved in ${settings:-bench.local.env}; './bench.sh init' writes one to fill in)" matches "$tp" '[1-9][0-9]*' || die "--tp must be a positive integer" matches "$pp" '[1-9][0-9]*' || die "--pp must be a positive integer" @@ -151,7 +260,12 @@ if [ -n "$server_cmd_file" ]; then [ -r "$server_cmd_file" ] || die "cannot read if [ -n "$env_file" ]; then [ -r "$env_file" ] || die "cannot read $env_file"; fi tmp=$(mktemp -d) -trap 'rm -rf "$tmp"' EXIT INT TERM + +# Warnings print as they come and are repeated after the summary, so none +# scroll away during a long run; meta.json keeps them too. +warnings="$tmp/warnings" +: > "$warnings" +warn() { echo "bench.sh: warning: $*" >&2; printf '%s\n' "$*" >> "$warnings"; } hdr="$tmp/hdr" if [ -n "${BETTERBENCH_API_KEY:-}" ]; then printf 'Authorization: Bearer %s\n' "$BETTERBENCH_API_KEY" > "$hdr" @@ -206,6 +320,9 @@ else: print(f"greedy_variants={len(set(hashes))}\ngreedy_runs={len(hashes)}\ngreedy_hash={hashes[0]}") print("greedy_reasoning=" + ("yes" if all(thought) else "no" if not any(thought) else "mixed")) PY +if grep -q '^greedy_check=failed' "$tmp/measured"; then + warn "greedy check failed ($(sed -n 's/^greedy_error=//p' "$tmp/measured")); the result has no greedy hash" +fi # ---------------------------------------------------------------- collect if [ -n "$env_file" ]; then @@ -233,7 +350,7 @@ fi [ -n "$pcie" ] && printf 'pcie=%s\n' "$pcie" [ -n "$special" ] && printf 'special_notes=%s\n' "$special" [ -n "$mem_bw" ] && printf 'mem_bw=%s\n' "$mem_bw" - printf 'betterbench=%s\nbetterbench_build=%s\n' "$have_ver" "$bb_build" + printf 'betterbench=%s\n' "$have_ver" printf 'bench_standard=%s\nrun_mode=%s\nconcurrency=%s\n' "$STANDARD_VERSION" \ "$([ $quick = 1 ] && echo quick || echo full)" "$([ $no_conc = 1 ] && echo off || echo on)" } > "$tmp/mandatory" @@ -255,8 +372,13 @@ if [ -n "$cmd_src" ]; then python3 - "$tmp/cmd" "$tmp/cmd.red" <<'PY' import re, sys s = open(sys.argv[1], encoding="utf-8", errors="replace").read() -s = re.sub(r'(?i)\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY)[A-Z0-9_]*=)\S+', r'\1', s) -s = re.sub(r'(?i)(--(?:api-key|hf-token|token)[= ])\S+', r'\1', s) +# Env assignments (FOO_TOKEN=x, -e FOO_TOKEN=x, --env=FOO_TOKEN=x) - not +# flags like --max-num-batched-tokens=8192, hence no '-' right before. +s = re.sub(r'(?i)(?', s) +s = re.sub(r'(?i)((?', s) +# user:password@ in URLs (proxies, registries) +s = re.sub(r'(?i)(\b[a-z][a-z0-9+.-]*://[^\s:/@]+:)[^\s@/]+@', r'\1@', s) open(sys.argv[2], "w", encoding="utf-8").write(s if s.endswith("\n") else s + "\n") PY fi @@ -264,35 +386,303 @@ fi # The notes are grouped for reading: one chip per topic, nothing twice. # The context size is left out - BetterBench shows it from --max-model-len. # launch.json: the settings parsed from the launch command, for meta.json. -python3 "$here/notes.py" "$tmp/mandatory" "$tmp/collected" "$tmp/measured" "$tmp/cmd.red" \ - "$tmp/launch.json" "$here/models.tsv" > "$tmp/notes" +WARNINGS=$warnings MODELS=$here/models.txt \ +python3 - "$tmp/mandatory" "$tmp/collected" "$tmp/measured" "$tmp/cmd.red" "$tmp/launch.json" \ + > "$tmp/notes" <<'PY' +import json, os, re, shlex, sys +def warn(msg): + print("bench.sh: warning: " + msg, file=sys.stderr) + with open(os.environ["WARNINGS"], "a", encoding="utf-8") as f: + f.write(msg + "\n") +def kv(path): + with open(path, encoding="utf-8") as f: + return dict(l.rstrip("\n").split("=", 1) for l in f if "=" in l) +m, c, meas = kv(sys.argv[1]), kv(sys.argv[2]), kv(sys.argv[3]) +cmd = open(sys.argv[4], encoding="utf-8").read().strip() +def g(k): + v = c.get(k, "") + return "" if v in ("", "unknown") else v +def join(*parts): + return " · ".join(p for p in parts if p) or "unknown" -engine=$(get engine) gpu=$(get gpu_model) ctx=$(get ctx) -[ "$engine" != unknown ] || echo "bench.sh: warning: engine not detected; result is hard to compare" >&2 +vendor = {"intel": "Intel", "nvidia": "NVIDIA", "amd": "AMD"}.get(g("gpu_vendor"), g("gpu_vendor")) +count = g("gpu_count") if g("gpu_count") != "0" else "" # 0: nothing detected +gpu = join(" ".join(p for p in (count and count + "x", vendor if vendor != "none" else "", + g("gpu_model")) if p), + g("gpu_vram_gb") and g("gpu_vram_gb") + " GB", + g("gpu_driver") and "driver " + g("gpu_driver")) + +link, top = g("pcie_link"), g("pcie_max") +if m.get("pcie"): + pcie = m["pcie"] + " (declared)" +elif link and top and link != top: + pcie = f"{link} now, {top} max" # idle GPUs drop the link speed +else: + pcie = link or "unknown" +if g("rebar"): + pcie += " · ReBAR " + g("rebar") + +pl, det = m["power_limit"], g("gpu_power_limit_w") +if pl == "stock": + power = join("stock", det and det + " W") +else: + power = pl + " W" + if det and abs(float(det) - float(pl)) > 1: + power += f" (GPU reports {det} W)" + +virt = g("virt") +host = join(g("cpu_model"), g("ram_gb") and g("ram_gb") + " GB RAM", g("os"), + g("kernel") and "kernel " + g("kernel"), virt != "none" and virt and "VM " + virt) + +# Settings in the launch command that swing results but no API reports: +# batch sizes, flash attention, KV types, env flags. Flags left out of the +# command are the engine's defaults, which change between versions. +try: + words = shlex.split(cmd.replace("\\\n", " ")) +except ValueError: + words = cmd.split() +env, flags, prog = {}, {}, None +BOOL = {"--no-mmap", "--mlock", "--enforce-eager", "--enable-prefix-caching", + "--no-enable-prefix-caching", "--enable-chunked-prefill", + "--no-enable-chunked-prefill", "--cont-batching", "-cb", "--no-cont-batching", "-nocb", + "-cmoe", "--cpu-moe", "-rm", "--rm", "-d", "--detach", "-it", "-i", "--privileged", + "--init", "--jinja", "--no-webui", "--metrics", "--trust-remote-code", + "--enable-auto-tool-choice", "--disable-log-requests", "--disable-log-stats"} +def is_value(x): # the next word is this flag's value: not a flag, or a number + return x is not None and (not x.startswith("-") or re.fullmatch(r"-[0-9.]+", x)) +FA_VALUES = {"on", "off", "auto", "1", "0", "true", "false"} +i = 0 +while i < len(words): + 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 not is_value(nxt): + 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 values should be what the launch command sets (AGENTS.md +# step 4). Only what the command states is checked; defaults are assumed +# only where the standard defines them (llama.cpp KV f16, vLLM tp/pp 1). +def expect(name, declared, wanted, why): + if wanted is not None and declared != wanted: + warn(f"--{name} {declared} but the launch command sets {why}: declare --{name} {wanted}") + +if cmd and launch_kind == "llama.cpp": + k, v = flag("-ctk", "--cache-type-k"), flag("-ctv", "--cache-type-v") + if k or v: + k, v = k or "f16", v or "f16" + expect("kv", m["kv"], k if k == v else f"{k}/{v}", f"K {k}, V {v}") +elif cmd and launch_kind == "vllm": + kvd, dt = flag("--kv-cache-dtype"), str(flag("--dtype") or "") + if kvd and kvd != "auto": + expect("kv", m["kv"], kvd, f"--kv-cache-dtype {kvd}") + elif dt in ("bfloat16", "float16", "half"): + expect("kv", m["kv"], "bf16" if dt == "bfloat16" else "f16", + f"--kv-cache-dtype {kvd or 'unset'} with --dtype {dt}") + +# Speculative decoding. +spec_cmd = None +if cmd and launch_kind == "llama.cpp": + if flag("-md", "--model-draft", "-hfd", "-hfrd", "--hf-repo-draft"): + n = flag("--draft-max", "--draft", "--draft-n") + if n and str(n).isdigit(): + spec_cmd = (f"draft:{n}", f"a draft model with --draft-max {n}") + elif not m["spec"].startswith("draft:"): # the default N varies between builds + warn(f"--spec {m['spec']} but the launch command loads a draft model (-md):" + " declare draft:N, N = the build's --draft-max default") + else: + spec_cmd = ("none", "no draft model") +elif cmd and launch_kind == "vllm": + sc, n = flag("--speculative-config"), flag("--num-speculative-tokens") + if sc not in (None, True): + try: + j = json.loads(sc) + except ValueError: + j = dict(re.findall(r'"?(method|num_speculative_tokens|model)"?\s*[:=]\s*"?([\w./-]+)', sc)) + meth = str(j.get("method") or ("draft" if j.get("model") else "")) + meth = ("mtp" if "mtp" in meth else "draft" if meth.startswith("draft") else + meth if meth in ("eagle", "eagle3", "ngram") else None) + n = j.get("num_speculative_tokens") or n + if meth and n: + spec_cmd = (f"{meth}:{n}", f"--speculative-config {sc}") + elif not flag("--speculative-model"): + spec_cmd = ("none", "no --speculative-config") +if spec_cmd: + expect("spec", m["spec"], spec_cmd[0], spec_cmd[1]) + +if cmd and launch_kind == "vllm": + expect("tp", m["tp"], str(flag("--tensor-parallel-size", "-tp") or 1), "that tensor parallel size") + expect("pp", m["pp"], str(flag("--pipeline-parallel-size", "-pp") or 1), "that pipeline parallel size") + +# Thinking switched off (or on) in the launch command. +think_cmd = None +if str(flag("--reasoning-budget")) == "0": + think_cmd = "--reasoning-budget 0" +et = re.search(r'enable_thinking"?\s*:\s*(true|false)', cmd, re.I) +if et: + think_cmd = think_cmd or f"enable_thinking: {et.group(1).lower()}" +if think_cmd and ("false" in think_cmd or "budget 0" in think_cmd): + expect("thinking", m["thinking"], "off", think_cmd) +elif think_cmd and m["thinking"] == "off": + warn(f"--thinking off but the launch command sets {think_cmd}") + +# Results only count for the standard models (models.txt = the README's table). +std = {} +with open(os.environ["MODELS"], encoding="utf-8") as f: + for line in f: + p = line.split() + if len(p) == 3 and not p[0].startswith("#"): + std[p[0]] = (p[1], p[2]) +sha = g("model_sha256") +if sha in std: + sha_note = f"sha256 {sha[:12]} (standard: {std[sha][1]})" + if m["quant"] != std[sha][0]: + warn(f"--quant {m['quant']} but the model file is {std[sha][1]}: declare --quant {std[sha][0]}") +elif sha: + sha_note = f"sha256 {sha[:12]} (not a standard model)" + warn(f"the model file (sha256 {sha[:12]}) is not one of the standard models in the README;" + " results only count for those files") +else: + sha_note = "" +mb = g("model_bytes") +model_file = join(g("model_file"), mb and f"{int(mb) / 1e9:.2f} GB", sha_note) +mem_bw = join(g("gpu_mem_bw_gbs") and + f'{g("gpu_mem_bw_gbs")} GB/s measured ({g("gpu_mem_bw_tool") or "?"})', + m.get("mem_bw") and m["mem_bw"] + " GB/s declared") +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" + +# --thinking is declared, but the greedy replies show whether the model +# reasoned: check one against the other. +seen = meas.get("greedy_reasoning") +thinking = join(m["thinking"], {"yes": "reasoning seen", "no": "no reasoning seen", + "mixed": "reasoning in some replies"}.get(seen, "")) +if m["thinking"] == "off" and seen in ("yes", "mixed"): + warn("--thinking off, but the greedy replies contain reasoning;" + " check the server's chat template or reasoning flags") +elif m["thinking"] in ("on", "low", "medium", "high") and seen == "no": + warn(f"--thinking {m['thinking']}, but the greedy replies contain no" + " reasoning; thinking may be off on the server") + +eng = g("engine") +engine = join(" ".join(p for p in (eng, g("engine_version")) if p), + g("engine_slots") and g("engine_slots") + " slots", + g("engine_image") and "image " + g("engine_image"), + g("proxy") not in ("", "none") and "via " + g("proxy")) + +notes = [ + ("submitter", m["submitter"]), + ("gpu", gpu), + ("pcie", pcie), + ("power_limit", power), + ("host", host), + ("engine", engine), + ("model_file", model_file), + ("mem_bw", mem_bw), + ("parallel", f"tp {m['tp']} · pp {m['pp']}"), + ("precision", f"weights {m['quant']} · kv {m['kv']}"), + ("launch", launch), + ("env_flags", env_flags), + ("spec", m["spec"]), + ("thinking", thinking), + ("greedy_check", greedy), + ("run", join(m["run_mode"], "concurrency " + m["concurrency"], + "bench-standard " + m["bench_standard"], "betterbench " + m["betterbench"])), +] +if m.get("special_notes"): + notes.append(("special_notes", m["special_notes"])) +for k, v in notes: + print(f"{k}={v}") +PY + +engine=$(get engine) gpu=$(get gpu_model) count=$(get gpu_count) ctx=$(get ctx) +[ "$engine" != unknown ] || warn "engine not detected; result is hard to compare" if [ "$power_src" = declared ] && [ "$power_limit" != stock ] && matches "$pl" '[0-9.]+' && [ "$(awk -v a="$pl" -v b="$power_limit" 'BEGIN{print (a-b>1||b-a>1)}')" = 1 ]; then - echo "bench.sh: warning: --power-limit $power_limit W but the GPU reports $pl W" >&2 + warn "--power-limit $power_limit W but the GPU reports $pl W" fi -# File names: ____x-[_quick][_2], -# with N the GPUs the model runs on (tp x pp); _2, _3, ... for another run of -# the same setup on the same day. Fields are joined with _ since -# model names have dashes. The run folder and the exported results.json/.html -# are named alike, so a file sent on its own still says what it is. +matches "$count" '[2-9]|[1-9][0-9]+' && gpu="${count}x-$gpu" slug() { tr 'A-Z' 'a-z' | sed -e 's/[^a-z0-9.]\{1,\}/-/g' -e 's/^-//' -e 's/-$//'; } -gpu=$(printf '%s' "$gpu" | slug) -name="$(printf '%s' "$model" | slug)_$(printf '%s' "$engine" | slug)_$((tp * pp))x-${gpu:-unknown}" -run_id="$(date +%y%m%d)_$(printf '%s' "$submitter" | slug)_$name" -[ $quick = 1 ] && run_id="${run_id}_quick" -base=$run_id i=1 -while [ -e "$results_dir/$run_id" ] || [ -e "$results_dir/$run_id.failed" ]; do - i=$((i + 1)); run_id="${base}_$i" -done -run_dir="$results_dir/$run_id" -results="$run_dir/$run_id.json" +name=$(printf '%s-%s-%s' "$model" "$engine" "$gpu" | slug) + +run_dir="$results_dir/$(date +%Y%m%d-%H%M%S)-$(printf '%s' "$submitter" | slug)-$name" # ---------------------------------------------------------------- run set -- run --no-update-check --endpoint "$endpoint" --model "$model" \ - --config "$run_dir/config.json" --name "$name" --out "$results" + --config "$run_dir/config.json" --name "$name" --out "$run_dir/results.json" [ $quick = 1 ] && set -- "$@" --quick [ $no_conc = 1 ] && set -- "$@" --no-concurrency # Through a proxy /v1/models often lacks the context size; hand over what the @@ -305,11 +695,16 @@ if [ $dry = 1 ]; then printf ' betterbench' for a; do case $a in *[[:space:]]*) printf " '%s'" "$a" ;; *) printf ' %s' "$a" ;; esac; done echo + if [ -s "$warnings" ]; then + echo "$(wc -l < "$warnings") warning(s) - fix or explain them before the real run:" + sed 's/^/ - /' "$warnings" + fi exit 0 fi mkdir -p "$results_dir" mkdir "$run_dir" || die "cannot create $run_dir" +run_dir_made=$run_dir cp "$here/config.json" "$run_dir/config.json" [ -n "$cmd_src" ] && cp "$tmp/cmd.red" "$run_dir/server-cmd.txt" @@ -342,47 +737,43 @@ with open(sys.argv[3], "w", encoding="utf-8") as f: PY # Power is sampled where the GPU is: only when BetterBench runs on the server. -sampler="" +# The sampler exits at once when it finds nothing to read. if [ -z "$env_file" ]; then sh "$here/gpu-power.sh" 2 > "$run_dir/power.csv" 2>/dev/null & sampler=$! - trap 'kill "$sampler" 2>/dev/null || true; rm -rf "$tmp"' EXIT INT TERM fi echo "running betterbench -> $run_dir" >&2 [ $verbose = 1 ] && sed 's/^/ note: /' "$tmp/notes" >&2 t_start=$(date +%s.%N) -# Full output always goes to betterbench.log; the terminal gets all of it -# (--verbose) or the progress lines and anything that looks like trouble. -# timeline.tsv stamps each progress line, for the energy of each phase. -{ PYTHONUNBUFFERED=1 betterbench "$@" 2>&1 || echo $? > "$tmp/bb_rc"; } | - tee "$run_dir/betterbench.log" | - python3 -uc 'import sys, time -tl = open(sys.argv[1], "w", encoding="utf-8") -for line in iter(sys.stdin.readline, ""): - if line.startswith("["): - tl.write(f"{time.time():.3f}\t{line}"); tl.flush() - sys.stdout.write(line); sys.stdout.flush()' "$run_dir/timeline.tsv" | - if [ $verbose = 1 ]; then cat; else grep --line-buffered -E '^\[|^phases|warn|WARN|rror|Traceback' || true; fi >&2 -if [ -s "$tmp/bb_rc" ]; then - mv "$run_dir" "$run_dir.failed" 2>/dev/null || true - die "betterbench failed (exit $(cat "$tmp/bb_rc")); output in $run_dir.failed/betterbench.log" -fi +# Full output always goes to betterbench.log; the terminal follows it: all of +# it (--verbose), or the progress lines and anything that looks like trouble. +: > "$run_dir/betterbench.log" +PYTHONUNBUFFERED=1 betterbench "$@" > "$run_dir/betterbench.log" 2>&1 & +child=$! +tail -n +1 -f --pid="$child" "$run_dir/betterbench.log" | + if [ $verbose = 1 ]; then cat; else grep --line-buffered -E '^\[|^phases|warn|WARN|rror|Traceback' || true; fi >&2 & +follower=$! +bb_rc=0 +wait "$child" || bb_rc=$? +child="" +wait "$follower" 2>/dev/null || true t_end=$(date +%s.%N) if [ -n "$sampler" ]; then - kill "$sampler" 2>/dev/null; wait "$sampler" 2>/dev/null || true + kill "$sampler" 2>/dev/null || true + wait "$sampler" 2>/dev/null || true + sampler="" [ -s "$run_dir/power.csv" ] || rm -f "$run_dir/power.csv" fi - -# Energy (whole run and per phase) 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 the results file. -T0=$t_start T1=$t_end python3 "$here/postrun.py" "$run_dir" "$results" || - echo "bench.sh: warning: post-run figures failed" >&2 +if [ "$bb_rc" != 0 ]; then + mv "$run_dir" "$run_dir.failed" 2>/dev/null || true + run_dir_made="" + die "betterbench failed (exit $bb_rc); output in $run_dir.failed/betterbench.log" +fi # BetterBench with GGZ14/BetterBench#4 fingerprints PCIe and BAR itself # (env.gpu.pci), on the machine BetterBench runs on. Say so when that is not # the benchmarked GPU, or when it disagrees with collect-env.sh. -ENV_FILE=$env_file python3 - "$results" "$tmp/collected" <<'PY' || true +ENV_FILE=$env_file WARNINGS=$warnings python3 - "$run_dir/results.json" "$tmp/collected" <<'PY' || true import json, os, sys pci = ((json.load(open(sys.argv[1], encoding="utf-8")).get("env") or {}).get("gpu") or {}).get("pci") if not pci: @@ -397,9 +788,117 @@ if mine is None: 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) + msg = (f"ReBAR {rebar} per collect-env.sh, but BetterBench reads " + f"{mine.get('resizable_bar')} ({mine.get('largest_bar_mib')} MiB BAR)") + print("bench.sh: warning: " + msg, file=sys.stderr) + open(os.environ["WARNINGS"], "a", encoding="utf-8").write(msg + "\n") PY +# Energy per token and decode as % of memory bandwidth, from what the run +# measured. They come after the run, so they go to meta.json ("post_run"), +# not into the notes of results.json. +T0=$t_start T1=$t_end WARNINGS=$warnings python3 - "$run_dir" <<'PY' || warn "post-run figures failed" +import json, os, statistics, sys +d = sys.argv[1] +res = json.load(open(f"{d}/results.json", encoding="utf-8")) +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)") +warnings = [w for w in open(os.environ["WARNINGS"], encoding="utf-8").read().splitlines() if w] +if warnings: + L.append(f" {len(warnings)} warning(s):") + L += [f" - {w}" for w in warnings] +print("\n" + "\n".join(L), file=sys.stderr) +with open(f"{d}/summary.txt", "w", encoding="utf-8") as f: + f.write("\n".join(x[2:] for x in L) + "\n") + +meta["post_run"] = post +meta["warnings"] = warnings +with open(f"{d}/meta.json", "w", encoding="utf-8") as f: + json.dump(meta, f, indent=2) + f.write("\n") +PY + echo echo "done: $run_dir" ls -1 "$run_dir" diff --git a/dev/build.sh b/dev/build.sh index ef1d88b..5eea84e 100755 --- a/dev/build.sh +++ b/dev/build.sh @@ -1,7 +1,8 @@ #!/bin/sh # build.sh - pack dev/ into the one bench.sh at the repo root, which is all -# people download. It unpacks the helpers to a temp dir and runs dev's -# bench.sh from there, with results and bench.local.env next to itself. +# people download. It unpacks the helpers to a temp dir and exec's dev's +# bench.sh from there, with results and bench.local.env next to itself; that +# script removes the temp dir (BENCH_UNPACKED) when it exits. # # usage: dev/build.sh (then commit the root bench.sh with dev/) # dev/build.sh --check (exit 1 if the root bench.sh is out of date) @@ -9,7 +10,7 @@ set -eu dev=$(cd "$(dirname "$0")" && pwd) out="$dev/../bench.sh" -files="bench.sh collect-env.sh gpu-power.sh gguf_kv.py 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 mem-bw.py config.json standard.env models.txt" eof=__BENCH_STANDARD_EOF__ . "$dev/standard.env" @@ -36,7 +37,8 @@ EOF cat "$dev/$f" printf '%s\n' "$eof" done - printf 'sh "$d/bench.sh" "$@"\n' + printf 'trap - EXIT INT TERM\n' + printf 'BENCH_UNPACKED=$d exec sh "$d/bench.sh" "$@"\n' } > "$tmp" if [ "${1:-}" = --check ]; then diff --git a/dev/collect-env.sh b/dev/collect-env.sh index c4255a6..b316d03 100755 --- a/dev/collect-env.sh +++ b/dev/collect-env.sh @@ -11,7 +11,7 @@ # --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), -# HASH_MODEL=0 (skip hashing the model file) +# HASH_MODEL=0 (skip hashing the model file; hashes are cached by size and mtime) set -u LC_ALL=C; export LC_ALL @@ -34,7 +34,9 @@ while [ $# -gt 0 ]; do done tmp=$(mktemp -d) || exit 1 -trap 'rm -rf "$tmp"' EXIT INT TERM +trap 'rm -rf "$tmp"' EXIT +trap 'exit 130' INT +trap 'exit 143' TERM # Header via a file so the key never shows up in `ps`. if [ -n "$api_key" ]; then printf 'Authorization: Bearer %s\n' "$api_key" > "$tmp/hdr" else printf 'Accept: application/json\n' > "$tmp/hdr"; fi @@ -107,12 +109,47 @@ pcie_of() { return 0 } +# hostpath PATH - the host path behind a path inside the server's container, +# from the -v / --mount flags of the launch command in $tmp/cmd; prints +# nothing when no bind mount covers it. +hostpath() { + [ -s "$tmp/cmd" ] && have python3 || return 0 + python3 - "$tmp/cmd" "$1" <<'PY' 2>/dev/null +import os, re, sys +cmd, path = open(sys.argv[1], encoding="utf-8", errors="replace").read(), sys.argv[2] +maps = re.findall(r'(?:^|\s)(?:-v|--volume)[ =](\S+?):(/[^\s:]*)', cmd) +for m in re.finditer(r'--mount[ =](\S+)', cmd): + o = dict(p.split("=", 1) for p in m.group(1).split(",") if "=" in p) + src, dst = o.get("source") or o.get("src"), o.get("target") or o.get("destination") or o.get("dst") + if src and dst: + maps.append((src, dst)) +best = None +for src, dst in maps: + dst = dst.rstrip("/") or "/" + src = os.path.expandvars(os.path.expanduser(src.strip("'\""))) + if src.startswith("/") and (path == dst or path.startswith(dst.rstrip("/") + "/")): + if best is None or len(dst) > len(best[1]): # the innermost mount wins + best = (src, dst) +if best: + print(best[0].rstrip("/") + path[len(best[1].rstrip("/")):]) +PY +} + +# hf_snapshot HF_HOME REPO_ID - the snapshot dir of a Hugging Face cache entry +hf_snapshot() { + r="$1/hub/models--$(printf '%s' "$2" | sed 's|/|--|g')" + [ -d "$r/snapshots" ] || return 1 + if [ -f "$r/refs/main" ] && [ -d "$r/snapshots/$(cat "$r/refs/main")" ]; then + printf '%s\n' "$r/snapshots/$(cat "$r/refs/main")" + else + set -- "$r"/snapshots/*/ + [ $# = 1 ] && [ -d "$1" ] && printf '%s\n' "${1%/}" + fi +} + # ---------------------------------------------------------------- GPU gpu_vendor=none gpu_model="" gpu_count=0 gpu_vram_gb="" gpu_driver="" gpu_power_limit_w="" gpu_bdf="" -# 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 \ +if have nvidia-smi && q=$(nvidia-smi --query-gpu=name,memory.total,driver_version,power.limit,pci.bus_id \ --format=csv,noheader,nounits 2>/dev/null) && [ -n "$q" ]; then gpu_vendor=nvidia gpu_count=$(printf '%s\n' "$q" | grep -c .) @@ -123,10 +160,6 @@ 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 @@ -138,8 +171,6 @@ 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 @@ -154,24 +185,7 @@ 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 @@ -215,6 +229,7 @@ os=$( (. /etc/os-release 2>/dev/null && printf '%s' "${PRETTY_NAME:-}") ) kernel=$(uname -r 2>/dev/null) # ---------------------------------------------------------------- engine +[ -n "$cmd_file" ] && cp "$cmd_file" "$tmp/cmd" 2>/dev/null proxy=none engine=unknown engine_version="" model_file="" ctx="" engine_slots="" if [ -n "$endpoint" ]; then base=${endpoint%/}; base=${base%/v1} @@ -254,44 +269,77 @@ if [ -n "$endpoint" ]; then fi fi - # Behind llama-swap the launch command is known: keep it, and map a - # container path (-v HOST:/model) back to the host path. + # Behind llama-swap the launch command is known: keep it (it wins over + # --server-cmd-file for finding the container and the mounts). if [ "$proxy" = llama-swap ] && [ -n "$model" ] && fetch "$base/running" "$tmp/running"; then export JARG="$model" - jget "$tmp/running" 'next((r.get("cmd") for r in j["running"] if r.get("model") == arg), "")' > "$tmp/cmd" - if [ -s "$tmp/cmd" ]; then + jget "$tmp/running" 'next((r.get("cmd") for r in j["running"] if r.get("model") == arg), "")' > "$tmp/cmd.swap" + if [ -s "$tmp/cmd.swap" ]; then + mv "$tmp/cmd.swap" "$tmp/cmd" [ -n "$cmd_out" ] && cp "$tmp/cmd" "$cmd_out" - if [ -n "$model_file" ] && have python3; then - host=$(python3 - "$tmp/cmd" "$model_file" <<'PY' 2>/dev/null -import re, sys -cmd, path = open(sys.argv[1]).read(), sys.argv[2] -for src, dst in re.findall(r'(?:-v|--volume)[ =](\S+?):(/[^\s:]*)', cmd): - if path == dst or path.startswith(dst.rstrip("/") + "/"): - print(src + path[len(dst):]); break -PY -) - [ -n "$host" ] && model_file=$host - fi fi fi fi -# Weight bytes as stored: a single file, the parts of a split GGUF -# (-00001-of-0000N.gguf), or the *.safetensors of a model directory, without -# an MTP head (*mtp*), which plain decoding doesn't read. -model_bytes="" -if [ -f "$model_file" ]; then - case $model_file in - *-00001-of-[0-9]*.gguf) set -- "${model_file%-00001-of-*}"-[0-9]*-of-[0-9]*.gguf ;; - *) set -- "$model_file" ;; +# model_path: where the weights are on this machine. The engine reports its +# own view: a path inside its container (mapped back through -v / --mount), +# or, for vLLM, often a Hugging Face repo id (looked up in the HF cache, the +# container's and this machine's). +model_path="" +if [ -n "$model_file" ]; then + model_path=$(hostpath "$model_file") + [ -n "$model_path" ] && [ -e "$model_path" ] || model_path=$model_file + case $model_path in + /*|.*) ;; + */*) if [ ! -e "$model_path" ]; then + cenv=$( [ -s "$tmp/cmd" ] && tr '\n' ' ' < "$tmp/cmd" | sed -n 's/.*[ =]HF_HOME=\([^ ]*\).*/\1/p') + for root in $(hostpath "${cenv:-/root/.cache/huggingface}") $cenv \ + "${HF_HOME:-$HOME/.cache/huggingface}"; do + snap=$(hf_snapshot "$root" "$model_file") && { model_path=$snap; break; } + done + fi ;; esac - model_bytes=$(stat -c %s "$@" 2>/dev/null | awk '{s += $1} END {if (s) printf "%d", s}') -elif [ -d "$model_file" ]; then - model_bytes=$(find "$model_file" -maxdepth 1 -name '*.safetensors' ! -name '*mtp*' -exec stat -c %s {} + 2>/dev/null | - awk '{s += $1} END {if (s) printf "%d", s}') + [ -e "$model_path" ] || model_path="" fi -[ -s "$tmp/cmd" ] || { [ -n "$cmd_file" ] && cp "$cmd_file" "$tmp/cmd" 2>/dev/null; } +# Weight bytes as stored: a single file, the parts of a split GGUF +# (-00001-of-0000N.gguf), or the *.safetensors of a model directory. stat -L: +# the HF cache keeps files as symlinks into blobs/. +model_bytes="" model_sha256="" +set -- +if [ -f "$model_path" ]; then + case $model_path in + *-00001-of-[0-9]*.gguf) set -- "${model_path%-00001-of-*}"-[0-9]*-of-[0-9]*.gguf ;; + *) set -- "$model_path" ;; + esac +elif [ -d "$model_path" ]; then + set -- "$model_path"/*.safetensors + [ -e "$1" ] || set -- +fi +[ $# -gt 0 ] && model_bytes=$(stat -L -c %s "$@" 2>/dev/null | awk '{s += $1} END {if (s) printf "%d", s}') + +# The hash the README's model table lists: sha256 of the GGUF, or of a repo's +# per-file *.safetensors hashes in name order. Split GGUFs aren't hashed. +# Cached by path, size and mtime, since hashing 15 GB takes a while. +case $model_path in *-00001-of-[0-9]*.gguf) split=1 ;; *) split=0 ;; esac +if [ "${HASH_MODEL:-1}" != 0 ] && [ -n "$model_bytes" ] && [ $split = 0 ] && have sha256sum; then + sig=$(stat -L -c '%n %s %Y' "$@" 2>/dev/null | cksum | cut -d' ' -f1) + cache="${XDG_CACHE_HOME:-$HOME/.cache}/bench-standard/model-sha256" + model_sha256=$(awk -v s="$sig" -v p="$model_path" -F '\t' '$1 == s && $2 == p {print $3; exit}' "$cache" 2>/dev/null) + if [ -z "$model_sha256" ]; then + echo "collect-env: hashing $model_path ($((model_bytes / 1000000000)) GB; once, it's cached; HASH_MODEL=0 skips) ..." >&2 + if [ -f "$model_path" ]; then + model_sha256=$(sha256sum "$model_path" | cut -c1-64) + else + model_sha256=$(cd "$model_path" && sha256sum -- *.safetensors | sort -k2 | sha256sum | cut -c1-64) + fi + case $model_sha256 in + [0-9a-f]*) mkdir -p "${cache%/*}" 2>/dev/null && + printf '%s\t%s\t%s\n' "$sig" "$model_path" "$model_sha256" >> "$cache" 2>/dev/null ;; + *) model_sha256="" ;; + esac + fi +fi # A docker server: the exact image, since tags like llama.cpp's server-intel # move daily (the llama.cpp build itself is in engine_version). container="" engine_image="" @@ -302,40 +350,12 @@ if [ -n "$container" ] && have docker && engine_image=$(printf '%s' "$i" | sed 's/@sha256:\(.\{12\}\).*/@\1/') 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). -# 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 - 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). -# The first time takes a while for a big file, then it's cached. -# HASH_MODEL=0 skips it. -model_sha256="" -here=$(cd "$(dirname "$0")" && pwd) -if [ "${HASH_MODEL:-1}" != 0 ] && [ -e "$model_file" ] && have python3; then - echo "collect-env: hashing the model file (cached after the first time) ..." >&2 - model_sha256=$(python3 "$here/model_hash.py" "$model_file" 2>/dev/null) -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) @@ -344,6 +364,7 @@ if [ "${MEASURE_BW:-1}" != 0 ]; then else r="" fi + case $r in [0-9]*' '[0-9]*) ;; *) r="" ;; esac # "GBPS MIB", or nothing usable if [ -n "$r" ]; then gpu_mem_bw_gbs=${r% *} gpu_mem_bw_tool="torch copy, random, ${r#* } MiB" elif have clpeak && [ -n "$gpu_model" ]; then @@ -367,10 +388,6 @@ 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" @@ -388,10 +405,8 @@ kv engine_version "$engine_version" kv engine_slots "$engine_slots" kv engine_image "$engine_image" kv model_file "$model_file" +kv model_path "$model_path" kv model_bytes "$model_bytes" -kv model_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 diff --git a/dev/gguf_kv.py b/dev/gguf_kv.py deleted file mode 100644 index 03d37f5..0000000 --- a/dev/gguf_kv.py +++ /dev/null @@ -1,90 +0,0 @@ -"""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 diff --git a/dev/gpu-power.sh b/dev/gpu-power.sh index f4101f6..b51b916 100755 --- a/dev/gpu-power.sh +++ b/dev/gpu-power.sh @@ -1,15 +1,16 @@ #!/bin/sh # gpu-power.sh - run ON THE INFERENCE SERVER. Samples the power draw and the -# 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 +# 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 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). +# mhz is the mean graphics clock over the GPUs. +# Prints nothing at all when no supported tool is found (nvidia-smi, xpu-smi, +# or amdgpu's hwmon files in sysfs, which have no energy counter). # # usage: gpu-power.sh [INTERVAL_S] (default 2) +# GPU_POWER_SYSFS=DIR: the sysfs root for the amdgpu lookup (tests) set -u LC_ALL=C; export LC_ALL @@ -19,26 +20,35 @@ 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,clocks.mem \ + 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; m += $4} - END {if (NR) printf "%.2f,%s,%.0f,%.0f\n", w, nj ? "" : sprintf("%.3f", j), c / NR, m / NR}' + 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. 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" + # one call takes about a second sample() { - 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)}' + 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 + # amdgpu: power1_average (older kernels) or power1_input, in microwatts; + # freq1_input is the graphics clock in Hz. + amd="" + for h in "${GPU_POWER_SYSFS:-/sys}"/bus/pci/drivers/amdgpu/*:*/hwmon/hwmon*; do + { [ -r "$h/power1_average" ] || [ -r "$h/power1_input" ]; } && amd="$amd $h" + done + [ -n "$amd" ] || exit 0 + sample() { + for h in $amd; do + p=$(cat "$h/power1_average" 2>/dev/null || cat "$h/power1_input" 2>/dev/null) + f=$(cat "$h/freq1_input" 2>/dev/null) + echo "${p:-0} ${f:-0}" + done | awk '$1 > 0 {w += $1 / 1e6; c += $2 / 1e6; n++} + END {if (n) printf "%.2f,,%.0f\n", w, c / n}' + } fi while :; do diff --git a/dev/model_hash.py b/dev/model_hash.py deleted file mode 100644 index 2c5ca35..0000000 --- a/dev/model_hash.py +++ /dev/null @@ -1,77 +0,0 @@ -"""model_hash.py - SHA256 of a model, as the README's Models section defines it. - -usage: model_hash.py PATH (prints the hash, or nothing when PATH can't be read) - -A file: its SHA256, like `sha256sum FILE`. A directory: the SHA256 over the -per-file hashes of its *.safetensors, in byte order of the names, exactly like -`sha256sum *.safetensors | LC_ALL=C sort -k2 | sha256sum`. - -Hashing a 16 GB file takes a while, so per-file hashes are cached in -~/.cache/bench-standard/sha256.tsv, keyed by path, size and mtime. -""" -import hashlib -import os -import sys - -CACHE = os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), - "bench-standard", "sha256.tsv") - - -def _load_cache(): - cache = {} - try: - with open(CACHE, encoding="utf-8") as f: - for line in f: - p = line.rstrip("\n").split("\t") - if len(p) == 4: - cache[(p[0], p[1], p[2])] = p[3] - except OSError: - pass - return cache - - -def _save_cache(cache): - try: - os.makedirs(os.path.dirname(CACHE), exist_ok=True) - tmp = CACHE + f".{os.getpid()}" - with open(tmp, "w", encoding="utf-8") as f: - for (path, size, mtime), h in sorted(cache.items()): - f.write(f"{path}\t{size}\t{mtime}\t{h}\n") - os.replace(tmp, CACHE) - except OSError: - pass - - -def file_sha256(path, cache): - st = os.stat(path) - key = (os.path.realpath(path), str(st.st_size), str(st.st_mtime_ns)) - if key not in cache: - h = hashlib.sha256() - with open(path, "rb") as f: - for block in iter(lambda: f.read(1 << 22), b""): - h.update(block) - cache[key] = h.hexdigest() - return cache[key] - - -def model_sha256(path, cache=None): - cache = _load_cache() if cache is None else cache - if os.path.isdir(path): - names = sorted((n for n in os.listdir(path) if n.endswith(".safetensors")), - key=lambda n: n.encode()) - if not names: - return None - listing = "".join(f"{file_sha256(os.path.join(path, n), cache)} {n}\n" for n in names) - return hashlib.sha256(listing.encode()).hexdigest() - return file_sha256(path, cache) - - -if __name__ == "__main__": - try: - cache = _load_cache() - h = model_sha256(sys.argv[1], cache) - _save_cache(cache) - except (OSError, IndexError): - h = None - if h: - print(h) diff --git a/dev/models.tsv b/dev/models.tsv deleted file mode 100644 index e27011f..0000000 --- a/dev/models.tsv +++ /dev/null @@ -1,5 +0,0 @@ -# name engine quant sha256 (a GGUF file, or a safetensors directory: README, Models) -Qwen3.5-9B llama.cpp Q4_K_M 03b74727a860a56338e042c4420bb3f04b2fec5734175f4cb9fa853daf52b7e8 -Qwen3.8-27B llama.cpp UD-Q4_K_M 322e194ff79741c7baa497c240f677f54b201b0efab44ca8e50f122b39123482 -Qwen3.5-9B vllm w4a16 cca16f9855b9f92eee5876ddc8656ed6397316ffc65b9f17ca1939a9549e4c26 -Qwen3.8-27B vllm w4a16 bffa6b23fa11be557fe9de4b122a8bb99f537ad7a1a4effa702f7d0c677778f7 diff --git a/dev/models.txt b/dev/models.txt new file mode 100644 index 0000000..ff88adf --- /dev/null +++ b/dev/models.txt @@ -0,0 +1,7 @@ +# The standard models: results only count for these files. Same as the +# README's model table; change both together and bump STANDARD_VERSION. +# sha256 (a GGUF file, or a repo's *.safetensors as in the README) --quant name +03b74727a860a56338e042c4420bb3f04b2fec5734175f4cb9fa853daf52b7e8 Q4_K_M Qwen3.5-9B-Q4_K_M.gguf +322e194ff79741c7baa497c240f677f54b201b0efab44ca8e50f122b39123482 UD-Q4_K_M Qwen3.8-27B-UD-Q4_K_M.gguf +cca16f9855b9f92eee5876ddc8656ed6397316ffc65b9f17ca1939a9549e4c26 w4a16 RedHatAI/Qwen3.5-9B-quantized.w4a16 +bffa6b23fa11be557fe9de4b122a8bb99f537ad7a1a4effa702f7d0c677778f7 w4a16 RedHatAI/Qwen3.8-27B-INT4 diff --git a/dev/notes.py b/dev/notes.py deleted file mode 100644 index 686ee8b..0000000 --- a/dev/notes.py +++ /dev/null @@ -1,250 +0,0 @@ -"""notes.py - the notes bench.sh hands BetterBench, one per topic. - -usage: notes.py MANDATORY COLLECTED MEASURED CMD LAUNCH_JSON MODELS_TSV > notes -The first three are key=value files (declared, detected by collect-env.sh, -measured by the greedy check), CMD the redacted launch command (may be -empty). Writes the parsed launch settings to LAUNCH_JSON and prints -key=value notes; warnings go to stderr. -""" -import json, shlex, sys -def kv(path): - with open(path, encoding="utf-8") as f: - return dict(l.rstrip("\n").split("=", 1) for l in f if "=" in l) -m, c, meas = kv(sys.argv[1]), kv(sys.argv[2]), kv(sys.argv[3]) -models = [l.rstrip("\n").split("\t") for l in open(sys.argv[6], encoding="utf-8") - if l.strip() and not l.startswith("#")] -cmd = open(sys.argv[4], encoding="utf-8").read().strip() -def g(k): - v = c.get(k, "") - return "" if v in ("", "unknown") else v -def join(*parts): - return " · ".join(p for p in parts if p) or "unknown" - -vendor = {"intel": "Intel", "nvidia": "NVIDIA", "amd": "AMD"}.get(g("gpu_vendor"), g("gpu_vendor")) -count = g("gpu_count") -gpu = join(" ".join(p for p in (count and count + "x", vendor if vendor != "none" else "", - g("gpu_model")) if p), - g("gpu_vram_gb") and g("gpu_vram_gb") + " GB", - g("gpu_driver") and "driver " + g("gpu_driver"), - 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"): - pcie = m["pcie"] + " (declared)" -elif link and top and link != top: - pcie = f"{link} now, {top} max" # idle GPUs drop the link speed -else: - pcie = link or "unknown" -if g("rebar"): - pcie += " · ReBAR " + g("rebar") - -pl, det = m["power_limit"], g("gpu_power_limit_w") -if pl == "stock": - power = join("stock", det and det + " W") -else: - power = pl + " W" - if det and abs(float(det) - float(pl)) > 1: - power += f" (GPU reports {det} W)" - -virt = g("virt") -host = join(g("cpu_model"), g("ram_gb") and g("ram_gb") + " GB RAM", g("os"), - g("kernel") and "kernel " + g("kernel"), virt != "none" and virt and "VM " + virt) - -# Settings in the launch command that swing results but no API reports: -# batch sizes, flash attention, KV types, env flags. Flags left out of the -# command are the engine's defaults, which change between versions. -try: - words = shlex.split(cmd.replace("\\\n", " ")) -except ValueError: - words = cmd.split() -env, flags, prog = {}, {}, None -BOOL = {"--no-mmap", "--mlock", "--enforce-eager", "--enable-prefix-caching", - "--no-enable-prefix-caching", "--enable-chunked-prefill", - "--no-enable-chunked-prefill", "--cont-batching", "-cb", "--no-cont-batching", "-nocb", - "-cmoe", "--cpu-moe", "-rm", "--rm", "-d", "--detach", "-it", "-i", "--privileged"} -FA_VALUES = {"on", "off", "auto", "1", "0", "true", "false"} -i = 0 -while i < len(words): - w = words[i] - nxt = words[i + 1] if i + 1 < len(words) else None - if prog is None and "=" in w and not w.startswith("-") and w.split("=", 1)[0].isidentifier(): - k, v = w.split("=", 1); env[k] = v # FOO=1 cmd - elif prog is None and not w.startswith("-") and w != "env": - prog = w - elif w in ("-e", "--env") and nxt is not None and not nxt.startswith("-"): # docker -e K=V - k, _, v = nxt.partition("="); env[k] = v if _ else "(inherited)"; i += 1 - elif w.startswith("--env="): - k, _, v = w[6:].partition("="); env[k] = v if _ else "(inherited)" - elif w.startswith("-e") and len(w) > 2 and "=" in w and w[2:].split("=")[0].isidentifier(): - k, v = w[2:].split("=", 1); env[k] = v - elif w.startswith("-"): - if "=" in w and w.startswith("--"): - k, v = w.split("=", 1); flags[k] = v - elif w in ("-fa", "--flash-attn"): - if nxt is not None and nxt.lower() in FA_VALUES: - flags[w] = nxt; i += 1 - else: - flags[w] = "on" # older bare -fa - elif w in BOOL or nxt is None or nxt.startswith("-"): - flags[w] = True - else: - flags[w] = nxt; i += 1 - i += 1 - -def flag(*names): - for n in names: - if n in flags: - return flags[n] - return None - -LLAMA = [("b", ("-b", "--batch-size")), ("ub", ("-ub", "--ubatch-size")), - ("fa", ("-fa", "--flash-attn")), ("ctk", ("-ctk", "--cache-type-k")), - ("ctv", ("-ctv", "--cache-type-v")), ("ngl", ("-ngl", "--gpu-layers", "--n-gpu-layers")), - ("np", ("-np", "--parallel")), ("t", ("-t", "--threads")), - ("sm", ("-sm", "--split-mode")), ("ts", ("-ts", "--tensor-split")), - ("ot", ("-ot", "--override-tensor")), ("ncmoe", ("-ncmoe", "--n-cpu-moe")), - ("cmoe", ("-cmoe", "--cpu-moe")), ("no-mmap", ("--no-mmap",)), ("mlock", ("--mlock",)), - ("nocb", ("-nocb", "--no-cont-batching"))] -LLAMA_ALWAYS = {"b", "ub", "fa", "ctk", "ctv"} # shown as "default" when not set -VLLM = ["--max-num-batched-tokens", "--max-num-seqs", "--kv-cache-dtype", - "--gpu-memory-utilization", "--dtype", "--quantization", "--block-size", - "--enforce-eager", "--enable-chunked-prefill", "--no-enable-chunked-prefill", - "--enable-prefix-caching", "--no-enable-prefix-caching", "--attention-backend", - "--compilation-config", "-O", "--speculative-config"] -launch_kind = g("engine") -if launch_kind not in ("llama.cpp", "vllm"): - launch_kind = ("llama.cpp" if prog and "llama-server" in prog or flag("-ngl", "-ub", "-ctk") - else "vllm" if any(f in flags for f in VLLM) else "") -settings = {} -if launch_kind == "llama.cpp": - for name, al in LLAMA: - v = flag(*al) - if v is not None: - settings[name] = "on" if v is True else v - elif name in LLAMA_ALWAYS: - settings[name] = "default" -elif launch_kind == "vllm": - for f in VLLM: - if f in flags: - settings[f.lstrip("-")] = "on" if flags[f] is True else "".join(str(flags[f]).split()) -if not cmd: - launch = "unknown (pass --server-cmd-file)" -else: - launch = " · ".join(k if v == "on" and k in ("no-mmap", "mlock", "nocb", "cmoe") or - k.startswith(("enable-", "no-enable-", "enforce-")) else f"{k} {v}" - for k, v in settings.items()) or "no tuning flags" -# Offline switches and cache paths don't change the numbers. -QUIET = {"HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE", "HF_DATASETS_OFFLINE", "HF_HOME", - "VLLM_CACHE_ROOT", "PATH", "HOME", "TZ", "LANG", "LC_ALL"} -env_flags = (" · ".join(f"{k}={v}" for k, v in env.items() if k not in QUIET) or "none" - ) if cmd else "unknown" -json.dump({"engine": launch_kind or None, "settings": settings, "env": env, "flags": flags}, - open(sys.argv[5], "w", encoding="utf-8"), indent=2, default=str) - -# The declared --kv should be what the command sets. -kvset = [x for x in (settings.get("ctk"), settings.get("ctv"), settings.get("kv-cache-dtype")) - if x and x not in ("default", "auto")] -if kvset and m["kv"] not in kvset + ["/".join(kvset), "_".join(kvset)]: - print(f"bench.sh: warning: --kv {m['kv']} but the launch command sets " - f"{'/'.join(kvset)}", file=sys.stderr) - -# The model file against the standard models: results only count for those. -mb, sha = g("model_bytes"), g("model_sha256") -std = next((r for r in models if len(r) >= 4 and r[3] == sha), None) if sha else None -if std: - check = f"standard: {std[0]} {std[2]}" - if m["quant"] != std[2]: - print(f"bench.sh: warning: --quant {m['quant']}, but the file is the standard " - f"{std[0]} {std[2]}; declare --quant {std[2]}", file=sys.stderr) -elif sha: - check = f"not a standard model (sha256 {sha[:12]})" - print("bench.sh: warning: the model file is not one of the standard models " - "(README, Models), so the result won't count", file=sys.stderr) -else: - check = "hash not checked" -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": - greedy = f'differs: {meas["greedy_variants"]} variants in {meas["greedy_runs"]} · first {meas["greedy_hash"]}' -else: - greedy = "failed" - -# --thinking is declared, but the greedy replies show whether the model -# reasoned: check one against the other. -seen = meas.get("greedy_reasoning") -thinking = join(m["thinking"], {"yes": "reasoning seen", "no": "no reasoning seen", - "mixed": "reasoning in some replies"}.get(seen, "")) -if m["thinking"] == "off" and seen in ("yes", "mixed"): - print("bench.sh: warning: --thinking off, but the greedy replies contain reasoning;" - " check the server's chat template or reasoning flags", file=sys.stderr) -elif m["thinking"] in ("on", "low", "medium", "high") and seen == "no": - print(f"bench.sh: warning: --thinking {m['thinking']}, but the greedy replies contain no" - " reasoning; thinking may be off on the server", file=sys.stderr) - -# The BetterBench build: a release tag says nothing more than the version, a -# commit or local changes do (two installs can share a version number). -build = m.get("betterbench_build", "") -betterbench = "betterbench " + m["betterbench"] -if build and build not in ("v" + m["betterbench"], m["betterbench"]): - betterbench += " @ " + build - -eng = g("engine") -engine = join(" ".join(p for p in (eng, g("engine_version")) if p), - g("engine_slots") and g("engine_slots") + " slots", - g("engine_image") and "image " + g("engine_image"), - g("proxy") not in ("", "none") and "via " + g("proxy")) - -notes = [ - ("submitter", m["submitter"]), - ("gpu", gpu), - ("pcie", pcie), - ("power_limit", power), - ("host", host), - ("engine", engine), - ("model_file", model_file), - ("mem_bw", mem_bw), - ("parallel", f"tp {m['tp']} · pp {m['pp']}"), - ("precision", f"weights {m['quant']} · kv {m['kv']}"), - ("max_ctx", max_ctx), - ("launch", launch), - ("env_flags", env_flags), - ("spec", m["spec"]), - ("thinking", thinking), - ("greedy_check", greedy), - ("run", join(m["run_mode"], "concurrency " + m["concurrency"], - "bench-standard " + m["bench_standard"], betterbench)), -] -if m.get("special_notes"): - notes.append(("special_notes", m["special_notes"])) -for k, v in notes: - if v: - print(f"{k}={v}") diff --git a/dev/postrun.py b/dev/postrun.py deleted file mode 100644 index 603172e..0000000 --- a/dev/postrun.py +++ /dev/null @@ -1,253 +0,0 @@ -"""postrun.py - figures that need the finished run, and the summary. - -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[,mem_mhz]) and timeline.tsv (epochBetterBench 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. -""" -import bisect -import json -import os -import re -import statistics -import sys - - -def read_power(path): - rows = [] - if os.path.exists(path): - for line in open(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[4]) if len(p) > 4 and p[4] else 0.0)) - except (ValueError, IndexError): - pass - return rows - - -def energy_curve(rows): - """(times, cumulative joules): from the energy counter when every sample - has one, else integrated from the power samples.""" - ts = [r[0] for r in rows] - if all(r[2] is not None for r in rows) and rows[-1][2] >= rows[0][2]: - return ts, [r[2] - rows[0][2] for r in rows], "energy counter" - cum = [0.0] - for a, b in zip(rows, rows[1:]): - cum.append(cum[-1] + (b[0] - a[0]) * (a[1] + b[1]) / 2) - return ts, cum, "integrated power" - - -def joules_between(ts, cum, t0, t1): - """Energy between two moments, interpolating between samples.""" - def at(t): - if t <= ts[0]: - return cum[0] - if t >= ts[-1]: - return cum[-1] - i = bisect.bisect_right(ts, t) - f = (t - ts[i - 1]) / (ts[i] - ts[i - 1]) - return cum[i - 1] + f * (cum[i] - cum[i - 1]) - return max(0.0, at(t1) - at(t0)) - - -SEGMENT = re.compile(r"^\[(single|prefill|concurrency)\]\s+(.*)$") -WARMUP = re.compile(r"warmup (\d+) \+ (\d+)") - - -def segments(timeline, t_end): - """BetterBench prints a progress line when each piece of work starts; a - piece lasts until the next line. Yields (phase, key, warm-up factor, t0, t1).""" - marks = [] - for t, line in timeline: - m = SEGMENT.match(line) - if not m or "skip" in m.group(2): - continue - phase, rest = m.groups() - key = rest.split(":")[0].strip() - if phase == "concurrency": - key = re.sub(r"\D", "", key) - w = WARMUP.search(rest) - factor = (int(w.group(1)) + int(w.group(2))) / int(w.group(2)) if w and int(w.group(2)) else 1.0 - marks.append((t, phase, key, factor)) - for i, (t, phase, key, factor) in enumerate(marks): - yield phase, key, factor, t, marks[i + 1][0] if i + 1 < len(marks) else t_end - - -def phase_energy(res, rows, timeline, t_end): - """Joules and joules per token for decode, prefill and each concurrency - level. Warm-up passes draw power but aren't in the results, so their - tokens are estimated from the measured passes of the same piece.""" - ts, cum, _ = energy_curve(rows) - single = res.get("single_stream") or {} - prefill = {str(p.get("target_depth")): p for p in res.get("prefill") or []} - conc = {str(x.get("level")): x for x in res.get("concurrency") or []} - out = {"decode": {"joules": 0.0, "seconds": 0.0, "tokens": 0.0}, - "prefill": {"joules": 0.0, "seconds": 0.0, "tokens": 0.0}, "concurrency": {}} - for phase, key, factor, t0, t1 in segments(timeline, t_end): - j = joules_between(ts, cum, t0, t1) - if phase == "single": - tok = sum(r.get("completion_tokens") or 0 for r in single.get(key, []) if r.get("ok", True)) - d = out["decode"] - elif phase == "prefill": - depth = re.sub(r"\D", "", key) - tok = sum(prefill.get(depth, {}).get("prompt_tokens") or []) - d = out["prefill"] - else: - x = conc.get(key, {}) - tok, factor = x.get("aggregate_tps", 0) * x.get("wall_s", 0), 1.0 - d = out["concurrency"].setdefault(key, {"joules": 0.0, "seconds": 0.0, "tokens": 0.0}) - d["joules"] += j - d["seconds"] += t1 - t0 - d["tokens"] += tok * factor - def finish(d, per=1): - return {"joules": round(d["joules"]), "avg_w": round(d["joules"] / d["seconds"], 1) if d["seconds"] else None, - "tokens_incl_warmup_est": round(d["tokens"]), - "j_per_token" if per == 1 else "j_per_1k_tokens": - round(d["joules"] / d["tokens"] * per, 3) if d["tokens"] else None} - result = {} - if out["decode"]["seconds"]: - result["decode"] = finish(out["decode"]) - if out["prefill"]["seconds"]: - result["prefill"] = finish(out["prefill"], per=1000) - if out["concurrency"]: - result["concurrency"] = {k: finish(v) for k, v in out["concurrency"].items()} - return result - - -def roofline(single, c, m): - """Batch-1 decode reads all weights once per token: decode t/s x weight - bytes is the bandwidth it reaches. The weights are what the engine loaded - (vLLM logs it per worker) or else what is stored; tensor parallelism - spreads them over tp GPUs, each with its own bandwidth.""" - def num(v): - try: - return float(v) - except (TypeError, ValueError): - return None - tps = [r["decode_tps"] for r in single if r.get("decode_tps")] - bw = num(c.get("gpu_mem_bw_gbs")) or num(m.get("mem_bw")) - tp = int(m.get("tp") or 1) - loaded, stored = num(c.get("model_loaded_gib")), num(c.get("model_bytes")) - if loaded: - nbytes, src = loaded * 2**30 * tp, "loaded (engine log)" - elif stored: - nbytes, src = stored, "stored files" - else: - return None - if not tps or not bw: - return None - med = statistics.median(tps) - eff = med * nbytes / 1e9 - return {"decode_tps_median": round(med, 2), "weight_bytes": int(nbytes), "weight_source": src, - "mem_bw_gbs": bw * tp, "gpus": tp, "effective_gbs": round(eff, 1), - "pct_of_mem_bw": round(100 * eff / (bw * tp), 1)} - - -def main(d, results=None): - res = json.load(open(results or f"{d}/results.json", encoding="utf-8")) - meta = json.load(open(f"{d}/meta.json", encoding="utf-8")) - c, m = meta["collected"], meta["mandatory"] - t0, t1 = float(os.environ["T0"]), float(os.environ["T1"]) - post = {"wall_s": round(t1 - t0, 1)} - - 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 = read_power(f"{d}/power.csv") - timeline = [] - if os.path.exists(f"{d}/timeline.tsv"): - for line in open(f"{d}/timeline.tsv", encoding="utf-8"): - t, _, text = line.rstrip("\n").partition("\t") - try: - timeline.append((float(t), text)) - except ValueError: - pass - if len(rows) >= 2: - ts, cum, src = energy_curve(rows) - span = ts[-1] - ts[0] - joules = cum[-1] - 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)}") - 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 - - r = roofline(single, c, m) - if r: - post["roofline"] = r - - # 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, dec=0): - return "—" if x is None else f"{x:,.{dec}f} {unit}" - notes = meta["notes"] - tps = [x["decode_tps"] for x in single if x.get("decode_tps")] - 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(x.get('ttft_ms') for x 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 r: - 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 " - f"(weights {r['weight_bytes'] / 1e9:.2f} GB, {r['weight_source']})") - 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 "") - 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 = [] - if ph.get("decode", {}).get("j_per_token") is not None: - parts.append(f"decode {ph['decode']['j_per_token']} J/tok at {ph['decode']['avg_w']} W") - if ph.get("prefill", {}).get("j_per_1k_tokens") is not None: - parts.append(f"prefill {ph['prefill']['j_per_1k_tokens']} J/1k tok") - if parts: - L.append(" energy " + " · ".join(parts)) - if ph.get("concurrency"): - L.append(" energy by conc. " + " ".join( - f"{k}: {v['j_per_token']} J/tok" for k, v in ph["concurrency"].items() - if v.get("j_per_token") is not None)) - L.append(f" energy (total) {e['joules'] / 1000:.1f} kJ, " - f"{e['j_per_output_token']} J per output token over the 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 fh: - json.dump(meta, fh, indent=2) - fh.write("\n") - - -if __name__ == "__main__": - main(*sys.argv[1:3]) diff --git a/dev/standard.env b/dev/standard.env index 299a5aa..9b9e052 100644 --- a/dev/standard.env +++ b/dev/standard.env @@ -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.6.0 +# config.json, models.txt, the minimum BetterBench or the recorded fields change. +STANDARD_VERSION=0.5.0 # Oldest BetterBench that has everything bench.sh uses; newer ones run too, # and the version goes into the run note so compare shows a mismatch. BETTERBENCH_MIN_VERSION=0.6.1 diff --git a/dev/test.sh b/dev/test.sh new file mode 100644 index 0000000..e879ed4 --- /dev/null +++ b/dev/test.sh @@ -0,0 +1,189 @@ +#!/bin/sh +# shellcheck disable=SC2034 # variables are read inside the eval'd check strings +# test.sh - end-to-end tests of the one-file bench.sh, without a GPU: a fake +# OpenAI-compatible server (dev/test/fake_server.py) and a fake betterbench +# (dev/test/betterbench) stand in for the real ones. +# +# usage: sh dev/test.sh (needs python3, curl; rebuilds nothing, checks the build) + +set -u +dev=$(cd "$(dirname "$0")" && pwd) +root=$(cd "$dev/.." && pwd) +t=$(mktemp -d) +pids="" +trap 'for p in $pids; do kill "$p" 2>/dev/null; done; rm -rf "$t"' EXIT +pass=0 fail=0 +ok() { pass=$((pass + 1)); printf 'ok %s\n' "$1"; } +bad() { fail=$((fail + 1)); printf 'FAIL %s\n' "$1"; [ -f "$t/out" ] && sed 's/^/ | /' "$t/out" | tail -n 25; } +check() { if (eval "$2"); then ok "$1"; else bad "$1"; fi; } # check NAME SHELL-TEST + +PATH="$dev/test:$PATH"; export PATH +MEASURE_BW=0 XDG_CACHE_HOME="$t/cache" BENCH_HOME="$t/home"; export MEASURE_BW XDG_CACHE_HOME BENCH_HOME +unset BETTERBENCH_API_KEY BENCH_SUBMITTER BENCH_QUANT BENCH_KV BENCH_SPEC BENCH_THINKING 2>/dev/null || true +mkdir -p "$t/home" "$t/models" "$t/tmpdir" +printf 'fake gguf weights\n' > "$t/models/test.gguf" + +# serve PORT ENGINE REASONING MODEL_PATH +serve() { + python3 "$dev/test/fake_server.py" "$@" & pids="$pids $!" + i=0; until curl -s "http://127.0.0.1:$1/v1/models" >/dev/null || [ $i -gt 50 ]; do sleep 0.1; i=$((i + 1)); done +} +serve 18431 llama.cpp 0 "$t/models/test.gguf" +serve 18432 vllm 0 "Org/Repo" +serve 18433 llama.cpp 1 "/models/test.gguf" +LL=http://127.0.0.1:18431/v1 VL=http://127.0.0.1:18432/v1 LR=http://127.0.0.1:18433/v1 + +# bench ENDPOINT CMDFILE ARGS... - the one-file bench.sh with the declared values +bench() { + e=$1 c=$2; shift 2 + TMPDIR="$t/tmpdir" sh "$root/bench.sh" --endpoint "$e" --model test-model --tp 1 --pp 1 \ + --quant Q4_K_M --kv f16 --spec none --thinking default --submitter tester --power-limit 200 \ + --results-dir "$t/res" ${c:+--server-cmd-file "$c"} "$@" > "$t/out" 2>&1 +} +note() { sed -n "s/^$1=//p" "$t/notes"; } +# dry-run notes: the --note values the dry run would pass +dry_notes() { bench "$@" --dry-run; python3 - "$t/out" > "$t/notes" <<'PY' +import shlex, sys +line = next(l for l in open(sys.argv[1]) if l.startswith(" betterbench")) +w = shlex.split(line) +print("\n".join(w[i + 1] for i, x in enumerate(w) if x == "--note")) +PY +} + +# ------------------------------------------------------------------ build +check "bench.sh is built from dev/" 'sh "$dev/build.sh" --check >/dev/null 2>&1' +check "shell syntax" 'for f in "$root/bench.sh" "$dev"/*.sh; do sh -n "$f" || exit 1; done' + +# ------------------------------------------------------------------ argument checks +bench "$LL" "" --spec bogus; check "rejects a bad --spec" 'grep -q "spec must be" "$t/out"' +TMPDIR="$t/tmpdir" sh "$root/bench.sh" --endpoint "$LL" > "$t/out" 2>&1 +check "lists missing mandatory values" 'grep -q "missing mandatory value(s): --model --tp" "$t/out"' +bench "$LL" "" --temperature 0; check "refuses BetterBench flags" 'grep -q "not allowed" "$t/out"' + +# ------------------------------------------------------------------ a quick run +printf 'llama-server -m %s -ngl 99 -fa on -b 4096 -t -1 -e HF_TOKEN=hf_secret\n' "$t/models/test.gguf" > "$t/cmd1" +bench "$LL" "$t/cmd1"; rc=$? +run=$(sed -n 's/^done: //p' "$t/out") +check "quick run finishes (no GPU, the sampler exits at once)" '[ $rc = 0 ] && [ -d "$run" ]' +check "run folder has every file" 'for f in results.json results.html meta.json config.json server-cmd.txt summary.txt betterbench.log; do [ -s "$run/$f" ] || exit 1; done' +check "no empty power.csv without a GPU" '[ ! -e "$run/power.csv" ]' +check "summary printed" 'grep -q "decode (batch 1) 52.0 t/s" "$t/out"' +check "meta.json has post-run figures and warnings" 'python3 -c "import json,sys; m=json.load(open(sys.argv[1])); assert \"post_run\" in m and \"warnings\" in m" "$run/meta.json"' +check "secrets redacted" '! grep -q hf_secret "$run/server-cmd.txt" && grep -q "HF_TOKEN=" "$run/server-cmd.txt"' +check "results in --results-dir, helpers cleaned up" '[ -z "$(ls -A "$t/tmpdir")" ] && [ ! -e "$t/home/results" ]' +check "model hashed, flagged as non-standard" 'grep -q "not one of the standard models" "$t/out"' +check "model hash is cached" 'bench "$LL" "$t/cmd1" --dry-run; ! grep -q "collect-env: hashing" "$t/out"' + +# ------------------------------------------------------------------ launch flags and cross-checks +dry_notes "$LL" "$t/cmd1" +check "launch note parsed (negative values stay values)" '[ "$(note launch)" = "b 4096 · ub default · fa on · ctk default · ctv default · ngl 99 · t -1" ]' +check "model_file note has size and hash" 'note model_file | grep -q "0.00 GB · sha256 [0-9a-f]\{12\} (not a standard model)"' + +printf 'llama-server -m /m.gguf -ctk q8_0\n' > "$t/cmd2" +bench "$LL" "$t/cmd2" --kv q8_0 --dry-run +check "--kv: K set, V default -> q8_0/f16" 'grep -q "declare --kv q8_0/f16" "$t/out"' +bench "$LL" "$t/cmd2" --kv q8_0/f16 --dry-run +check "--kv q8_0/f16 accepted" '! grep -q "warning: --kv" "$t/out"' + +printf 'llama-server -m /m.gguf -md /d.gguf --draft-max 8 --reasoning-budget 0\n' > "$t/cmd3" +bench "$LL" "$t/cmd3" --dry-run +check "--spec checked against a draft model" 'grep -q "declare --spec draft:8" "$t/out"' +check "--thinking checked against --reasoning-budget 0" 'grep -q "declare --thinking off" "$t/out"' +check "dry run recaps warnings" 'grep -q "warning(s) - fix or explain" "$t/out"' + +cat > "$t/cmd4" <<'EOF' +VLLM_USE_V1=1 vllm serve Org/Repo -tp 2 --max-num-batched-tokens=8192 \ + --speculative-config '{"method": "mtp", "num_speculative_tokens": 5}' --api-key sk-secret +EOF +bench "$VL" "$t/cmd4" --dry-run +check "vllm: --spec from --speculative-config" 'grep -q "declare --spec mtp:5" "$t/out"' +check "vllm: --tp from -tp" 'grep -q "declare --tp 2" "$t/out"' +dry_notes "$VL" "$t/cmd4" --spec mtp:5 --tp 2 +check "vllm: matching values give no warning" '! grep -q "warning: --" "$t/out"' +check "vllm: --max-num-batched-tokens=N not redacted" 'note launch | grep -q "max-num-batched-tokens 8192"' +check "vllm: env flags recorded" '[ "$(note env_flags)" = "VLLM_USE_V1=1" ]' + +bench "$LR" "" --thinking off --dry-run +check "--thinking off vs reasoning in the replies" 'grep -q "thinking off, but the greedy replies contain reasoning" "$t/out"' + +# ------------------------------------------------------------------ finding the weights +# docker without llama-swap: the container path maps back through -v +printf 'docker run --rm -v %s:/models img -m /models/test.gguf\n' "$t/models" > "$t/cmd5" +dry_notes "$LR" "$t/cmd5" +check "docker -v mapping without llama-swap" 'note model_file | grep -q "^/models/test.gguf · 0.00 GB · sha256"' + +# vLLM repo id -> HF cache snapshot, safetensors as symlinks into blobs/ +hf="$t/hf/hub/models--Org--Repo"; mkdir -p "$hf/blobs" "$hf/refs" "$hf/snapshots/abc123" +printf 'A%.0s' $(seq 1000) > "$hf/blobs/b1"; printf 'B%.0s' $(seq 2000) > "$hf/blobs/b2" +ln -s ../../blobs/b1 "$hf/snapshots/abc123/model-00001-of-00002.safetensors" +ln -s ../../blobs/b2 "$hf/snapshots/abc123/model-00002-of-00002.safetensors" +printf 'abc123' > "$hf/refs/main" +HF_HOME="$t/hf" sh "$root/bench.sh" collect-env --endpoint "$VL" --model test-model > "$t/env" 2>/dev/null +want=$(cd "$hf/snapshots/abc123" && sha256sum *.safetensors | LC_ALL=C sort -k2 | sha256sum | cut -c1-64) +check "HF repo id resolved, symlink sizes followed" 'grep -qx "model_bytes=3000" "$t/env"' +check "repo hash equals the README recipe" 'grep -qx "model_sha256=$want" "$t/env"' + +# ------------------------------------------------------------------ failures and signals +FAKE_BB_FAIL=3 bench "$LL" "$t/cmd1"; rc=$? +check "betterbench failure -> .failed folder, exit 1" '[ $rc = 1 ] && grep -q "betterbench failed (exit 3)" "$t/out" && ls -d "$t"/res/*.failed >/dev/null 2>&1' + +FAKE_BB_SLEEP=60 TMPDIR="$t/tmpdir" sh "$root/bench.sh" --endpoint "$LL" --model test-model --tp 1 --pp 1 \ + --quant Q4_K_M --kv f16 --spec none --thinking default --submitter tester --power-limit 200 \ + --results-dir "$t/res2" > "$t/out" 2>&1 & +p=$! +i=0; until grep -q "running betterbench" "$t/out" || [ $i -gt 100 ]; do sleep 0.1; i=$((i + 1)); done +sleep 0.5; s0=$(date +%s); kill -TERM "$p"; wait "$p"; rc=$?; s1=$(date +%s) +check "TERM stops a run at once, exit 143" '[ $rc = 143 ] && [ $((s1 - s0)) -lt 5 ]' +check "interrupted run folder marked, no done:" 'ls -d "$t"/res2/*.interrupted >/dev/null 2>&1 && ! grep -q "^done:" "$t/out"' +check "no betterbench left running" '! pgrep -f "FAKE_BB_SLEEP|dev/test/betterbench run" >/dev/null 2>&1' +check "helpers cleaned up after a signal" '[ -z "$(ls -A "$t/tmpdir")" ]' + +# ------------------------------------------------------------------ the settings file +# plain bench.sh (no declared values on the command line) with BENCH_HOME=$t/home +plain() { TMPDIR="$t/tmpdir" sh "$root/bench.sh" "$@" > "$t/out" 2>&1; } +plain init; rc=$? +check "init writes bench.local.env next to bench.sh" '[ $rc = 0 ] && grep -q "^BENCH_SUBMITTER=" "$t/home/bench.local.env"' +plain init; rc=$? +check "init doesn't overwrite" '[ $rc = 1 ] && grep -q "exists" "$t/out"' +plain --dry-run +check "an unfilled file names what's missing and how to save it" 'grep -q "missing mandatory value(s): --model --quant --submitter" "$t/out" && grep -q "bench.sh init" "$t/out"' +s="$t/home/bench.local.env" +sed -e "s|^BENCH_SUBMITTER=.*|BENCH_SUBMITTER=filer # me|" \ + -e "s|^BENCH_ENDPOINT=.*|BENCH_ENDPOINT=$LL|" -e "s|^BENCH_MODEL=.*|BENCH_MODEL=test-model|" \ + -e "s|^BENCH_SERVER_CMD_FILE=.*|BENCH_SERVER_CMD_FILE=cmd.txt|" -e "s|^BENCH_QUANT=.*|BENCH_QUANT=Q4_K_M|" \ + -e 's|^# BENCH_POWER_LIMIT=250 .*|export BENCH_POWER_LIMIT=200|' \ + -e 's|^# BENCH_SPECIAL_NOTES=.*|BENCH_SPECIAL_NOTES="two words # not a comment" # a comment|' \ + -e 's|^# BENCH_RESULTS_DIR=.*|BENCH_RESULTS_DIR=res|' "$s" > "$s.new" && mv "$s.new" "$s" +printf 'llama-server -m /m.gguf -ngl 99\n' > "$t/home/cmd.txt" +(cd / && TMPDIR="$t/tmpdir" sh "$root/bench.sh" --dry-run > "$t/out" 2>&1); rc=$? +python3 - "$t/out" > "$t/notes" <<'PY' +import shlex, sys +line = next((l for l in open(sys.argv[1]) if l.startswith(" betterbench")), "") +w = shlex.split(line) +print("\n".join(w[i + 1] for i, x in enumerate(w) if x == "--note")) +PY +check "a filled file runs with no flags at all" '[ $rc = 0 ] && grep -q "settings from .*bench.local.env: BENCH_SUBMITTER" "$t/out"' +check "file: comments stripped, quotes kept, export accepted" '[ "$(note submitter)" = filer ] && [ "$(note special_notes)" = "two words # not a comment" ] && note power_limit | grep -q "^200 W"' +check "file: relative paths are relative to the file" 'note launch | grep -q "ngl 99" && grep -q "would write $t/home/res/" "$t/out"' +plain --dry-run --kv q8_0 +check "a flag wins over the file" 'grep -q "weights Q4_K_M · kv q8_0" "$t/out"' +BENCH_SUBMITTER=envname plain --dry-run +check "the environment wins over the file" 'grep -q "submitter=envname" "$t/out"' +sed 's|^BENCH_SUBMITTER=.*|BENCH_SUBMITTER=other|' "$s" > "$t/home/other.env" +plain --settings "$t/home/other.env" --dry-run +check "--settings picks another file" 'grep -q "submitter=other" "$t/out"' +printf 'BETTERBENCH_API_KEY=sk-x\n' > "$t/key.env"; plain --settings "$t/key.env" --dry-run; rc=$? +check "an API key in the file is refused" '[ $rc = 1 ] && grep -q "keep the API key out of files" "$t/out"' +printf 'BENCH_KV=$(touch %s/pwned)\n' "$t" > "$t/code.env"; plain --settings "$t/code.env" --dry-run +check "the file is data, never run" '[ ! -e "$t/pwned" ]' +rm -f "$s" + +# ------------------------------------------------------------------ power sampling +f="$t/sys/bus/pci/drivers/amdgpu/0000:03:00.0/hwmon/hwmon1"; mkdir -p "$f" +echo 150000000 > "$f/power1_input"; echo 2100000000 > "$f/freq1_input" +GPU_POWER_SYSFS="$t/sys" timeout 2 sh "$dev/gpu-power.sh" 1 > "$t/power" 2>/dev/null +check "amdgpu power via sysfs" 'grep -q "^[0-9.]*,150.00,,2100$" "$t/power"' + +echo +echo "$pass passed, $fail failed" +[ $fail = 0 ] diff --git a/dev/test/betterbench b/dev/test/betterbench new file mode 100755 index 0000000..aa67248 --- /dev/null +++ b/dev/test/betterbench @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +"""A fake betterbench for dev/test.sh: writes a plausible results.json. +FAKE_BB_SLEEP=S sleeps S seconds first; FAKE_BB_FAIL=N exits N.""" +import json, os, sys, time +a = sys.argv[1:] +if a[:1] == ["--version"]: + print("betterbench " + os.environ.get("FAKE_BB_VERSION", "0.6.1")); sys.exit() +print("[1/3] single stream"); sys.stdout.flush() +time.sleep(float(os.environ.get("FAKE_BB_SLEEP", "0"))) +if os.environ.get("FAKE_BB_FAIL"): + print("Traceback: boom"); sys.exit(int(os.environ["FAKE_BB_FAIL"])) +out = a[a.index("--out") + 1] +rec = [{"ok": True, "completion_tokens": 256, "decode_tps": 50.0 + i, "ttft_ms": 120 + i} for i in range(5)] +res = {"single_stream": {"code": rec}, + "concurrency": [{"level": 1, "aggregate_tps": 50, "wall_s": 10}, + {"level": 4, "aggregate_tps": 160, "wall_s": 10}], + "prefill": [{"target_depth": 4000, "pp_tps": [1500, 1600]}, {"target_depth": 64000, "skipped": True}], + "env": {}, "argv": a} +json.dump(res, open(out, "w")) +open(out.replace(".json", ".html"), "w").write("") +print("[3/3] done") diff --git a/dev/test/fake_server.py b/dev/test/fake_server.py new file mode 100644 index 0000000..c89c7e9 --- /dev/null +++ b/dev/test/fake_server.py @@ -0,0 +1,53 @@ +"""fake_server.py - a stand-in OpenAI-compatible server for dev/test.sh. + +usage: fake_server.py PORT ENGINE [REASONING] [MODEL_PATH] + ENGINE llama.cpp | vllm + REASONING 1: replies carry reasoning_content + MODEL_PATH what /props or /v1/models reports as the model file +""" +import json +import sys +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +port, engine = int(sys.argv[1]), sys.argv[2] +reasoning = len(sys.argv) > 3 and sys.argv[3] == "1" +model_path = sys.argv[4] if len(sys.argv) > 4 else "/models/test.gguf" + + +class H(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def send(self, obj, code=200): + b = json.dumps(obj).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(b))) + self.end_headers() + self.wfile.write(b) + + def do_GET(self): + p = self.path.rstrip("/") + if engine == "llama.cpp" and p == "/props": + self.send({"build_info": "b9999-abcdef0", "model_path": model_path, + "total_slots": 4, "default_generation_settings": {"n_ctx": 32768}}) + elif engine == "vllm" and p == "/version": + self.send({"version": "0.99.0"}) + elif p == "/v1/models": + self.send({"data": [{"id": "test-model", "owned_by": engine.replace(".cpp", ""), + "root": model_path, "max_model_len": 32768}]}) + else: + self.send({"error": "not found"}, 404) + + def do_POST(self): + n = int(self.headers.get("Content-Length", 0)) + req = json.loads(self.rfile.read(n) or b"{}") + if req.get("model") != "test-model": + return self.send({"error": "unknown model"}, 404) + msg = {"role": "assistant", "content": "2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37."} + if reasoning: + msg["reasoning_content"] = "Let me think about primes." + self.send({"choices": [{"message": msg, "finish_reason": "stop"}]}) + + +ThreadingHTTPServer(("127.0.0.1", port), H).serve_forever() diff --git a/dev/tests/test_gguf_kv.py b/dev/tests/test_gguf_kv.py deleted file mode 100644 index fbd7521..0000000 --- a/dev/tests/test_gguf_kv.py +++ /dev/null @@ -1,73 +0,0 @@ -"""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(" img /model " - "--max-num-batched-tokens=4224 --max-num-seqs=4 --kv-cache-dtype=int8_k_int4_v " - "--no-enable-prefix-caching " - "'--compilation-config={\"cudagraph_mode\": \"FULL_DECODE_ONLY\"}'") - - -def run(tmp_path, cmd=LLAMA_CMD, **over): - files = {} - for name, base in (("m", MANDATORY), ("c", COLLECTED), ("x", MEASURED)): - d = {**base, **over.get(name, {})} - files[name] = tmp_path / name - files[name].write_text("".join(f"{k}={v}\n" for k, v in d.items())) - (tmp_path / "cmd").write_text(cmd) - p = subprocess.run([sys.executable, os.path.join(DEV, "notes.py"), files["m"], files["c"], - files["x"], tmp_path / "cmd", tmp_path / "launch.json", - os.path.join(DEV, "models.tsv")], capture_output=True, text=True, check=True) - notes = dict(line.split("=", 1) for line in p.stdout.splitlines()) - return notes, p.stderr, json.loads((tmp_path / "launch.json").read_text()) - - -def test_llama_launch_and_env(tmp_path): - notes, err, launch = run(tmp_path) - assert notes["launch"] == "b 4096 · ub 1024 · fa on · ctk q8_0 · ctv q8_0 · ngl 99 · np 4 · no-mmap" - assert notes["env_flags"] == "GGML_SYCL_DISABLE_OPT=0 · ZES_ENABLE_SYSMAN=1" # offline switch left out - assert launch["env"]["HF_HUB_OFFLINE"] == "1" # but kept in meta - assert "warning" not in err - - -def test_llama_defaults_shown(tmp_path): - notes, _, _ = run(tmp_path, cmd="llama-server -m /m.gguf -ngl 99 -fa", m={"kv": "f16"}) - assert notes["launch"] == "b default · ub default · fa on · ctk default · ctv default · ngl 99" - - -def test_vllm_launch_env_and_kv_warning(tmp_path): - notes, err, _ = run(tmp_path, cmd=VLLM_CMD, c={"engine": "vllm"}) - assert "max-num-batched-tokens 4224" in notes["launch"] - assert "no-enable-prefix-caching" in notes["launch"] - assert 'compilation-config {"cudagraph_mode":"FULL_DECODE_ONLY"}' in notes["launch"] - assert notes["env_flags"] == "K8V4_PREFILL=onednn · HF_TOKEN=" - assert "--kv q8_0 but the launch command sets int8_k_int4_v" in err - - -def test_no_command(tmp_path): - notes, _, _ = run(tmp_path, cmd="") - assert notes["launch"] == "unknown (pass --server-cmd-file)" - assert notes["env_flags"] == "unknown" - - -def test_standard_model(tmp_path): - notes, err, _ = run(tmp_path) - assert notes["model_file"].endswith("standard: Qwen3.8-27B UD-Q4_K_M") - assert "standard models" not in err - - -def test_standard_model_wrong_quant(tmp_path): - _, err, _ = run(tmp_path, m={"quant": "Q4_K_M"}) - assert "declare --quant UD-Q4_K_M" in err - - -def test_other_model(tmp_path): - notes, err, _ = run(tmp_path, c={"model_sha256": "ab" * 32}) - assert "not a standard model (sha256 abababababab)" in notes["model_file"] - assert "won't count" in err - - -def test_model_not_hashed(tmp_path): - notes, _, _ = run(tmp_path, c={"model_sha256": ""}) - assert notes["model_file"].endswith("hash not checked") - - -def test_thinking_checked_against_replies(tmp_path): - notes, err, _ = run(tmp_path, m={"thinking": "off"}) - assert notes["thinking"] == "off · reasoning seen" - assert "--thinking off, but the greedy replies contain reasoning" in err - notes, err, _ = run(tmp_path, m={"thinking": "high"}, x={"greedy_reasoning": "no"}) - assert "--thinking high, but the greedy replies contain no reasoning" in err - _, err, _ = run(tmp_path, m={"thinking": "default"}, x={"greedy_reasoning": "no"}) - assert "thinking" not in err - - -def test_run_note_betterbench_build(tmp_path): - notes, _, _ = run(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 diff --git a/dev/tests/test_postrun.py b/dev/tests/test_postrun.py deleted file mode 100644 index 219641f..0000000 --- a/dev/tests/test_postrun.py +++ /dev/null @@ -1,58 +0,0 @@ -"""postrun.py: energy per phase and the bandwidth figure.""" -import os -import sys - -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -import postrun # noqa: E402 - - -def test_joules_between_interpolates(): - ts, cum = [0.0, 10.0, 20.0], [0.0, 1000.0, 3000.0] - assert postrun.joules_between(ts, cum, 5, 15) == 1500.0 - assert postrun.joules_between(ts, cum, -5, 30) == 3000.0 - - -def test_energy_curve_counter_or_integrated(): - rows = [(0, 100, 50.0, 0), (10, 100, 1050.0, 0)] - assert postrun.energy_curve(rows)[1] == [0.0, 1000.0] - rows = [(0, 100, None, 0), (10, 300, None, 0)] - ts, cum, src = postrun.energy_curve(rows) - assert cum == [0.0, 2000.0] and src == "integrated power" - - -def test_phase_energy_with_warmup_and_levels(): - # a steady 100 W, so energy = 100 J per second of each piece - rows = [(float(t), 100.0, 100.0 * t, 2000.0) for t in range(0, 101)] - timeline = [(0.0, "[single] chat: warmup 1 + 4 runs"), - (10.0, "[prefill] depth ~2000 tok: warmup 2 + 8"), - (20.0, "[prefill] skip depth ~64000: needs more"), - (30.0, "[concurrency] level 2: 48 requests")] - res = {"single_stream": {"chat": [{"ok": True, "completion_tokens": 100}] * 4}, - "prefill": [{"target_depth": 2000, "prompt_tokens": [1000] * 8}], - "concurrency": [{"level": 2, "aggregate_tps": 10.0, "wall_s": 50.0}]} - ph = postrun.phase_energy(res, rows, timeline, 80.0) - # decode: 10 s = 1000 J; 400 measured tokens, x 5/4 for the warm-up pass - assert ph["decode"] == {"joules": 1000, "avg_w": 100.0, "tokens_incl_warmup_est": 500, - "j_per_token": 2.0} - # prefill runs until the concurrency line (the skip line starts nothing): 20 s - assert ph["prefill"]["joules"] == 2000 - assert ph["prefill"]["j_per_1k_tokens"] == round(2000 / (8000 * 10 / 8) * 1000, 3) - # level 2: 50 s = 5000 J for 500 tokens - assert ph["concurrency"]["2"]["j_per_token"] == 10.0 - - -def test_roofline_prefers_loaded_weights_and_scales_with_tp(): - single = [{"decode_tps": 100.0}] - c = {"gpu_mem_bw_gbs": "500", "model_bytes": "4000000000", "model_loaded_gib": "1.0"} - r = postrun.roofline(single, c, {"tp": "2"}) - assert r["weight_source"] == "loaded (engine log)" - assert r["weight_bytes"] == 2 * 2**30 - assert r["mem_bw_gbs"] == 1000.0 - assert r["pct_of_mem_bw"] == round(100 * 100 * 2 * 2**30 / 1e9 / 1000, 1) - - -def test_roofline_falls_back_to_stored_and_declared_bw(): - r = postrun.roofline([{"decode_tps": 50.0}], {"model_bytes": "4000000000"}, - {"tp": "1", "mem_bw": "400"}) - assert r["weight_source"] == "stored files" and r["pct_of_mem_bw"] == 50.0 - assert postrun.roofline([{"decode_tps": 50.0}], {}, {"tp": "1", "mem_bw": "400"}) is None