Archived
radiance 1.13.0
New models: - Tencent Hy-Memory (HYV3) from its BF16, FP8 and GGUF checkpoints, with its native tool calls - M2XFP4: metadata-augmented MXFP4 weights for Qwen3.8-27B and its DFlash2 drafter (top-1 89.1% -> 92.4% against plain MXFP4), its quantiser and recipe, and ParoQuant's M2XFP4 checkpoints - Gemma 4 E2B/E4B audio input; NVIDIA-Nemotron-3.5-Bolt-E4B in int8 and 4-bit, on two cards by default; Ornith-1.5-122B compose files Speed: - Weight reads beside the decode all-reduces (qwen35_fp8, gemma3; --weight-prefetch, on by default): the 27B MXFP4 with DFlash2 61.2 -> 67.9 tok/s at c1, TranslateGemma 27B +13% - Head-256 split-KV decode attention at 256 workgroups and without bank conflicts (27B: +3-5% a step at 25-41K context), and the prefill KV split for small launches (a short turn over a long context decodes the other sequences 27% faster in that step) - MXFP4 decode gate_up, activation and fp8 quantiser in one launch (27B, Gemma 3 up to 64 rows: TranslateGemma +2-5% at 2-8 streams) - ParoQuant int4/int5 tiled GEMMs 6-9% faster - Speculation: a step's tokens are sent before the drafter's passes end, no step waits behind one that ends its requests, and the MTP head's first draft no longer collapses after short chats in the prefix cache Features: - --kv-resident N: KV streaming for a context bigger than VRAM (qwen4exp_fp8, GLM-5.3) - MiniMax-H3: reference media and keyframe conditioning with the VAE encoders - Krea 2 rebalance presets balanced, detail and subtle - The dashboard's request history; a stall watch that reports a frozen step's thread and stack - rad-tune at the served configuration, collectives measured as the exchange; Gemma 4 E2B/E4B's per-layer embeddings read ahead off the step path - A GPTQ calibration tap and recipe for Gemma 4 31B's w4a8 container Fixes: - The two-rank all-reduce checks that a peer's push has landed before reducing it - z-lab's DFlash drafter on Gemma 4 31B keeps drafting after a prefix-cache hit - MiniMax-H3's modulation rows Changes: Plugin ABI 31: out-of-tree plugins must be rebuilt. RADIANCE_PREFETCH_BESIDE is --weight-prefetch now; RADIANCE_NO_HUGE_PAGES, RADIANCE_IDS_EARLY, RADIANCE_ATTN_BAND_SPLIT, R4D_PREFILL_SPLITS, RAD_PLE_TIMING and RAD_PLE_CACHE_ROWS are gone.
This commit is contained in:
commit
6645337f69
198 files changed
+20904
-3240
No files matched your search
@@ -39,6 +39,11 @@ header lists its own. Scripts that only attach to a live server need `curl` and
|
||||
| `mctrace.sh` | A MiniCPM5-2B decode trace under `rocprofv3`, on its own server, formatted for `libr4d/isa/tsum.sh`, mainly for its `blocks` column. |
|
||||
| `ident.sh` | Run-to-run reproducibility at a fixed configuration: one hash per (temperature, question), to compare against another run of the same configuration. A speculative run need not match a non-speculative one byte for byte (the split-K count is chosen from M, so reduction orders differ and a near-tie can flip late in a long answer), but a divergence within the first sentence or two is a defect. |
|
||||
| `cardclock.py` | What holds each card's clock under sustained load, and which card a tensor-parallel step waits for (the slowest rank ends the step). Reads every AMD card's `gpu_metrics` table ten times a second and counts a throttler bit only when the clock is lower while it is set (some firmware keeps a bit on at idle). Shows the engine's step counters per window, so a slow window is attributed to slower steps, fewer tokens per step or host time between steps. Drives its own greedy load, or with `--watch` only samples a server under real traffic; `--compare` shows two saved runs side by side. Read-only on the cards. |
|
||||
| `kv-resident-vs-stock.sh` | This build with `--kv-resident 32768` against the stock 1.10.0 image without it, in interleaved ABBA rounds of one cold start a request; the mean paired delta with per-round values and a t interval (`ROUNDS` sets the resolution, ~2.0 % at 4). Both arms must tokenize the 16 110-token prompt alike and report `cached_tokens` 0. |
|
||||
| `kv-union.sh` | How large a ring must be: the union of distinct blocks one `kv_resolve` launch selects at 64k/128k-token prompts, the ring climbed from the 32 768-token floor until no launch overflows. Reports resolves, lookups, misses, the largest union and prefill time, and the overflow message verbatim; its last arm decodes a ~34k-token history past the floor ring against streaming off and passes only if the ring evicted. |
|
||||
| `kv-parity.sh` | That a ring covering the group's context streams nothing and changes no output byte: a dense and a sparse prompt without the flag and with `--kv-resident 4096` (the whole `--max-model-len x --max-num-seqs`), compared byte for byte, with `--profile-ops` showing no `kv_resolve` issued. |
|
||||
| `kv-multiturn-recall.py` | Whether planted facts survive twenty turns whose history outgrows the ring: the same transcript with streaming off and with `--kv-resident 32768` under `--max-model-len 65536`, a code planted at turn 2 and a surname at turn 5 asked at turn 20 (~49k prompt tokens). Fails if the off arm missed the cache on continuing turns or the on arm streamed nothing. |
|
||||
| `kv-stage-parity-64k.sh` | The prefill stage: streaming off against `--kv-resident 32768` on a ~64k-token document, so every chunk past 32 768 tokens takes the one-layer stage; byte-identical output, the staged copies checked in layer order, and both arms' VRAM split printed. A run that takes the ring instead fails. |
|
||||
| `statsdump.py` | Records `/stats` to a JSONL file, one row per poll (`--every`, default 1 s), so the dashboard's figures can be read back over time on a machine without a Prometheus scraper. A row is the engine's snapshot verbatim plus the poll's time `t` and the gap since the last good poll `dt_s`; nothing is derived. The file is appended to and rotated at `--max-mib` (default 256, five generations). A failed poll leaves no row; a run that wrote no row, or can no longer write its file, exits 1. The key is taken from `--api-key` or `RADIANCE_API_KEY`. |
|
||||
| `stampgaps.py` | Reads the CSV that `RADIANCE_AQL_STAMP=N` writes (every dispatch of one recorded pass in N on card 0, start and end) and prints per kind of pass (told apart by tape length) the median wall, the busy time as the union over the queues, the idle share, the gap before an ordered start (p50, p90, sum) and the kernels by share of the dispatch time. The idle share is what chained launches could win at most, the gaps what they would remove. Stamping costs throughput of its own when passes are short (one in 50: 0.3 % at one GLM-5.3 stream, 4 % at eight), so take N larger at high concurrency. |
|
||||
| `oracle.sh` | Every op compared against libref on the operands the model issued, which rad-kbench cannot do: its operands are its own (dense, rank 2), while the engine's are arena slices and weights loaded from a file. Starts its own server on :8302. Read it for `MISMATCH` lines, and for `NOT CHECKED` lines naming rows whose weight layout has no published inverse and so cannot be compared. |
|
||||
|
||||
Executable
+246
@@ -0,0 +1,246 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A planted fact survives twenty turns of a conversation whose history outgrows the KV ring.
|
||||
|
||||
Each turn's prompt is the previous one plus a little, so the prefix cache serves the common prefix
|
||||
and only the tail is prefilled. With a ring smaller than the history (32 768 tokens against a
|
||||
48 932-token transcript) the blocks a hit names have been through the host mirror and back, and a
|
||||
wrong copy shows as fluent text carrying a different name, which only a fact-check catches. One
|
||||
request with the whole transcript, or a ring covering the context, cannot show it; so the
|
||||
transcript goes turn by turn with a small ring, against the same transcript with streaming off.
|
||||
|
||||
What it asserts:
|
||||
* every arm answers the code, the name and the torque correctly (the code and torque are the
|
||||
same-turn facts; the name is the one planted at turn 2 and asked at turn 20, nineteen turns and
|
||||
~35k tokens later);
|
||||
* the off arm and the on arm each served a real prefix hit -- later turns report cached tokens,
|
||||
otherwise the arm is not a reuse test at all and this script fails rather than passing quietly;
|
||||
* the on arm streamed (nonzero kv_stream_misses_total), otherwise it is not the streamed arm.
|
||||
|
||||
Run it on the host; it starts each arm's server in the toolchain container, with MODELS (default
|
||||
~/models) mounted at /models and the tree at /src:
|
||||
MODELS=/path/to/models python3 scripts/kv-multiturn-recall.py
|
||||
|
||||
Not in CI: it needs a model, both cards, and ~6 minutes. Exit 0 only if every arm is correct and
|
||||
both arms are proven to have hit the cache; 2 if an arm did not come up or did not answer.
|
||||
"""
|
||||
import argparse, json, os, subprocess, sys, time, urllib.request
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
BUILD = os.environ.get("BUILD", "/src/build")
|
||||
MODELS = os.environ.get("MODELS", os.path.expanduser("~/models"))
|
||||
MODEL = os.environ.get("MODEL", "/models/qwen3.8-next-flash-fp8-iq4r-moe.rad")
|
||||
OUT = os.environ.get("OUT", "/tmp/radiance-kv-multiturn")
|
||||
BASE = ["--model", MODEL, "--tp", "2", "--tp-wire", "exact", "--max-num-seqs", "2",
|
||||
"--max-model-len", "65536",
|
||||
"--placement", "expert_tiered", "--host-pool-mib", "23652", "--gpu-headroom-mib", "96",
|
||||
"--kv-cache-dtype", "fp8", "--prefix-cache-mib", "1024", "--prefix-cache-ttl", "0",
|
||||
"--vision-tower-placement", "ram", "--num-speculative-tokens", "0", "--deterministic",
|
||||
"--host", "127.0.0.1", "--api-key", "test"]
|
||||
|
||||
# The planted facts, exactly the shape §4u/A measured: the code in turn 2 and the surname in turn 5,
|
||||
# asked together at turn 20. The code survives the window; the surname came back invented
|
||||
# ("Ilse Koch" for "Ilse Varga") in a 32 768-token ring whose history had outgrown it.
|
||||
CODE = "The maintenance code for bay seven is QX-4471."
|
||||
NAME = ("The duty archivist for the east wing on the day of the catalogue check was named "
|
||||
"Ilse Varga.")
|
||||
TORQUE = "" # not planted in this transcript; the question asks for what is here
|
||||
QUESTION = ("Question: what is the maintenance code for bay seven, and who was the duty archivist "
|
||||
"for the east wing on the day of the catalogue check? Answer with both values.")
|
||||
RECORD = ("Record %d: the archivist checked the shelf, noted the catalogue number, and returned the "
|
||||
"volume to the east wing of the reading room.")
|
||||
PAD = 65 # register lines a turn: ~2 010 tokens as the chat template counts them
|
||||
N_TURNS = 20
|
||||
CODE_TURN = 2
|
||||
NAME_TURN = 5
|
||||
MAX_TOKENS = 400 # forced past EOS, as measured: ~2 430 tokens of live context a turn
|
||||
|
||||
|
||||
def log(*a):
|
||||
print(*a, flush=True)
|
||||
|
||||
|
||||
def http(port, path, body=None, timeout=3600):
|
||||
req = urllib.request.Request(f"http://127.0.0.1:{port}{path}", data=None if body is None else json.dumps(body).encode(),
|
||||
headers={"Authorization": "Bearer test", "Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read())
|
||||
|
||||
|
||||
def health(port):
|
||||
try:
|
||||
with urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{port}/health",
|
||||
headers={"Authorization": "Bearer test"}), timeout=2) as r:
|
||||
return r.status == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def metrics(port):
|
||||
try:
|
||||
with urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{port}/metrics",
|
||||
headers={"Authorization": "Bearer test"}), timeout=5) as r:
|
||||
txt = r.read().decode()
|
||||
except Exception:
|
||||
return {}
|
||||
out = {}
|
||||
for line in txt.splitlines():
|
||||
if line.startswith("radiance:") and " " in line:
|
||||
k, v = line.rsplit(" ", 1)
|
||||
k = k.split("{")[0][len("radiance:"):]
|
||||
try:
|
||||
out[k] = float(v)
|
||||
except ValueError:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def engine_pid():
|
||||
for p in os.listdir("/proc"):
|
||||
if not p.isdigit():
|
||||
continue
|
||||
try:
|
||||
if open(f"/proc/{p}/comm").read().strip() == "radiance":
|
||||
return int(p)
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
class Server:
|
||||
"""One engine, in its own container, killed by name at the end and on any error path."""
|
||||
|
||||
def __init__(self, tag, port, flags):
|
||||
self.tag, self.port, self.name = tag, port, f"mt-{tag}"
|
||||
self.logf = f"{OUT}/{tag}.server.log"
|
||||
self.flags = BASE + list(flags) + ["--port", str(port)]
|
||||
|
||||
def start(self):
|
||||
self.p = subprocess.Popen([
|
||||
"docker", "run", "--rm", "--name", self.name, "--user", "1000:1000", "-e", "HOME=/tmp",
|
||||
"--device", "/dev/kfd", "--device", "/dev/dri", "--group-add", "990", "--group-add", "44",
|
||||
"--security-opt", "seccomp=unconfined", "--network", "host",
|
||||
"-v", f"{ROOT}:/src", "-v", f"{MODELS}:/models", "-w", "/src", "rad-toolchain:latest",
|
||||
"bash", "-lc", f"RADIANCE_HOME={BUILD}/radiance_home {BUILD}/bin/radiance " + " ".join(self.flags)],
|
||||
stdout=open(self.logf, "w"), stderr=subprocess.STDOUT)
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 300:
|
||||
if health(self.port):
|
||||
log(f"[{self.tag}] health after {time.time() - t0:.0f}s")
|
||||
return
|
||||
if self.p.poll() is not None:
|
||||
log(open(self.logf).read()[-2000:])
|
||||
raise SystemExit(f"arm {self.tag}: engine exited before health")
|
||||
time.sleep(1)
|
||||
raise SystemExit(f"arm {self.tag}: no health after 300s")
|
||||
|
||||
def stop(self):
|
||||
subprocess.run(["docker", "rm", "-f", self.name], capture_output=True)
|
||||
for _ in range(120):
|
||||
if engine_pid() is None:
|
||||
return
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def turn_text(t):
|
||||
body = " ".join(RECORD % i for i in range(t * 400, t * 400 + PAD))
|
||||
if t == CODE_TURN:
|
||||
return f"{CODE} {body} Begin the session log."
|
||||
if t == NAME_TURN:
|
||||
return f"{NAME} {body} Continue the register."
|
||||
if t == N_TURNS:
|
||||
return f"{body} {QUESTION}"
|
||||
return f"{body} Continue the register."
|
||||
|
||||
|
||||
def run_arm(tag, port, flags):
|
||||
srv = Server(tag, port, flags)
|
||||
try:
|
||||
srv.start()
|
||||
msgs, rows, answers = [], [], {}
|
||||
m0 = metrics(port)
|
||||
for t in range(1, N_TURNS + 1):
|
||||
msgs.append({"role": "user", "content": turn_text(t)})
|
||||
a = None
|
||||
for _ in range(2):
|
||||
try:
|
||||
a = http(port, "/v1/chat/completions",
|
||||
{"model": "qwen4exp", "temperature": 0, "seed": 12345,
|
||||
"max_tokens": MAX_TOKENS, "ignore_eos": True,
|
||||
"chat_template_kwargs": {"enable_thinking": False}, "messages": msgs})
|
||||
break
|
||||
except Exception as e:
|
||||
log(f"[{tag}] turn {t} failed: {e}")
|
||||
time.sleep(2)
|
||||
if a is None:
|
||||
raise SystemExit(f"arm {tag}: turn {t} failed twice")
|
||||
m1 = metrics(port)
|
||||
d = round(m1.get("kv_stream_misses_total", 0) - m0.get("kv_stream_misses_total", 0))
|
||||
m0 = m1
|
||||
u = a.get("usage", {})
|
||||
txt = a["choices"][0]["message"]["content"]
|
||||
answers[t] = txt
|
||||
rows.append({"turn": t, "prompt": u.get("prompt_tokens"),
|
||||
"cached": (u.get("prompt_tokens_details") or {}).get("cached_tokens", 0),
|
||||
"misses": d})
|
||||
log(f"[{tag}] turn {t:2d} prompt={rows[-1]['prompt']} cached={rows[-1]['cached']} misses+={d}")
|
||||
msgs.append({"role": "assistant", "content": txt})
|
||||
finally:
|
||||
srv.stop()
|
||||
return {"tag": tag, "rows": rows, "answers": answers}
|
||||
|
||||
|
||||
def check(name, text):
|
||||
"""Both values, compared case- and punctuation-insensitively, so formatting cannot hide a wrong
|
||||
fact and cannot fail a right one. The surname is the recorded failure: 'Ilse Koch' came back for
|
||||
'Ilse Varga', so both parts are required, in that order and adjacent."""
|
||||
flat = " ".join("".join(c.lower() if c.isalnum() else " " for c in text).split())
|
||||
return ("qx 4471" in flat or "qx4471" in flat) and ("ilse varga" in flat)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--only", choices=("on", "off"), help="run one arm")
|
||||
ap.add_argument("--port", type=int, default=8181)
|
||||
args = ap.parse_args()
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
# A ring at the floor (32 768 tokens, 8 192 blocks) under a context that outgrows it: every
|
||||
# turn past 32 768 tokens has history the ring cannot hold, so a hit can only be served from the
|
||||
# host copy. This is the shape in which the planted name came back wrong.
|
||||
arms = [("off", []), ("on", ["--kv-resident", "32768"])]
|
||||
if args.only:
|
||||
arms = [a for a in arms if a[0] == args.only]
|
||||
results, bad = {}, []
|
||||
for i, (tag, flags) in enumerate(arms):
|
||||
results[tag] = run_arm(tag, args.port + i, flags)
|
||||
r = results[tag]
|
||||
final = r["answers"][N_TURNS]
|
||||
hits = sum(1 for row in r["rows"][1:] if row["cached"] > 0)
|
||||
log(f"[{tag}] FINAL: {r['answers'][N_TURNS]!r}")
|
||||
log(f"[{tag}] facts {'OK' if check(tag, final) else 'WRONG'}, "
|
||||
f"cached on {hits}/{N_TURNS - 1} continuing turns, "
|
||||
f"streamed {sum(row['misses'] for row in r['rows'])} blocks")
|
||||
json.dump(results, open(f"{OUT}/multiturn.json", "w"), indent=1)
|
||||
for tag, r in results.items():
|
||||
final = r["answers"][N_TURNS]
|
||||
hits = sum(1 for row in r["rows"][1:] if row["cached"] > 0)
|
||||
if not check(tag, final):
|
||||
bad.append(f"{tag}: wrong facts")
|
||||
if tag == "off" and hits < N_TURNS - 2:
|
||||
bad.append(f"off: only {hits} turns served from the cache -- not a reuse arm")
|
||||
if tag == "on" and not any(row["misses"] for row in r["rows"]):
|
||||
bad.append("on: streamed nothing")
|
||||
if len(arms) == 2:
|
||||
same = results["on"]["answers"][N_TURNS] == results["off"]["answers"][N_TURNS]
|
||||
log(f"[*] on and off agree byte for byte: {same}")
|
||||
if not same:
|
||||
bad.append("on and off differ")
|
||||
json.dump(results, open(f"{OUT}/multiturn.json", "w"), indent=1)
|
||||
if bad:
|
||||
log("FAIL: " + "; ".join(bad))
|
||||
return 1
|
||||
log("PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+272
@@ -0,0 +1,272 @@
|
||||
#!/bin/bash
|
||||
# That a --kv-resident ring covering the group's context streams nothing and changes no output byte
|
||||
# on the QSA model (docs/KV-STREAMING.md §3.1).
|
||||
#
|
||||
# One server per arm, the same requests to each, the completions compared byte for byte. The on arm
|
||||
# passes --kv-resident 4096 with --max-num-seqs 1 --max-model-len 4096, exactly the group's context,
|
||||
# and must report at startup that nothing streams and issue no kv_resolve (--profile-ops). Only the
|
||||
# servers this script starts are stopped, by pid.
|
||||
#
|
||||
# Run inside the toolchain container, where the binary and its libraries live, with io_uring
|
||||
# allowed (Docker's default seccomp profile refuses it):
|
||||
# docker run --rm --security-opt seccomp=unconfined --user 1000:1000 -e HOME=/tmp \
|
||||
# --device /dev/kfd --device /dev/dri --group-add 990 --group-add 44 \
|
||||
# -v "$PWD":/src -v /path/to/models:/models -w /src rad-toolchain:latest \
|
||||
# bash -lc 'bash scripts/kv-parity.sh'
|
||||
#
|
||||
# Two deterministic prompts: a sparse one of ~3000 tokens, since the sparse path engages only above
|
||||
# qsa_exact_to = 2051, and a short dense one. Both fit the 4096-token context.
|
||||
#
|
||||
# Exit status: 0 if both arms answered, byte-identical, with no streaming and no resolve on the on
|
||||
# arm; 1 on a difference or streaming overhead; 2 if an arm did not come up or did not answer.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
BUILD="${BUILD:-$ROOT/build}"
|
||||
MODEL="${MODEL:-/models/qwen3.8-next-flash-fp8-iq4r-moe.rad}"
|
||||
PORT="${PORT:-8123}"
|
||||
OUT="${OUT:-/tmp/radiance-kv-parity}"
|
||||
SPARSE_LINES="${SPARSE_LINES:-100}" # ~3028 prompt tokens: above qsa_exact_to, so sparse
|
||||
DENSE_LINES="${DENSE_LINES:-20}" # ~600 prompt tokens: below it, so dense, no kv_resolve
|
||||
MAXTOK="${MAXTOK:-256}"
|
||||
SEED="${SEED:-12345}"
|
||||
# Exactly the one-sequence context the server is configured with (--max-num-seqs 1 x
|
||||
# --max-model-len 4096), so this ring covers the group and nothing streams.
|
||||
RESIDENT="${RESIDENT:-4096}"
|
||||
|
||||
BIN="$BUILD/bin/radiance"
|
||||
export RADIANCE_HOME="$BUILD/radiance_home" # absolute: the engine will not find the kernels without it
|
||||
[ -x "$BIN" ] || { echo "no engine at $BIN (build it first; this script builds nothing)" >&2; exit 2; }
|
||||
[ -f "$MODEL" ] || { echo "no model at $MODEL" >&2; exit 2; }
|
||||
command -v curl >/dev/null || { echo "curl is needed" >&2; exit 2; }
|
||||
|
||||
mkdir -p "$OUT"
|
||||
SERVER_PID=""
|
||||
cleanup() {
|
||||
# Only our own process, by the pid this script recorded: the engine is one process (its TP ranks
|
||||
# are threads), so there is no group to sweep and nothing else can be hit by mistake. No pkill.
|
||||
if [ -n "$SERVER_PID" ] && kill -0 "$SERVER_PID" 2>/dev/null; then
|
||||
kill -TERM "$SERVER_PID" 2>/dev/null || true
|
||||
# Generous: with --profile-ops the per-op table is printed by ~Engine on SIGTERM, and killing
|
||||
# before it lands would lose the only per-op issue counts the engine ever reports.
|
||||
for _ in $(seq 1 240); do kill -0 "$SERVER_PID" 2>/dev/null || break; sleep 0.25; done
|
||||
kill -KILL "$SERVER_PID" 2>/dev/null || true
|
||||
fi
|
||||
SERVER_PID=""
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
# A one-line prompt, so the request body needs no JSON string escapes at all: the records are
|
||||
# joined with spaces deliberately (text is identical in both arms either way).
|
||||
gen_prompt() {
|
||||
local n="$1" i first=$(( $1 + 1 )) last=$(( $1 + 10 ))
|
||||
for ((i = 1; i <= n; i++)); do
|
||||
printf 'Record %d: the archivist checked the shelf, noted the catalogue number, and returned the volume to the east wing of the reading room. ' "$i"
|
||||
done
|
||||
printf 'Continue the register: write records %d through %d in the same form, one per line.' "$first" "$last"
|
||||
}
|
||||
gen_prompt "$SPARSE_LINES" > "$OUT/prompt-sparse.txt"
|
||||
gen_prompt "$DENSE_LINES" > "$OUT/prompt-dense.txt"
|
||||
|
||||
# The raw JSON-escaped value of the completion's "content". Escaping is a deterministic function of
|
||||
# the text, so equal escaped bytes mean equal text -- and comparing the escaped form is strictly
|
||||
# safer than any unescaper this script could carry.
|
||||
content_of() {
|
||||
awk '
|
||||
{ s = $0
|
||||
i = index(s, "\"message\":"); if (i == 0) exit 1
|
||||
s = substr(s, i)
|
||||
i = index(s, "\"content\":\""); if (i == 0) exit 1
|
||||
s = substr(s, i + 11)
|
||||
out = ""
|
||||
for (j = 1; j <= length(s); j++) {
|
||||
c = substr(s, j, 1)
|
||||
if (c == "\\") { out = out substr(s, j, 2); j++; continue }
|
||||
if (c == "\"") break
|
||||
out = out c
|
||||
}
|
||||
printf "%s", out
|
||||
}' "$1"
|
||||
}
|
||||
|
||||
# One arm: start a server, wait for /health (never a blind sleep), ask once, stop the server.
|
||||
# `$1` is the arm's name, `$2` its prompt, the rest is the streaming flags -- identical otherwise,
|
||||
# which is the point. Returns non-zero (and leaves the engine's last errors on stderr) if the arm
|
||||
# could not serve, so every arm gets to report before the script decides.
|
||||
run_arm() { local arm="$1" prompt="$2"; shift 2
|
||||
local log="$OUT/$arm.log" req="$OUT/$arm.req.json" resp="$OUT/$arm.json"
|
||||
echo "== $arm: $* =="
|
||||
( exec "$BIN" --model "$MODEL" \
|
||||
--tp 2 --tp-wire exact \
|
||||
--max-num-seqs 1 --max-model-len 4096 --placement expert_tiered --host-pool-mib 23652 \
|
||||
--kv-cache-dtype fp8 --prefix-cache-mib 4096 --vision-tower-placement ram \
|
||||
--num-speculative-tokens 0 --deterministic \
|
||||
"$@" --host 127.0.0.1 --port "$PORT" --api-key test ) > "$log" 2>&1 &
|
||||
SERVER_PID=$!
|
||||
|
||||
local i code
|
||||
for i in $(seq 1 180); do # 15 min at 5 s: a cold load of this container is under a minute
|
||||
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
|
||||
echo "FAIL $arm: the engine exited before serving; last errors:" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$log" | tail -12 >&2 || tail -12 "$log" >&2
|
||||
cleanup
|
||||
return 1
|
||||
fi
|
||||
code=$(curl -s -m 3 -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/health" 2>/dev/null || true)
|
||||
[ "$code" = 200 ] && break
|
||||
sleep 5
|
||||
done
|
||||
if [ "${code:-}" != 200 ]; then
|
||||
echo "FAIL $arm: /health did not answer" >&2
|
||||
cleanup
|
||||
return 1
|
||||
fi
|
||||
|
||||
# temperature 0 and a fixed seed: greedy, so the only thing that can move a token is the engine.
|
||||
local prompt_text
|
||||
prompt_text=$(cat "$prompt")
|
||||
printf '{"model":"%s","temperature":0,"seed":%s,"max_tokens":%s,"chat_template_kwargs":{"enable_thinking":false},"messages":[{"role":"user","content":"%s"}]}' \
|
||||
"qwen4exp" "$SEED" "$MAXTOK" "$prompt_text" > "$req"
|
||||
code=$(curl -s -m 900 -o "$resp" -w '%{http_code}' \
|
||||
-H "Authorization: Bearer test" -H "Content-Type: application/json" \
|
||||
--data-binary "@$req" "http://127.0.0.1:$PORT/v1/chat/completions" 2>/dev/null || true)
|
||||
if [ "${code:-}" != 200 ]; then
|
||||
echo "FAIL $arm: /v1/chat/completions answered $code; last errors:" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$log" | tail -12 >&2 || tail -12 "$log" >&2
|
||||
cleanup
|
||||
return 1
|
||||
fi
|
||||
content_of "$resp" > "$OUT/$arm.txt"
|
||||
if [ ! -s "$OUT/$arm.txt" ]; then
|
||||
echo "FAIL $arm: empty completion text" >&2
|
||||
cleanup
|
||||
return 1
|
||||
fi
|
||||
|
||||
# What the prompt actually cost, straight from the engine: it must be past qsa_exact_to for the
|
||||
# sparse arm, and cached_tokens 0 shows the whole prompt was prefilled on this server (a prefix
|
||||
# hit would leave the arm's own token count unproven).
|
||||
local ptok ctok cache
|
||||
ptok=$(grep -o '"prompt_tokens":[0-9]*' "$resp" | head -1 | cut -d: -f2)
|
||||
ctok=$(grep -o '"completion_tokens":[0-9]*' "$resp" | head -1 | cut -d: -f2)
|
||||
cache=$(grep -o '"cached_tokens":[0-9]*' "$resp" | head -1 | cut -d: -f2)
|
||||
echo " prompt_tokens=$ptok completion_tokens=$ctok cached_tokens=$cache"
|
||||
echo " sha256 $(sha256sum "$OUT/$arm.txt" | cut -d' ' -f1) ($(wc -c < "$OUT/$arm.txt") bytes)"
|
||||
echo "$ptok $ctok $cache" > "$OUT/$arm.counts"
|
||||
|
||||
cleanup
|
||||
return 0
|
||||
}
|
||||
|
||||
# What a byte comparison cannot tell you, asserted on the streaming log:
|
||||
# - no `kv_resolve` refusal and no GPU fault / fatal.
|
||||
# - the "nothing streams" line, and no streamed-group line: the ring covered the context, so the
|
||||
# group kept the base engine's resident path rather than a cheapened streamed one.
|
||||
assert_streaming_log() {
|
||||
local arm="$1"
|
||||
local log="$OUT/$1.log"
|
||||
local bad=0
|
||||
if grep -q "refused op 'kv_resolve'" "$log"; then
|
||||
echo "FAIL $arm: kv_resolve was refused at issue" >&2; bad=1
|
||||
fi
|
||||
if grep -q "GPU memory fault" "$log"; then
|
||||
echo "FAIL $arm: a GPU memory fault was reported" >&2; bad=1
|
||||
fi
|
||||
if grep -q "^radiance: fatal:" "$log"; then
|
||||
echo "FAIL $arm: the engine reported a fatal error" >&2; bad=1
|
||||
fi
|
||||
if ! grep -q "^I kv streaming: nothing streams" "$log"; then
|
||||
echo "FAIL $arm: no 'nothing streams' startup line: --kv-resident $RESIDENT did not cover the context" >&2; bad=1
|
||||
fi
|
||||
if grep -q "^I kv streaming: [0-9].*stream (" "$log"; then
|
||||
echo "FAIL $arm: a group streamed even though the ring covers its context" >&2; bad=1
|
||||
fi
|
||||
return $bad
|
||||
}
|
||||
|
||||
# Count the kv_resolve issues the engine itself accounted for, per op instance. `--profile-ops`
|
||||
# prints a per-op table (calls, total ms, us/call, op, geometry) on shutdown and every
|
||||
# RADIANCE_PROFILE_EVERY steps, and it is the only place the engine states how many times an op was
|
||||
# issued: no ctl counter reaches /metrics and no launch is logged. There is one kv_resolve op per
|
||||
# layer, so every row carries the same count; the largest is this arm's per-layer total.
|
||||
# A row is ` <calls> <total ms> <us/call> <site> <join> <wait> <op> <geometry> ...`, so the op is
|
||||
# matched as a whole field and the count is field 1. Prints the count (0 if the op never appears).
|
||||
resolves_issued() {
|
||||
grep -E '^ +[0-9]+ ' "$1" 2>/dev/null |
|
||||
awk '{ for (i = 1; i <= NF; i++) if ($i == "kv_resolve") { if ($1 + 0 > mx) mx = $1 + 0; break } }
|
||||
END { print mx + 0 }'
|
||||
}
|
||||
|
||||
# Ask one profiled question: how many times was kv_resolve issued per layer on this shape? $1 = arm
|
||||
# name, $2 = the prompt. The count lands in $OUT/$arm.resolves. The profiled servers are used for
|
||||
# this evidence only -- their completions are not compared, because --profile-ops restores
|
||||
# synchronisations that make it a different run (its own caveat prints so).
|
||||
run_profile_probe() {
|
||||
local arm="$1" prompt="$2"
|
||||
local log="$OUT/$arm.log" got
|
||||
echo "== probe $arm: --profile-ops =="
|
||||
run_arm "$arm" "$prompt" --kv-resident "$RESIDENT" --profile-ops || return 1
|
||||
got=$(resolves_issued "$log")
|
||||
echo " kv_resolve issues per layer: $got"
|
||||
echo "$got" > "$OUT/$arm.resolves"
|
||||
return 0
|
||||
}
|
||||
|
||||
# The short arms first, then the arms the change is about: whatever the sparse arm
|
||||
# does must not hide the evidence the cheap arms produce.
|
||||
FAILED=0
|
||||
run_arm off-dense "$OUT/prompt-dense.txt" || FAILED=1
|
||||
run_arm on-dense "$OUT/prompt-dense.txt" --kv-resident "$RESIDENT" || FAILED=1
|
||||
|
||||
assert_streaming_log on-dense || FAILED=1
|
||||
|
||||
# A ring smaller than the context is scripts/kv-stage-parity-64k.sh's case; this script keeps the
|
||||
# covering configuration.
|
||||
|
||||
run_arm off-sparse "$OUT/prompt-sparse.txt" || FAILED=1
|
||||
run_arm on-sparse "$OUT/prompt-sparse.txt" --kv-resident "$RESIDENT" || FAILED=1
|
||||
assert_streaming_log on-sparse || FAILED=1
|
||||
|
||||
echo "== kv streaming lines from on-sparse.log =="
|
||||
grep -E "kv streaming:" "$OUT/on-sparse.log" || echo " (none: no streaming report line at all)"
|
||||
|
||||
# Execution, not configuration: the byte comparison above is worthless if a resolve ran on a group
|
||||
# this configuration says is resident. A ring that covers the context must issue no kv_resolve at
|
||||
# all -- on either the dense or the sparse path -- because the batch hands the arch a null stream.
|
||||
run_profile_probe proof-dense "$OUT/prompt-dense.txt" || FAILED=1
|
||||
run_profile_probe proof-sparse "$OUT/prompt-sparse.txt" || FAILED=1
|
||||
if [ -s "$OUT/proof-dense.resolves" ] && [ -s "$OUT/proof-sparse.resolves" ]; then
|
||||
dense_n=$(cat "$OUT/proof-dense.resolves")
|
||||
sparse_n=$(cat "$OUT/proof-sparse.resolves")
|
||||
echo "== resolve execution: $sparse_n per layer on the sparse arm, $dense_n on the dense arm =="
|
||||
if [ "$sparse_n" -ne 0 ] || [ "$dense_n" -ne 0 ]; then
|
||||
echo "FAIL: a covering ring issued $sparse_n/$dense_n resolves per layer: it streamed when it" >&2
|
||||
echo " should have kept the base engine's resident path" >&2
|
||||
FAILED=1
|
||||
fi
|
||||
else
|
||||
echo "FAIL: a probe arm produced no per-op table, so execution is unproven" >&2
|
||||
FAILED=1
|
||||
fi
|
||||
|
||||
# The sparse prompt must be past qsa_exact_to, so the sparse path actually ran (and still issued no
|
||||
# resolve, because the ring covers the context).
|
||||
if [ -s "$OUT/on-sparse.counts" ]; then
|
||||
read -r ptok _ _ < "$OUT/on-sparse.counts"
|
||||
if [ "$ptok" -le 2051 ]; then
|
||||
echo "FAIL: the sparse prompt is $ptok tokens, at or below qsa_exact_to 2051: the dense path" >&2
|
||||
echo " ran, so the sparse path this check is about was never exercised. Raise SPARSE_LINES." >&2
|
||||
FAILED=1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$FAILED" -ne 0 ]; then
|
||||
echo "FAIL: an arm did not serve, a log was not clean, or a covering ring streamed anyway" >&2
|
||||
echo " (see above); no zero-overhead claim can be made" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
echo "== compare =="
|
||||
cmp "$OUT/off-sparse.txt" "$OUT/on-sparse.txt" || { echo "FAIL: the sparse arms differ" >&2; exit 1; }
|
||||
cmp "$OUT/off-dense.txt" "$OUT/on-dense.txt" || { echo "FAIL: the dense arms differ" >&2; exit 1; }
|
||||
echo "PASS: both arms byte-identical, with a covering ring streaming nothing and issuing no resolve"
|
||||
Executable
+664
@@ -0,0 +1,664 @@
|
||||
#!/bin/bash
|
||||
# The decode gap between streaming and the stock engine, as a paired number with an interval.
|
||||
#
|
||||
# The shape: a 16 110-token prompt generated here (sha256 c34ad060...f3a5, gen_prompt 522),
|
||||
# 8 192 generated tokens, this build with --kv-resident 32768 (8 192 blocks, so the group streams and
|
||||
# every decode launch resolves) against the stock image stilldeadcode/radiance:1.10.0 without it.
|
||||
# Every other flag is the same in both arms.
|
||||
#
|
||||
# SPEC (default 0) sets --num-speculative-tokens in both arms. With speculation a step emits
|
||||
# 1 + SPEC tokens, so ms/step comes from the engine's step clock (/metrics
|
||||
# engine_step_seconds_decode_total / engine_steps_decode_total), tokens a step from MAXTOK over the
|
||||
# decode steps, and acceptance from timings.draft_n_accepted / draft_n, printed per start because it
|
||||
# is bimodal.
|
||||
#
|
||||
# Method: interleaved ABBA rounds of one cold start a request, alternating which arm goes first. The
|
||||
# two arms cannot hold the cards together, and a second request in one process starts from a
|
||||
# partly filled ring, a different workload. Each round gives one paired delta (ours ms/step over
|
||||
# stock's); the mean, the per-round values, the spread and a t interval are reported. A start takes
|
||||
# about 4 min, and at a cross-arm sd of 1.4 points the detectable difference is ~2.8 % at 2 rounds
|
||||
# and ~2.0 % at 4; resolving 1 % needs ~16 rounds.
|
||||
#
|
||||
# Same input in both arms: the prompt's sha256 must match, every server must tokenize it to the
|
||||
# target count before its request, and every response must report that count with cached_tokens 0.
|
||||
# A mismatch stops the run.
|
||||
#
|
||||
# Run on the host (the docker CLI talks to the daemon; the engine runs in the toolchain container
|
||||
# with the model mounted and io_uring unconfined):
|
||||
# bash scripts/kv-resident-vs-stock.sh # 2 rounds, ~16 min
|
||||
# ROUNDS=4 bash scripts/kv-resident-vs-stock.sh # ~32 min
|
||||
# SPEC=3 ROUNDS=12 bash scripts/kv-resident-vs-stock.sh # speculation on, ~20 min
|
||||
#
|
||||
# Environment (defaults in parentheses): ROUNDS (2), MAXTOK (8192), RESIDENT (32768), SPEC (0),
|
||||
# PORT (8141), OUT (/tmp/radiance-kv-resident-vs-stock), BUILD (/src/build, the tree as the
|
||||
# toolchain container sees it), MODEL ($HOME/models/qwen3.8-next-flash-fp8-iq4r-moe.rad),
|
||||
# STOCK_IMAGE (stilldeadcode/radiance:1.10.0), TOOLCHAIN (rad-toolchain:latest), SEED (12345).
|
||||
# TARGET_TOKENS (16110), PROMPT_LINES (522) and PROMPT_SHA are the workload and pinned.
|
||||
#
|
||||
# Exit status: 0 if every round measured and the arms agreed on the prompt; 2 if the environment,
|
||||
# an arm, a token count, a ring check or the model file failed (the reason is on stderr).
|
||||
set -euo pipefail
|
||||
|
||||
usage() {
|
||||
awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "$0"
|
||||
}
|
||||
|
||||
ROUNDS="${ROUNDS:-2}"
|
||||
MAXTOK="${MAXTOK:-8192}"
|
||||
RESIDENT="${RESIDENT:-32768}"
|
||||
SPEC="${SPEC:-0}"
|
||||
PORT="${PORT:-8141}"
|
||||
OUT="${OUT:-/tmp/radiance-kv-resident-vs-stock}"
|
||||
BUILD="${BUILD:-/src/build}"
|
||||
MODEL="${MODEL:-$HOME/models/qwen3.8-next-flash-fp8-iq4r-moe.rad}"
|
||||
STOCK_IMAGE="${STOCK_IMAGE:-stilldeadcode/radiance:1.10.0}"
|
||||
TOOLCHAIN="${TOOLCHAIN:-rad-toolchain:latest}"
|
||||
SEED="${SEED:-12345}"
|
||||
|
||||
# The workload, pinned: the canonical prompt, and what the server counted it as.
|
||||
PROMPT_LINES=522
|
||||
TARGET_TOKENS=16110
|
||||
PROMPT_SHA=c34ad06069bc07c791e61789ffbace20f5879781c9fbc2eb7ea009e09cb3f3a5
|
||||
# Pinned so "the model is the expected file" is a check and not a hope: the whole 122 GB is too
|
||||
# much to hash every run, so the size plus the first 4 MiB identifies the conversion.
|
||||
MODEL_BYTES=121969901568
|
||||
MODEL_HEAD_SHA=f2958962468b9b112ebc4bcf78d6da9b270477c7b636a0ded7418b7298e434b4
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--help|-h) usage; exit 0 ;;
|
||||
--rounds) [ $# -ge 2 ] || { echo "--rounds needs a value" >&2; exit 2; }; ROUNDS="$2"; shift 2 ;;
|
||||
--spec) [ $# -ge 2 ] || { echo "--spec needs a value" >&2; exit 2; }; SPEC="$2"; shift 2 ;;
|
||||
*) echo "unknown option: $1 (--help for usage)" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
case "$ROUNDS" in
|
||||
''|*[!0-9]*) echo "ROUNDS must be a positive integer, got '$ROUNDS'" >&2; exit 2 ;;
|
||||
esac
|
||||
[ "$ROUNDS" -ge 2 ] || { echo "ROUNDS must be at least 2: one round has no spread, so no interval" >&2; exit 2; }
|
||||
case "$SPEC" in
|
||||
''|*[!0-9]*) echo "SPEC must be a non-negative integer, got '$SPEC'" >&2; exit 2 ;;
|
||||
esac
|
||||
[ "$SPEC" -le 8 ] || { echo "SPEC $SPEC is deeper than the drafter is built for (0-8)" >&2; exit 2; }
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
MODEL_IN="/models/$(basename "$MODEL")"
|
||||
RING_BLOCKS=$(( RESIDENT / 4 )) # one KV block is 4 tokens (docs/KV-STREAMING.md §3.9)
|
||||
|
||||
die() { echo "FAIL: $*" >&2; exit 2; }
|
||||
|
||||
command -v docker >/dev/null || die "docker is needed: this script drives both arms as containers"
|
||||
docker image inspect "$STOCK_IMAGE" >/dev/null 2>&1 || die "no image $STOCK_IMAGE (docker pull it)"
|
||||
docker image inspect "$TOOLCHAIN" >/dev/null 2>&1 || die "no image $TOOLCHAIN"
|
||||
[ -x "$BUILD/bin/radiance" ] || die "no engine at $BUILD/bin/radiance (build it first; this script builds nothing)"
|
||||
[ -d "$BUILD/radiance_home" ] || die "no RADIANCE_HOME at $BUILD/radiance_home"
|
||||
[ -f "$MODEL" ] || die "no model at $MODEL"
|
||||
[ "$(stat -c %s "$MODEL")" = "$MODEL_BYTES" ] || \
|
||||
die "$MODEL is $(stat -c %s "$MODEL") bytes, expected $MODEL_BYTES: not the pinned conversion"
|
||||
head -c 4194304 "$MODEL" | sha256sum | cut -d' ' -f1 | grep -qx "$MODEL_HEAD_SHA" || \
|
||||
die "$MODEL's first 4 MiB do not hash to $MODEL_HEAD_SHA: not the pinned conversion"
|
||||
# The host that drives docker has wget but not necessarily curl (the toolchain container has both);
|
||||
# either will do, and the request's own `timings` block is the clock, so neither has to report one.
|
||||
HAVE_CURL=0
|
||||
if command -v curl >/dev/null; then HAVE_CURL=1
|
||||
elif ! command -v wget >/dev/null; then die "curl or wget is needed to talk to the engine"
|
||||
fi
|
||||
BASE="http://127.0.0.1:$PORT"
|
||||
AUTH="Authorization: Bearer test"
|
||||
|
||||
http_get() { # $1 path, $2 out file, $3 timeout s; prints the HTTP status
|
||||
local url="$BASE$1" out="$2" to="${3:-30}" c
|
||||
if [ "$HAVE_CURL" = 1 ]; then
|
||||
c=$(curl -s -m "$to" -o "$out" -w '%{http_code}' -H "$AUTH" "$url" 2>/dev/null) || c=000
|
||||
else
|
||||
wget -S -nv -O "$out" --timeout="$to" --header="$AUTH" "$url" 2>"$out.hdr" || true
|
||||
c=$(awk '/HTTP\//{ c = $2 } END { print (c == "" ? "000" : c) }' "$out.hdr")
|
||||
fi
|
||||
printf '%s\n' "${c:-000}"
|
||||
}
|
||||
|
||||
http_post() { # $1 path, $2 body file, $3 out file, $4 timeout s; prints the HTTP status
|
||||
local url="$BASE$1" body="$2" out="$3" to="${4:-60}" c
|
||||
if [ "$HAVE_CURL" = 1 ]; then
|
||||
c=$(curl -s -m "$to" -o "$out" -w '%{http_code}' \
|
||||
-H "$AUTH" -H "Content-Type: application/json" --data-binary "@$body" "$url" 2>/dev/null) || c=000
|
||||
else
|
||||
wget -S -nv -O "$out" --timeout="$to" --header="$AUTH" \
|
||||
--header="Content-Type: application/json" --post-file="$body" "$url" 2>"$out.hdr" || true
|
||||
c=$(awk '/HTTP\//{ c = $2 } END { print (c == "" ? "000" : c) }' "$out.hdr")
|
||||
fi
|
||||
printf '%s\n' "${c:-000}"
|
||||
}
|
||||
|
||||
# The cards are exclusive: one server at a time, so anything else already running is a refusal and
|
||||
# not something this script may stop (rules 1-3 of AGENTS.md, which also covers radiance-*).
|
||||
RUNNING=$(docker ps -q | wc -l)
|
||||
if [ "$RUNNING" -ne 0 ]; then
|
||||
echo "FAIL: $RUNNING container(s) already running; the cards are exclusive to one server:" >&2
|
||||
docker ps --format ' {{.Names}} {{.Image}}' >&2
|
||||
echo " free them (that is the operator's call) and run this again" >&2
|
||||
exit 2
|
||||
fi
|
||||
mkdir -p "$OUT"
|
||||
|
||||
if [ "$(http_get /health "$OUT/health.probe.json" 2)" != 000 ]; then
|
||||
die "something already answers on 127.0.0.1:$PORT/health; pick PORT=..."
|
||||
fi
|
||||
|
||||
RUN_NAME="" # the one container this script may kill, ever
|
||||
# `docker rm -f` both kills and removes, and is retried until the container is really gone: a
|
||||
# container left behind holds the cards and blocks the next start (and the next operator).
|
||||
stop_arm() {
|
||||
[ -n "$RUN_NAME" ] || return 0
|
||||
local name="$RUN_NAME" i
|
||||
docker rm -f "$name" >/dev/null 2>&1 || true
|
||||
for i in $(seq 1 60); do
|
||||
docker inspect "$name" >/dev/null 2>&1 || { RUN_NAME=""; return 0; }
|
||||
sleep 0.5
|
||||
done
|
||||
echo "FAIL: $name is still present after 30 s; remove it by hand before reusing the cards" >&2
|
||||
RUN_NAME=""
|
||||
return 0
|
||||
}
|
||||
cleanup() { stop_arm; }
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
# One line of ~30 tokens, the same generator shape as scripts/kv-union.sh -- and 522 of them is the
|
||||
# c34ad060 prompt byte for byte. Distinct record numbers keep it away from repetitive-text
|
||||
# pathologies, and the closing instruction is what the model continues.
|
||||
gen_prompt() {
|
||||
local lines="$1" i first=$(( $1 + 1 )) last=$(( $1 + 10 ))
|
||||
for ((i = 1; i <= lines; i++)); do
|
||||
printf 'Record %d: the archivist checked the shelf, noted the catalogue number, and returned the volume to the east wing of the reading room. ' "$i"
|
||||
done
|
||||
printf 'Continue the register: write records %d through %d in the same form, one per line.' "$first" "$last"
|
||||
}
|
||||
|
||||
gen_prompt "$PROMPT_LINES" > "$OUT/prompt.txt"
|
||||
PROMPT_BYTES=$(sha256sum "$OUT/prompt.txt" | cut -d' ' -f1)
|
||||
[ "$PROMPT_BYTES" = "$PROMPT_SHA" ] || \
|
||||
die "the generated prompt hashes to $PROMPT_BYTES, not the canonical $PROMPT_SHA"
|
||||
|
||||
# temperature 0 and a fixed seed: greedy, so the only thing that can move a token is the engine.
|
||||
# ignore_eos keeps the generated count at MAXTOK on both arms even if the model wants to stop.
|
||||
printf '{"model":"qwen4exp","temperature":0,"seed":%s,"max_tokens":%s,"ignore_eos":true,"chat_template_kwargs":{"enable_thinking":false},"messages":[{"role":"user","content":"%s"}]}' \
|
||||
"$SEED" "$MAXTOK" "$(cat "$OUT/prompt.txt")" > "$OUT/req.json"
|
||||
|
||||
# The two arms differ in exactly one thing: the streaming flags. Everything else is identical,
|
||||
# including --prefix-cache-ttl 0 (a prefix hit would leave the arm's own prompt uncounted) and
|
||||
# --num-speculative-tokens $SPEC (0 is the shipped shape; SPEC>0 puts it on on both arms).
|
||||
# A ring under one decode step's selection is raised, not refused, and a raised ring
|
||||
# would make the ours arm's block count differ from RESIDENT/4 -- which the ring check below
|
||||
# fails on, so this script can never silently measure a ring the operator did not ask for. At
|
||||
# --max-num-seqs 2 and SPEC 3 that ceiling is 2 x 4 x 513 = 4 104 blocks, under 8 192, so 32 768
|
||||
# tokens is not raised.
|
||||
FLAGS=(--model "$MODEL_IN" --tp 2 --tp-wire exact --max-num-seqs 2 --max-model-len 204800
|
||||
--placement expert_tiered --host-pool-mib 23652 --gpu-headroom-mib 96
|
||||
--kv-cache-dtype fp8 --prefix-cache-mib 1024 --prefix-cache-ttl 0
|
||||
--vision-tower-placement ram --num-speculative-tokens "$SPEC" --deterministic
|
||||
--host 127.0.0.1 --port "$PORT" --api-key test)
|
||||
|
||||
start_arm() { # $1 arm, $2 tag; sets RUN_NAME and writes $OUT/$2.server.log
|
||||
local arm="$1" tag="$2"
|
||||
RUN_NAME="kv-rvs-$$-$tag"
|
||||
case "$arm" in
|
||||
ours)
|
||||
docker run --rm --name "$RUN_NAME" --user 1000:1000 -e HOME=/tmp \
|
||||
--device /dev/kfd --device /dev/dri --group-add 990 --group-add 44 \
|
||||
--security-opt seccomp=unconfined --network host \
|
||||
-v "$ROOT:/src" -v "$(dirname "$MODEL"):/models" \
|
||||
-w /src "$TOOLCHAIN" \
|
||||
bash -lc "RADIANCE_HOME=$BUILD/radiance_home exec $BUILD/bin/radiance ${FLAGS[*]} --kv-resident $RESIDENT" \
|
||||
> "$OUT/$tag.server.log" 2>&1 &
|
||||
;;
|
||||
stock)
|
||||
docker run --rm --name "$RUN_NAME" \
|
||||
--device /dev/kfd --device /dev/dri --group-add 990 --group-add 44 \
|
||||
--security-opt seccomp=unconfined --network host \
|
||||
-v "$(dirname "$MODEL"):/models" \
|
||||
"$STOCK_IMAGE" "${FLAGS[@]}" \
|
||||
> "$OUT/$tag.server.log" 2>&1 &
|
||||
;;
|
||||
*) die "unknown arm '$arm'" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Readiness is /health, never a blind wait. A container that dies while we poll is a hard failure:
|
||||
# it is either a bad flag, a card that someone else took, or a refusal worth reading.
|
||||
wait_health() { # $1 tag
|
||||
local tag="$1" i code status missing=0
|
||||
for i in $(seq 1 240); do
|
||||
# `docker run` returns before the container is in the running state, and --rm removes a
|
||||
# container as soon as its process ends, so only a state that stays gone is a failure.
|
||||
status=$(docker inspect -f '{{.State.Status}}' "$RUN_NAME" 2>/dev/null || echo gone)
|
||||
case "$status" in
|
||||
running|created|restarting) missing=0 ;;
|
||||
*)
|
||||
missing=$(( missing + 1 ))
|
||||
if [ "$missing" -ge 2 ]; then
|
||||
echo "FAIL: $tag's engine exited before /health; last errors:" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$OUT/$tag.server.log" | tail -12 >&2 || \
|
||||
tail -12 "$OUT/$tag.server.log" >&2
|
||||
return 2
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
code=$(http_get /health "$OUT/$tag.health.json" 3)
|
||||
[ "$code" = 200 ] && { printf '%s\n' "$i" > "$OUT/$tag.health_polls"; return 0; }
|
||||
sleep 1
|
||||
done
|
||||
echo "FAIL: $tag's /health did not answer in 240 s; last errors:" >&2
|
||||
tail -12 "$OUT/$tag.server.log" >&2
|
||||
return 2
|
||||
}
|
||||
|
||||
# The server's own count of the prompt the chat endpoint will render -- the same template, the same
|
||||
# variables -- so the two arms are provably on one input before either is timed.
|
||||
tokenize_count() {
|
||||
printf '{"messages":[{"role":"user","content":"%s"}],"chat_template_kwargs":{"enable_thinking":false}}' \
|
||||
"$(cat "$OUT/prompt.txt")" > "$OUT/tokenize.req.json"
|
||||
http_post /tokenize "$OUT/tokenize.req.json" "$OUT/tokenize.resp.json" 120 >/dev/null
|
||||
grep -o '"count":[0-9]*' "$OUT/tokenize.resp.json" | head -1 | cut -d: -f2 || true
|
||||
}
|
||||
|
||||
# A number from a JSON body: `<key>: <number>`. Bounded to the first hit, which is the one the OAI
|
||||
# usage block carries first (there is no nesting under those keys).
|
||||
jnum() { # $1 file, $2 key
|
||||
grep -o "\"$2\": *[-0-9.eE+]*" "$1" | head -1 | sed 's/.*: *//' || true
|
||||
}
|
||||
|
||||
# The value of one /metrics counter, by its bare name. Anchored on `{` or a space after the name so
|
||||
# `engine_steps_total` cannot pick up `engine_steps_decode_total`; the first sample is the only one
|
||||
# (one model, one engine). Prints nothing when the counter is absent.
|
||||
metric() { # $1 metrics file, $2 counter name (without the radiance: prefix)
|
||||
[ -s "$1" ] || return 0
|
||||
grep -E "^radiance:$2(\\{| )" "$1" 2>/dev/null | head -1 | awk '{print $NF}' || true
|
||||
}
|
||||
|
||||
# The engine's own report of a streamed group at request end, from the log line. Prints
|
||||
# `resolves lookups misses ring union maxmiss claims overflow`, or six dashes if the line is absent.
|
||||
stream_end() { # $1 log
|
||||
grep -E "kv streaming: group '.*' request end:" "$1" | tail -1 |
|
||||
sed -E "s/.*request end: ([0-9]+) resolves, ([0-9]+) lookups, ([0-9]+) misses.*ring ([0-9]+) blocks, largest launch union ([0-9]+) distinct blocks, largest launch misses ([0-9]+), largest launch claims ([0-9]+), overflow (no|LATCHED).*/\1 \2 \3 \4 \5 \6 \7 \8/" \
|
||||
| grep -E '^[0-9]+ ' || echo "- - - - - - - -"
|
||||
}
|
||||
|
||||
# The ring the engine actually carved, from its startup report:
|
||||
# `streaming: 8192 blocks resident in vram_kv at +6885376 = 200.00 MiB, ...`
|
||||
ring_line() { # $1 log -> "blocks MiB"
|
||||
grep -oE "streaming: *[0-9]+ blocks resident in vram_kv at \+[0-9]+ = *[0-9.]+ MiB" "$1" |
|
||||
head -1 | sed -E 's/.*streaming: *([0-9]+) blocks.*= *([0-9.]+) MiB/\1 \2/' || true
|
||||
}
|
||||
|
||||
# `vram_kv 618.00 MiB the cache's share` -- the placement table, not the "budget ... free" line.
|
||||
vram_kv() { grep -E "^ *vram_kv +[0-9.]+ (MiB|GiB) +the cache's share" "$1" | head -1 |
|
||||
sed -E 's/^ *vram_kv +([0-9.]+ (MiB|GiB)).*/\1/' || true; }
|
||||
|
||||
# `experts 11.22 GiB 95% of it` -- residency in the elastic region.
|
||||
experts() { grep -E "^ *experts +[0-9.]+ GiB +[0-9]+% of it" "$1" | head -1 |
|
||||
sed -E 's/^ *experts +([0-9.]+) GiB +([0-9]+)% of it/\1 \2/' || true; }
|
||||
|
||||
# One start: a server, one request, a kill. Kills only the container this script named, and always
|
||||
# before the other arm starts, so the cards never hold two engines. Writes one line of
|
||||
# $OUT/starts.tsv: round arm order ms_step prefill_tps ttft decode_tps wall ptok ctok cached.
|
||||
run_start() { # $1 arm, $2 round, $3 order (1 = first in the round)
|
||||
local arm="$1" round="$2" order="$3"
|
||||
local tag="$arm$round" log="$OUT/$arm$round.server.log" resp="$OUT/$arm$round.json"
|
||||
local t code ptok ctok cached tokencount
|
||||
|
||||
local ord="2nd"; [ "$order" = 1 ] && ord="1st"
|
||||
echo "== $tag: $arm, round $round of $ROUNDS, $ord in the round =="
|
||||
start_arm "$arm" "$tag"
|
||||
wait_health "$tag" || { stop_arm; return 2; }
|
||||
|
||||
tokencount=$(tokenize_count)
|
||||
[ "${tokencount:-0}" = "$TARGET_TOKENS" ] || {
|
||||
echo "FAIL $tag: /tokenize counts this prompt as ${tokencount:-?} tokens, expected $TARGET_TOKENS" >&2
|
||||
stop_arm; return 2
|
||||
}
|
||||
echo "$tokencount" > "$OUT/$tag.tokens"
|
||||
|
||||
t0=$(date +%s%N)
|
||||
code=$(http_post /v1/chat/completions "$OUT/req.json" "$resp" 3600)
|
||||
t1=$(date +%s%N)
|
||||
printf '%s %s\n' "$code" "$(awk -v a="$t0" -v b="$t1" 'BEGIN{printf "%.1f", (b-a)/1e9}')" \
|
||||
> "$OUT/$tag.wall"
|
||||
|
||||
# The counters are read before the kill: /metrics belongs to the live process. Ours' are always
|
||||
# read (the ring's byte and overflow counters live there); stock's only when speculation makes
|
||||
# its step clock the paired quantity.
|
||||
if [ "$arm" = ours ] || [ "$SPEC" -gt 0 ]; then
|
||||
http_get /metrics "$OUT/$tag.metrics" 10 >/dev/null || true
|
||||
fi
|
||||
stop_arm
|
||||
|
||||
if [ "$code" != 200 ]; then
|
||||
echo "FAIL $tag: /v1/chat/completions answered $code; last errors:" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$log" | tail -12 >&2 || tail -12 "$log" >&2
|
||||
return 2
|
||||
fi
|
||||
|
||||
ptok=$(jnum "$resp" prompt_tokens); ctok=$(jnum "$resp" completion_tokens)
|
||||
cached=$(jnum "$resp" cached_tokens)
|
||||
[ "$ptok" = "$TARGET_TOKENS" ] || {
|
||||
echo "FAIL $tag: usage.prompt_tokens is ${ptok:-?}, expected $TARGET_TOKENS" >&2; return 2; }
|
||||
[ "$ctok" = "$MAXTOK" ] || {
|
||||
echo "FAIL $tag: usage.completion_tokens is ${ctok:-?}, expected $MAXTOK" >&2; return 2; }
|
||||
[ "${cached:-0}" = 0 ] || {
|
||||
echo "FAIL $tag: cached_tokens ${cached:-?} -- a prefix hit would make the arms' prefill" >&2
|
||||
echo " a different workload" >&2; return 2; }
|
||||
|
||||
# The clocks are the engine's own `timings` block, so they do not depend on which HTTP client ran:
|
||||
# prompt_per_second is the prefill, ttft_ms the first token, predicted_per_second the decode (one
|
||||
# token a step with speculation off), predicted_ms the decode wall. `wall` is the harness's total.
|
||||
local ms pre ttft decode_tps dwall wall
|
||||
ms=$(awk -v p="$(jnum "$resp" predicted_per_second)" 'BEGIN{ if (p > 0) printf "%.4f", 1000/p; else print "-" }')
|
||||
decode_tps=$(jnum "$resp" predicted_per_second)
|
||||
pre=$(jnum "$resp" prompt_per_second)
|
||||
ttft=$(awk -v t="$(jnum "$resp" ttft_ms)" 'BEGIN{ printf "%.3f", t/1000 }')
|
||||
dwall=$(awk -v t="$(jnum "$resp" predicted_ms)" 'BEGIN{ printf "%.1f", t/1000 }')
|
||||
wall=$(cut -d' ' -f2 "$OUT/$tag.wall")
|
||||
|
||||
# Speculation on: a step emits up to 1 + SPEC tokens, so 1000/predicted_per_second is ms a token
|
||||
# and is not the quantity two arms are compared on. The engine's own decode step clock is, and
|
||||
# both arms report it under the same name. Draft acceptance is printed per start because stock
|
||||
# starts can be bimodal in it (81.7% and 98.6% on different starts); averaging that hides which
|
||||
# mode a start landed in.
|
||||
local steps="" tokstep="" dnum="" dacc="" dacc_pct="" spf="" smx=""
|
||||
if [ "$SPEC" -gt 0 ]; then
|
||||
local secs
|
||||
steps=$(metric "$OUT/$tag.metrics" engine_steps_decode_total)
|
||||
secs=$(metric "$OUT/$tag.metrics" engine_step_seconds_decode_total)
|
||||
spf=$(metric "$OUT/$tag.metrics" engine_steps_prefill_total)
|
||||
smx=$(metric "$OUT/$tag.metrics" engine_steps_mixed_total)
|
||||
dnum=$(jnum "$resp" draft_n)
|
||||
dacc=$(jnum "$resp" draft_n_accepted)
|
||||
case "${steps:-x}" in ''|*[!0-9]*) steps="";; esac
|
||||
[ -n "$steps" ] && [ "$steps" -gt 0 ] || {
|
||||
echo "FAIL $tag: no engine_steps_decode_total in /metrics, so ms/step has no clock" >&2
|
||||
return 2; }
|
||||
ms=$(awk -v s="$secs" -v n="$steps" 'BEGIN{ if (n > 0 && s > 0) printf "%.4f", 1000*s/n; else print "-" }')
|
||||
[ "$ms" != "-" ] || {
|
||||
echo "FAIL $tag: engine_step_seconds_decode_total is '${secs:-?}' for $steps steps" >&2
|
||||
return 2; }
|
||||
tokstep=$(awk -v n="$MAXTOK" -v s="$steps" 'BEGIN{ printf "%.3f", n/s }')
|
||||
# A start whose drafter never ran is not a spec-on measurement, and neither is one whose
|
||||
# acceptance counters are missing: both are the shape, not the result.
|
||||
case "${dnum:-x}${dacc:-x}" in *[!0-9]*) dnum="";; esac
|
||||
[ -n "$dnum" ] && [ "$dnum" -gt 0 ] || {
|
||||
echo "FAIL $tag: timings carries no draft_n under --num-speculative-tokens $SPEC," >&2
|
||||
echo " so the drafter did not run and this is not a spec-on start" >&2; return 2; }
|
||||
[ "${dacc:-0}" -le "$dnum" ] || {
|
||||
echo "FAIL $tag: draft_n_accepted ${dacc:-?} exceeds draft_n $dnum" >&2; return 2; }
|
||||
dacc_pct=$(awk -v a="$dacc" -v n="$dnum" 'BEGIN{ printf "%.1f", 100*a/n }')
|
||||
fi
|
||||
|
||||
if [ "$arm" = ours ]; then
|
||||
# The ring checks. A run whose ring did not stream, overflowed, or held a different number of
|
||||
# blocks is not the configuration this script claims to measure, so it stops here.
|
||||
grep -q "kv streaming: [0-9].*stream (" "$log" || {
|
||||
echo "FAIL $tag: no 'group(s) stream' startup line: --kv-resident $RESIDENT did not" >&2
|
||||
echo " leave the group streaming" >&2; return 2; }
|
||||
read -r res lk mi rb mu mm cl ov < <(stream_end "$log")
|
||||
[ "${ov:-}" = no ] || { echo "FAIL $tag: ring overflow '$ov' on the request-end line" >&2; return 2; }
|
||||
[ "${rb:-0}" = "$RING_BLOCKS" ] || {
|
||||
echo "FAIL $tag: the ring holds ${rb:-?} blocks, expected $RING_BLOCKS for $RESIDENT tokens" >&2
|
||||
return 2; }
|
||||
[ "${mu:-0}" -le "${rb:-0}" ] || {
|
||||
echo "FAIL $tag: largest launch union ${mu:-?} exceeds the ${rb:-?}-block ring" >&2; return 2; }
|
||||
[ "${mi:-0}" -gt 0 ] || {
|
||||
echo "FAIL $tag: no misses -- the ring covered the context, so nothing streamed" >&2; return 2; }
|
||||
read -r ring_blocks ring_mib < <(ring_line "$log") || true
|
||||
[ "${ring_blocks:-0}" = "$RING_BLOCKS" ] || {
|
||||
echo "FAIL $tag: startup reports ${ring_blocks:-?} blocks resident, expected $RING_BLOCKS" >&2
|
||||
return 2; }
|
||||
printf '%s %s %s %s %s %s %s %s\n' "$res" "$lk" "$mi" "$rb" "$mu" "$mm" "$cl" "$ov" \
|
||||
> "$OUT/$tag.stream"
|
||||
printf '%s %s\n' "${ring_blocks:-?}" "${ring_mib:-?}" > "$OUT/$tag.ring"
|
||||
else
|
||||
grep -q "kv streaming: [0-9].*stream (" "$log" && {
|
||||
echo "FAIL $tag: the stock arm streamed, so it was not the stock configuration" >&2; return 2; }
|
||||
fi
|
||||
printf '%s\n' "$(vram_kv "$log")" > "$OUT/$tag.vram_kv"
|
||||
printf '%s\n' "$(experts "$log")" > "$OUT/$tag.experts"
|
||||
|
||||
# Speculation's own columns go on the same line, after the twelve: every reader of columns 1-12
|
||||
# above is unchanged, so a SPEC=0 run writes the twelve-column starts.tsv, byte for byte.
|
||||
if [ "$SPEC" -gt 0 ]; then
|
||||
printf '%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s\n' \
|
||||
"$round" "$arm" "$order" "$ms" "$pre" "$ttft" "$decode_tps" "$dwall" "$ptok" "$ctok" \
|
||||
"${cached:-0}" "$wall" "$steps" "$tokstep" "$dnum" "$dacc" "$dacc_pct" "$spf" "$smx" \
|
||||
"$SPEC" >> "$OUT/starts.tsv"
|
||||
else
|
||||
printf '%s %s %s %s %s %s %s %s %s %s %s %s\n' \
|
||||
"$round" "$arm" "$order" "$ms" "$pre" "$ttft" "$decode_tps" "$dwall" "$ptok" "$ctok" \
|
||||
"${cached:-0}" "$wall" >> "$OUT/starts.tsv"
|
||||
fi
|
||||
|
||||
if [ "$SPEC" -gt 0 ]; then
|
||||
printf ' ms/step %s, %.2f tok/s, %.3f tok/step, %s decode steps, draft %s/%s = %.1f%% accepted, prefill %.1f tok/s, request %.1f s\n' \
|
||||
"$ms" "$decode_tps" "$tokstep" "$steps" "$dacc" "$dnum" "$dacc_pct" "$pre" "$wall"
|
||||
else
|
||||
printf ' ms/step %s, decode %.2f tok/s, prefill %.1f tok/s, TTFT %.3f s, decode wall %.1f s, request %.1f s\n' \
|
||||
"$ms" "$decode_tps" "$pre" "$ttft" "$dwall" "$wall"
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
# t quantiles, two-sided. The table covers the round counts this script is usable at; beyond 30 the
|
||||
# normal value is within 0.2% and the interval is dominated by the spread, not the quantile.
|
||||
tval() { # $1 df, $2 95|90
|
||||
local df="$1" q="$2"
|
||||
if [ "$q" = 95 ]; then
|
||||
case "$df" in
|
||||
1) echo 12.706 ;; 2) echo 4.303 ;; 3) echo 3.182 ;; 4) echo 2.776 ;; 5) echo 2.571 ;;
|
||||
6) echo 2.447 ;; 7) echo 2.365 ;; 8) echo 2.306 ;; 9) echo 2.262 ;; 10) echo 2.228 ;;
|
||||
11) echo 2.201 ;; 12) echo 2.179 ;; 13) echo 2.160 ;; 14) echo 2.145 ;; 15) echo 2.131 ;;
|
||||
16) echo 2.120 ;; 17) echo 2.110 ;; 18) echo 2.101 ;; 19) echo 2.093 ;; 20) echo 2.086 ;;
|
||||
21) echo 2.080 ;; 22) echo 2.074 ;; 23) echo 2.069 ;; 24) echo 2.064 ;; 25) echo 2.060 ;;
|
||||
26) echo 2.056 ;; 27) echo 2.052 ;; 28) echo 2.048 ;; 29) echo 2.045 ;; 30) echo 2.042 ;;
|
||||
*) echo 1.960 ;;
|
||||
esac
|
||||
else
|
||||
case "$df" in
|
||||
1) echo 6.314 ;; 2) echo 2.920 ;; 3) echo 2.353 ;; 4) echo 2.132 ;; 5) echo 2.015 ;;
|
||||
6) echo 1.943 ;; 7) echo 1.895 ;; 8) echo 1.860 ;; 9) echo 1.833 ;; 10) echo 1.812 ;;
|
||||
11) echo 1.796 ;; 12) echo 1.782 ;; 13) echo 1.771 ;; 14) echo 1.761 ;; 15) echo 1.753 ;;
|
||||
16) echo 1.746 ;; 17) echo 1.740 ;; 18) echo 1.734 ;; 19) echo 1.729 ;; 20) echo 1.725 ;;
|
||||
21) echo 1.721 ;; 22) echo 1.717 ;; 23) echo 1.714 ;; 24) echo 1.711 ;; 25) echo 1.708 ;;
|
||||
26) echo 1.706 ;; 27) echo 1.703 ;; 28) echo 1.701 ;; 29) echo 1.699 ;; 30) echo 1.697 ;;
|
||||
*) echo 1.645 ;;
|
||||
esac
|
||||
fi
|
||||
}
|
||||
|
||||
printf 'prompt sha256 %s (%s bytes), %s tokens, request sha256 %s\n' \
|
||||
"$PROMPT_BYTES" "$(wc -c < "$OUT/prompt.txt")" "$TARGET_TOKENS" \
|
||||
"$(sha256sum "$OUT/req.json" | cut -d' ' -f1)"
|
||||
printf 'arms: stock=%s ours=%s --kv-resident %s (%s blocks)\n' \
|
||||
"$STOCK_IMAGE" "$BUILD/bin/radiance" "$RESIDENT" "$RING_BLOCKS"
|
||||
if [ "$SPEC" -gt 0 ]; then
|
||||
printf 'speculation: --num-speculative-tokens %s on both arms; ms/step = engine_step_seconds_decode_total /\n' "$SPEC"
|
||||
printf ' engine_steps_decode_total (one step emits up to %s tokens), acceptance = timings.draft_n_accepted / draft_n\n' \
|
||||
"$(( SPEC + 1 ))"
|
||||
printf 'rounds: %s per arm, %s starts, ~%s min\n\n' "$ROUNDS" "$(( ROUNDS * 2 ))" "$(( ROUNDS * 9 / 6 ))"
|
||||
else
|
||||
printf 'rounds: %s per arm, %s starts, ~%s min\n\n' "$ROUNDS" "$(( ROUNDS * 2 ))" "$(( ROUNDS * 9 ))"
|
||||
fi
|
||||
|
||||
: > "$OUT/starts.tsv"
|
||||
STARTED=$(date +%s)
|
||||
r=1
|
||||
while [ "$r" -le "$ROUNDS" ]; do
|
||||
# ABBA: the arm that goes first alternates by round, so the two arms share first position and no
|
||||
# arm is always measured on the cooler or hotter side of a round.
|
||||
if [ $(( r % 2 )) -eq 1 ]; then
|
||||
run_start stock "$r" 1 || exit 2
|
||||
run_start ours "$r" 2 || exit 2
|
||||
else
|
||||
run_start ours "$r" 1 || exit 2
|
||||
run_start stock "$r" 2 || exit 2
|
||||
fi
|
||||
r=$(( r + 1 ))
|
||||
done
|
||||
ELAPSED=$(( $(date +%s) - STARTED ))
|
||||
|
||||
# ---- ours' counters, per round ----------------------------------------------------------------
|
||||
echo
|
||||
echo "== ours, per round (the engine's own request-end line; bytes and overflow from /metrics) =="
|
||||
printf '%-5s %9s %11s %9s %6s %9s %10s %9s %8s\n' \
|
||||
round resolves lookups misses ring union maxmiss bytes overflow
|
||||
for r in $(seq 1 "$ROUNDS"); do
|
||||
read -r res lk mi rb mu mm cl ov < "$OUT/ours$r.stream"
|
||||
bytes=$(grep -E "^radiance:kv_stream_bytes_total" "$OUT/ours$r.metrics" 2>/dev/null | head -1 |
|
||||
awk '{print $NF}' || true)
|
||||
ovm=$(grep -E "^radiance:stream_overflow_total" "$OUT/ours$r.metrics" 2>/dev/null | head -1 |
|
||||
awk '{print $NF}' || true)
|
||||
printf '%-5s %9s %11s %9s %6s %9s %10s %9s %8s\n' \
|
||||
"$r" "$res" "$lk" "$mi" "$rb" "$mu" "$mm" "${bytes:--}" "${ovm:-$ov}"
|
||||
done
|
||||
read -r ring_blocks ring_mib < "$OUT/ours1.ring"
|
||||
echo "ring (ours): ${ring_blocks} blocks = ${ring_mib} MiB resident in vram_kv, ${RESIDENT} tokens"
|
||||
echo "vram_kv: ours $(cat "$OUT/ours1.vram_kv") stock $(cat "$OUT/stock1.vram_kv")"
|
||||
echo "experts: ours $(awk '{print $1 " GiB (" $2 "%)"}' "$OUT/ours1.experts") of the elastic region,"
|
||||
echo " stock $(awk '{print $1 " GiB (" $2 "%)"}' "$OUT/stock1.experts")"
|
||||
|
||||
# ---- both arms, per round ---------------------------------------------------------------------
|
||||
echo
|
||||
if [ "$SPEC" -gt 0 ]; then
|
||||
echo "== both arms, per round (ms/step from the engine's decode step clock; delta = ours over stock) =="
|
||||
else
|
||||
echo "== both arms, per round (ms/step from predicted_per_second; delta = ours over stock) =="
|
||||
fi
|
||||
printf '%-5s %-6s %10s %10s %9s %10s %10s\n' round first ms_stock ms_ours delta% stock_tps ours_tps
|
||||
for r in $(seq 1 "$ROUNDS"); do
|
||||
sms=$(awk -v r="$r" '$1 == r && $2 == "stock" {print $4}' "$OUT/starts.tsv")
|
||||
oms=$(awk -v r="$r" '$1 == r && $2 == "ours" {print $4}' "$OUT/starts.tsv")
|
||||
stp=$(awk -v r="$r" '$1 == r && $2 == "stock" {print $7}' "$OUT/starts.tsv")
|
||||
otp=$(awk -v r="$r" '$1 == r && $2 == "ours" {print $7}' "$OUT/starts.tsv")
|
||||
first=$(awk -v r="$r" '$1 == r && $3 == 1 {print $2}' "$OUT/starts.tsv")
|
||||
awk -v r="$r" -v f="$first" -v s="$sms" -v o="$oms" -v st="$stp" -v ot="$otp" 'BEGIN{
|
||||
printf "%-5s %-6s %10.3f %10.3f %+8.2f%% %10.2f %10.2f\n", r, f, s, o, 100*(o/s-1), st, ot }'
|
||||
done
|
||||
|
||||
# ---- speculation: per start, because acceptance is the bimodal variable ----------------------
|
||||
if [ "$SPEC" -gt 0 ]; then
|
||||
echo
|
||||
echo "== speculation, per start (acceptance per start: stock starts can be bimodal) =="
|
||||
printf '%-7s %-6s %8s %9s %8s %6s %14s %7s %7s\n' \
|
||||
start arm ms_step tok/s tok/step steps accepted/drafted accept% p/m/d
|
||||
while read -r rnd arm ord ms pre ttft dtps dwall ptok ctok cached wall \
|
||||
steps tokstep dnum dacc dpct spf smx spec; do
|
||||
printf '%-7s %-6s %8.4f %9.2f %8.3f %6s %14s %7.1f%% %s/%s/%s\n' \
|
||||
"$arm$rnd" "$arm" "$ms" "$dtps" "$tokstep" "$steps" "$dacc/$dnum" "$dpct" \
|
||||
"$spf" "$smx" "$steps"
|
||||
done < "$OUT/starts.tsv"
|
||||
|
||||
echo
|
||||
echo "== draft acceptance per arm, sorted (two clusters here = a bimodal winner) =="
|
||||
for arm in stock ours; do
|
||||
list=$(awk -v a="$arm" '$2 == a { printf "%.1f ", $17 }' "$OUT/starts.tsv")
|
||||
stats=$(awk -v a="$arm" '$2 == a { v[n++] = $17; s += $17 }
|
||||
END { if (!n) { print "no starts"; exit }
|
||||
m = s/n; mn = v[0]; mx = v[0]
|
||||
for (i = 0; i < n; i++) { if (v[i] < mn) mn = v[i]; if (v[i] > mx) mx = v[i] }
|
||||
ss = 0; for (i = 0; i < n; i++) ss += (v[i]-m)^2
|
||||
printf "n=%d mean %.1f%% min %.1f%% max %.1f%% sd %.2f points", n, m, mn, mx,
|
||||
(n > 1 ? sqrt(ss/(n-1)) : 0) }' "$OUT/starts.tsv")
|
||||
printf '%-6s %s %s\n' "$arm" "$list" "$stats"
|
||||
done
|
||||
|
||||
echo
|
||||
echo "== paired tok/s (secondary: under speculation the arms do not emit the same tokens, so a"
|
||||
echo " tok/s ratio mixes step time with tokens a step and is not a speed ratio)"
|
||||
awk '$2 == "stock" { s[$1] = $7 } $2 == "ours" { o[$1] = $7 }
|
||||
END { for (r = 1; r <= '"$ROUNDS"'; r++) { d = 100*(o[r]/s[r]-1); n = r;
|
||||
t += d; if (r == 1 || d < mn) mn = d; if (r == 1 || d > mx) mx = d }
|
||||
printf " mean %+.2f%%, range %+.2f%% .. %+.2f%%\n", t/n, mn, mx }' "$OUT/starts.tsv"
|
||||
fi
|
||||
|
||||
# ---- arm summaries ----------------------------------------------------------------------------
|
||||
echo
|
||||
echo "== per-arm means over the run =="
|
||||
printf '%-7s %12s %10s %12s %12s %10s\n' arm prefill_tps TTFT_s decode_tps decode_wall_s ms_step
|
||||
for arm in stock ours; do
|
||||
awk -v a="$arm" '$2 == a { p+=$5; t+=$6; d+=$7; w+=$8; m+=$4; n++ }
|
||||
END { printf "%-7s %12.1f %10.3f %12.2f %12.1f %10.3f\n", a, p/n, t/n, d/n, w/n, m/n }' \
|
||||
"$OUT/starts.tsv"
|
||||
done
|
||||
|
||||
# ---- paired statistics ------------------------------------------------------------------------
|
||||
awk -v a=stock '$2 == a { s[$1] = $4 } $2 == "ours" { o[$1] = $4 } END {
|
||||
for (r = 1; r <= '"$ROUNDS"'; r++) printf "%.6f\n", 100*(o[r]/s[r] - 1) }' \
|
||||
"$OUT/starts.tsv" > "$OUT/deltas.txt"
|
||||
|
||||
read -r n mean sd sem ci95 ci90 min max mdb n1 n09 < <(
|
||||
awk -v t95="$(tval $(( ROUNDS - 1 )) 95)" \
|
||||
-v t90="$(tval $(( ROUNDS - 1 )) 90)" '
|
||||
{ d[NR] = $1; s += $1 }
|
||||
END {
|
||||
m = s/NR; ss = 0
|
||||
for (i = 1; i <= NR; i++) ss += (d[i] - m)^2
|
||||
sd = NR > 1 ? sqrt(ss/(NR-1)) : 0
|
||||
sem = sd/sqrt(NR)
|
||||
mn = d[1]; mx = d[1]
|
||||
for (i = 2; i <= NR; i++) { if (d[i] < mn) mn = d[i]; if (d[i] > mx) mx = d[i] }
|
||||
a1 = (2.8*sd/1.0)^2; a9 = (2.8*sd/0.9)^2
|
||||
r1 = int(a1) + (a1 > int(a1) ? 1 : 0); if (r1 < 2) r1 = 2
|
||||
r9 = int(a9) + (a9 > int(a9) ? 1 : 0); if (r9 < 2) r9 = 2
|
||||
printf "%d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.1f %.1f\n",
|
||||
NR, m, sd, sem, t95*sem, t90*sem, mn, mx, 2.8*sd/sqrt(NR), r1, r9
|
||||
}' "$OUT/deltas.txt")
|
||||
|
||||
echo
|
||||
echo "== the paired deltas (ours against stock, same round; + = ours slower) =="
|
||||
r=1
|
||||
while [ "$r" -le "$ROUNDS" ]; do
|
||||
printf 'round %-3s %+7.2f%%\n' "$r" "$(sed -n "${r}p" "$OUT/deltas.txt")"
|
||||
r=$(( r + 1 ))
|
||||
done
|
||||
echo "paired mean $mean% sd $sd sem $sem range $min% .. $max%"
|
||||
echo "95% CI $mean ± $ci95 (t, $(( ROUNDS - 1 )) df) -> $(awk -v m="$mean" -v c="$ci95" \
|
||||
'BEGIN{printf "%.2f%% .. %.2f%%", m-c, m+c}')"
|
||||
echo "90% CI $mean ± $ci90"
|
||||
echo "unpaired: $(awk '$2 == "stock" { s += $4; ns++ } $2 == "ours" { o += $4; no++ }
|
||||
END { printf "%+.2f%%", 100*((o/no)/(s/ns) - 1) }' "$OUT/starts.tsv") (meaning what pairing bought or cost)"
|
||||
echo
|
||||
# Two readings of the same n. The run's own interval is the honest resolution: at n=2 the sd has one
|
||||
# degree of freedom, so the t interval is wide and the sd is barely estimated. The sd-based minimum
|
||||
# detectable difference at a cross-arm sd of 1.4 points is what the header's round counts come from,
|
||||
# so both are printed rather than whichever flatters this run.
|
||||
echo "at n=$n this run's interval is ±$(awk -v c="$ci95" 'BEGIN{printf "%.2f%%", c}') (95%), and from its own"
|
||||
echo " sd ($sd points) the minimum detectable difference would be $(awk -v m="$mdb" 'BEGIN{printf "%.2f%%", m}')"
|
||||
echo " (2.8 x sd / sqrt(n), 95% two-sided, 80% power) -- with $(( ROUNDS - 1 )) df read the interval, not the sd."
|
||||
echo " At that cross-arm sd of 1.4 points: n=2 detects 2.8%, n=4 2.0%, n=16 1.0%, n=19-20 0.9%."
|
||||
echo " This run's own sd would need $(awk -v n="$n1" 'BEGIN{printf "%.0f", n}') paired rounds for 1% and $(awk -v n="$n09" 'BEGIN{printf "%.0f", n}') for 0.9%."
|
||||
awk -v m="$mean" -v c="$ci95" 'BEGIN{
|
||||
where = (m - c > 0 || m + c < 0) ? "excludes" : "includes"
|
||||
printf "reading: %+.2f%% %s zero (95%%): ", m, where
|
||||
}'
|
||||
if awk -v m="$mean" -v c="$ci95" 'BEGIN{ exit !(m - c > 0 || m + c < 0) }'; then
|
||||
echo "ours is slower by a margin this run can resolve"
|
||||
else
|
||||
echo "the gap is inside this run's noise; state it as a band, and raise ROUNDS to narrow it"
|
||||
fi
|
||||
if [ "$SPEC" -gt 0 ]; then
|
||||
echo
|
||||
echo "speculation read: the sd above carries the draft-acceptance mix, which is the bimodal"
|
||||
echo " variable (81.7% and 98.6% on different stock starts). The acceptance table is the"
|
||||
echo " evidence on whether the modes split evenly across the arms; whichever arm drew the high"
|
||||
echo " mode more often has part of this delta from acceptance, not from streaming."
|
||||
fi
|
||||
echo "wall: ${ELAPSED} s for $(( ROUNDS * 2 )) starts; raw under $OUT"
|
||||
# A container that is being removed still shows in `docker ps` for a moment after `docker inspect`
|
||||
# starts failing, so let the count settle instead of reporting a leak that is not there.
|
||||
LEFT=1
|
||||
for i in $(seq 1 20); do
|
||||
LEFT=$(docker ps -q | wc -l)
|
||||
if [ "$LEFT" -eq 0 ]; then break; fi
|
||||
sleep 0.5
|
||||
done
|
||||
echo "leftover containers: $LEFT"
|
||||
|
||||
exit 0
|
||||
Executable
+216
@@ -0,0 +1,216 @@
|
||||
#!/bin/bash
|
||||
# That the prefill stage is exact: with a ring smaller than the context, a long prompt prefilled
|
||||
# above qsa_exact_to is byte-identical to streaming off, and every staged layer was copied in layer
|
||||
# order (docs/KV-STREAMING.md §3.5.1).
|
||||
#
|
||||
# The ring is the floor, --kv-resident 32768 (8 192 blocks of 4), and the document ~64k tokens, so
|
||||
# every chunk whose history passes 32 768 tokens must take the stage. A byte-identical result is
|
||||
# evidence only if something staged, so do not shorten the document.
|
||||
#
|
||||
# Run inside the toolchain container (io_uring and the cards), with the model mounted:
|
||||
# docker run --rm --security-opt seccomp=unconfined --user 1000:1000 -e HOME=/tmp \
|
||||
# --device /dev/kfd --device /dev/dri --group-add 990 --group-add 44 \
|
||||
# -v "$PWD":/src -v /path/to/models:/models -w /src rad-toolchain:latest \
|
||||
# bash -lc 'bash scripts/kv-stage-parity-64k.sh'
|
||||
#
|
||||
# One fresh server per arm, temperature 0, --deterministic, one request a server. Exit 0 only if
|
||||
# both arms served, the bytes match, the on arm staged in layer order and the pool report shows the
|
||||
# streamed configuration; 1 on a byte difference or missing staging; 2 if an arm failed.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
BUILD="${BUILD:-$ROOT/build}"
|
||||
MODEL="${MODEL:-/models/qwen3.8-next-flash-fp8-iq4r-moe.rad}"
|
||||
PORT="${PORT:-8124}"
|
||||
OUT="${OUT:-/tmp/radiance-kv-stage-parity-64k}"
|
||||
LINES="${LINES:-2120}" # ~64k prompt tokens: well past the 32 768-token ring
|
||||
MAXTOK="${MAXTOK:-64}"
|
||||
SEED="${SEED:-12345}"
|
||||
MAXLEN="${MAXLEN:-81920}" # the prompt, the generated tokens and the template
|
||||
# 8 192 blocks of 4 tokens: the floor. Above decode's one-step union and below the document, so the
|
||||
# second half of the prefill must stage instead of resolving. Speculation stays 0 here: this script
|
||||
# measures the stage path, and a spec arm would only change the ring's raise arithmetic.
|
||||
RESIDENT="${RESIDENT:-32768}"
|
||||
|
||||
BIN="$BUILD/bin/radiance"
|
||||
export RADIANCE_HOME="$BUILD/radiance_home"
|
||||
[ -x "$BIN" ] || { echo "no engine at $BIN (build it first; this script builds nothing)" >&2; exit 2; }
|
||||
[ -f "$MODEL" ] || { echo "no model at $MODEL" >&2; exit 2; }
|
||||
command -v curl >/dev/null || { echo "curl is needed" >&2; exit 2; }
|
||||
|
||||
mkdir -p "$OUT"
|
||||
SERVER_PID=""
|
||||
cleanup() {
|
||||
if [ -n "$SERVER_PID" ] && kill -0 "$SERVER_PID" 2>/dev/null; then
|
||||
kill -TERM "$SERVER_PID" 2>/dev/null || true
|
||||
for _ in $(seq 1 240); do kill -0 "$SERVER_PID" 2>/dev/null || break; sleep 0.25; done
|
||||
kill -KILL "$SERVER_PID" 2>/dev/null || true
|
||||
fi
|
||||
SERVER_PID=""
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
gen_prompt() {
|
||||
local n="$1" i first=$(( $1 + 1 )) last=$(( $1 + 10 ))
|
||||
for ((i = 1; i <= n; i++)); do
|
||||
printf 'Record %d: the archivist checked the shelf, noted the catalogue number, and returned the volume to the east wing of the reading room. ' "$i"
|
||||
done
|
||||
printf 'Continue the register: write records %d through %d in the same form, one per line.' "$first" "$last"
|
||||
}
|
||||
gen_prompt "$LINES" > "$OUT/prompt.txt"
|
||||
|
||||
content_of() {
|
||||
awk '
|
||||
{ s = $0
|
||||
i = index(s, "\"message\":"); if (i == 0) exit 1
|
||||
s = substr(s, i)
|
||||
i = index(s, "\"content\":\""); if (i == 0) exit 1
|
||||
s = substr(s, i + 11)
|
||||
out = ""
|
||||
for (j = 1; j <= length(s); j++) {
|
||||
c = substr(s, j, 1)
|
||||
if (c == "\\") { out = out substr(s, j, 2); j++; continue }
|
||||
if (c == "\"") break
|
||||
out = out c
|
||||
}
|
||||
printf "%s", out
|
||||
}' "$1"
|
||||
}
|
||||
|
||||
# $1 arm name, $2 the streaming flags, $3.. extra environment VAR=value.
|
||||
run_arm() {
|
||||
# The off arm passes no flags: with `set -u` a bare $2 made the whole script die on its first
|
||||
# arm, so the flags and the trailing VAR=value list are both optional.
|
||||
local arm="$1" flags="${2:-}"
|
||||
shift; [ "$#" -gt 0 ] && shift
|
||||
local log="$OUT/$arm.log" req="$OUT/$arm.req.json" resp="$OUT/$arm.json"
|
||||
local envs=("$@")
|
||||
echo "== $arm: $flags ${envs[*]:-} =="
|
||||
( exec env "${envs[@]}" "$BIN" --model "$MODEL" \
|
||||
--tp 2 --tp-wire exact \
|
||||
--max-num-seqs 1 --max-model-len "$MAXLEN" --placement expert_tiered --host-pool-mib 23652 \
|
||||
--kv-cache-dtype fp8 --prefix-cache-mib 4096 --vision-tower-placement ram \
|
||||
--num-speculative-tokens 0 --deterministic \
|
||||
$flags --host 127.0.0.1 --port "$PORT" --api-key test ) > "$log" 2>&1 &
|
||||
SERVER_PID=$!
|
||||
|
||||
local i code
|
||||
for i in $(seq 1 240); do
|
||||
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
|
||||
echo "FAIL $arm: the engine exited before serving; last errors:" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$log" | tail -12 >&2 || tail -12 "$log" >&2
|
||||
cleanup; return 1
|
||||
fi
|
||||
code=$(curl -s -m 3 -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/health" 2>/dev/null || true)
|
||||
[ "$code" = 200 ] && break
|
||||
sleep 5
|
||||
done
|
||||
if [ "${code:-}" != 200 ]; then
|
||||
echo "FAIL $arm: /health did not answer" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$log" | tail -12 >&2 || true
|
||||
cleanup; return 1
|
||||
fi
|
||||
|
||||
local prompt_text
|
||||
prompt_text=$(cat "$OUT/prompt.txt")
|
||||
printf '{"model":"%s","temperature":0,"seed":%s,"max_tokens":%s,"chat_template_kwargs":{"enable_thinking":false},"messages":[{"role":"user","content":"%s"}]}' \
|
||||
"qwen4exp" "$SEED" "$MAXTOK" "$prompt_text" > "$req"
|
||||
code=$(curl -s -m 1800 -o "$resp" -w '%{http_code}' \
|
||||
-H "Authorization: Bearer test" -H "Content-Type: application/json" \
|
||||
--data-binary "@$req" "http://127.0.0.1:$PORT/v1/chat/completions" 2>/dev/null || true)
|
||||
if [ "${code:-}" != 200 ]; then
|
||||
echo "FAIL $arm: /v1/chat/completions answered $code; last errors:" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$log" | tail -12 >&2 || tail -12 "$log" >&2
|
||||
cleanup; return 1
|
||||
fi
|
||||
content_of "$resp" > "$OUT/$arm.txt"
|
||||
if [ ! -s "$OUT/$arm.txt" ]; then echo "FAIL $arm: empty completion text" >&2; cleanup; return 1; fi
|
||||
|
||||
local ptok ctok cache
|
||||
ptok=$(grep -o '"prompt_tokens":[0-9]*' "$resp" | head -1 | cut -d: -f2)
|
||||
ctok=$(grep -o '"completion_tokens":[0-9]*' "$resp" | head -1 | cut -d: -f2)
|
||||
cache=$(grep -o '"cached_tokens":[0-9]*' "$resp" | head -1 | cut -d: -f2)
|
||||
echo " prompt_tokens=$ptok completion_tokens=$ctok cached_tokens=$cache"
|
||||
echo " sha256 $(sha256sum "$OUT/$arm.txt" | cut -d' ' -f1) ($(wc -c < "$OUT/$arm.txt") bytes)"
|
||||
echo "$ptok $ctok $cache" > "$OUT/$arm.counts"
|
||||
cleanup
|
||||
return 0
|
||||
}
|
||||
|
||||
# The layer sequence the prefill stages. Each staged pass visits the group's layers in order, so
|
||||
# the trace is runs of one strictly-increasing sequence; every run after the first must equal the
|
||||
# first (a skipped or repeated stage breaks both properties).
|
||||
check_stage_order() {
|
||||
local log="$OUT/on.log"
|
||||
grep 'kv streaming: stage layer ' "$log" |
|
||||
sed -E 's/.*stage layer ([0-9]+).*/\1/' > "$OUT/stages.txt" || true
|
||||
local n
|
||||
n=$(wc -l < "$OUT/stages.txt")
|
||||
echo " stage layers traced: $n"
|
||||
if [ "$n" -lt 2 ]; then
|
||||
echo "FAIL: no staged layers were traced; the prefill did not take the stage view" >&2
|
||||
return 1
|
||||
fi
|
||||
awk '
|
||||
{ l[NR] = $1 + 0 }
|
||||
END {
|
||||
# The first run ends at the first non-increase.
|
||||
end = 1
|
||||
while (end < NR && l[end + 1] > l[end]) end++
|
||||
if (end < 2) { print "FAIL: the first staged run is not increasing"; exit 1 }
|
||||
for (i = 2; i <= end; ++i)
|
||||
if (l[i] <= l[i-1]) { print "FAIL: layers out of order at line " i; exit 1 }
|
||||
# Every later run must repeat the first exactly.
|
||||
i = end + 1
|
||||
while (i <= NR) {
|
||||
for (j = 1; j <= end; ++j) {
|
||||
if (i > NR) break
|
||||
if (l[i] != l[j]) { print "FAIL: stage run at line " i " differs from the first"; exit 1 }
|
||||
++i
|
||||
}
|
||||
}
|
||||
printf(" one staged run of %d layers, repeated %d time(s), in order\n", end, (NR / end) - 1)
|
||||
}' "$OUT/stages.txt" || return 1
|
||||
if grep -q "refused op 'kv_resolve'" "$log"; then
|
||||
echo "FAIL: kv_resolve was refused at issue on the staged arm" >&2; return 1
|
||||
fi
|
||||
if grep -q "GPU memory fault" "$log"; then
|
||||
echo "FAIL: a GPU memory fault was reported" >&2; return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
FAILED=0
|
||||
run_arm off || FAILED=1
|
||||
run_arm on "--kv-resident $RESIDENT" RADIANCE_KV_STAGE_TRACE=1 || FAILED=1
|
||||
|
||||
if [ "$FAILED" -eq 0 ]; then
|
||||
if ! grep -q "kv streaming: prefill staging" "$OUT/on.log"; then
|
||||
echo "FAIL: the streaming configuration is not in the on arm's log" >&2
|
||||
FAILED=1
|
||||
fi
|
||||
read -r ptok _ _ < "$OUT/on.counts"
|
||||
if [ "${ptok:-0}" -le 2051 ]; then
|
||||
echo "FAIL: the prompt is $ptok tokens, at or below qsa_exact_to 2051; prefill was dense," >&2
|
||||
echo " so raise LINES and rerun: this run would not prove the sparse staged path" >&2
|
||||
FAILED=1
|
||||
elif [ "${ptok:-0}" -le "$RESIDENT" ]; then
|
||||
echo "FAIL: the prompt is $ptok tokens, at or under the $RESIDENT-token ring: it fits, so" >&2
|
||||
echo " nothing streamed and the stage was not taken. Raise LINES, never lower RESIDENT" >&2
|
||||
FAILED=1
|
||||
fi
|
||||
check_stage_order || FAILED=1
|
||||
fi
|
||||
|
||||
echo "== KV pool before and after (from each arm's vram split and kv report) =="
|
||||
grep -E "vram split|^I kv:|^I kv .*streaming" "$OUT/off.log" | sed 's/^/ off: /' || true
|
||||
grep -E "vram split|^I kv:|^I kv .*streaming|prefill staging" "$OUT/on.log" | sed 's/^/ on: /' || true
|
||||
|
||||
if [ "$FAILED" -ne 0 ]; then
|
||||
echo "FAIL: an arm did not serve, the bytes were not compared, or staging was not proven" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
echo "== compare =="
|
||||
cmp "$OUT/off.txt" "$OUT/on.txt" || { echo "FAIL: the two arms differ" >&2; exit 1; }
|
||||
echo "PASS: byte-identical with a 32 768-token floor ring, prefill staged in layer order"
|
||||
Executable
+252
@@ -0,0 +1,252 @@
|
||||
#!/bin/bash
|
||||
# How large a KV streaming ring has to be: the union of distinct blocks one kv_resolve launch
|
||||
# selects, against context length (docs/KV-STREAMING.md §3.5).
|
||||
#
|
||||
# At decode a launch selects at most max_seqs * (topk + 1) blocks; above qsa_exact_to prefill
|
||||
# issues one sparse row per query, so a launch can select much of the history. This runs the
|
||||
# 32 768-token floor ring on longer contexts, so misses happen, and reads the counters the engine
|
||||
# logs at prefill completion and request end (ctl[10] and ctl[11]). An arm whose launch overflows is
|
||||
# failed by the engine with the ring and the union; the union is read from that message.
|
||||
#
|
||||
# The last arm checks for stale copies: a prompt below qsa_exact_to (dense prefill, no resolve)
|
||||
# decoded over a history larger than the ring, so decode evicts and re-copies blocks throughout,
|
||||
# compared byte for byte with streaming off. A stale copy shows only as wrong text.
|
||||
#
|
||||
# Run inside the toolchain container, with the model mounted:
|
||||
# docker run --rm --security-opt seccomp=unconfined -e HOME=/tmp \
|
||||
# --device /dev/kfd --device /dev/dri --group-add 990 --group-add 44 \
|
||||
# -v "$PWD":/src -v /path/to/models:/models -w /src rad-toolchain:latest \
|
||||
# bash -lc 'bash scripts/kv-union.sh'
|
||||
#
|
||||
# Paths are in-container: MODEL=/models/... and BUILD (default the tree's build/). Exit status: 0 if
|
||||
# every arm reported, 1 if the stale arm's texts differ, 2 if an arm did not serve or answer.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
BUILD="${BUILD:-$ROOT/build}"
|
||||
MODEL="${MODEL:-/models/qwen3.8-next-flash-fp8-iq4r-moe.rad}"
|
||||
PORT="${PORT:-8124}"
|
||||
OUT="${OUT:-/tmp/radiance-kv-union}"
|
||||
# The measurement arms climb 32768 -> 131072 tokens (8 192 -> 32 768 blocks of 4), starting at the
|
||||
# floor. Nothing here runs a ring below 32 768: that is the smallest ring the operator runs, and a
|
||||
# rung under it would measure a configuration the engine either raises (a decode step's selection
|
||||
# under speculation) or that nobody deploys. A prompt at or under the ring is not a streaming case
|
||||
# at all -- the group keeps its cache resident and no resolve is issued -- so every arm's context is
|
||||
# longer than the floor ring. The stale arm's ring is the floor too, and its history is pushed past
|
||||
# it by a ~34k-token prompt plus 512 decoded tokens, so decode evicts and re-copies every step.
|
||||
STALE_RING="${STALE_RING:-32768}"
|
||||
SEED="${SEED:-12345}"
|
||||
|
||||
BIN="$BUILD/bin/radiance"
|
||||
export RADIANCE_HOME="$BUILD/radiance_home" # absolute: the engine will not find the kernels without it
|
||||
[ -x "$BIN" ] || { echo "no engine at $BIN (build it first; this script builds nothing)" >&2; exit 2; }
|
||||
[ -f "$MODEL" ] || { echo "no model at $MODEL" >&2; exit 2; }
|
||||
command -v curl >/dev/null || { echo "curl is needed" >&2; exit 2; }
|
||||
|
||||
mkdir -p "$OUT"
|
||||
SERVER_PID=""
|
||||
cleanup() {
|
||||
# Only our own process, by the pid this script recorded: the engine is one process (its TP ranks
|
||||
# are threads), so there is no group to sweep and nothing else can be hit by mistake. No pkill.
|
||||
if [ -n "$SERVER_PID" ] && kill -0 "$SERVER_PID" 2>/dev/null; then
|
||||
kill -TERM "$SERVER_PID" 2>/dev/null || true
|
||||
for _ in $(seq 1 240); do kill -0 "$SERVER_PID" 2>/dev/null || break; sleep 0.25; done
|
||||
kill -KILL "$SERVER_PID" 2>/dev/null || true
|
||||
fi
|
||||
SERVER_PID=""
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
# One line of text is ~30 tokens at this tokeniser, so a context of N tokens is about N / 30 lines.
|
||||
# The records are distinct numbers, which keeps the prompt away from repetitive-text pathologies.
|
||||
gen_prompt() { local lines="$1" i first=$(( $1 + 1 )) last=$(( $1 + 10 ))
|
||||
for ((i = 1; i <= lines; i++)); do
|
||||
printf 'Record %d: the archivist checked the shelf, noted the catalogue number, and returned the volume to the east wing of the reading room. ' "$i"
|
||||
done
|
||||
printf 'Continue the register: write records %d through %d in the same form, one per line.' "$first" "$last"
|
||||
}
|
||||
|
||||
# The raw JSON-escaped completion text: equal escaped bytes mean equal text, and comparing the
|
||||
# escaped form is safer than any unescaper this script could carry.
|
||||
content_of() {
|
||||
awk '
|
||||
{ s = $0
|
||||
i = index(s, "\"message\":"); if (i == 0) exit 1
|
||||
s = substr(s, i)
|
||||
i = index(s, "\"content\":\""); if (i == 0) exit 1
|
||||
s = substr(s, i + 11)
|
||||
out = ""
|
||||
for (j = 1; j <= length(s); j++) {
|
||||
c = substr(s, j, 1)
|
||||
if (c == "\\") { out = out substr(s, j, 2); j++; continue }
|
||||
if (c == "\"") break
|
||||
out = out c
|
||||
}
|
||||
printf "%s", out
|
||||
}' "$1"
|
||||
}
|
||||
|
||||
# The engine's own report of one streamed group, from the prefill-complete / request-end line.
|
||||
# Prints: resolves lookups misses union maxmisses overflow
|
||||
stream_line() {
|
||||
grep -E "kv streaming: group '.*' (prefill complete|request end):" "$1" | tail -1 |
|
||||
sed -E "s/.*: ([0-9]+) resolves, ([0-9]+) lookups, ([0-9]+) misses.*largest launch union ([0-9]+) distinct blocks, largest launch misses ([0-9]+), overflow (LATCHED|no).*/\1 \2 \3 \4 \5 \6/" |
|
||||
{ read -r a b c d e f 2>/dev/null && echo "$a $b $c $d $e $f" || echo "- - - - - -"; }
|
||||
}
|
||||
|
||||
# One arm: a server, one request, a stop. $1 name, $2 prompt file, $3 max_model_len, $4 max_tokens,
|
||||
# the rest are the streaming flags. Writes $OUT/$1.{log,json,txt,counts,wall}.
|
||||
run_arm() { local arm="$1" prompt="$2" ctx="$3" maxtok="$4"; shift 4
|
||||
local log="$OUT/$arm.log" req="$OUT/$arm.req.json" resp="$OUT/$arm.json"
|
||||
echo "== $arm: max-model-len $ctx, max_tokens $maxtok, $* =="
|
||||
( exec "$BIN" --model "$MODEL" \
|
||||
--tp 2 --tp-wire exact \
|
||||
--max-num-seqs 1 --max-model-len "$ctx" --placement expert_tiered --host-pool-mib 23652 \
|
||||
--kv-cache-dtype fp8 --prefix-cache-mib 4096 --vision-tower-placement ram \
|
||||
--num-speculative-tokens 0 --deterministic \
|
||||
"$@" --host 127.0.0.1 --port "$PORT" --api-key test ) > "$log" 2>&1 &
|
||||
SERVER_PID=$!
|
||||
|
||||
local i code
|
||||
for i in $(seq 1 240); do # 20 min at 5 s; a cold load of this container is under a minute
|
||||
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
|
||||
echo "FAIL $arm: the engine exited before serving; last errors:" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$log" | tail -12 >&2 || tail -12 "$log" >&2
|
||||
cleanup
|
||||
return 1
|
||||
fi
|
||||
code=$(curl -s -m 3 -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/health" 2>/dev/null || true)
|
||||
[ "$code" = 200 ] && break
|
||||
sleep 5
|
||||
done
|
||||
if [ "${code:-}" != 200 ]; then
|
||||
echo "FAIL $arm: /health did not answer" >&2
|
||||
cleanup
|
||||
return 1
|
||||
fi
|
||||
|
||||
local prompt_text
|
||||
prompt_text=$(cat "$prompt")
|
||||
printf '{"model":"qwen4exp","temperature":0,"seed":%s,"max_tokens":%s,"chat_template_kwargs":{"enable_thinking":false},"messages":[{"role":"user","content":"%s"}]}' \
|
||||
"$SEED" "$maxtok" "$prompt_text" > "$req"
|
||||
# The wall time of the answer: time_starttransfer is the first token, i.e. the prefill's cost, on
|
||||
# an arm that succeeds; a failed arm reports the time to the refusal, which is the whole prefill.
|
||||
local t
|
||||
t=$(curl -s -m 3600 -o "$resp" -w '%{http_code} %{time_starttransfer} %{time_total}' \
|
||||
-H "Authorization: Bearer test" -H "Content-Type: application/json" \
|
||||
--data-binary "@$req" "http://127.0.0.1:$PORT/v1/chat/completions" 2>/dev/null || echo "000 0 0")
|
||||
code=${t%% *}
|
||||
echo "$t" > "$OUT/$arm.wall"
|
||||
local ptok
|
||||
ptok=$(grep -o '"prompt_tokens":[0-9]*' "$resp" | head -1 | cut -d: -f2 || true)
|
||||
# A failed overflow request has no usage block; the stream line still carries the measurement.
|
||||
[ -n "$ptok" ] && echo "$ptok" > "$OUT/$arm.ptok"
|
||||
content_of "$resp" > "$OUT/$arm.txt" 2>/dev/null || true
|
||||
stream_line "$log" > "$OUT/$arm.stream"
|
||||
echo " http=$code prompt_tokens=${ptok:-?} stream=[$(cat "$OUT/$arm.stream")]"
|
||||
cleanup
|
||||
return 0
|
||||
}
|
||||
|
||||
FAILED=0
|
||||
# The curve: contexts of roughly 64k and 128k tokens. The short points of the record (4k, 16k) are
|
||||
# gone rather than re-run: at the 32 768-token floor the ring covers a 4k or 16k context, the group
|
||||
# stays resident and no resolve is issued, so there is no union to report. Each prompt is a little
|
||||
# short of the bound so the chat template and the record numbers do not push it over
|
||||
# --max-model-len. The bound is twice the prompt, so the KV pool is large enough for the ring beside
|
||||
# the linear state.
|
||||
#
|
||||
# A ring too small for a launch is not served: the arm reports the union of the launch that overflowed
|
||||
# and fails, which is a lower bound, not the curve. So an arm is retried with a ring twice as deep
|
||||
# until no launch overflows -- the ring the arm finally ran with is the honest answer for that
|
||||
# context, and the union the launch's size. Sizes are tokens, one block is 4.
|
||||
declare -a NAMES=(ctx64k ctx128k)
|
||||
declare -a LINES=(2100 4200)
|
||||
declare -a CTX=(69632 139264)
|
||||
for k in 0 1; do
|
||||
gen_prompt "${LINES[$k]}" > "$OUT/${NAMES[$k]}.prompt.txt"
|
||||
# max_tokens 8: enough to run a few decode steps (decode is where the union is small) without
|
||||
# letting a measurement arm spend its time generating.
|
||||
ok=1
|
||||
for ring in 32768 65536 131072; do # the floor first, then the same search in floor-sized steps
|
||||
|
||||
run_arm "${NAMES[$k]}" "$OUT/${NAMES[$k]}.prompt.txt" "${CTX[$k]}" 8 \
|
||||
--kv-resident "$ring" || { ok=0; break; }
|
||||
echo "$ring" > "$OUT/${NAMES[$k]}.ring"
|
||||
if grep -q "kv streaming overflow:" "$OUT/${NAMES[$k]}.log"; then
|
||||
echo " overflowed a $ring-token ring; retrying deeper"
|
||||
continue
|
||||
fi
|
||||
break
|
||||
done
|
||||
[ "$ok" = 1 ] || FAILED=1
|
||||
done
|
||||
|
||||
# The staleness check: a ~34k-token prompt (above qsa_exact_to, so prefill is the sparse path the
|
||||
# resolve serves) streamed into the floor ring -- 32 768 tokens, 8 192 blocks -- then 512 decoded
|
||||
# tokens. The prompt's history is already past the ring when prefill ends and decode pushes it
|
||||
# further, so decode evicts and re-copies blocks every step: the exact case a stale copy would show
|
||||
# in, where the block a step writes is often the block the previous step made resident, and the
|
||||
# store now precedes the resolve. If a miss copied a block the store had not yet written, or an
|
||||
# eviction raced an attention still reading the slot, the text differs from the control.
|
||||
#
|
||||
# The ring is not shrunk to manufacture that pressure: the floor is 32 768 and a ring below it is a
|
||||
# shape the engine raises (and the operator never runs), so the *context* is what goes past the
|
||||
# ring. Here that is the prompt plus the 512 generated tokens; nothing about the arm is starved.
|
||||
#
|
||||
# A prompt BELOW qsa_exact_to cannot be used: that prefill is dense, and the dense attention reads a
|
||||
# block id as a pool slot with no resolve at all (docs/KV-STREAMING.md §3.5), so the sparse path the
|
||||
# resolve serves would not be the one this arm compares.
|
||||
gen_prompt 1150 > "$OUT/stale.prompt.txt"
|
||||
# --max-model-len above the prompt plus the generated tokens, and above the ring: at the prompt's own
|
||||
# length the ring would be the context, which streams nothing.
|
||||
run_arm stale-off "$OUT/stale.prompt.txt" 45056 512 || FAILED=1
|
||||
run_arm stale-on "$OUT/stale.prompt.txt" 45056 512 \
|
||||
--kv-resident "$STALE_RING" || FAILED=1
|
||||
if [ -s "$OUT/stale-off.txt" ] && [ -s "$OUT/stale-on.txt" ]; then
|
||||
# The comparison is only evidence of the copy path if the ring actually evicted: a miss count above
|
||||
# the peak union can only be a block copied more than once, i.e. evicted and needed again.
|
||||
read -r _ _ smiss _ sunion _ _ < "$OUT/stale-on.stream" || true
|
||||
if [ "${smiss:--}" != "-" ] && [ "${smiss:-0}" -le "${sunion:-0}" ]; then
|
||||
echo "FAIL: the stale arm made $smiss misses against a union of $sunion: nothing was evicted," >&2
|
||||
echo " so the run says nothing about a miss copying a block the store wrote" >&2
|
||||
FAILED=1
|
||||
fi
|
||||
if cmp -s "$OUT/stale-off.txt" "$OUT/stale-on.txt"; then
|
||||
echo "PASS: the floor-ring decode is byte-identical to streaming off ($(wc -c < "$OUT/stale-on.txt") bytes)"
|
||||
echo identical > "$OUT/stale.verdict"
|
||||
else
|
||||
echo "FAIL: the floor-ring decode differs from streaming off -- a stale or torn copy" >&2
|
||||
echo different > "$OUT/stale.verdict"
|
||||
FAILED=1
|
||||
fi
|
||||
else
|
||||
echo "FAIL: a stale arm produced no completion text" >&2
|
||||
echo missing > "$OUT/stale.verdict"
|
||||
FAILED=1
|
||||
fi
|
||||
|
||||
# A refusal naming the ring and the union is the honest outcome for an arm that overflowed, and it is
|
||||
# the measurement itself; print it once, verbatim, so the number is in the summary too.
|
||||
echo "== overflow refusals =="
|
||||
grep -h -E "^E kv streaming overflow:" "$OUT"/ctx*.log 2>/dev/null | sort -u || true
|
||||
|
||||
echo
|
||||
echo "== union by context (streamed group: kv_attn) =="
|
||||
printf '%-7s %8s %8s %8s %10s %10s %9s %8s %10s %10s\n' \
|
||||
arm prompt ring resolves lookups misses max_union max_miss overflow prefill_s
|
||||
for arm in "${NAMES[@]}"; do
|
||||
read -r res lk mi mu mm ov < "$OUT/$arm.stream" || true
|
||||
ptok=$(cat "$OUT/$arm.ptok" 2>/dev/null || echo "?")
|
||||
# The prefill's wall time: the first token on an arm that answered, the refusal on one that
|
||||
# overflowed (its prefill ran to completion before the engine failed it).
|
||||
pt=$(awk '{ print ($1 == 200 ? $2 : $3) }' "$OUT/$arm.wall" 2>/dev/null || echo "?")
|
||||
ring=$(cat "$OUT/$arm.ring" 2>/dev/null || echo "?")
|
||||
printf '%-7s %8s %8s %8s %10s %10s %9s %8s %10s %10s\n' \
|
||||
"$arm" "${ptok:--}" "$ring" "${res:--}" "${lk:--}" "${mi:--}" "${mu:--}" "${mm:--}" "${ov:--}" "${pt:--}"
|
||||
done
|
||||
|
||||
if [ "$FAILED" -ne 0 ]; then
|
||||
echo "FAIL: an arm did not serve, or the floor-ring text was not byte-identical" >&2
|
||||
exit 2
|
||||
fi
|
||||
Reference in new issue
Block a user