radiance 1.0.0

This commit is contained in:
Deadcode committed 2026-10-04 12:02:41 +02:00
commit ae74a8aebf
616 files changed
+338692

No files matched your search

+54
View File
@@ -0,0 +1,54 @@
# scripts/
Shell harnesses that drive a **running** engine: bring a model up, measure it, and assert on what
comes back over the wire. They are versioned with the engine because a measurement is only
reproducible if the thing that took it is, and because what each one encodes is an argument — why
a window is sampled the way it is, which counter is the honest one — that is expensive to
reconstruct from the number alone.
The scripts that start a server or a conversion expect the build at
`$HOME/workspace/radiance/build` and the containers under `$HOME/models/rad/`; every default is
an environment override (`M=` for the container, `P=` for the port, and so on — each script's
header lists its own). The ones that only attach to a live server need nothing but `curl` and
`jq`. Scripts resolve each other by `$(dirname "$0")`.
## Bringing a model up
| | |
|---|---|
| `mcserve.sh` | MiniCPM5-2B with its DSpark drafter (`minicpm5-2b-dspark.v2.rad`), left running on :8100. Records why `--max-model-len` is the container's `n_ctx_train` and why a dense model of this size needs no explicit VRAM split. |
| `fnserve.sh` | Qwen3.8-Flash-Next, the production container `w4nl64-i8lm.rad`, same contract. Records the production flags and why: the 200K context and the 0.82 expert/cache ratio that keeps the prefix cache useful at it, the 2048-token chunk, the prefix-cache tiers and the lossy `wht6` cross-rank wire. |
| `fnstop.sh` | Stops whichever is running and waits for the process to go. |
| `convdspark.sh` | Rebuilds the container `mcserve.sh` serves, with the drafter merged. The conversion of record. |
| `convfn.sh` | Rebuilds the container `fnserve.sh` serves from `data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe`. Needs `CALIB=<dir>`: the recipe's expert rule runs GPTQ against the calibration Grams there (`docs/MOE-W4.md`). |
| `hfget.sh` | Fetches a checkpoint from Hugging Face with `curl` and `jq`. Resumable, and it leaves behind the duplicate weight formats a large repo often carries beside its safetensors. |
## Measuring
| | |
|---|---|
| `cstep2.sh` | Steady-state decode ms/step at a given concurrency, against a live server. Waits until exactly C sequences are running before sampling and re-checks at the end: a window whose edges carry fewer than C describes no concurrency at all. Model-agnostic (`P=` picks the port). |
| `dprofd.sh` | Per-op device timing (`--profile-ops`) at depth and concurrency, on the 27B dense model with its DFlash2 drafter (`q38-27b-fp8-df2.v2.rad`). The counters are cumulative and a run starts with prefill, so a single dump is a mixture of two populations — difference two dumps taken after prefill has ended. |
| `fnpf.sh` | Prefill throughput of whatever server is on `$P`, over the repository's own prose, with a fresh nonce a rep so the prefix cache cannot make a rep free. Prints card temperature and clock beside every rep. |
| `fnconc.sh` | What a long prefill costs the decoders running beside it, and the prefill's own time, on one clock: alone, then contended, with a warm pass discarded. |
| `fntrace.sh` | A Flash-Next prefill under `rocprofv3`, with the link counters from `/stats` across the same request, so the streamed-read rate of the MoE GEMM can be computed. |
| `mctrace.sh` | A MiniCPM5-2B decode trace under `rocprofv3`, formatted for `libr4d/isa/tsum.sh`. The `blocks` column is what the trace is for. |
| `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 is not expected to match a non-speculative one byte for byte — the split-K count is chosen from M, so the two take different reduction orders and can flip a near-tie late in a long answer — but a divergence within the first sentence or two is a defect. |
| `diskstall.py` | What restoring a conversation from the disk tier costs: the returning request's time to first token, and the longest stall it puts on a stream decoding beside it. |
| `oracle.sh` | Every op compared against libref on the operands the model actually issued, which is the gap rad-kbench cannot close: its operands are its own, dense and rank-2, and an engine's are slices of arenas and weights off a file. Reads for two things — a MISMATCH, and the NOT CHECKED lines that name the rows whose weight layout has no published inverse and therefore cannot be compared at all. |
## Regression checks against a live server
These cover what `tests/chat_test.cpp` structurally cannot: the server, the wire format, and a
real model's output.
| | |
|---|---|
| `apikeys.sh` | Every request key on the lists in `core/server/oai.cpp`: a rejected key must be refused by name, an inert one accepted and ignored, an accepted one honoured — and a key the deployment cannot satisfy (`logprobs`, `grammar` on chat) refused rather than answered without it. |
| `fndrop.sh` | Clients that disconnect mid-request, at points derived from a timed full request: the server must stay up and keep answering a reference question identically. |
| `tierident.sh` | Whether a session that left VRAM comes back byte for byte, both halves of it. The VRAM repeat is the control: without it a differing hash proves nothing, because a cache hit could have been tie-divergent. A run where nothing moved is a failure, not a pass. On a hybrid model the linear-state checks are COUNTERS and not hashes — a lost snapshot is invisible in the text, because the engine replays from further back and produces the same answer. |
| `tiercross.sh` | The same question with TWO sessions in flight, which is the only way to see one being served the other's context or state — with a single conversation in the server there is no other conversation's bytes to be served. Compares each restore against that session's DEVICE-HIT run rather than its cold one, because a hybrid session's reuse is clamped to the last reachable checkpoint and a cold run reuses nothing by definition. |
| `mctools.sh` | The tool-call shapes that are hardest to parse — an array argument, two calls in one reply, prose before a call, plain chat with tools available. Asserts `finish_reason` and that no `<function`/`<param`/CDATA marker reaches content. |
| `mcstream.sh` | Tool-call replies **streamed**, asserting on raw SSE fragments rather than on the assembled message. Content cannot be retracted once sent, so a repair applied at the end is not a fix; this is the check that sees the difference. |
| `mcagent.sh` | What speculation is worth on an agentic workload — `/v1/chat/completions` with tools, which is a constrained decode. Speculation on and off alternate across restarts because the speculation depth is a server-level setting. |
| `mcdecl.sh` | How often the drafter actually proposes. `draft_acceptance_ratio` is conditional on having drafted, so it reads healthy while tokens-per-step collapses; blocks-per-step is the quantity that separates the two. |
+153
View File
@@ -0,0 +1,153 @@
#!/bin/sh
# Does this server actually do what it says about request keys, against one that is ALREADY UP?
#
# The rule the whole API rests on is that A REQUEST THAT RETURNS 200 MEANS EVERY FIELD OF IT WAS
# HONOURED: a parameter this engine does not implement is REFUSED, not quietly dropped. That rule
# is only worth anything if it is true of every key on the list, and the list lives in
# core/server/oai.cpp in three parts -- accepted, inert, rejected-with-a-reason. This checks the
# running server against it.
#
# THE TWO FAILURES THAT MATTER POINT IN OPPOSITE DIRECTIONS:
#
# a REJECTED key that returns 200 is the rule broken -- the caller asked for a sampler the
# device does not have and got a plausible answer computed without it;
#
# an INERT key that returns 400 breaks the official SDKs, which send `user`, `store` and
# friends unprompted and cannot be told not to.
#
# A rejected key is refused on its NAME, so the value it carries does not matter and every case
# below sends 1. An accepted key is not checked here: it would need a valid value per key, and a
# 400 would then be ambiguous between "refused the key" and "disliked the value".
#
# P=8100 scripts/apikeys.sh
P="${P:-8100}"
H="${H:-127.0.0.1}"
U="http://$H:$P"
pass=0; fail=0
# code and blamed parameter for a chat request carrying one extra key
probe() { # $1 = key, $2 = json value
jq -n --arg k "$1" --argjson v "$2" \
'{messages:[{role:"user",content:"hi"}],max_tokens:4,temperature:0} + {($k): $v}' \
> "$WORK/q.json"
code=$(curl -s -o "$WORK/r.json" -w '%{http_code}' -m 120 -X POST "$U/v1/chat/completions" \
-H 'Content-Type: application/json' --data @"$WORK/q.json")
param=$(jq -r '.error.param // ""' < "$WORK/r.json" 2>/dev/null)
printf '%s %s' "$code" "$param"
}
want_refused() { # $1 = key
set -- "$1" $(probe "$1" 1)
if [ "$2" = "400" ] && [ "$3" = "$1" ]; then
pass=$((pass + 1))
else
fail=$((fail + 1)); printf ' FAIL %-24s expected 400 naming it, got %s %s\n' "$1" "$2" "$3"
fi
}
want_accepted() { # $1 = key, $2 = json value
set -- "$1" $(probe "$1" "$2")
if [ "$2" = "200" ]; then
pass=$((pass + 1))
else
fail=$((fail + 1)); printf ' FAIL %-24s expected 200, got %s (param %s)\n' "$1" "$2" "$3"
fi
}
WORK=$(mktemp -d "${TMPDIR:-/tmp}/apikeys.XXXXXX"); trap 'rm -rf "$WORK"' EXIT INT TERM
echo "checking $U against the key lists in core/server/oai.cpp"
echo " rejected keys must be refused, by name:"
for k in logit_bias functions function_call best_of suffix \
mirostat mirostat_tau mirostat_eta top_n_sigma \
dynatemp_range dynatemp_exponent lora modalities audio prediction \
continue_final_message cache_prompt; do
want_refused "$k"
done
echo " inert keys must be accepted and ignored:"
for k in user metadata store service_tier safety_identifier prompt_cache_key; do
want_accepted "$k" '"x"'
done
# AN ACCEPTED KEY NEEDS A VALID VALUE, or a 400 is ambiguous between "refused the key" and
# "disliked the value" -- so each of these carries one the schema actually allows, and the ones
# that only make sense together are sent together.
merge() { # $1 = label, $2 = json object to merge into a minimal chat request
jq -n --argjson o "$2" \
'{messages:[{role:"user",content:"hi"}],max_tokens:4,temperature:0} + $o' > "$WORK/q.json"
code=$(curl -s -o "$WORK/r.json" -w '%{http_code}' -m 120 -X POST "$U/v1/chat/completions" \
-H 'Content-Type: application/json' --data @"$WORK/q.json")
if [ "$code" = "200" ]; then
pass=$((pass + 1))
else
fail=$((fail + 1))
printf ' FAIL %-24s expected 200, got %s: %s\n' "$1" "$code" \
"$(jq -r '.error.message // ""' < "$WORK/r.json" | head -c 90)"
fi
}
echo " accepted keys must be honoured, not refused:"
merge model '{"model":"m"}'
merge n '{"n":1}'
merge seed '{"seed":1}'
merge stop '{"stop":["\n\n"]}'
merge temperature '{"temperature":0.7}'
merge top_p '{"top_p":0.9}'
merge top_k '{"top_k":20}'
merge min_p '{"min_p":0.05}'
merge typical_p '{"typical_p":0.95}'
merge presence_penalty '{"presence_penalty":0.1}'
merge frequency_penalty '{"frequency_penalty":0.1}'
merge repetition_penalty '{"repetition_penalty":1.05}'
merge repeat_last_n '{"repeat_last_n":64}'
merge xtc '{"xtc_probability":0.1,"xtc_threshold":0.15}'
merge dry '{"dry_multiplier":0.5,"dry_base":1.75,"dry_allowed_length":2,"dry_penalty_last_n":64,"dry_sequence_breakers":["\n"]}'
merge priority '{"priority":0}'
merge ignore_eos '{"ignore_eos":false}'
merge response_format '{"response_format":{"type":"text"}}'
merge tools '{"tools":[{"type":"function","function":{"name":"f","description":"d","parameters":{"type":"object","properties":{}}}}],"tool_choice":"auto","parallel_tool_calls":true}'
merge add_generation_prompt '{"add_generation_prompt":true}'
merge max_completion_tokens '{"max_completion_tokens":4}'
merge chat_template_kwargs '{"chat_template_kwargs":{"enable_thinking":false}}'
merge reasoning_effort '{"reasoning_effort":"low"}'
merge enable_thinking '{"enable_thinking":false}'
merge stream '{"stream":true,"stream_options":{"include_usage":true}}'
# AND TWO ACCEPTED KEYS ARE REFUSED BY CAPABILITY RATHER THAN BY VETTING, which is the rule
# working and not a hole in it: being on the accepted list means the engine UNDERSTANDS the key,
# not that every deployment can satisfy it. What matters is that it refuses instead of answering
# unconstrained, so what is asserted here is the refusal, with the key named.
#
# logprobs -- `supports_logprobs` is initialised false and set true nowhere in the tree, so this
# engine never returns per-token probabilities. /server_info reports `logprobs: false`, which is
# where a client should look before asking.
#
# grammar and response_format ON CHAT -- both pass through the chat template, which may rewrite
# or drop them. A template that returns no grammar for a request that asked for one leaves the
# caller parsing free prose against a schema they were told was enforced, so it is a refusal.
# On /v1/completions there is no template in the way and the same grammar works.
want_capability_refusal() { # $1 = label, $2 = object, $3 = key that must be blamed
jq -n --argjson o "$2" \
'{messages:[{role:"user",content:"hi"}],max_tokens:4,temperature:0} + $o' > "$WORK/q.json"
code=$(curl -s -o "$WORK/r.json" -w '%{http_code}' -m 120 -X POST "$U/v1/chat/completions" \
-H 'Content-Type: application/json' --data @"$WORK/q.json")
param=$(jq -r '.error.param // ""' < "$WORK/r.json" 2>/dev/null)
if [ "$code" != "200" ] && [ "$param" = "$3" ]; then
pass=$((pass + 1))
else
fail=$((fail + 1))
printf ' FAIL %-24s expected a refusal naming %s, got %s %s\n' "$1" "$3" "$code" "$param"
fi
}
echo " and two accepted keys this deployment cannot satisfy must REFUSE, not answer anyway:"
want_capability_refusal logprobs '{"logprobs":true,"top_logprobs":1}' logprobs
want_capability_refusal "grammar (chat)" '{"grammar":"root ::= \"ok\""}' grammar
echo " and a key on no list at all must be refused, naming it:"
want_refused "no_such_parameter_at_all"
printf '\n %d passed, %d failed\n' "$pass" "$fail"
[ "$fail" -eq 0 ] || exit 1
+20
View File
@@ -0,0 +1,20 @@
#!/bin/sh
# Rebuild the DSpark container for MiniCPM5-2B that scripts/mcserve.sh serves
# (minicpm5-2b-dspark.v2.rad): the bf16 checkpoint with the drafter merged in, every linear made
# block fp8 by data/recipes/minicpm5-2b-dspark.recipe, served by arch/llama_dense_fp8. It writes
# a .new.rad beside it, because the output is removed before the conversion starts.
cd "$HOME/workspace/radiance/build" || exit 1
RECIPE=${RECIPE:-$HOME/workspace/radiance/data/recipes/minicpm5-2b-dspark.recipe}
SRC=$HOME/models/openbmb/MiniCPM5-2B
DRAFT=$HOME/models/openbmb/MiniCPM5-2B-DSpark
OUT=$HOME/models/rad/minicpm5-2b-dspark.new.rad
[ -d "$DRAFT" ] || { echo "no drafter checkpoint at $DRAFT"; exit 1; }
rm -f "$OUT"
./bin/rad-convert "$SRC" -o "$OUT" \
--home "$HOME/workspace/radiance/build/radiance_home" \
--tokenizer "$SRC/tokenizer.json" \
--draft-model "$DRAFT" \
--recipe "$RECIPE" \
-v 2>&1 | tail -25
[ -s "$OUT" ] || { echo CONVERT_FAILED; exit 1; }
echo CONVERT_OK "$OUT"
+50
View File
@@ -0,0 +1,50 @@
#!/bin/sh
# Rebuild the Qwen3.8-Flash-Next container `fnserve.sh` serves. THE CONVERSION OF RECORD.
#
# The recipe is the whole format decision: it names what each weight is quantised to, and the
# container records it (rad-info --recipe), so the engine serves the file in the format it was
# packed in and nothing else. The default, data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe, builds the
# production container w4nl64-i8lm.rad; its header says what each weight becomes and what that
# measures.
#
# CALIB=<dir> IS REQUIRED BY THAT RECIPE. Its routed-expert rule runs GPTQ against `calib=$CALIB`,
# and the converter refuses a recipe that names an unset variable. The directory holds each
# layer's pooled Grams and each expert's own down Gram, recorded from the bf16 model over THIS
# checkpoint (docs/MOE-W4.md, "Calibration"): Grams taken from another checkpoint are not
# transferable, and a layer with no file is packed without error feedback.
#
# A recipe whose rules do not name $CALIB (RECIPE=data/recipes/qwen4exp-w4.recipe, say) rounds its
# experts to nearest with absmax scales; CALIB=<dir> then puts them through int4 GPTQ instead, by
# the --quant rule that recipe's header names, which goes ahead of the recipe's own.
#
# OUT is removed before the conversion starts, so its default is a .new.rad beside the served
# container rather than the served container itself.
#
# CALIB=<dir> [SRC=<checkpoint dir>] [OUT=<container>] [RECIPE=<file>] scripts/convfn.sh
set -e
cd "$HOME/workspace/radiance/build" || exit 1
SRC=${SRC:-$HOME/models/Qwen/Qwen3.8-Flash-Next}
OUT=${OUT:-$HOME/models/rad/w4nl64-i8lm.new.rad}
RECIPE=${RECIPE:-$HOME/workspace/radiance/data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe}
[ -d "$SRC" ] || { echo "no checkpoint at $SRC"; exit 1; }
[ -f "$SRC/tokenizer.json" ] || { echo "no tokenizer.json in $SRC"; exit 1; }
[ -f "$RECIPE" ] || { echo "no recipe at $RECIPE"; exit 1; }
[ -z "$CALIB" ] || [ -d "$CALIB" ] || { echo "no calibration directory at $CALIB"; exit 1; }
if grep -q '^[^#]*\$CALIB' "$RECIPE"; then
[ -n "$CALIB" ] || { echo "$RECIPE quantises against \$CALIB: set CALIB=<calibration dir>"; exit 1; }
export CALIB
set --
elif [ -n "$CALIB" ]; then
export CALIB
set -- --quant 'blk.*.ffn_*_exps.*.weight=gptq:codes=i4,group=128,scale=bf16,transform=fwht128,calib=$CALIB'
else
set --
fi
rm -f "$OUT"
./bin/rad-convert "$SRC" -o "$OUT" \
--home "$HOME/workspace/radiance/build/radiance_home" \
--tokenizer "$SRC/tokenizer.json" \
--recipe "$RECIPE" "$@" \
-v 2>&1 | tail -30
[ -s "$OUT" ] || { echo CONVERT_FAILED; exit 1; }
echo CONVERT_OK "$OUT"
+46
View File
@@ -0,0 +1,46 @@
#!/bin/sh
# STEADY-STATE decode step time at concurrency, against a LIVE server (no restart).
#
# ignore_eos pins every sequence to the same length so none retires mid-window; we wait until
# exactly C are RUNNING, sample the counters across a window in the middle, and re-check the
# count at the end -- a window whose edges carry fewer than C sequences reports a step time that
# is not any concurrency's. Model-agnostic: P= picks the port.
P=${P:-8100}
U="http://127.0.0.1:$P"
LEVELS="${LEVELS:-1 2 3 4 5 6 8}"
MT=${MT:-900}
WIN=${WIN:-6}
Q="Write a complete, heavily commented Go implementation of a generic LRU cache with a fixed capacity, O(1) get and put, a doubly linked list, a mutex for concurrent use, table-driven tests for every method, and a long prose explanation of every design decision you made."
m() { curl -s -m 10 "$U/metrics" | grep -F "$1" | grep -v '^#' | awk '{print $NF}' | head -1; }
waitidle() { i=0; while [ $i -lt 240 ]; do [ "$(m 'vllm:num_requests_running')" = "0" ] && return 0; i=$((i+1)); sleep 1; done; return 1; }
printf '%-4s %9s %9s %10s %10s %9s\n' C steps tok tok/step ms/step accept%
for C in $LEVELS; do
waitidle || { echo "C=$C busy"; continue; }
i=0
while [ $i -lt "$C" ]; do
i=$((i+1))
curl -s -m 600 -o /dev/null "$U/v1/completions" -H 'Content-Type: application/json' \
-d "{\"model\":\"q\",\"prompt\":\"$Q\",\"max_tokens\":$MT,\"temperature\":0,\"ignore_eos\":true}" &
done
# ramp: wait until exactly C are running
j=0; while [ $j -lt 120 ]; do [ "$(m 'vllm:num_requests_running')" = "$C" ] && break; j=$((j+1)); sleep 0.5; done
sleep 3 # let the ramp's ragged edge pass
[ "$(m 'vllm:num_requests_running')" = "$C" ] || { echo "C=$C never reached"; wait; continue; }
s0=$(m 'radiance:engine_steps_decode_total'); d0=$(m 'radiance:decode_tokens_total')
r0=$(m 'radiance:draft_tokens_total'); a0=$(m 'radiance:draft_accepted_total')
p0=$(m 'radiance:prefill_tokens_total'); T0=$(date +%s.%N)
sleep "$WIN"
s1=$(m 'radiance:engine_steps_decode_total'); d1=$(m 'radiance:decode_tokens_total')
r1=$(m 'radiance:draft_tokens_total'); a1=$(m 'radiance:draft_accepted_total')
p1=$(m 'radiance:prefill_tokens_total'); T1=$(date +%s.%N)
run=$(m 'vllm:num_requests_running')
awk -v C="$C" -v ds=$((s1-s0)) -v dd=$((d1-d0)) -v dr=$((r1-r0)) -v da=$((a1-a0)) \
-v dp=$((p1-p0)) -v t0="$T0" -v t1="$T1" -v run="$run" 'BEGIN{
tag = (run+0!=C? " <- count moved to " run : "") (dp>0? " <- prefill " dp " in window" : "")
if (ds<=0) { printf "%-4s %9s\n", C, "NO-STEPS"; exit }
printf "%-4s %9d %9d %10.3f %10.2f %9.1f%s\n", C, ds, dd, dd/ds, 1000*(t1-t0)/ds, (dr>0?100.0*da/dr:0), tag
}'
wait
done
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
# diskstall.py -- what bringing a conversation back from DISK costs: the returning request's time to
# first token, and the stall it puts on a conversation decoding beside it.
#
# A restore out of disk is the one tier move that reads files, and where it reads them decides who
# waits. So this measures both halves: the request that asked (TTFT, and how much of its prompt the
# cache served) and a bystander that asked for nothing (the longest gap between its streamed chunks
# while the restore ran, against its median gap outside that window).
#
# scripts/diskstall.py [--port 8100] [--session 20000] [--fill 30000]
#
# THE SERVER MUST HAVE A HOST TIER THE FILLER OVERFLOWS, or the session is restored out of host
# memory and nothing here touches the disk -- the run then says so and exits non-zero:
# --prefix-cache-host-mib 512 --prefix-cache-disk-mib 8192 --prefix-cache-dir <dir>
# holds about 27K tokens on Qwen3.8-Flash-Next, so --session 20000 --fill 30000 puts the session
# on disk. The session must still FIT the host tier: a restore reads through it.
import argparse, json, random, statistics, sys, threading, time, urllib.request
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=8100)
ap.add_argument("--host", default="127.0.0.1")
ap.add_argument("--session", type=int, default=20000, help="tokens in the returning conversation")
ap.add_argument("--fill", type=int, default=30000, help="tokens of filler that push it out of RAM")
ap.add_argument("--wait", type=int, default=240, help="seconds to wait for it to reach disk")
ap.add_argument("--seed", type=int, default=7)
a = ap.parse_args()
base = f"http://{a.host}:{a.port}"
WORDS = ["ledger", "valve", "crate", "harbor", "signal", "copper", "lantern", "orchard", "gravel",
"tunnel", "beacon", "anchor", "quarry", "saddle", "furnace", "meadow", "cobalt", "pylon"]
def text(seed, ntok):
r = random.Random(seed)
return " ".join(r.choice(WORDS) for _ in range(int(ntok / 1.25)))
def post(path, body, timeout=1800):
req = urllib.request.Request(base + path, data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read())
def get(path):
with urllib.request.urlopen(base + path, timeout=30) as r:
return json.loads(r.read())
def complete(prompt, n=1):
t0 = time.time()
d = post("/v1/completions", {"model": "m", "prompt": prompt, "max_tokens": n,
"temperature": 0, "stream": False})
u = d.get("usage") or {}
cached = (u.get("prompt_tokens_details") or {}).get("cached_tokens")
return time.time() - t0, u.get("prompt_tokens"), cached
def row_for(tokens):
for s in get("/sessions")["sessions"]:
if tokens <= s["tokens"] <= tokens + 8:
return s
return None
session = text(a.seed, a.session) + "\nName one word above.\nAnswer:"
t, n_prompt, _ = complete(session)
print(f"session {n_prompt} tokens prefilled in {t:.1f}s")
t, n_fill, _ = complete(text(a.seed + 1, a.fill) + "\nName one word above.\nAnswer:")
print(f"filler {n_fill} tokens prefilled in {t:.1f}s")
# ON DISK AND NOWHERE ELSE: not in VRAM (the loan takes a clean entry's blocks), not in RAM (the
# filler's copies took the slots, which the disk copy made free to give up).
t0 = time.time()
while True:
s = row_for(n_prompt)
if s and s["on_device"] == 0 and s["on_host"] == 0 and s["on_disk"] > 0 and not s["moving"]:
break
if time.time() - t0 > a.wait:
print(f"diskstall: the session never left RAM and VRAM for disk: {s}", file=sys.stderr)
sys.exit(1)
time.sleep(1)
print(f"on disk {s['on_disk']} blocks, snapshots device/host/disk "
f"{s['snap_device']}/{s['snap_host']}/{s['snap_disk']}, after {time.time()-t0:.0f}s")
# ---- the bystander: a stream that only decodes ----------------------------------------------------
stamps = []
def bystander():
req = urllib.request.Request(base + "/v1/completions", data=json.dumps({
"model": "m", "prompt": "Write a long story about a lighthouse keeper.\n\n",
"max_tokens": 1500, "temperature": 0.7, "seed": 1, "ignore_eos": True,
"stream": True}).encode(), headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=1800) as r:
for line in r:
if line.startswith(b"data:") and not line.startswith(b"data: [DONE]"):
stamps.append(time.time())
th = threading.Thread(target=bystander)
th.start()
while len(stamps) < 40:
time.sleep(0.05)
time.sleep(2.0)
moved0 = get("/sessions")["moved"]
t_ask = time.time()
ttft, n2, cached = complete(session + " the")
t_done = time.time()
moved1 = get("/sessions")["moved"]
time.sleep(2.0)
th.join()
gaps_in, gaps_out = [], []
for x, y in zip(stamps, stamps[1:]):
(gaps_in if y >= t_ask and x <= t_done else gaps_out).append(y - x)
promoted = moved1["promoted"] - moved0["promoted"]
print(f"restore {promoted} entries promoted; prompt {n2} cached {cached}; TTFT {ttft*1000:.0f} ms")
print(f"bystander median gap {statistics.median(gaps_out)*1000:.1f} ms outside the restore, "
f"longest {max(gaps_in)*1000:.1f} ms during it ({len(gaps_in)} chunks)")
if not cached or cached < n_prompt // 2:
print("diskstall: the returning request was not served from the cache", file=sys.stderr)
sys.exit(1)
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
# Per-op device timing (--profile-ops) AT DEPTH and AT CONCURRENCY, on the 27B dense model with
# its DFlash2 drafter: C requests of a ~16K-token prompt (PROMPT=<file>), so every
# context-scaling op (attn_paged above all) shows the weight it carries at a real KV depth rather
# than at a few dozen tokens.
#
# THE COUNTERS ARE CUMULATIVE AND THE RUN STARTS WITH PREFILL, so a single table is a mixture:
# ~30 chunked-prefill steps at 4096 tokens sit under every decode step that follows. This dumps
# every EVERY steps (RADIANCE_PROFILE_EVERY) and leaves them all in the log; differencing two dumps
# that are both after prefill ended is the only way to get a decode-only table out of it.
P=8129
C="${C:-8}"
EVERY="${EVERY:-20}"
MT="${MT:-400}"
cd "$HOME/workspace/radiance/build" || exit 1
pkill -f "bin/radianc[e]"; while pgrep -f "bin/radianc[e]" >/dev/null; do sleep 1; done; sleep 3
: > "$HOME/dprofd.log"
[ -n "$KVFP8" ] && export RADIANCE_QWEN35_KV_FP8=1 # read by nothing: the KV width is --kv-cache-dtype
GPU_MAX_ALLOC_PERCENT=100 GPU_MAX_HEAP_SIZE=100 RADIANCE_PROFILE_EVERY="$EVERY" \
./bin/radiance --model "${M:-$HOME/models/rad/q38-27b-fp8-df2.v2.rad}" \
--radiance-home "$HOME/workspace/radiance/build/radiance_home" \
--max-num-seqs 8 --max-model-len 24000 --checkpoint-slots 0 --no-prefix-cache \
--tp 2 --tp-wire wht6 --tp-wire-min-kb 128 --vram-weights-mib 20000 --vram-kv-mib 8000 \
--max-num-batched-tokens 4096 --num-speculative-tokens ${DEPTH:-auto} \
--profile-ops --port $P >> "$HOME/dprofd.log" 2>&1 &
for i in $(seq 1 150); do
[ "$(curl -s -m 3 -o /dev/null -w %{http_code} http://localhost:$P/health 2>/dev/null)" = 200 ] && break
pgrep -f "bin/radianc[e]" >/dev/null || { echo "DIED"; grep -iE "^E " "$HOME/dprofd.log" | tail -5; exit 1; }
sleep 5
done
jq -Rs "{model:\"m\",prompt:.,max_tokens:$MT,temperature:0}" < "${PROMPT:-$HOME/lpcode16k.txt}" > /tmp/dpd.json
PIDS=; i=0
while [ $i -lt $C ]; do
curl -s -m 1800 http://localhost:$P/v1/completions -H "Content-Type: application/json" -d @/tmp/dpd.json -o /tmp/dpd_$i.out &
PIDS="$PIDS $!"; i=$((i+1))
done
wait $PIDS
echo "C=$C kvfp8=${KVFP8:-0} completion_tokens $(jq -r '.usage.completion_tokens' /tmp/dpd_0.out)"
sleep 2
pkill -f "bin/radianc[e]"; while pgrep -f "bin/radianc[e]" >/dev/null; do sleep 1; done
grep -c "per-op device timing, rank 0" "$HOME/dprofd.log" | sed 's/^/dumps: /'
echo DPROFDDONE
+87
View File
@@ -0,0 +1,87 @@
#!/bin/sh
# What a long prefill costs the requests already running beside it, and what the prefill chunk
# does to both halves of that trade.
#
# WHY IT CANNOT BE MEASURED ALONE. A bigger prefill chunk holds the device for longer in one
# go, so every decode step queued behind it waits that much longer. Run by itself a long prompt
# only shows the good half -- the chunk is worth tens of percent of prefill -- and the bill
# arrives on other people's sequences. Both halves have to be on the same clock.
#
# WARM FIRST. `expert_tiered` faults its tier in on the first requests, so a cold first pass
# charges the whole cold tier to the alone arm and comes back with contention making the decoders
# FASTER. The first pass ("warm") is discarded; each later pass runs both arms back to back.
#
# THE DECODERS USE ignore_eos SO THEIR LENGTH IS FIXED. A decoder that stops early leaves the
# contended window measuring fewer streams than the alone window did, which reads as contention
# being free.
#
# P=8100 C=4 DEC=300 PROMPT=24000 scripts/fnconc.sh
#
# Reports, per arm: the decoders' wall alone, their wall with the prefill landing beside them,
# and the prefill's own wall.
P="${P:-8100}"
H="${H:-127.0.0.1}"
C="${C:-4}" # co-running decoders
DEC="${DEC:-300}" # tokens each decoder generates
PROMPT="${PROMPT:-24000}" # the long request's token target
BPT="${BPT:-4}"
ROOT="${ROOT:-$(dirname "$0")/..}"
URL="http://$H:$P"
CORPUS=/dev/shm/fnconc-corpus.txt
# Grown when a later run wants more than the last one did: `head -c` on a corpus that is too
# short returns what there is rather than failing, so the arm would time a prompt it did not send.
want=$((PROMPT * BPT + 4096))
if [ "$(wc -c < "$CORPUS" 2>/dev/null || echo 0)" -lt "$want" ]; then
: > "$CORPUS"
while [ "$(wc -c < "$CORPUS")" -lt "$want" ]; do
cat "$ROOT"/spec.md "$ROOT"/docs/*.md >> "$CORPUS" 2>/dev/null || exit 1
done
fi
decoder() {
curl -s --max-time 900 -X POST "$URL/v1/completions" -H 'Content-Type: application/json' \
-d "{\"prompt\":\"$1 count upward and do not stop:\",\"max_tokens\":$DEC,\"ignore_eos\":true,\"temperature\":0}" \
> /dev/null
}
long_request() {
{ printf 'long %s\n\n' "$(date +%s%N)"; head -c $((PROMPT * BPT)) "$CORPUS"; } > /dev/shm/fnconc-p.txt
jq -Rs '{prompt: ., max_tokens: 1, temperature: 0}' < /dev/shm/fnconc-p.txt > /dev/shm/fnconc-b.json
t0=$(date +%s.%N)
curl -s --max-time 900 -X POST "$URL/v1/completions" -H 'Content-Type: application/json' \
--data-binary @/dev/shm/fnconc-b.json > /dev/shm/fnconc-out.json
t1=$(date +%s.%N)
awk -v a="$t0" -v b="$t1" 'BEGIN { printf "%.2f", b - a }'
}
# C decoders, timed. `wait` would also wait on anything else this shell started, so the pids are
# collected and waited on by name.
decoders_wall() {
t0=$(date +%s.%N); pids=
i=0; while [ "$i" -lt "$C" ]; do decoder "d$1$i" & pids="$pids $!"; i=$((i + 1)); done
for p in $pids; do wait "$p"; done
t1=$(date +%s.%N)
awk -v a="$t0" -v b="$t1" 'BEGIN { printf "%.2f", b - a }'
}
arm() {
tag="$1"
alone=$(decoders_wall "a$tag")
t0=$(date +%s.%N); pids=
i=0; while [ "$i" -lt "$C" ]; do decoder "c$tag$i" & pids="$pids $!"; i=$((i + 1)); done
lw=$(long_request)
for p in $pids; do wait "$p"; done
t1=$(date +%s.%N)
cont=$(awk -v a="$t0" -v b="$t1" 'BEGIN { printf "%.2f", b - a }')
pt=$(jq -r '.usage.prompt_tokens // 0' /dev/shm/fnconc-out.json)
awk -v al="$alone" -v co="$cont" -v lw="$lw" -v pt="$pt" -v t="$tag" 'BEGIN {
printf " %-10s decoders alone %6.2f s beside a prefill %6.2f s (%+5.1f%%) prefill %6.2f s = %.0f tok/s\n",
t, al, co, 100 * (co - al) / al, lw, pt / lw;
}'
}
echo "$C decoders x $DEC tokens, long prompt ~$PROMPT tokens, server $URL"
arm "warm"
arm "pass1"
arm "pass2"
+97
View File
@@ -0,0 +1,97 @@
#!/bin/sh
# What happens when a client goes away mid-request, against a server that is ALREADY RUNNING.
#
# WHY THIS EXISTS. A disconnect calls the scheduler's reap at an arbitrary point in the step loop,
# so anything that holds a raw Request* across that point -- the step plan's entry, a drafter's
# snapshot -- is a use-after-free that takes the whole server down. Every other harness in this
# tree waits for its requests, so none of them can see that.
#
# SURVIVING IS NOT THE TEST. A server that stays up and then answers differently has a freed slot
# feeding a live sequence, which is the same defect wearing a quieter shirt. So a reference answer
# is taken first, the drops happen, and the same question is asked again: the hashes have to match.
#
# THE DROP POINTS ARE DERIVED, NOT WRITTEN DOWN. One full request is timed first and the drops are
# placed at fractions of it, because a drop point past the end of the request is not a drop at all
# -- it is curl waiting for a response that already arrived, and it reports PASS having exercised
# nothing.
#
# `--max-time` is the disconnect: curl closes the socket where it lands. A drop is confirmed by
# `running` falling back to zero well before the request would have finished on its own.
#
# EVERY OBSERVATION COUNTS, NOT THE LAST ONE. A transient divergence right after a burst is the
# interesting case and a final re-check hides it: ask again and the answer is right, so the run
# reports clean. The verdict below is over all of them.
#
# AND ONE DIVERGENCE IS NOT A FINDING HERE. A single completion hash can diverge on an unchanged
# binary -- concurrency decides batch composition and greedy decoding differs at a tie -- so a
# diverged row means RUN IT AGAIN, several times, before believing it. The reference question
# itself is stable against an idle server; it is the contended path that can tie-flip.
#
# P=8100 scripts/fndrop.sh
P="${P:-8100}"
H="${H:-127.0.0.1}"
ROOT="${ROOT:-$(dirname "$0")/..}"
URL="http://$H:$P"
C=/dev/shm/fndrop-corpus.txt
BPT=3
LONG="${LONG:-20000}" # tokens of prompt, so prefill is a measurable slice
GEN="${GEN:-3000}" # tokens of generation, so decode is a long one too
want=$((LONG * BPT + 8192))
touch "$C"
[ "$(wc -c < "$C")" -ge "$want" ] || { : > "$C"
while [ "$(wc -c < "$C")" -lt "$want" ]; do cat "$ROOT"/spec.md "$ROOT"/docs/*.md >> "$C" 2>/dev/null || exit 1; done; }
alive() { pgrep -f "bin/radianc[e]" >/dev/null && echo ALIVE || echo DEAD; }
healthy() { curl -s -m 5 "$URL/health" >/dev/null 2>&1 && echo ok || echo unreachable; }
running() { curl -s -m 5 "$URL/stats" | jq -r '.running // "?"'; }
ref() {
curl -s -m 300 -X POST "$URL/v1/completions" -H 'Content-Type: application/json' \
-d '{"prompt":"List the first five prime numbers, comma separated.","max_tokens":48,
"temperature":0}' | jq -r '.choices[0].text // "ERR"' | sha256sum | cut -c1-16
}
body() {
{ printf 'drop %s\n\n' "$(date +%s%N)"; head -c $((LONG * BPT)) "$C"; } > /dev/shm/fndrop-p.txt
jq -Rs --argjson g "$GEN" '{prompt: ., max_tokens: $g, ignore_eos: true, temperature: 0}' \
< /dev/shm/fndrop-p.txt > /dev/shm/fndrop-b.json
}
send() { body; curl -s -m "$1" -o /dev/null -X POST "$URL/v1/completions" \
-H 'Content-Type: application/json' --data-binary @/dev/shm/fndrop-b.json 2>/dev/null; return 0; }
echo "server $URL, prompt ~$LONG tokens + $GEN generated"
base=$(ref)
t0=$(date +%s.%N); send 900; t1=$(date +%s.%N)
FULL=$(awk -v a="$t0" -v b="$t1" 'BEGIN{printf "%.0f", b-a}')
[ "$FULL" -lt 6 ] && { echo "a full request is only ${FULL}s -- raise LONG or GEN so the phases are separable"; exit 1; }
printf ' a full request takes %ss; dropping inside it\n' "$FULL"
printf ' %-40s %-7s %-10s %-9s %s\n' step alive health 'running+2s' answer
printf ' %-40s %-7s %-10s %-9s %s <- reference\n' "before any drop" "$(alive)" "$(healthy)" "-" "$base"
BAD=0; SEEN=0
observe() { # $1 = label; records the answer against the reference rather than only printing it
a=$(ref); SEEN=$((SEEN + 1)); [ "$a" = "$base" ] || BAD=$((BAD + 1))
printf " %-40s %-7s %-10s %-9s %s%s\n" "$1" "$(alive)" "$(healthy)" "$(running)" "$a" \
"$( [ "$a" = "$base" ] || echo " <- DIVERGED" )"
}
drop() { # $1 = seconds, $2 = label
send "$1"; sleep 2; observe "$2"
}
drop $((FULL / 8 + 1)) "dropped at 1/8 of it (early prefill)"
drop $((FULL / 3 + 1)) "dropped at 1/3 of it"
drop $((FULL / 2 + 1)) "dropped at 1/2 of it"
drop $((FULL * 3 / 4)) "dropped at 3/4 of it (deep in decode)"
for s in $((FULL / 4 + 1)) $((FULL / 3 + 1)) $((FULL / 4 + 1)) $((FULL / 2 + 1)); do send "$s" & done
send 900 &
wait
sleep 2
observe "four concurrent drops + one survivor"
echo
if [ "$BAD" -eq 0 ]; then
printf ' all %d answers matched the reference\n' "$SEEN"
else
printf ' %d of %d answers DIVERGED from the reference -- run it again before believing it\n' \
"$BAD" "$SEEN"
fi
+78
View File
@@ -0,0 +1,78 @@
#!/bin/sh
# Prefill throughput against a server that is ALREADY RUNNING, and nothing else.
#
# WHY IT IS NOT A SERVE HARNESS. Prefill speed is a property of the deployment's flags -- the
# chunk, the tensor-parallel width, the expert/cache split -- so a harness that brings its own
# server measures the flags it chose rather than the ones in use. This one attaches to whatever is
# on $P and reports what that server does; use scripts/fnserve.sh to put one there.
#
# THE PROMPT IS PROSE, NOT RANDOM WORDS. A generated word of random letters is three tokens rather
# than one, so a token target computed from a word count is off by a factor of three -- and, worse,
# a stream of tokens the model has never seen together routes differently through a mixture of
# experts than text does, which is the thing a prefill measurement is mostly measuring. The corpus
# is the repository's own markdown, repeated to length.
#
# THE PREFIX CACHE MAKES A SECOND REP FREE, so every rep opens with a different nonce. A cache
# matches from the START of the prompt, so a leading nonce invalidates the whole match while a
# trailing one would leave every block but the last a hit -- and the run would report a prefill
# rate for work that was never done. `cached_tokens` is printed so that this is visible rather
# than assumed.
#
# THE CARD'S CLOCK IS PART OF THE MEASUREMENT. Prefill drifts downward over a sustained run as the
# part heats, monotonically and across runs as well as within them, so a single number is not
# comparable across runs taken at different times. Temperature and sclk are printed beside every
# rep for the same reason a bench prints its build id: without them a thermostat reads as a
# regression.
#
# P=8100 N=8000 REPS=3 scripts/fnpf.sh
#
# N is a token TARGET reached through an assumed bytes-per-token; the rate is computed from the
# `prompt_tokens` the server reports, so the approximation does not enter the answer.
P="${P:-8100}"
H="${H:-127.0.0.1}"
N="${N:-8000}"
REPS="${REPS:-3}"
BPT="${BPT:-4}" # bytes of this corpus per token, measured at about 4.0
ROOT="${ROOT:-$(dirname "$0")/..}"
URL="http://$H:$P"
CORPUS="${CORPUS:-/dev/shm/fnpf-corpus.txt}"
# One corpus, built once and reused, so successive runs prefill the same bytes. GROWN when a
# later run wants more than the last one did: `head -c` on a corpus that is too short silently
# returns what there is, so a sweep that raised N would report a rate for a prompt it did not
# send -- and the prompt_tokens column makes that visible only to a reader who was looking.
want=$((N * BPT + 4096))
if [ "$(wc -c < "$CORPUS" 2>/dev/null || echo 0)" -lt "$want" ]; then
: > "$CORPUS"
while [ "$(wc -c < "$CORPUS")" -lt "$want" ]; do
cat "$ROOT"/spec.md "$ROOT"/docs/*.md >> "$CORPUS" 2>/dev/null || exit 1
done
fi
card() {
rocm-smi --showtemp --showclocks --csv 2>/dev/null |
awk -F, 'NR>1 && $1 ~ /card/ { printf "%s ", $2 }' | head -c 48
}
stats() { curl -s --max-time 5 "$URL/stats"; }
echo "server $URL, target $N tokens, $REPS reps, corpus $(wc -c < "$CORPUS") bytes"
for r in $(seq 0 "$REPS"); do
{ printf 'request %s %s\n\n' "$r" "$(date +%s%N)"
head -c $((N * BPT)) "$CORPUS"
} > /dev/shm/fnpf-prompt.txt
jq -Rs '{prompt: ., max_tokens: 1, temperature: 0}' < /dev/shm/fnpf-prompt.txt \
> /dev/shm/fnpf-body.json
t0=$(date +%s.%N)
out=$(curl -s --max-time 1800 -X POST "$URL/v1/completions" \
-H 'Content-Type: application/json' --data-binary @/dev/shm/fnpf-body.json)
t1=$(date +%s.%N)
pt=$(printf '%s' "$out" | jq -r '.usage.prompt_tokens // "ERR"')
ct=$(printf '%s' "$out" | jq -r '.usage.prompt_tokens_details.cached_tokens // 0')
[ "$pt" = "ERR" ] && { echo " failed: $(printf '%s' "$out" | head -c 300)"; exit 1; }
awk -v t0="$t0" -v t1="$t1" -v pt="$pt" -v ct="$ct" -v r="$r" -v c="$(card)" 'BEGIN {
d = t1 - t0;
printf " %-6s %7d tok %6d cached %8.3f s %8.1f tok/s %s\n",
(r == 0 ? "warm" : "rep " r), pt, ct, d, pt / d, c;
}'
done
+122
View File
@@ -0,0 +1,122 @@
#!/bin/sh
# Bring up Qwen3.8-Flash-Next as a long-lived server and LEAVE IT RUNNING: start it, wait for
# /health, print the endpoints and exit with the server still up. The default container is the
# production one, w4nl64-i8lm.rad, built by data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe
# (scripts/convfn.sh).
#
# 200K CONTEXT, AND WHY THE RATIO IS 0.82 RATHER THAN 0.75. --max-model-len reserves nothing per
# request; it sets the WORST CASE that --expert-vs-cache-ratio sizes the paged pool against. At
# 200000 x 8 sequences the default 0.75 binds: the cache takes its full quarter of the elastic pool,
# and the routed experts it displaces fit in neither VRAM nor the host pool, so without
# --weights-disk-tier the planner refuses at load ("DID NOT FIT").
#
# The pool is a CAPACITY, not a per-request cap. A token costs 7.31 KiB across the two paged
# groups (kv_attn 26.00 KiB and kv_qsa_bkey 3.25 KiB per 4-token block), so one 200K sequence is
# 1.43 GiB. 0.87 is enough for one-shot requests (a 200K and a 120K sequence at once) but not
# for multi-turn ones: with prefix caching a finished sequence's blocks stay HELD so the next turn
# can reuse them, so the demand is the live SESSIONS, and a context of T tokens occupies about
# 1.8 x T pool tokens. At 0.87 two ~184K sessions do not fit, the cache evicts exactly what the
# next turn asks for, and every turn re-prefills its whole context (0% prefix hit; minutes per
# turn instead of seconds). 0.82 holds about two concurrent 200K sessions (99% hit on the second
# turn) for about 1.4% of decode step time, since the experts lose 5% of the elastic pool; 0.84
# holds one. Watch kv_util: the hit rate falls off a cliff between 0.75 and 0.81 of the pool.
#
# Defaults are the production shape (gpu-headroom-mib 96, expert-vs-cache-ratio 0.82,
# kv-cache-dtype fp8, max-num-batched-tokens 2048, tp 2, speculation depth 3), with the prefix
# cache on and --checkpoint-slots at its default, because multi-turn chat wants both.
#
# THE CHUNK IS 2048. `--max-num-batched-tokens` is the prefill chunk when checkpoints are off, and
# it sets how many routed rows the MoE GEMM sees at once. Part of the expert weight is not in
# VRAM (it is pinned host memory, read over the link inside the kernel), so a smaller chunk
# re-reads every expert's weight for fewer tokens: 2048 prefills about 55% faster than 512.
#
# - 4096 IS NOT A 4096 CHUNK: plan_chunk splits at --checkpoint-interval (2048) before the
# budget applies, so it runs 2048 chunks while the activation arena, which grows with the
# BUDGET and is charged before the expert/KV split, takes resident experts for a chunk it never
# gets. Startup names which of the two bound the chunk. A real 4096 chunk (with
# --checkpoint-interval 4096) is no faster either: the larger arena costs more resident experts
# than the amortisation returns.
# - It does not cost co-running decoders: queued behind a prefill that finishes sooner, they
# finish sooner at 2048 than at 512 (scripts/fnconc.sh measures both halves).
# - It does not cost the prefix cache: the KV pool loses about 3% to the larger arena and two
# ~180K sessions still hit 99% with no evictions.
# - It costs about 0.6% of decode step time at one stream (scripts/cstep2.sh), from the resident
# experts the arena takes; at eight streams the difference is below what the harness resolves.
# - It changes the text. A different chunk is a different batch shape, so a prefill sums in a
# different order and a tie can land on a different token; each chunk size is stable on its
# own. Pin the chunk before recording anything to compare against later.
#
# THE PREFIX CACHE IS TIERED, AND THE ENGINE LEAVES THE TIERS OFF BY DEFAULT. Both
# --prefix-cache-host-mib and --prefix-cache-disk-mib are zero unless asked for, so a server started
# without them drops a conversation's context the moment the pool needs the blocks. This deployment
# keeps finished turns in host memory and then on disk, where they cost the card nothing.
#
# The ELASTIC half needs no flag and cannot be turned off: the pool holds the blocks it is using
# plus a buffer derived from the chunk, and the expert slab takes the VRAM it releases. That leans
# on --gpu-headroom-mib, which is why the 96 above matters -- startup names any shortfall and holds
# it back on top of the reserve.
#
# --prefix-cache-host-mib finished conversations are copied here at once and their VRAM goes
# to the expert slab; a return restores instead of re-prefilling. Part
# of it is the linear-state snapshot store, sized in proportion to what
# a session holds in snapshots against blocks; startup says how many
# snapshots it holds. On this model a snapshot is 113 MiB and
# --checkpoint-slots counts snapshots for the whole server, not per
# sequence, so the snapshot store is the binding resource: without it
# only the conversations whose snapshots are still in a device slot
# resume without re-prefilling their whole transcript.
# --prefix-cache-disk-mib every host copy is also written to disk under --prefix-cache-dir, so
# a full host tier gives its oldest slots up for nothing. Costs no RAM
# and no VRAM. It holds conversation content UNENCRYPTED.
#
# THE HOST NUMBER IS DELIBERATELY SMALL BECAUSE OF THE N-GRAM TABLE. The tier's arena is PINNED,
# and the 47.68 GiB n-gram (PLE) table is read through the container's own mmap, so it lives in
# the page cache -- and pinned bytes come out of the same host RAM. Taking too much here turns a
# decode step's minor faults into major ones, a far worse trade than a smaller snapshot store.
# Watch /proc/<pid>/stat majflt across a prefill before raising it.
#
# THE CROSS-RANK WIRE IS THE ROTATED 6-BIT ONE (--tp-wire wht6). An all-reduce at or above
# --tp-wire-min-kb (128 KiB: every prefill chunk, and decode from seven streams up) carries a
# Walsh-Hadamard-rotated 6-bit payload instead of bf16 -- 2.6x fewer bytes over PCIe -- inside the
# gated residual's fused writes. Against the exact wire at a 2048-token chunk it prefills about 6%
# faster and decodes about 1% faster at eight streams; at one stream nothing changes, because its
# messages stay under the floor and go exact.
#
# IT IS LOSSY, by about as much as a trade this model already makes. Over greedy continuations of
# 160 code and prose prompts, compared at every position while the two prefixes still agree, wht6
# agrees with the exact wire at 91.4% of positions -- the same as E4M3 hyper-connection matrices
# against bf16 ones (91.3%), which the container already carries. WIRE=exact serves the exact wire.
#
# Binds 0.0.0.0 so a client on another host can reach it. Stop it with scripts/fnstop.sh.
P="${P:-8100}"
M="${M:-$HOME/models/rad/w4nl64-i8lm.rad}"
cd "$HOME/workspace/radiance/build" || exit 1
pkill -f "bin/radianc[e]"; while pgrep -f "bin/radianc[e]" >/dev/null; do sleep 1; done; sleep 2
env GPU_MAX_ALLOC_PERCENT=100 GPU_MAX_HEAP_SIZE=100 $EXTRA_ENV \
nohup ./bin/radiance --model "$M" \
--radiance-home "$HOME/workspace/radiance/build/radiance_home" \
--host 0.0.0.0 --port "$P" \
--max-num-seqs ${SEQS:-8} --max-model-len ${MLEN:-200000} \
--tp ${TP:-2} --placement expert_tiered --host-pool-mib ${HOSTPOOL:-12288} \
--gpu-headroom-mib ${HR:-96} --expert-vs-cache-ratio ${RATIO:-0.82} --kv-cache-dtype ${KVD:-fp8} \
--prefix-cache-host-mib ${KVHOST:-4096} \
--prefix-cache-dir ${KVDIR:-$HOME/kvcache} --prefix-cache-disk-mib ${KVDISK:-131072} \
--num-speculative-tokens ${NS:-3} \
--max-num-batched-tokens ${MNBT:-2048} \
--tp-wire ${WIRE:-wht6} \
$EXTRA > "$HOME/fnserve.log" 2>&1 &
echo "starting, log: ~/fnserve.log"
for i in $(seq 1 150); do
[ "$(curl -s -m 3 -o /dev/null -w %{http_code} http://localhost:$P/health 2>/dev/null)" = 200 ] && break
pgrep -f "bin/radianc[e]" >/dev/null || { echo "DIED after ${i}x4s"; grep -iE "^E |error|refus" "$HOME/fnserve.log" | tail -20; exit 1; }
sleep 4
done
[ "$(curl -s -m 3 -o /dev/null -w %{http_code} http://localhost:$P/health 2>/dev/null)" = 200 ] || {
echo "DID NOT START in 10 min"; grep -iE "^E |error" "$HOME/fnserve.log" | tail -20; exit 1; }
IP=$(ip -4 -o addr show scope global | awk '{split($4,a,"/"); print a[1]; exit}')
echo "UP pid $(pgrep -f "bin/radianc[e]" | tr "\n" " ")"
echo " completions http://$IP:$P/v1/completions"
echo " chat http://$IP:$P/v1/chat/completions"
echo " dashboard http://$IP:$P/"
echo " metrics http://$IP:$P/metrics"
grep -iE "serving on|listening on|KV cache|placement" "$HOME/fnserve.log" | tail -8
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
pkill -f "bin/radianc[e]" && echo "stopping" || echo "not running"
while pgrep -f "bin/radianc[e]" >/dev/null; do sleep 1; done
echo "stopped"
+83
View File
@@ -0,0 +1,83 @@
#!/bin/sh
# Qwen3.8-Flash-Next PREFILL under rocprofv3 kernel tracing, and the link counters beside it.
#
# WHAT IT ANSWERS. `moe_gemm_q` is the largest item in a prefill step and most of what it waits on
# is expert weight that is not resident, read where it lies -- which for a host-pooled unit means
# crossing the link inside the kernel. Neither half of that is visible alone: a trace says how long
# the GEMM ran and says nothing about bytes, and /stats says how many bytes were streamed and
# nothing about when. Taking both across the same run gives the rate the streamed read actually
# achieves, which is the only number that says whether the kernel is at the link's ceiling or
# leaving it idle.
#
# PREFILL ONLY, AND THAT IS WHY tsum's WINDOW IS NOT USED. tsum.sh keys its steady-state window on
# a marker that fires once per DECODE step; with max_tokens 1 there is no such run, so it falls
# back to summing the whole trace and every number is per RUN. That is what isolation wants here --
# the run IS the prefill -- but it does mean the model load's own kernels are in the total, so the
# prompt has to be long enough that they are noise.
#
# N=20000 OUT=<trace dir> scripts/fntrace.sh
#
# The default container is the production one, w4nl64-i8lm.rad (see scripts/fnserve.sh).
P="${P:-8164}"
M="${M:-$HOME/models/rad/w4nl64-i8lm.rad}"
N="${N:-20000}"
BPT="${BPT:-4}"
OUT="${OUT:-$HOME/traces/fnpf}"
ROOT="${ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
CORPUS=/dev/shm/fntrace-corpus.txt
cd "$HOME/workspace/radiance/build" || exit 1
want=$((N * BPT + 4096))
if [ "$(wc -c < "$CORPUS" 2>/dev/null || echo 0)" -lt "$want" ]; then
: > "$CORPUS"
while [ "$(wc -c < "$CORPUS")" -lt "$want" ]; do
cat "$ROOT"/spec.md "$ROOT"/docs/*.md >> "$CORPUS" 2>/dev/null || exit 1
done
fi
pkill -f "bin/radianc[e]"; while pgrep -f "bin/radianc[e]" >/dev/null; do sleep 1; done; sleep 2
rm -rf "$OUT"; mkdir -p "$OUT"
env GPU_MAX_ALLOC_PERCENT=100 GPU_MAX_HEAP_SIZE=100 $EXTRA_ENV \
"$ROOT/libr4d/isa/trace.sh" "$OUT" -- \
./bin/radiance --model "$M" \
--radiance-home "$HOME/workspace/radiance/build/radiance_home" \
--host 127.0.0.1 --port "$P" \
--max-num-seqs ${SEQS:-8} --max-model-len ${MLEN:-200000} \
--tp ${TP:-2} --placement expert_tiered --host-pool-mib ${HOSTPOOL:-12288} \
--gpu-headroom-mib ${HR:-96} --expert-vs-cache-ratio ${RATIO:-0.82} --kv-cache-dtype ${KVD:-fp8} \
--num-speculative-tokens ${NS:-3} \
--max-num-batched-tokens ${MNBT:-2048} \
$EXTRA > "$HOME/fntrace.log" 2>&1 &
for i in $(seq 1 150); do
[ "$(curl -s -m 3 -o /dev/null -w %{http_code} http://127.0.0.1:$P/health 2>/dev/null)" = 200 ] && break
pgrep -f "bin/radianc[e]" >/dev/null || { echo "DIED"; grep -iE "^E |error" "$HOME/fntrace.log" | tail -10; exit 1; }
sleep 4
done
[ "$(curl -s -m 3 -o /dev/null -w %{http_code} http://127.0.0.1:$P/health)" = 200 ] || { echo "DID NOT START"; exit 1; }
st() { curl -s -m 5 "http://127.0.0.1:$P/stats" | jq -r ".link.$1 // 0"; }
s0=$(st stream_bytes); a0=$(st ar_bytes); h0=$(st h2d_bytes)
{ printf 'trace %s\n\n' "$(date +%s%N)"; head -c $((N * BPT)) "$CORPUS"; } > /dev/shm/fntrace-p.txt
jq -Rs '{prompt: ., max_tokens: 1, temperature: 0}' < /dev/shm/fntrace-p.txt > /dev/shm/fntrace-b.json
t0=$(date +%s.%N)
out=$(curl -s -m 1800 -X POST "http://127.0.0.1:$P/v1/completions" \
-H 'Content-Type: application/json' --data-binary @/dev/shm/fntrace-b.json)
t1=$(date +%s.%N)
s1=$(st stream_bytes); a1=$(st ar_bytes); h1=$(st h2d_bytes)
pt=$(printf '%s' "$out" | jq -r '.usage.prompt_tokens // 0')
# UNDER rocprofv3 THE SERVER CAN REFUSE TO DIE ON SIGTERM. The profiler chains its own handler
# onto the signal and the process then sits in finalisation indefinitely -- so an unbounded wait
# here loses the run, and the trace CSV is already on disk by that point. Escalate rather than
# spin.
pkill -f "bin/radianc[e]"
i=0; while pgrep -f "bin/radianc[e]" >/dev/null && [ $i -lt 30 ]; do sleep 1; i=$((i + 1)); done
pgrep -f "bin/radianc[e]" >/dev/null && { echo "did not exit on TERM under the profiler, killing"; pkill -9 -f "bin/radianc[e]"; sleep 2; }
awk -v t0="$t0" -v t1="$t1" -v pt="$pt" -v s="$((s1 - s0))" -v a="$((a1 - a0))" -v h="$((h1 - h0))" 'BEGIN {
d = t1 - t0;
printf "\nprefill %d tok in %.3f s = %.1f tok/s\n", pt, d, pt / d;
printf " streamed %10.2f GB over the request (%.2f GB/s over its wall, ALL ranks)\n", s/1e9, s/1e9/d;
printf " promotions %10.2f GB all-reduce %8.2f GB\n", h/1e9, a/1e9;
printf "\nDivide the streamed GB by moe_gemm_q device time below for the rate the read achieves.\n";
}'
sh "$ROOT/libr4d/isa/tsum.sh" "$OUT/k_kernel_trace.csv"
+107
View File
@@ -0,0 +1,107 @@
#!/bin/sh
# hfget.sh -- fetch a Hugging Face repo with curl and jq, and nothing else.
#
# The engine and its tooling do not depend on Python, so `huggingface-cli` is not assumed. The API
# gives a file listing as JSON and every file has a stable resolve/ URL, which is all a downloader
# needs.
#
# scripts/hfget.sh <repo-id> [dest-dir] [revision]
#
# Set HF_TOKEN for a gated or private repo. Re-running resumes: a file whose local size already
# matches the listing is skipped and a short one is continued with `curl -C -`, so an interrupted
# transfer of a 300 GB checkpoint costs only what it had not finished.
#
# WEIGHT DUPLICATES ARE SKIPPED. Many repos carry the same tensors several times over -- safetensors
# beside the older pickle .bin, an ONNX export, a GGUF conversion -- and on a large checkpoint each
# copy is hundreds of gigabytes of the same numbers. When the listing holds any .safetensors, every
# other weight format is left behind.
#
# HFGET_JOBS concurrent transfers, default 4. These are long sequential reads: a few streams
# saturate the link and more only makes the destination seek.
set -e
# ---- child mode: one file, named by "<size><tab><path>" in $1, everything else inherited -------
# sh cannot export a function, so parallelism is one re-entry of this script per file under
# `xargs -P` rather than a worker pool.
if [ -n "$HFGET_CHILD" ]; then
size=${1%% *}; path=${1#* }
out=$HFGET_DEST/$path
if [ -f "$out" ]; then
cur=$(wc -c < "$out")
if [ "$cur" = "$size" ]; then echo " = $path"; exit 0; fi
echo " + $path (resuming at $cur of $size)"
else
echo " > $path"
fi
mkdir -p "$(dirname "$out")"
if [ -n "$HF_TOKEN" ]; then
curl -sSL --fail --retry 5 --retry-delay 5 --retry-all-errors -C - \
-H "Authorization: Bearer $HF_TOKEN" \
-o "$out" "https://huggingface.co/$HFGET_REPO/resolve/$HFGET_REV/$path"
else
curl -sSL --fail --retry 5 --retry-delay 5 --retry-all-errors -C - \
-o "$out" "https://huggingface.co/$HFGET_REPO/resolve/$HFGET_REV/$path"
fi
got=$(wc -c < "$out")
[ "$got" = "$size" ] || { echo "hfget: $path is $got bytes, listing says $size" >&2; exit 1; }
exit 0
fi
# ---- parent ------------------------------------------------------------------------------------
repo=$1
[ -n "$repo" ] || { echo "usage: hfget.sh <repo-id> [dest-dir] [revision]" >&2; exit 2; }
dest=${2:-$HOME/models/$repo}
rev=${3:-main}
jobs=${HFGET_JOBS:-4}
command -v jq >/dev/null || { echo "hfget: jq is required" >&2; exit 2; }
echo "hfget: listing $repo@$rev"
# THE LISTING IS PAGINATED AND THE PAGE SIZE IS SMALL. A large checkpoint runs to a hundred-odd
# shards and the API returns fifty entries with a `Link: ...; rel="next"` header. Taking only the
# first page is the worst possible failure here: every file it did fetch is the right length, so
# the size check passes and the converter is handed a checkpoint missing two thirds of its
# tensors. Follow the cursor until there is no next link.
api="https://huggingface.co/api/models/$repo/tree/$rev?recursive=true&expand=true"
listing='[]'
page=0
while [ -n "$api" ]; do
hdr=$(mktemp "${TMPDIR:-/tmp}/hfhdr.XXXXXX")
if [ -n "$HF_TOKEN" ]; then
body=$(curl -sSL --fail-with-body -D "$hdr" -H "Authorization: Bearer $HF_TOKEN" "$api")
else
body=$(curl -sSL --fail-with-body -D "$hdr" "$api")
fi
[ "$(printf '%s' "$body" | jq -r 'type')" = "array" ] || {
rm -f "$hdr"
echo "hfget: $(printf '%s' "$body" | jq -r '.error // .message // .')" >&2
echo "hfget: a gated or private repo needs HF_TOKEN in the environment" >&2; exit 1; }
listing=$(printf '%s\n%s' "$listing" "$body" | jq -s 'add')
api=$(tr -d '\r' < "$hdr" | sed -n 's/^[Ll]ink: *<\([^>]*\)>; *rel="next".*/\1/p' | head -1)
rm -f "$hdr"
page=$((page + 1))
[ "$page" -gt 200 ] && { echo "hfget: listing did not terminate after 200 pages" >&2; exit 1; }
done
echo "hfget: $page page(s) of listing"
have_st=$(printf '%s' "$listing" | jq '[.[] | select(.path | endswith(".safetensors"))] | length')
sel='.[] | select(.type == "file")'
[ "$have_st" -gt 0 ] && sel="$sel"' | select((.path | test("\\.(bin|pth|msgpack|h5|onnx|onnx_data|gguf)$")) | not)'
list=$(mktemp "${TMPDIR:-/tmp}/hfget.XXXXXX")
trap 'rm -f "$list"' EXIT INT TERM
printf '%s' "$listing" | jq -r "$sel"' | "\(.size)\t\(.path)"' > "$list"
n=$(wc -l < "$list")
[ "$n" -gt 0 ] || { echo "hfget: the listing has no files" >&2; exit 1; }
need=$(awk -F'\t' '{s += $1} END {printf "%.1f", s / 1073741824}' "$list")
mkdir -p "$dest"
free=$(df -BG --output=avail "$dest" | tail -1 | tr -dc '0-9')
echo "hfget: $n file(s), $need GiB -> $dest"
[ "$have_st" -gt 0 ] && echo "hfget: safetensors present, pickle weight formats skipped"
echo "hfget: $free GiB free on the destination filesystem"
awk -v n="$need" -v f="$free" 'BEGIN { if (n > f) { print "hfget: THE DOWNLOAD DOES NOT FIT"; exit 1 } }'
export HFGET_CHILD=1 HFGET_DEST="$dest" HFGET_REPO="$repo" HFGET_REV="$rev"
self=$(cd "$(dirname "$0")" && pwd)/$(basename "$0")
tr '\n' '\0' < "$list" | xargs -0 -P "$jobs" -I{} sh "$self" "{}" \
|| { echo "hfget: incomplete -- re-run to resume" >&2; exit 1; }
echo "hfget: complete -- $(du -sh "$dest" | cut -f1) in $dest"
+38
View File
@@ -0,0 +1,38 @@
#!/bin/sh
# ident.sh -- is this server reproducible? One hash per (temperature, question), so a run can be
# compared against another run of the SAME configuration.
#
# WHAT IT PROVES: run-to-run determinism at a fixed configuration, across restarts. On
# Qwen3.8-Flash-Next at tp2 with the MTP head at depth 3, two servers started from scratch give
# the same six hashes: temperature 0, 0.7 and 1.0, both questions.
#
# WHAT IT DOES NOT PROVE: that a SPECULATIVE run matches a NON-SPECULATIVE one byte for byte.
# `narrow_ksplit` chooses the split count of the fp8 GEMM's finisher from M, so the same row
# computed at M=1 (one token at a time) and at M=8 (a verify block) is not bit-identical, and a
# long answer can flip a near-tie somewhere past its first few hundred characters, both
# continuations equally good. `--deterministic` does not change that -- it pins placement and
# never reaches a kernel.
#
# BUT A SHORT COMMON PREFIX IS A DEFECT, NOT A TIE. On Qwen3.8-Flash-Next at tp2, depth 3 against
# --num-speculative-tokens 0 gives the same six hashes here, and over longer answers the two agree
# for hundreds of characters before any flip. A speculative run that leaves the non-speculative
# text within the first sentence or two is computing something different after a rejected draft --
# rolling state read from a rejected token is exactly that shape -- and is worth bisecting. If
# byte-identity across that boundary is ever required everywhere, the work is plumbing a pinned
# split count into the fp8 GEMM, and it costs throughput at one M or the other.
#
# P=8100 scripts/ident.sh # against a server already up
P=${P:-8100}
WORK=$(mktemp -d "${TMPDIR:-/tmp}/ident.XXXXXX"); trap 'rm -rf "$WORK"' EXIT INT TERM
ask() {
jq -n --arg p "$2" --argjson t "$1" \
'{model:"m",messages:[{role:"user",content:$p}],max_tokens:200,temperature:$t,seed:12345,
chat_template_kwargs:{enable_thinking:false}}' > "$WORK/iq.json"
curl -s -m 900 http://localhost:$P/v1/chat/completions -H "Content-Type: application/json" \
-d @"$WORK/iq.json" | jq -r '.choices[0].message.content' | sha256sum | cut -c1-16
}
Q1="Implement an LRU cache in Go with a fixed capacity and a small test."
Q2="Explain why merge sort is O(n log n), briefly."
for T in 0 0.7 1.0; do
printf "temp %-4s %s %s\n" "$T" "$(ask $T "$Q1")" "$(ask $T "$Q2")"
done
+24
View File
@@ -0,0 +1,24 @@
#!/bin/sh
# What speculation is worth on the AGENT's OWN WORKLOAD: /v1/chat/completions with tools, which
# is a constrained decode. Arms alternate across server restarts because n_spec is a server-level
# setting and cannot be varied inside one process.
T='[{"type":"function","function":{"name":"write","description":"write a file","parameters":{"type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"}},"required":["path","content"]}}},{"type":"function","function":{"name":"bash","description":"run a shell command","parameters":{"type":"object","properties":{"cmd":{"type":"string"}},"required":["cmd"]}}},{"type":"function","function":{"name":"read","description":"read a file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}}]'
Q="Write a long, heavily commented C implementation of a chess board representation with FEN parsing, then explain every design decision in detail."
U="http://127.0.0.1:8111"
m() { curl -s -m 10 "$U/metrics" | grep -F "$1" | grep -v '^#' | awk '{print $NF}' | head -1; }
arm() { # $1 label $2 extra
P=8111 TP=2 MLEN=16384 SEQS=8 EXTRA="$2" sh "$(dirname "$0")/mcserve.sh" >/dev/null 2>&1 || { echo "$1 DIED"; return; }
curl -s -m 300 -o /dev/null "$U/v1/completions" -H 'Content-Type: application/json' -d '{"model":"q","prompt":"warm","max_tokens":32,"temperature":0}'
s0=$(m 'radiance:engine_steps_decode_total'); d0=$(m 'radiance:decode_tokens_total')
t0=$(date +%s.%N)
curl -s -m 600 -o /tmp/a.out "$U/v1/chat/completions" -H 'Content-Type: application/json' \
-d "{\"model\":\"m\",\"messages\":[{\"role\":\"user\",\"content\":\"$Q\"}],\"tools\":$T,\"max_tokens\":900,\"temperature\":0}"
t1=$(date +%s.%N)
s1=$(m 'radiance:engine_steps_decode_total'); d1=$(m 'radiance:decode_tokens_total')
n=$(jq -r '.usage.completion_tokens // 0' /tmp/a.out)
awk -v l="$1" -v t0="$t0" -v t1="$t1" -v n="$n" -v ds=$((s1-s0)) -v dd=$((d1-d0)) 'BEGIN{
if (ds<=0) { printf "%-14s NO STEPS\n", l; exit }
printf "%-14s %7.3f ms/step %6.3f tok/step %6.1f tok/s\n", l, 1000*(t1-t0)/ds, dd/ds, n/(t1-t0) }'
}
for pass in 1 2; do arm "spec-off" "--num-speculative-tokens 0"; arm "spec-auto" ""; done
pkill -f "bin/radianc[e]"
+25
View File
@@ -0,0 +1,25 @@
#!/bin/sh
# HOW OFTEN DOES THE DRAFTER ACTUALLY PROPOSE? draft_tokens_total/depth is the number of draft
# BLOCKS; over decode steps that is the fraction of steps that speculated at all. accept% is
# conditional on having drafted, so a high accept% with tok/step ~1.2 can only mean most steps
# never drafted. The server log says the drafter may DECLINE ("prompt lookup fills in").
P=8112; U="http://127.0.0.1:$P"
pad() { i=0; W=""; while [ $i -lt "$1" ]; do
W="$W static int eval_piece_$1_$i(const Board *b, int sq) { return b->squares[sq] * 100 + $i; }"
i=$((i+1)); done; printf '%s' "$W"; }
P=8112 TP=2 MLEN=131072 SEQS=8 sh "$(dirname "$0")/mcserve.sh" >/dev/null 2>&1 || { echo DIED; exit 1; }
g() { curl -s -m 10 "$U/metrics"|grep -F "$1"|grep -v '^#'|awk '{print $NF}'|head -1; }
printf '%8s %9s %9s %10s %10s %9s\n' ctx steps blocks blocks/step tok/step accept%
for N in 4 60 260 1040; do
jq -n --arg c "$(pad $N)" '{model:"m",max_tokens:400,temperature:0,
messages:[{role:"user",content:("Here is a file:\n\n"+$c+"\n\nSummarise what this code does in detail.")}]}' > /tmp/dc.json
s0=$(g engine_steps_decode_total); d0=$(g decode_tokens_total); r0=$(g draft_tokens_total); a0=$(g draft_accepted_total)
curl -s -m 900 -o /tmp/dc.out "$U/v1/chat/completions" -H 'Content-Type: application/json' -d @/tmp/dc.json
s1=$(g engine_steps_decode_total); d1=$(g decode_tokens_total); r1=$(g draft_tokens_total); a1=$(g draft_accepted_total)
awk -v ctx="$(jq -r '.usage.prompt_tokens // 0' /tmp/dc.out)" -v ds=$((s1-s0)) -v dd=$((d1-d0)) \
-v dr=$((r1-r0)) -v da=$((a1-a0)) 'BEGIN{
if(ds<=0){print " NO STEPS"; exit}
b=dr/7
printf "%8d %9d %9d %10.3f %10.3f %9.1f\n", ctx, ds, b, b/ds, dd/ds, (dr>0?100.0*da/dr:0) }'
done
pkill -f "bin/radianc[e]"
+45
View File
@@ -0,0 +1,45 @@
#!/bin/sh
# Bring up MiniCPM5-2B (fp8) as a long-lived server and LEAVE IT RUNNING.
#
# The sibling of scripts/fnserve.sh, for the small dense model. Same contract: start it, wait for
# /health, print the endpoints, exit with the server still up. Stop it with scripts/fnstop.sh.
#
# WHY THE VRAM FLAGS ARE ABSENT. This is a DENSE model, so every weight is static and the
# planner takes it off the top as a floor; --expert-vs-cache-ratio then divides an elastic pool
# that has no expert side to claim it, and the slack crosses over to the cache. Stating
# --vram-weights-mib here would only cap what does not need capping.
#
# WHY 131072 AND NOT 200000. n_ctx_train is 131072 for this checkpoint; the 200K context
# scripts/fnserve.sh serves is a property of the Flash-Next model, which a 2B model cannot honour.
#
# KV is 21.0 KiB a token at fp8 (42 layers x 2 kv heads x 128 x 2 planes), halved per rank at
# tp 2, so a full-length sequence costs 1.38 GiB a rank and 8 of them do not fit -- the pool is
# a capacity, not a per-request reservation, and it backs however many the cache can hold.
P="${P:-8100}"
M="${M:-$HOME/models/rad/minicpm5-2b-dspark.v2.rad}"
cd "$HOME/workspace/radiance/build" || exit 1
pkill -f "bin/radianc[e]"; while pgrep -f "bin/radianc[e]" >/dev/null; do sleep 1; done; sleep 2
env GPU_MAX_ALLOC_PERCENT=100 GPU_MAX_HEAP_SIZE=100 $EXTRA_ENV \
nohup ./bin/radiance --model "$M" \
--radiance-home "$HOME/workspace/radiance/build/radiance_home" \
--host 0.0.0.0 --port "$P" \
--max-num-seqs ${SEQS:-8} --max-model-len ${MLEN:-131072} \
--tp ${TP:-2} \
--gpu-headroom-mib ${HR:-160} --kv-cache-dtype ${KVD:-fp8} \
--max-num-batched-tokens ${MNBT:-512} \
$EXTRA > "$HOME/mcserve.log" 2>&1 &
echo "starting, log: ~/mcserve.log"
for i in $(seq 1 150); do
[ "$(curl -s -m 3 -o /dev/null -w %{http_code} http://localhost:$P/health 2>/dev/null)" = 200 ] && break
pgrep -f "bin/radianc[e]" >/dev/null || { echo "DIED after ${i}x4s"; grep -iE "^E |error|refus" "$HOME/mcserve.log" | tail -20; exit 1; }
sleep 4
done
[ "$(curl -s -m 3 -o /dev/null -w %{http_code} http://localhost:$P/health 2>/dev/null)" = 200 ] || {
echo "DID NOT START in 10 min"; grep -iE "^E |error" "$HOME/mcserve.log" | tail -20; exit 1; }
IP=$(ip -4 -o addr show scope global | awk "{split(\$4,a,\"/\"); print a[1]; exit}")
echo "UP pid $(pgrep -f "bin/radianc[e]" | tr "\n" " ")"
echo " completions http://$IP:$P/v1/completions"
echo " chat http://$IP:$P/v1/chat/completions"
echo " dashboard http://$IP:$P/"
echo " metrics http://$IP:$P/metrics"
grep -iE "serving on|listening on|KV cache|placement|budget" "$HOME/mcserve.log" | tail -10
+27
View File
@@ -0,0 +1,27 @@
#!/bin/sh
# Tool-call replies STREAMED, which is how an agent client talks to this server: content is sent
# as it grows and cannot be retracted, so a tool call repaired only at the end would leave the
# client showing the raw XML AND the call. Asserts on the RAW SSE bytes, not on the assembled
# message.
# The port is an override (P=, default 8100): this harness attaches to a server that is already
# up rather than starting one.
P=${P:-8100}
WORK=$(mktemp -d "${TMPDIR:-/tmp}/mcstream.XXXXXX"); trap 'rm -rf "$WORK"' EXIT INT TERM
T='[{"type":"function","function":{"name":"bash","description":"run a shell command","parameters":{"type":"object","properties":{"cmd":{"type":"string"}},"required":["cmd"]}}},{"type":"function","function":{"name":"write","description":"write a file","parameters":{"type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"}},"required":["path","content"]}}}]'
one() { # $1 label $2 prompt
curl -s -N -m 240 http://127.0.0.1:$P/v1/chat/completions -H 'Content-Type: application/json' \
-d "{\"model\":\"m\",\"messages\":[{\"role\":\"user\",\"content\":$2}],\"tools\":$T,\"stream\":true,\"max_tokens\":2500,\"temperature\":0}" > "$WORK/sse.txt"
# every content fragment the client would render, concatenated
jq -rj '.choices[0].delta.content // ""' < /dev/null 2>/dev/null
CONTENT=$(grep '^data: {' "$WORK/sse.txt" | sed 's/^data: //' | jq -rj '.choices[0].delta.content // ""' 2>/dev/null)
NCALLS=$(grep '^data: {' "$WORK/sse.txt" | sed 's/^data: //' | jq -r '[.choices[0].delta.tool_calls[]?.function.name//empty]|.[]' 2>/dev/null | grep -c . )
FIN=$(grep '^data: {' "$WORK/sse.txt" | sed 's/^data: //' | jq -r '.choices[0].finish_reason//empty' 2>/dev/null | grep -v '^$' | tail -1)
LEAK=no
case "$CONTENT" in *"<function"*|*"<param"*|*"CDATA"*|*"<tool_call>"*) LEAK=YES ;; esac
printf '%-16s finish=%-10s streamed-calls=%s LEAK-IN-STREAM=%s\n' "$1" "$FIN" "$NCALLS" "$LEAK"
[ "$LEAK" = YES ] && { echo " content was: $(printf '%s' "$CONTENT" | head -c 160)"; }
return 0
}
one "write-a-file" '"Write the file /work/hello.c containing a hello world program in C. Use the write tool."'
one "run-a-command" '"List the files in /work using the bash tool."'
one "plain-chat" '"In one sentence, what is a red-black tree?"'
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
# The four tool-call shapes that are hardest to parse -- an array argument, two calls in one
# reply, prose before a call, plain chat with tools available -- against a speculating container
# such as the DSpark one (scripts/mcserve.sh): speculation must not disturb the XML tool grammar.
# finish_reason tool_calls is the proof the SERVER parsed them; a call that comes back as prose in
# `content` is a call the parser did not close.
# The port is an override (P=, default 8100): this harness attaches to a server that is already
# up rather than starting one.
P=${P:-8100}
T='[{"type":"function","function":{"name":"edit","description":"edit a file","parameters":{"type":"object","properties":{"path":{"type":"string"},"edits":{"type":"array","items":{"type":"object","properties":{"oldText":{"type":"string"},"newText":{"type":"string"}}}}},"required":["path","edits"]}}},{"type":"function","function":{"name":"bash","description":"run a shell command","parameters":{"type":"object","properties":{"cmd":{"type":"string"}},"required":["cmd"]}}},{"type":"function","function":{"name":"write","description":"write a file","parameters":{"type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"}},"required":["path","content"]}}}]'
ask() { # $1 label $2 user message
r=$(curl -s -m 180 http://127.0.0.1:$P/v1/chat/completions -H 'Content-Type: application/json' \
-d "{\"model\":\"m\",\"messages\":[{\"role\":\"user\",\"content\":$2}],\"tools\":$T,\"max_tokens\":2500,\"temperature\":0}")
echo "$r" | jq -c --arg l "$1" '{test:$l, finish:.choices[0].finish_reason,
calls:[.choices[0].message.tool_calls[]?|{n:.function.name,a:(.function.arguments|tostring|.[0:90])}],
leak:(.choices[0].message.content//""|test("<function|<param|CDATA")),
content:((.choices[0].message.content//"")|.[0:70])}'
}
ask "edit-array-arg" '"In /work/t.py change the text def minimise: to def minimax: -- use the edit tool."'
ask "two-calls" '"Run ls /work and then run pwd, using the bash tool for each."'
ask "prose-then-call" '"Create /work/h.py containing print(\"hello\"). Explain what you will do first, then do it."'
ask "plain-chat" '"In one sentence, what is a hash map?"'
+32
View File
@@ -0,0 +1,32 @@
#!/bin/sh
# MiniCPM5-2B decode under rocprofv3 kernel tracing. The BLOCKS column is what this is for:
# a 2B dense model at tp2 has tiny N per rank, so every decode GEMM is a candidate for grid
# collapse -- 2048/tile_n workgroups on a 64-CU card leave most of it idle.
# N=<decode tokens> OUT=<trace dir> scripts/mctrace.sh
P=8102
M="${M:-$HOME/models/rad/minicpm5-2b-dspark.v2.rad}"
N="${N:-140}"
OUT="${OUT:-$HOME/traces/mc}"
cd "$HOME/workspace/radiance/build" || exit 1
pkill -f "bin/radianc[e]"; while pgrep -f "bin/radianc[e]" >/dev/null; do sleep 1; done; sleep 2
rm -rf "$OUT"; mkdir -p "$OUT"
env GPU_MAX_ALLOC_PERCENT=100 GPU_MAX_HEAP_SIZE=100 $EXTRA_ENV \
"$HOME/workspace/radiance/libr4d/isa/trace.sh" "$OUT" -- \
./bin/radiance --model "$M" \
--radiance-home "$HOME/workspace/radiance/build/radiance_home" \
--max-num-seqs 8 --max-model-len 16384 --tp 2 \
--gpu-headroom-mib 160 --kv-cache-dtype fp8 --max-num-batched-tokens 512 \
$EXTRA --port $P > "$HOME/mctrace.log" 2>&1 &
for i in $(seq 1 90); do
[ "$(curl -s -m 3 -o /dev/null -w %{http_code} http://localhost:$P/health 2>/dev/null)" = 200 ] && break
pgrep -f "bin/radianc[e]" >/dev/null || { echo DIED; tail -5 "$HOME/mctrace.log"; exit 1; }
sleep 2
done
curl -s -m 900 http://localhost:$P/v1/completions -H "Content-Type: application/json" \
-d "{\"model\":\"m\",\"prompt\":\"Write a long essay about the sea.\",\"max_tokens\":$N,\"temperature\":0,\"ignore_eos\":true}" -o /tmp/mct.out
echo "completion=$(jq -r .usage.completion_tokens /tmp/mct.out 2>/dev/null)"
pkill -f "bin/radianc[e]"
for i in $(seq 1 60); do pgrep -f "bin/radianc[e]" >/dev/null || break; sleep 1; done
for i in $(seq 1 120); do [ -s "$OUT/k_kernel_trace.csv" ] && break; sleep 2; done
for i in $(seq 1 60); do pgrep -f rocprofv[3] >/dev/null || break; sleep 2; done
echo TRACEDONE
+128
View File
@@ -0,0 +1,128 @@
#!/bin/sh
# Every matching op compared against libref ON THE OPERANDS THE DEVICE KERNEL WAS HANDED.
#
# rad-kbench falsifies one op at a time on operands IT invented: dense, rank-2, freshly filled. The
# engine's are row slices of a max_tok buffer, column slices of a fused projection, rank-3 views a
# scan kernel required, and weights that came off a file. A kernel can be correct at every shape
# rad-kbench knows and wrong at the one the model issues, so this runs the host row beside the
# device one on the real thing, every issue, and reports per operand.
#
# IT IS NOT A MEASUREMENT OF ANYTHING. Two device-to-host copies of every operand -- a fused
# gate_up weight is 170 MiB -- a host synchronisation per issue on every lane, and a reference
# kernel that is not trying to be fast. Keep MAXN small and the prompt short.
#
# ON A LARGE CONTAINER IT CAN STILL BE OOM-KILLED PART WAY THROUGH AND THAT IS THE HOST, NOT A
# DEFECT. A 166 GiB container with a 12 GiB host pool leaves little room for two copies of every
# operand of every issue; the run prints the verdicts it reached before it died, and those are as
# good as any others. Lower HOSTPOOL, or window the sweep with FROM/TO, to reach further in.
#
# ONE OPERAND CAN DO IT ON ITS OWN, AND THAT ONE IS NAMED RATHER THAN FATAL. The Flash-Next PLE
# gather reads a 47.68 GiB n-gram table, which no snapshot can hold on a host of ordinary size.
# An operand over RADIANCE_OP_ORACLE_MAXBYTES (4 GiB) is a NOT CHECKED line naming the operand and
# its size, so the sweep goes on; raise the cap to include it if the host can take three copies.
#
# WHAT A DISAGREEMENT DOES NOT MEAN. The kernel that claims a weight relayouts its canonical
# planes at load, and libr4d's fp8a8 weights are held in WMMA fragment order -- the same bytes,
# permuted. The oracle puts those back through the device row's own RadUnrelayoutFn to the planes
# and decodes them before it compares; a row that relayouts a weight and publishes no inverse is
# NOT CHECKED and says so by name. Read those lines: they are coverage this instrument does not
# have. The fp8 rows, the int8 (i8a8) block rows, the MoE 4-bit expert plane and the dense w4
# rows answer; the w8a16, w8a8, w2a8 and mxfp4 rows do not.
#
# NOT EVERY GAP IS AN INVERSE SOMEBODY HAS NOT WRITTEN, AND THIS ONE IS A MISSING ZERO POINT.
# `gemm_w2a8_nt` -- the 2-bit draft head, live on EVERY speculating container, and the same gap
# under all three drafters (mtp.draft_head.weight, dspark.draft_head.weight,
# dflash.draft_head.weight) -- is stored on an UNSIGNED ASYMMETRIC grid, value = (code - zero) *
# scale per (row, group of 128).
#
# An inverse for the WEIGHT operand alone cannot close it, and not because the permutation is hard:
# undoing the fragment order to a plane of unsigned codes is the same work the fp8 rows already do.
# The obstruction is that `zero` is not in that operand. The weight's zero plane is taken by
# `b_scale` beside its scale plane (r4d.w2a8.sz.g128, a packed pair a dword), and the reference
# reads `b` as codes and `b_scale` as a symmetric scale -- it has no zero point to apply.
#
# What would close it is a zero point in `gemm_nt_q`'s schema and an asymmetric reader in libref,
# which is a FEATURE and not a missing hook. The row is covered instead by r4d_selftest's own
# gemm_w2a8_nt case, against a host decode of the canonical planes -- and what the draft
# head produces is a PROPOSAL the target verifies with its own head, so an error here costs
# acceptance and cannot change a token the model emits.
#
# A COLLECTIVE IS CHECKED ONLY WHERE BOTH RANKS ARM ON THE SAME ISSUE, AND AN OPS FILTER IS WHAT
# BREAKS THAT. libref's all_reduce is a RENDEZVOUS: it parks on a barrier until every rank has
# handed in its message. The oracle arms each rank on that rank's OWN issue counter and spends
# that rank's OWN budget, so the two sides have to arrive together. Unfiltered they mostly do --
# about one collective in ten is refused over a tp2 decode. A NARROW ops list is what pulls
# them apart -- the budget is then spent only on the named ops, the ranks do not issue the same
# ones (an expert-parallel split alone sees to that), and one rank reaches the collective armed
# while the other does not. What comes back then is
#
# oracle #609 op 'all_reduce': the host kernel REFUSED ... with device error
# oracle #620 op 'all_reduce': the host kernel REFUSED ... with shape this kernel does not serve
#
# which are the 30-second barrier timeout and, on the next attempt, the peer's stale message
# length. Neither is a finding about all_reduce. Sweep collectives with OPS=*, or at TP=1 where
# world_size is 1 and the reference answers in place; the two-rank wire also has its own tests
# (tests/wire_test.cpp and the tp2 determinism gate).
#
# A ROUTED EXPERT GEMM IS THE EXPENSIVE ONE. Its weight operand is a table of the layer's whole
# expert set and the snapshot materialises all of it, twice, plus the inverted copy -- some
# gigabytes an issue. MAXN=2 is a sweep, not a limitation of the instrument.
#
# WHAT HAS NO HOST KERNEL AT ALL, on top of the inverses above. Ten ops the architectures declare
# have no libref row, so naming one reports "0 op(s) checked, N skipped for want of a host kernel":
# the five QSA ops (qsa_block_key, qsa_score, qsa_select, qsa_work, qsa_tail_store), dflash_conv,
# gate_quant_fp8, router_topk_scatter, qk_norm_rope_gate and ar_rmsnorm_quant_fp8.
#
# THAT IS NOT THE SAME AS UNCHECKED. Every one of them has a numeric case in r4d_selftest -- the
# QSA ops against f64 evaluations of their own formulae, a host sort and a host walk; the four
# fusions against the unfused pair they replace, which is a BYTE-IDENTICAL check and stronger than
# any tolerance this instrument applies. What the missing rows cost is this instrument's own
# question: whether the kernel holds on the ENGINE'S operands rather than on invented ones.
#
# ACROSS THE FOUR ARCHITECTURES THE GAPS ARE THE SAME THREE. Flash-Next (four-bit MoE, QSA, PLE),
# Qwen3.6-35B-A3B (fp8 MoE), the 27B dense with the DFlash2 drafter, and MiniCPM5-2B with DSpark
# issue 42 distinct op types between them, and every comparison made agrees. What every
# speculating container leaves NOT CHECKED is `gdn_recurrent_update` under the anchor state form
# (which r4d_selftest covers instead), `quant_act_i8`'s asum arm, and the w2a8 draft head weight
# above. Nothing else.
#
# A NARROW SWEEP IS STILL WORTH RUNNING: at MAXN=400 the budget is spent inside the prefill of a
# deep model, so the drafter and the sampler chain are only reached with FROM past it or with an OPS
# list that skips the GEMMs. Both, for a full picture.
#
# OPS=a,b op names, or * for every op MAXN=8 stop after this many checks
# FROM/TO issue-index window TOL=0.02 relative tolerance
# M=path container PROMPT/MT the request to run
P="${P:-8302}"
M="${M:-$HOME/models/rad/minicpm5-2b-dspark.v2.rad}"
pkill -f "port $P"; while pgrep -f "port $P" >/dev/null; do sleep 1; done
cd "$HOME/workspace/radiance/build" || exit 1
env GPU_MAX_ALLOC_PERCENT=100 GPU_MAX_HEAP_SIZE=100 \
RADIANCE_OP_ORACLE="${OPS:-*}" \
RADIANCE_OP_ORACLE_MAX="${MAXN:-8}" \
RADIANCE_OP_ORACLE_FROM="${FROM:-0}" \
RADIANCE_OP_ORACLE_TOL="${TOL:-0.02}" \
${TO:+RADIANCE_OP_ORACLE_TO=$TO} \
nohup ./bin/radiance --model "$M" \
--radiance-home "$HOME/workspace/radiance/build/radiance_home" \
--host 127.0.0.1 --port "$P" \
--max-num-seqs 1 --max-model-len "${MLEN:-8192}" --tp "${TP:-1}" \
--gpu-headroom-mib "${HR:-512}" --kv-cache-dtype "${KVD:-bf16}" \
--max-num-batched-tokens "${MNBT:-512}" $EXTRA \
> "$HOME/oracle.log" 2>&1 &
for i in $(seq 1 90); do
c=$(curl -s -m 3 -o /dev/null -w %{http_code} "http://127.0.0.1:$P/health" 2>/dev/null)
[ "$c" = 200 ] && break
pgrep -f "port $P" >/dev/null || { echo "DIED AT LOAD"; grep -E "^E " "$HOME/oracle.log" | tail -6; exit 1; }
sleep 4
done
[ "$c" = 200 ] || { echo "NO START"; grep -E "^E " "$HOME/oracle.log" | tail -6; exit 1; }
curl -s -m 900 "http://127.0.0.1:$P/v1/completions" -H 'Content-Type: application/json' \
-d "{\"model\":\"m\",\"prompt\":\"${PROMPT:-The capital of France is}\",\"max_tokens\":${MT:-2},\"temperature\":0}" \
| head -c 300
echo
pkill -f "port $P"; while pgrep -f "port $P" >/dev/null; do sleep 1; done
echo "=== verdicts ==="
# The per-operand detail stays in the log; a MISMATCH line names the op and the kernel, and the
# NOT CHECKED lines are the coverage gaps. Both are what a sweep is read for.
grep -E "oracle #|op oracle|NOT CHECKED" "$HOME/oracle.log" | sed 's/^W //'
+217
View File
@@ -0,0 +1,217 @@
#!/bin/sh
# tiercross.sh -- two conversations through the tiers at once. Does either get the other's state?
#
# WHY THIS IS NOT tierident.sh WITH A SECOND PROMPT. That script asks ONE prompt four times and
# compares the four answers, which proves a session survives the round trip. It cannot, by
# construction, see the failure this one is for: with a single conversation in the server there is
# no other conversation's bytes for it to be served. The cross-contamination failures a tiered
# cache can have -- an entry holding reassigned block ids, a checkpoint slot freed by one session
# and still named by another -- need two sessions in flight to show up at all.
#
# THE SCARCE RESOURCE IS THE CHECKPOINT SLOT, so run this with --checkpoint-slots low enough that
# the two sessions fight over it. That is what makes the retention policy and the victim scan run,
# which is what makes a snapshot get retired underneath a record that still names its slot:
#
# --checkpoint-slots 2 --prefix-cache-host-mib 512 --prefix-cache-disk-mib 16384 \
# --prefix-cache-dir <dir>
#
# EACH SESSION IS COMPARED ONLY TO ITSELF. A and B are different prompts and their answers differ
# for ordinary reasons; what must hold is that A's restored answer is A's cold answer. Corrupt
# state does not produce babble, it produces B's train of thought under A's question.
set -e
P=${P:-8100}
H=${H:-127.0.0.1}
TO_HOST=${TO_HOST:-10}
TO_DISK=${TO_DISK:-180}
FILL=${FILL:-1200}
N=${N:-48}
work=$(mktemp -d "${TMPDIR:-/tmp}/tiercross.XXXXXX")
trap 'rm -rf "$work"' EXIT INT TERM
command -v jq >/dev/null || { echo "tiercross: jq is required" >&2; exit 2; }
# TWO PROMPTS THAT SHARE NO PREFIX. A shared opening would put both sessions on the same chain for
# its length, and the blocks they then share are legitimately one another's -- which is the whole
# point of a prefix cache and would make a difference here unreadable. They diverge at token one.
#
# EACH HAS TO PRODUCE AN ANSWER. A wall of repeated sentences is a passage an instruction-tuned
# model can reasonably answer with a single EOS, and every arm of that session would then compare
# an empty string to an empty string. Both lengths are checked below, because a vacuous green here
# is worse than a red.
mk() { # mk <file> <subject> <opening> <question>
: > "$1"
i=0
while [ $i -lt 300 ]; do
printf '%s %d. %s ' "$2" "$i" "$3" >> "$1"
i=$((i + 1))
done
printf '\n%s\n\nAnswer: ' "$4" >> "$1"
}
mk "$work/a.txt" "Chapter" "The paged pool is layer-major, so one logical block is many small fragments rather than one extent." \
"Using only the passage above, write three sentences about it."
mk "$work/b.txt" "Entry" "The linear layer keeps one state per sequence and updates it token by token." \
"Using only the passage above, write three sentences about it."
# THE FILES ARE THE PROMPTS, READ VERBATIM, through jq's --rawfile. Flattening them into shell
# variables deletes the line breaks the prompts' SHAPE depends on, and a passage whose question
# ends up welded to the last sentence is one this model answers with an immediate EOS (the same
# reasoning is in tierident.sh).
ask() { # ask <who> <label> -> sha of the answer
f="$work/$(printf '%s' "$1" | tr 'AB' 'ab').txt"
jq -n --rawfile p "$f" --argjson n "$N" \
'{model:"m", prompt:$p, max_tokens:$n, temperature:0, seed:1234, stream:false}' \
> "$work/req.json"
curl -sS --fail -X POST "http://$H:$P/v1/completions" \
-H 'Content-Type: application/json' --data @"$work/req.json" > "$work/$2.json"
jq -r '.choices[0].text' < "$work/$2.json" > "$work/$2.txt"
sha1sum < "$work/$2.txt" | cut -d' ' -f1
}
# THE HIT LENGTH, which is what decides how the prefill is chunked and therefore the shape every
# GEMM in it runs at. Two restores that recovered different amounts of prefix are not the same
# computation, and comparing their output hashes would be comparing two different runs -- so this
# is printed beside every arm and checked before a mismatch is called corruption.
hit() { jq -r '.usage.prompt_tokens_details.cached_tokens' < "$work/$1.json"; }
fail=0
# WHAT A DIFFERING HASH MEANS, AND THE ONE THING THAT HAS TO BE RULED OUT FIRST.
#
# A hybrid session's reuse is clamped by the scheduler to the last LINEAR CHECKPOINT it can reach,
# not to the attention hit (core/sched/scheduler.cpp, admit_one: RadBatch carries one query length
# for every KV group, so the linear layers cannot be replayed over a longer range than the
# attention ones). So reuse is always a multiple of the checkpoint interval, and which multiple
# depends on which snapshots survived -- 0 on a cold run, 4096 or 6144 on a restored one.
#
# Reuse does not change the answer on Qwen3.8-Flash-Next: with no tiers running at all, the same
# prompt at reuse 0, 4096 and 6144 gives the same bytes. So a differing hash is a real difference
# and not an artefact of a shorter hit -- but it is the first thing to re-check if this fails on
# another model, because a near-tie that flips with the chunk boundary would look exactly like
# corruption and is not.
#
# THE COMPARISON IS AGAINST THE DEVICE-HIT ARM, not the cold one. A cold run reuses nothing by
# definition, so comparing a restore to it would always be comparing two different hit lengths;
# the device hit is the same query the restored arms run, served out of VRAM.
cmp_arm() { # cmp_arm <label> <sha> <ref sha> <reuse> <ref reuse>
if [ "$2" = "$3" ]; then
echo " ok $1 (reuse $4)"
return
fi
fail=$((fail + 1))
if [ "$4" = "$5" ]; then
echo " FAIL $1: SAME reuse ($4), different answer. This is corrupt state."
else
echo " FAIL $1: different answer, and it reused $4 where the reference reused $5."
echo " Almost certainly corruption -- reuse does not change the answer on the model"
echo " this was written against -- but confirm that on THIS model with the tiers"
echo " off before reporting it as one."
fi
}
# ---- pushing a session out of host memory --------------------------------------------------------
# NOTHING LEAVES HOST MEMORY ON A CLOCK. Every host copy is written on to disk as soon as it lands
# and keeps its host slot until another entry needs one, so the way to put a session on disk is to
# give the arena something else to hold: a prompt that shares no prefix with anything here and is
# bigger than the room the arena has left. The server must be started with a host tier FILL
# sections of it overflow; --prefix-cache-host-mib 512 holds about 27K tokens on
# Qwen3.8-Flash-Next, and the default FILL is about 30K.
fill_arena() {
: > "$work/fill.txt"
i=0
while [ $i -lt "$FILL" ]; do
printf 'Ledger line %d: warehouse north, shelf eleven, a part number and a count that nobody will ask about. ' "$i" >> "$work/fill.txt"
i=$((i + 1))
done
printf '\nName the warehouse.\n\nAnswer: ' >> "$work/fill.txt"
jq -n --rawfile p "$work/fill.txt" '{model:"m", prompt:$p, max_tokens:4, temperature:0, stream:false}' \
> "$work/fill.json"
curl -sS --fail -X POST "http://$H:$P/v1/completions" -H 'Content-Type: application/json' \
--data @"$work/fill.json" > /dev/null
}
# Until some blocks are on the disk tier, or TO_DISK seconds. The filler's copies are what take the
# slots, and they land after its request finishes.
wait_disk() {
t=0
while [ $t -lt "$TO_DISK" ]; do
curl -sS --fail "http://$H:$P/sessions" > "$work/w.json"
case "$(jq -r .blocks_sum_overlapping.disk < "$work/w.json")" in 0|null|"") ;; *) return 0 ;; esac
sleep 2; t=$((t + 2))
done
return 1
}
echo "tiercross: $H:$P, two sessions, ${TO_HOST}s for VRAM to go, $FILL filler sections"
CKS=$(curl -sS --fail "http://$H:$P/sessions" | jq -r .snapshots_moved.bytes_each)
[ "$CKS" = "0" ] && echo " (no recurrent state in this model; the attention half is still tested)"
A0=$(ask A a0); B0=$(ask B b0)
echo " first A $A0 reuse $(hit a0)"
echo " B $B0 reuse $(hit b0)"
# AND THEY MUST DIFFER. Two prompts that produce the same answer would make every comparison
# below pass whatever the tiers did with them.
if [ "$A0" = "$B0" ]; then
echo "tiercross: both prompts produced the same answer, so no comparison here can tell the" >&2
echo " two sessions apart. Change the prompts." >&2
exit 1
fi
for f in a0 b0; do
CN=$(wc -c < "$work/$f.txt")
[ "$CN" -lt 32 ] && { echo "tiercross: $f answered $CN bytes; every sha for it would match for that" >&2
echo " reason alone. Give that prompt something to answer." >&2; exit 1; }
done
# ---- the control: both sessions again, straight out of VRAM -------------------------------------
# THE SAME QUERY THE RESTORED ARMS WILL RUN. Without it a differing hash below proves nothing: this
# engine could be irreproducible across requests for reasons that have nothing to do with tiering,
# and the two sessions could be contaminating each other while both are still resident.
AH=$(ask A ah); BH=$(ask B bh)
echo " device A $AH reuse $(hit ah)"
echo " B $BH reuse $(hit bh)"
if [ "$AH" != "$A0" ] || [ "$BH" != "$B0" ]; then
echo " note: a device hit does not reproduce the cold answer. That is not necessarily wrong --"
echo " the hit reuses $(hit ah)/$(hit bh) tokens where the cold run reused nothing -- but every"
echo " comparison below is against the DEVICE HIT from here on, which is the like-for-like one."
fi
echo " waiting $((TO_HOST + 8))s..."
sleep $((TO_HOST + 8))
A1=$(ask A a1); B1=$(ask B b1)
echo " from RAM A $A1 reuse $(hit a1)"
echo " B $B1 reuse $(hit b1)"
cmp_arm "A restored from RAM is still A" "$A1" "$AH" "$(hit a1)" "$(hit ah)"
cmp_arm "B restored from RAM is still B" "$B1" "$BH" "$(hit b1)" "$(hit bh)"
echo " filling host memory with $FILL sections of something else..."
fill_arena
wait_disk || echo " note: nothing reached the disk tier within ${TO_DISK}s; the arm below may be a RAM restore"
sleep $((TO_HOST + 8))
A2=$(ask A a2); B2=$(ask B b2)
echo " from disk A $A2 reuse $(hit a2)"
echo " B $B2 reuse $(hit b2)"
cmp_arm "A restored from disk is still A" "$A2" "$AH" "$(hit a2)" "$(hit ah)"
cmp_arm "B restored from disk is still B" "$B2" "$BH" "$(hit b2)" "$(hit bh)"
curl -sS --fail "http://$H:$P/sessions" > "$work/s.json"
echo " moved: blocks to_host=$(jq -r .moved.to_host < "$work/s.json") to_disk=$(jq -r .moved.to_disk < "$work/s.json") promoted=$(jq -r .moved.promoted < "$work/s.json")"
if [ "$CKS" != "0" ]; then
echo " state: to_host=$(jq -r .snapshots_moved.to_host < "$work/s.json") to_disk=$(jq -r .snapshots_moved.to_disk < "$work/s.json") promoted=$(jq -r .snapshots_moved.promoted < "$work/s.json") dropped=$(jq -r .snapshots_moved.drops < "$work/s.json")"
# A RUN WITH NO CONTENTION TESTED THE EASY CASE. Two stores have to run out for the paths this
# script exists for to execute, and they are sized by different flags: --checkpoint-slots is
# the DEVICE pool the retention policy spends, and a share of --prefix-cache-host-mib (startup
# says how many snapshots) is the snapshot store the tiers spend. `drops` counts the second.
[ "$(jq -r .snapshots_moved.drops < "$work/s.json")" = "0" ] && \
echo " note: the snapshot store never overflowed -- lower --prefix-cache-host-mib to make the two sessions contend for it"
fi
if [ "$fail" -ne 0 ]; then
echo
echo "A session answering with the OTHER session's train of thought is what corruption looks"
echo "like. A reuse mismatch above is a different finding and the diffs below do not speak to it."
for pair in "ah a1" "ah a2" "bh b1" "bh b2"; do
set -- $pair
cmp -s "$work/$1.txt" "$work/$2.txt" || { echo "--- $1 vs $2"; diff "$work/$1.txt" "$work/$2.txt" | head -4; }
done
fi
echo
[ "$fail" -eq 0 ] && echo "tiercross: PASS -- neither session was served the other's context or state"
[ "$fail" -ne 0 ] && { echo "tiercross: $fail FAILURE(S)"; exit 1; }
exit 0
+283
View File
@@ -0,0 +1,283 @@
#!/bin/sh
# tierident.sh -- does a session that left VRAM come back BYTE FOR BYTE, both halves of it?
#
# This is the acceptance test for the idle session tiers (core/mem/kvtier.h). It is a byte
# comparison because CORRUPT KV DOES NOT READ AS BABBLE -- it reads as fluent, deterministic,
# coherent, plausible text that simply is not the text the model would have produced, and nothing
# that looks at the engine from outside notices it. Only a byte comparison against a known-good
# arm sees it.
#
# THE CONTROL IS THE WHOLE TEST. Arm 2 asks the same prompt again while the session is still in
# VRAM. If that does not reproduce arm 1 exactly, then this model at this temperature is not
# reproducible across requests at all and every later comparison is meaningless -- a differing sha
# would prove nothing, because a cache hit COULD have been legitimately tie-divergent. Run the
# control or do not run the test.
#
# ============================== AND ON A HYBRID MODEL, HALF THE TEST IS INVISIBLE ===============
#
# A session on a hybrid model is attention blocks AND a recurrent-state snapshot. The two are
# stored separately and can be lost separately -- and losing the snapshot IS NOT VISIBLE IN THE
# TEXT. The engine simply replays the linear layers from an older checkpoint, or from token zero,
# and produces exactly the same answer, slower. So byte identity proves the blocks came back and
# says nothing whatever about the state.
#
# That is why every snapshot assertion below is a counter and not a sha. A run where the blocks
# moved and the snapshots did not is a PASS by text and a FAILURE here, and it is the failure that
# matters: it is the difference between a restored 200K session costing a second and costing a
# minute of linear replay.
#
# scripts/tierident.sh # against a server already up on $P (default 8100)
#
# The server must be started with the tiers on, with a host tier small enough for the filler below
# to overflow it (see fill_arena), and with few enough checkpoint slots that the filler's snapshots
# push the session's out of the device pool -- a snapshot still in its device slot needs no
# promotion, and the path that brings one back from disk then never runs:
# --prefix-cache-host-mib 512 --prefix-cache-disk-mib 8192 --prefix-cache-dir <dir> \
# --checkpoint-slots 2
set -e
P=${P:-8100}
H=${H:-127.0.0.1}
TO_HOST=${TO_HOST:-10}
TO_DISK=${TO_DISK:-180}
FILL=${FILL:-1200}
N=${N:-48}
work=$(mktemp -d "${TMPDIR:-/tmp}/tierident.XXXXXX")
trap 'rm -rf "$work"' EXIT INT TERM
command -v jq >/dev/null || { echo "tierident: jq is required" >&2; exit 2; }
# A PROMPT LONG ENOUGH TO BE WORTH TIERING, AND LONGER THAN A CHECKPOINT INTERVAL. The unit of the
# attention half is the block, so a prompt of a few tokens occupies one and exercises nothing. The
# unit of the linear half is the checkpoint interval -- 2048 tokens by default -- and a prompt
# shorter than that produces NO snapshot at all, so every snapshot assertion below would be
# vacuously satisfied by a server where snapshot tiering is entirely broken.
#
# AND IT HAS TO ASK FOR SOMETHING. A wall of repeated sentences with no question at the end is a
# passage an instruction-tuned model can answer with a single EOS, and every arm would then compare
# an empty string to an empty string and report the control green. That is the same failure this
# whole script is built around -- a comparison that passes because neither side has any content --
# so the answer length is checked below as well.
: > "$work/p.txt"
i=0
while [ $i -lt 300 ]; do
printf 'Section %d. The cache stores conversation prefixes as content-hashed blocks, and the identity of a block includes every token before it. ' "$i" >> "$work/p.txt"
i=$((i + 1))
done
printf '\nUsing only the passage above, write three sentences about what a block identity includes and why it matters.\n\nAnswer: ' >> "$work/p.txt"
# THE FILE IS THE PROMPT, READ VERBATIM, through jq's --rawfile. Escaping it by hand into a shell
# variable doubles the backslash jq adds before every quote, and flattening its newlines welds the
# question onto the passage ("...why it matters.Answer:" on one line), which this model answers
# with an immediate EOS -- the empty-completion failure described above.
ask() { # ask <label> -> writes $work/<label>.txt, echoes its sha
jq -n --rawfile p "$work/p.txt" --argjson n "$N" \
'{model:"m", prompt:$p, max_tokens:$n, temperature:0, seed:1234, stream:false}' \
> "$work/req.json"
curl -sS --fail -X POST "http://$H:$P/v1/completions" \
-H 'Content-Type: application/json' --data @"$work/req.json" > "$work/$1.json"
jq -r '.choices[0].text' < "$work/$1.json" > "$work/$1.txt"
sha1sum < "$work/$1.txt" | cut -d' ' -f1
}
# ---- pushing a session out of host memory --------------------------------------------------------
# NOTHING LEAVES HOST MEMORY ON A CLOCK. Every host copy is written on to disk as soon as it lands
# and keeps its host slot until another entry needs one, so the way to put a session on disk is to
# give the arena something else to hold: a prompt that shares no prefix with anything here and is
# bigger than the room the arena has left. The server must be started with a host tier FILL
# sections of it overflow; --prefix-cache-host-mib 512 holds about 27K tokens on
# Qwen3.8-Flash-Next, and the default FILL is about 30K.
fill_arena() {
: > "$work/fill.txt"
i=0
while [ $i -lt "$FILL" ]; do
printf 'Ledger line %d: warehouse north, shelf eleven, a part number and a count that nobody will ask about. ' "$i" >> "$work/fill.txt"
i=$((i + 1))
done
printf '\nName the warehouse.\n\nAnswer: ' >> "$work/fill.txt"
jq -n --rawfile p "$work/fill.txt" '{model:"m", prompt:$p, max_tokens:4, temperature:0, stream:false}' \
> "$work/fill.json"
curl -sS --fail -X POST "http://$H:$P/v1/completions" -H 'Content-Type: application/json' \
--data @"$work/fill.json" > /dev/null
}
# Until some blocks are on the disk tier, or TO_DISK seconds. The filler's copies are what take the
# slots, and they land after its request finishes.
wait_disk() {
t=0
while [ $t -lt "$TO_DISK" ]; do
curl -sS --fail "http://$H:$P/sessions" > "$work/w.json"
case "$(jq -r .blocks_sum_overlapping.disk < "$work/w.json")" in 0|null|"") ;; *) return 0 ;; esac
sleep 2; t=$((t + 2))
done
return 1
}
snap() { curl -sS --fail "http://$H:$P/sessions" > "$work/s.json"; }
q() { jq -r "$1" < "$work/s.json"; }
# PROMPT TOKENS A LOOKUP COVERED WITH RECURRENT STATE. Moving a snapshot and moving it back proves
# the bytes travelled and nothing more; this is the number that says a hit then SERVED one. They
# are not the same claim -- a restore that puts the state back somewhere the chain cannot reach
# scores perfectly on the first and zero on this.
lin() { jq -r ".linear.cached_tokens" < "$work/s.json"; }
where() { # where -> "vram=N ram=N disk=N [+ snapshots]" for the whole server
snap
w="vram=$(q .blocks_sum_overlapping.device) ram=$(q .blocks_sum_overlapping.host) disk=$(q .blocks_sum_overlapping.disk)"
if [ "$(q .snapshots_moved.bytes_each)" != "0" ]; then
w="$w state: vram=$(q .snapshots.device) ram=$(q .snapshots.host) disk=$(q .snapshots.disk)"
fi
echo "$w"
}
fail=0
check() { # check <label> <sha> <expected>
if [ "$2" = "$3" ]; then echo " ok $1"
else echo " FAIL $1: $2 != $3"; fail=$((fail + 1)); fi
}
note() { echo " FAIL $1"; fail=$((fail + 1)); }
echo "tierident: $H:$P, ${TO_HOST}s for VRAM to go, $FILL filler sections to push host memory out"
# IS THERE A LINEAR HALF AT ALL. A pure-attention model has no snapshots and must not be failed
# for having none; a hybrid one with a snapshot store of zero slots is a real misconfiguration and
# is named as one rather than skipped.
snap
HYBRID=0
[ "$(q .snapshots_moved.bytes_each)" != "0" ] && HYBRID=1
if [ "$HYBRID" = 1 ]; then
echo " hybrid: snapshots are $(q .snapshots_moved.bytes_each) bytes, $(q .snapshots_moved.host_slots) ram slot(s), $(q .snapshots_moved.disk_slots) disk slot(s)"
[ "$(q .snapshots_moved.host_slots)" = "0" ] && \
note "the snapshot store has no room; an idle session's linear state cannot leave VRAM"
else
echo " this model has no recurrent state; the linear-state arms are not applicable"
fi
COLD=$(ask cold)
echo " cold $COLD [$(where)]"
# AN EMPTY ANSWER MAKES EVERY COMPARISON BELOW VACUOUS, and it is the easiest way for this script
# to report a confident green having tested nothing: three identical shas of the empty string.
CN=$(wc -c < "$work/cold.txt")
if [ "$CN" -lt 32 ]; then
echo "tierident: the model answered $CN bytes. Every sha below would match for that reason" >&2
echo " alone. Give the prompt something to answer and run again." >&2
exit 1
fi
# ---- the control -------------------------------------------------------------------------------
HOT=$(ask hot)
echo " device hit $HOT [$(where)]"
check "the same prompt twice from VRAM is byte-identical (THE CONTROL)" "$HOT" "$COLD"
if [ "$HOT" != "$COLD" ]; then
echo "tierident: the control failed, so nothing below would mean anything. Stopping." >&2
echo " This server is not reproducible across requests; fix that first." >&2
exit 1
fi
# ---- host --------------------------------------------------------------------------------------
echo " waiting $((TO_HOST + 8))s for the session to leave VRAM..."
sleep $((TO_HOST + 8))
W=$(where)
echo " after the host threshold [$W]"
# A RUN THAT MOVED NOTHING IS A FAILURE, NOT A PASS. This is the trap the whole script exists to
# avoid, turned on itself: if the session never left VRAM then every arm below is an ordinary
# device hit, the shas match for a reason that has nothing to do with tiering, and reporting PASS
# would be exactly the false confidence a byte comparison is supposed to replace.
snap
# A MISSING FIELD IS THE SAME FAILURE AS A ZERO: if the /sessions layout changes, this guard reads
# `null`, and treating that as a pass would pass vacuously.
case "$(q .blocks_sum_overlapping.host)" in 0|null|"") false ;; *) true ;; esac || note "the session never left VRAM -- nothing below would test anything
(--prefix-cache-host-mib set? is the maintenance pass running?)"
if [ "$HYBRID" = 1 ]; then
snap
[ "$(q .snapshots_moved.to_host)" = "0" ] && \
note "no linear-state snapshot reached RAM, so the restore below tests the blocks only
(starved: $(q .snapshots_moved.starved), dropped: $(q .snapshots_moved.drops))"
fi
snap
PROM0=$([ "$HYBRID" = 1 ] && q .snapshots_moved.promoted || echo 0)
LIN0=$([ "$HYBRID" = 1 ] && lin || echo 0)
DEV0=$([ "$HYBRID" = 1 ] && q .snapshots.device || echo 0)
FROMHOST=$(ask fromhost)
echo " restored from RAM $FROMHOST [$(where)]"
check "a session restored from RAM reproduces the cold answer" "$FROMHOST" "$COLD"
if [ "$HYBRID" = 1 ]; then
snap
# A SNAPSHOT STILL IN ITS DEVICE SLOT NEEDS NO PROMOTION: it stays there when the blocks go,
# and only the checkpoint pool's own pressure detaches it. Whether it was SERVED is the check
# below either way; this one only says which path served it.
if [ "$(q .snapshots_moved.promoted)" -gt "$PROM0" ]; then
echo " ok its linear state came back with it ($(( $(q .snapshots_moved.promoted) - PROM0 )) snapshot(s))"
elif [ "$DEV0" -gt 0 ]; then
echo " -- its linear state never left its device slot ($DEV0 there), so nothing was promoted"
else
note "the blocks came back and the linear state did not -- the answer is right and the
session will replay every recurrent layer from an older checkpoint to produce it"
fi
if [ "$(lin)" -gt "$LIN0" ]; then
echo " ok and the restored state was SERVED ($(( $(lin) - LIN0 )) prompt tokens covered by it)"
else
note "the snapshot came back and no lookup used it -- restored somewhere the chain
cannot reach, which costs the replay it was moved to avoid"
fi
fi
# ---- disk --------------------------------------------------------------------------------------
echo " filling host memory with $FILL sections of something else..."
fill_arena
wait_disk || true
echo " and waiting $((TO_HOST + 8))s for VRAM to go..."
sleep $((TO_HOST + 8))
W=$(where)
echo " after the filler [$W]"
snap
case "$(q .blocks_sum_overlapping.disk)" in 0|null|"") false ;; *) true ;; esac || note "the session never reached disk -- the arm below tests nothing
(--prefix-cache-disk-mib and --prefix-cache-dir set? a host tier FILL=$FILL sections overflow?)"
if [ "$HYBRID" = 1 ]; then
snap
[ "$(q .snapshots_moved.to_disk)" = "0" ] && \
note "no linear-state snapshot reached disk
(disk snapshot slots: $(q .snapshots_moved.disk_slots))"
fi
snap
PROM1=$([ "$HYBRID" = 1 ] && q .snapshots_moved.promoted || echo 0)
LIN1=$([ "$HYBRID" = 1 ] && lin || echo 0)
FROMDISK=$(ask fromdisk)
echo " restored from disk $FROMDISK [$(where)]"
check "a session restored from disk reproduces the cold answer" "$FROMDISK" "$COLD"
if [ "$HYBRID" = 1 ]; then
snap
if [ "$(q .snapshots_moved.promoted)" -gt "$PROM1" ]; then
echo " ok its linear state came back from disk too"
else
note "nothing promoted a snapshot out of disk -- the filler's snapshots did not push the
session's out of the device pool (--checkpoint-slots 2?), so the disk path never ran"
fi
if [ "$(lin)" -gt "$LIN1" ]; then
echo " ok and the state restored from disk was SERVED ($(( $(lin) - LIN1 )) prompt tokens)"
else
note "a snapshot came back from disk and no lookup used it"
fi
echo " snapshots: to_host=$(q .snapshots_moved.to_host) to_disk=$(q .snapshots_moved.to_disk) promoted=$(q .snapshots_moved.promoted) dropped=$(q .snapshots_moved.drops) starved=$(q .snapshots_moved.starved)"
fi
# ---- and the text itself, so a failure says WHERE ----------------------------------------------
if [ "$fail" -ne 0 ]; then
echo
echo "The first differing line, cold vs the failing arm:"
for arm in fromhost fromdisk; do
[ -f "$work/$arm.txt" ] || continue
if ! cmp -s "$work/cold.txt" "$work/$arm.txt"; then
echo "--- $arm"
diff "$work/cold.txt" "$work/$arm.txt" | head -6
fi
done
echo
echo "A DIFFERENCE IN THE TEXT IS CORRUPT KV, not a sampling artefact: the control above proved"
echo "this server reproduces itself from VRAM, so the only thing that changed is where the"
echo "bytes came back from. A snapshot failure with matching text is not corruption -- it is"
echo "the restore silently costing a linear replay it was built to avoid."
fi
echo
[ "$fail" -eq 0 ] && echo "tierident: PASS -- a session survives VRAM -> RAM -> disk byte for byte, state included"
[ "$fail" -ne 0 ] && { echo "tierident: $fail FAILURE(S)"; exit 1; }
exit 0