docs and harness: the design note, the flag rows, the kv-* scripts

This commit is contained in:
C_Tamas committed 2026-10-24 19:19:19 +07:00
1 parent 5b415b2ef8
commit b54a80de59
8 files changed
+2299

No files matched your search

+4
View File
@@ -38,6 +38,10 @@ and `agentreplay.py` need `python3`. Scripts find each other through `$(dirname
| `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` | The shipped comparison, paired: interleaved ABBA rounds of this build with `--kv-resident 32768` against the stock 1.10.0 image without it, one cold start per request (a second request in one process starts from a partly filled ring, a different workload). One paired delta a round, reported as the mean, the per-round values and a t interval; `ROUNDS` sets the resolution (~2.8% at 2, ~2.0% at 4). Every start is asked `/tokenize` for the canonical 16 110-token prompt and must answer that count, and every response's `usage.prompt_tokens` must agree again with `cached_tokens` 0, so both arms are provably on the same input. |
| `kv-union.sh` | How large a KV streaming ring has to be: the union of distinct blocks one `kv_resolve` launch selects, at 64k/128k-token prompts, climbed from the 32 768-token floor (8 192 blocks — the smallest ring this box runs and one the engine does not raise) until no launch overflows. Reports resolves, lookups, misses, the largest single-launch union and prefill wall time, plus the overflow refusal verbatim; its last arm decodes a sparse prompt whose ~34k-token history already exceeds the floor ring and compares with streaming off (no `--kv-resident`), and refuses to pass unless the ring actually evicted (misses above the peak union). Pressure is the context: the short-context points of the record are gone because a 4k/16k context fits the floor ring and streams nothing. |
| `kv-parity.sh` | That a `--kv-resident` ring covering the group's context changes no output byte and streams nothing: one server per arm, a dense and a sparse prompt with no flag and with `--kv-resident 4096` (its `--max-model-len x --max-num-seqs`), compared byte for byte, plus `--profile-ops` proving `kv_resolve` is never issued and the startup line saying nothing streams -- the base engine's path. |
| `kv-stage-parity-64k.sh` | Phase 2's prefill staging: streaming off (no `--kv-resident`) against `--kv-resident 32768` (the floor, 8 192 blocks) on a ~64k-token document, so every prefill chunk past 32 768 tokens has a history the ring cannot hold and must take the one-layer stage view instead of resolving; byte-identical output, the staged-copy trace counted and checked in layer order, and both arms' VRAM split printed. This is the shape that caught the §60 staged-prefill defect; a run that takes the ring instead of the stage 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`. |
| `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. |
+288
View File
@@ -0,0 +1,288 @@
#!/bin/bash
# Prove that a --kv-resident ring that covers the group's context changes no output byte and
# streams nothing at all on the QSA model.
#
# Why this exists: docs/KV-STREAMING.md §5 Phase 4 makes a ring at or above the group's context a
# plain resident pool -- no host mirror, no residency map, no stage view, no kv_resolve and a null
# RadKVStream -- so the base engine's path runs exactly. This script runs one server per arm, sends
# the same request to each, and compares the completion text byte for byte. The "on" arm passes
# --kv-resident 4096 with --max-num-seqs 1 --max-model-len 4096, i.e. exactly the group's context,
# and must say so at startup and issue no resolve at all; the off arm passes no flag. Any overhead
# the covering configuration adds would show up here as either a different completion, a streaming
# startup line, or a nonzero kv_resolve count.
#
# It builds nothing, and it touches only the server it starts: the engine is one process (its TP
# ranks are threads), so each arm is recorded under its own log in $OUT and killed by that pid at the
# end or on any error. Nothing else that matches bin/radiance is signalled -- no pkill anywhere.
#
# Run this INSIDE the toolchain container, with the model mounted, because that is where the binary
# and its kernel libraries live, and because the engine needs io_uring, which Docker's default
# seccomp profile refuses:
# 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 /home/j/src/radiance-kv-cache-streaming:/src -v /home/j/Documents/rad/models:/models \
# -v /tmp/opencode:/tmp/opencode -w /src rad-toolchain:latest bash -lc 'bash scripts/kv-parity.sh'
#
# Two prompts, both deterministic (a numbered record repeated, then "continue the register"): the
# sparse one is ~3000 tokens because the sparse path only engages above qsa_exact_to = 2051
# (arch/qwen4exp_fp8/qwen4exp_fp8.cpp:621-624) -- below it attention is dense and the selection is
# a different path, so a short prompt alone would prove nothing. Both fit the 4096-token context the
# ring covers. The short arm is there to show that path is untouched too.
#
# Exit status: 0 only if both arms produced a completion, the two are byte-identical, and the
# covering arm reported no streaming and no resolve; 1 on any 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:-/tmp/opencode/build-kv2}"
MODEL="${MODEL:-/models/qwen3.8-next-flash-fp8-iq4r-moe.rad}"
PORT="${PORT:-8123}"
OUT="${OUT:-/tmp/opencode/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
# Phase 2 admits a ring smaller than the context: a prefill or mixed step takes the group's
# one-layer stage view and never resolves, so the union of §3.5 is not a ring requirement. The
# staged-copy evidence (staged copies, in layer order, and byte parity) is
# scripts/kv-stage-parity-64k.sh, which runs the floor ring against a ~64k document; this script
# keeps the context-sized covering configuration it was written for.
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"
+692
View File
@@ -0,0 +1,692 @@
#!/bin/bash
# Measure the streaming-vs-stock decode gap at the canonical under-resident shape, as a paired
# number with an interval. The prompt is generated here, so a run does not depend on a file in /tmp
# surviving a reboot.
#
# The shape:
# 16 110-token prompt (sha256 c34ad060...f3a5) -- gen_prompt 522, generated below
# 8 192 generated tokens, --kv-resident 32768 (8 192 blocks = 200.00 MiB, inside a 204 800-token
# context, so the group streams and every decode launch resolves)
# stock image stilldeadcode/radiance:1.10.0 (no --kv-resident) against this build with it.
# Every other flag is identical between arms.
#
# SPEC (default 0) sets --num-speculative-tokens on *both* arms, which is the only thing that
# should differ between them. Two things change when it is on, and both are needed or the numbers
# mean nothing:
# - ms/step is no longer 1000/predicted_per_second. With speculation a step emits 1 + SPEC
# tokens, so predicted_per_second is tokens a second, not steps. ms/step is then the engine's
# own step clock, engine_step_seconds_decode_total / engine_steps_decode_total, which /metrics
# reports on both arms (the stock 1.10.0 image exposes the same counters). tok/s stays
# predicted_per_second, tokens a step is MAXTOK / decode steps, and draft acceptance is
# timings.draft_n_accepted / timings.draft_n -- the bimodal variable, printed per start so the
# modes are visible instead of averaged.
# - a start is ~6x shorter (spec 3 decodes 1 024 tokens in ~16 s, not ~206 s), so the same wall
# time buys many more pairs. SPEC=3 at ROUNDS=12 is ~20 min against ~16 min for ROUNDS=2 off.
#
# Method: interleaved ABBA rounds. Round r sends one request on each arm, the two starts adjacent
# in wall time, and alternates which arm goes first (round 1 stock first, round 2 ours first, ...).
# Each round yields one paired delta (ours ms/step over stock ms/step); the mean of those deltas,
# the per-round values, the spread and a t interval are reported. Interleaving cancels the
# common-mode part of session drift; the residual non-common-mode part is ±1.5 points, which is why
# the interval is wide.
#
# Why one cold start per request rather than one server per arm reused across its rounds: the two
# arms cannot hold the cards at once (each is `--tp 2` with --host-pool-mib 23652), so a server
# reused "across that arm's rounds" would have to be killed and restarted between them anyway. And
# a second request in the same process starts from a partly filled ring, i.e. it is not the same
# workload as the first. So each
# arm's rounds are adjacent cold starts, one request each, and only one server is ever on the cards.
#
# Cost and resolution: a start is ~18 s load + ~6 s prefill + 8 192 x ~26 ms
# decode, i.e. ~4 min, so ROUNDS=2 (two starts per arm, four in all) is ~16 min. At a cross-arm
# sd of 1.4 points the minimum detectable difference is 2.8 x sd / sqrt(n) (95%
# two-sided, 80% power): ~2.8% at 2 rounds, ~2.0% at 4. To resolve **1%** needs ~16 paired rounds
# and to resolve **0.9%** needs ~19-20, i.e. 32-40 cold starts and ~2.5 h of card time. A small
# default here is deliberate: this script states the shipped gap, it does not test a 1% change.
#
# What it proves about the two arms being on the same input: the prompt is regenerated here and its
# sha256 must equal the canonical one; *every* server started is asked POST /tokenize for that
# prompt and must answer the target count before its request runs; and every response's
# usage.prompt_tokens must equal the target again, with cached_tokens 0 (a prefix-cache hit would
# make the two arms' prefill a different workload). A mismatch kills the run.
#
# Run on the host, where the docker CLI talks to the daemon (the images and the build tree live
# here; the engine needs the model mounted and io_uring unconfined, which the script does):
# bash scripts/kv-resident-vs-stock.sh # 2 rounds, ~16 min
# ROUNDS=4 bash scripts/kv-resident-vs-stock.sh # ~32 min, ~2.0% resolution
# SPEC=3 ROUNDS=12 bash scripts/kv-resident-vs-stock.sh # speculation on, ~20 min, 12 pairs
#
# Env knobs (defaults in parentheses): ROUNDS (2), MAXTOK (8192), RESIDENT (32768), SPEC (0),
# PORT (8141), OUT (/tmp/opencode/kv-resident-vs-stock), BUILD (/tmp/opencode/build-kv3),
# MODEL (/home/j/Documents/rad/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 pinned on purpose: they are the
# workload, and a run against a different prompt is a different measurement.
#
# 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/opencode/kv-resident-vs-stock}"
BUILD="${BUILD:-/tmp/opencode/build-kv3}"
MODEL="${MODEL:-/home/j/Documents/rad/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" -v /tmp/opencode:/tmp/opencode \
-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
+224
View File
@@ -0,0 +1,224 @@
#!/bin/bash
# Prove Phase 2's prefill staging: with a ring smaller than the context, a long prompt prefilled
# above qsa_exact_to is byte-identical to streaming off (no --kv-resident at all), and every staged
# layer was copied into the one-layer view in order before its attention.
#
# The ring is the operator's floor, --kv-resident 32768 (8 192 blocks of 4). The document is ~64k
# tokens, so every prefill chunk whose history is longer than 32 768 tokens must take the view and
# stream: the ring cannot hold it. A ~16k prompt on the same ring fits it and would stage nothing
# (that is the 17k variant this script replaced), and a ring below the floor is not a configuration
# the engine runs anyway -- it raises it -- so this script keeps the 64k document and the 32 768
# ring. Eviction pressure comes from the length of the context, not from shrinking the ring.
#
# This is the pass that matters: a byte-identical result is only evidence if the run actually staged
# something, and a staged prefill that reads the previous layer's cache is still byte-identical to
# itself. The ring at the floor forces a staged chunk from 32 768 tokens on, so do not shorten the
# document to make the run cheaper.
#
# 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 /home/j/src/radiance-kv-cache-streaming:/src -v /home/j/Documents/rad/models:/models \
# -v /tmp/opencode:/out -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:-/out/build-kl}" # the tree the fix was measured on; override with BUILD=...
MODEL="${MODEL:-/models/qwen3.8-next-flash-fp8-iq4r-moe.rad}"
PORT="${PORT:-8124}"
OUT="${OUT:-/out/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"
+264
View File
@@ -0,0 +1,264 @@
#!/bin/bash
# Measure how large a KV streaming ring actually has to be: the union of distinct blocks one
# kv_resolve launch selects, as a function of context length.
#
# Why this exists: a streamed group's ring must hold every distinct block one launch selects. At
# decode that is at most max_seqs * (topk + 1) -- a thousand-odd. Above qsa_exact_to prefill issues
# one sparse row per query, so a launch (qsa_gq_rows = max_tok rows wide) can in principle select the
# whole live history, which is why docs/KV-STREAMING.md planned a layer-bulk prefill staging path
# (Phase 2). The design note assumed that worst case; this script measures the real union. It runs
# with the 32 768-token floor `--kv-resident` -- the smallest ring this engine is run with, and one
# the engine does not raise -- on contexts longer than that ring, so misses actually happen and the
# counters move. Nothing below the floor is measured: a smaller ring is not a stress shape (the
# engine raises one under a decode step's selection) and eviction pressure comes from the context.
# It reads the numbers the engine reports at prefill completion and request end (Engine::stream_probe,
# `ctl[10]`/`ctl[11]` of libref/ref_kvstream.cpp's control block).
#
# A ring that a launch overflows is not served: the resolve latches `ctl[3]`, and the request is
# FAILED at prefill completion with the ring size and the union that did not fit. Those arms report
# the union from that message and the completed-count line; nothing is recomputed by hand here.
#
# The last arm is the store/resolve staleness check: a prompt below qsa_exact_to (so prefill is dense
# and issues no resolve) streamed into a ring smaller than the history it decodes over, so decode
# evicts and re-copies blocks continuously, compared byte for byte against streaming off (no
# --kv-resident). A stale copy shows up as wrong text there, which no counter would reveal.
#
# Run this 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 /home/j/src/radiance-kv-cache-streaming:/src -v /home/j/Documents/rad/models:/models \
# -v /tmp/opencode:/tmp/opencode -w /src rad-toolchain:latest bash -lc 'bash scripts/kv-union.sh'
#
# Paths are in-container: MODEL=/models/... and BUILD=/tmp/opencode/build-kv2 (host paths are not
# visible inside it). Exit status: 0 if every arm reported, 1 if the stale arm's texts differ, 2 if
# an arm did not serve or did not answer at all.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BUILD="${BUILD:-/tmp/opencode/build-kv2}"
MODEL="${MODEL:-/models/qwen3.8-next-flash-fp8-iq4r-moe.rad}"
PORT="${PORT:-8124}"
OUT="${OUT:-/tmp/opencode/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