Merge upstream main (v1.17.0 -> v2.1.0) into the SYCL port

102 upstream commits. Nine conflicts resolved. Fork side of the merge:
- libxe2: declare the givens_dense_quant schema (upstream 2.0 dropped it
  from libavx and libref; the device libraries now each carry it).
- plain_norm becomes an ABI 42 append to RadBuildCtx; abi layout table
  regenerated, kTableAbi = 42.

Known before the PR: arch_test (MTP lint and pinned graph hashes for
qwen35_fp8, qwen35moe_fp8, qwen4exp with MTP).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
aneinanderandClaude Opus 5.5 committed 2026-11-18 15:06:17 +01:00
commit 4b70a96378
850 files changed
+157819 -58519

No files matched your search

+13 -10
View File
@@ -10,19 +10,21 @@ checkout the script is in, and default to containers under `$HOME/models/rad/` a
`$HOME/models/<org>/<name>`. A script that starts a server first stops any `radiance` already
running (`oracle.sh` only the one on its own port) and logs to `$HOME/<script>.log`. Most defaults
are environment overrides (`M=` for the container, `P=` for the port, and so on); each script's
header lists its own. Scripts that only attach to a live server need `curl` and `jq`; `cardclock.py`,
`agentreplay.py` and `stampgaps.py` need `python3`. Scripts find each other through `$(dirname "$0")`.
header lists its own. A script that starts a server passes its settings as a flag list to
`radiance-flags BIN FLAGS...`, which writes them as the YAML file the server reads (with `rad-yaml`,
beside BIN) and runs `BIN --config FILE` in its place. Scripts that only attach to a live server
need `curl` and `jq`; `cardclock.py`, `agentreplay.py` and `stampgaps.py` need `python3`. Scripts find each other through `$(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 checkpoint's `n_ctx_train` (131072) and what a token of KV costs. |
| `mcserve.sh` | MiniCPM5-2B IQ8R with its DSpark drafter (`minicpm5-2b-iq8r.rad`, int8 KV cache), left running on :8100. Records why `max-model-len` is the checkpoint's `n_ctx_train` (131072) and what a token of KV costs. |
| `fnserve.sh` | Qwen3.8-Flash-Next, the production container `w4nl64-i8lm.rad`, left running on :8100. Records the production flags and their reasons: the 200K context and how the expert/cache split sizes the pool for it, the 2048-token chunk, the host prefix-cache tier and the lossy `wht6` cross-rank wire. |
| `fnstop.sh` | Stops whichever server is running and waits for the process to exit. |
| `convdspark.sh` | Rebuilds the container `mcserve.sh` serves, with the drafter merged, as `minicpm5-2b-dspark.new.rad` beside it. The checkpoint and drafter paths are fixed; `RECIPE=` overrides the recipe. |
| `convdspark.sh` | Rebuilds the container `mcserve.sh` serves, with the drafter merged and every linear rotated int8 (`data/recipes/minicpm5-2b-iq8r.recipe`), as `minicpm5-2b-iq8r.new.rad` beside it. The checkpoint and drafter paths are fixed; `RECIPE=` overrides the recipe. |
| `convfn.sh` | Rebuilds the container `fnserve.sh` serves, as `w4nl64-i8lm.new.rad` beside it, 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 Hugging Face repo with `curl` and `jq`. Resumable, and skips the duplicate weight formats a repo often carries beside its safetensors. `radiance --model <repo id>` runs it. |
| `hfget.sh` | Fetches a Hugging Face repo with `curl` and `jq`. Resumable, and skips the duplicate weight formats a repo often carries beside its safetensors. A server whose `model` is a repo id runs it. |
| `krea2_native.py` | Rewrites a Krea 2 DiT single file in Krea's own key names (`turbo.safetensors`, civitai and ComfyUI finetunes) as diffusers' transformer file, bytes unchanged, so it converts as the `transformer/` of a Krea 2 pipeline directory (`docs/GUIDE.md`). |
| `krea2_rebalance_calib.py` | Measures the constant of each Krea 2 rebalance preset (`rebalance`: balanced, detail, subtle): the taps' mean squares over twenty prompts through a pipeline's text encoder, and the renormalising factor arch/krea2 holds for them (`docs/GUIDE.md`). Needs torch and transformers. |
@@ -31,7 +33,7 @@ header lists its own. Scripts that only attach to a live server need `curl` and
| | |
|---|---|
| `cstep2.sh` | Steady-state decode ms/step at each concurrency, against a live server. Waits until exactly C sequences are running before sampling and re-checks at the end, since a window with fewer than C at either edge measures no single concurrency. 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 (`qwen3.8-27b-fp8.rad`); starts its own server on :8129 and needs a ~16K-token prompt (`PROMPT=<file>`). The counters are cumulative and a run starts with prefill, so one dump mixes prefill and decode; difference two dumps taken after prefill has ended. |
| `dprofd.sh` | Per-op device timing (`profile-ops`) at depth and concurrency on the 27B dense model with its DFlash2 drafter (`qwen3.8-27b-fp8.rad`); starts its own server on :8129 and needs a ~16K-token prompt (`PROMPT=<file>`). The counters are cumulative and a run starts with prefill, so one dump mixes prefill and decode; difference two dumps taken after prefill has ended. |
| `fnpf.sh` | Prefill throughput of the server on `$P`, over the repository's own markdown, with a fresh nonce per rep so the prefix cache cannot serve it. Prints card temperature and clock beside every rep. |
| `agentreplay.py` | Several agent conversations at once against a live server, each growing turn by turn to `--context` tokens and handing tasks to subagents that share its system prompt while it waits (`--rewrite`: a client that replaces its last message every turn). Prints per kind of turn how much of the prompt the cache served and how many continuing turns prefilled their history again, and the prefix-cache counters across the run. The conversations follow `--seed` and carry a fresh nonce, so two servers (one flag apart, restarted between) are sent the same work and share nothing with an earlier run. Takes the key from `--api-key-file`, never the command line. |
| `fnconc.sh` | What a long prefill costs the decoders running beside it, and the prefill's own time, measured together: alone, then contended, with a warm pass discarded. |
@@ -39,14 +41,15 @@ header lists its own. Scripts that only attach to a live server need `curl` and
| `mctrace.sh` | A MiniCPM5-2B decode trace under `rocprofv3`, on its own server, formatted for `libr4d/isa/tsum.sh`, mainly for its `blocks` column. |
| `ident.sh` | Run-to-run reproducibility at a fixed configuration: one hash per (temperature, question), to compare against another run of the same configuration. A speculative run need not match a non-speculative one byte for byte (the split-K count is chosen from M, so reduction orders differ and a near-tie can flip late in a long answer), but a divergence within the first sentence or two is a defect. |
| `cardclock.py` | What holds each card's clock under sustained load, and which card a tensor-parallel step waits for (the slowest rank ends the step). Reads every AMD card's `gpu_metrics` table ten times a second and counts a throttler bit only when the clock is lower while it is set (some firmware keeps a bit on at idle). Shows the engine's step counters per window, so a slow window is attributed to slower steps, fewer tokens per step or host time between steps. Drives its own greedy load, or with `--watch` only samples a server under real traffic; `--compare` shows two saved runs side by side. Read-only on the cards. |
| `kv-resident-vs-stock.sh` | This build with `--kv-resident 32768` against the stock 1.10.0 image without it, in interleaved ABBA rounds of one cold start a request; the mean paired delta with per-round values and a t interval (`ROUNDS` sets the resolution, ~2.0 % at 4). Both arms must tokenize the 16 110-token prompt alike and report `cached_tokens` 0. |
| `kv-resident-vs-stock.sh` | This build with `kv-resident: 32768` against the stock 1.10.0 image without it, in interleaved ABBA rounds of one cold start a request; the mean paired delta with per-round values and a t interval (`ROUNDS` sets the resolution, ~2.0 % at 4). Both arms must tokenize the 16 110-token prompt alike and report `cached_tokens` 0. |
| `kv-union.sh` | How large a ring must be: the union of distinct blocks one `kv_resolve` launch selects at 64k/128k-token prompts, the ring climbed from the 32 768-token floor until no launch overflows. Reports resolves, lookups, misses, the largest union and prefill time, and the overflow message verbatim; its last arm decodes a ~34k-token history past the floor ring against streaming off and passes only if the ring evicted. |
| `kv-parity.sh` | That a ring covering the group's context streams nothing and changes no output byte: a dense and a sparse prompt without the flag and with `--kv-resident 4096` (the whole `--max-model-len x --max-num-seqs`), compared byte for byte, with `--profile-ops` showing no `kv_resolve` issued. |
| `kv-multiturn-recall.py` | Whether planted facts survive twenty turns whose history outgrows the ring: the same transcript with streaming off and with `--kv-resident 32768` under `--max-model-len 65536`, a code planted at turn 2 and a surname at turn 5 asked at turn 20 (~49k prompt tokens). Fails if the off arm missed the cache on continuing turns or the on arm streamed nothing. |
| `kv-stage-parity-64k.sh` | The prefill stage: streaming off against `--kv-resident 32768` on a ~64k-token document, so every chunk past 32 768 tokens takes the one-layer stage; byte-identical output, the staged copies checked in layer order, and both arms' VRAM split printed. A run that takes the ring instead fails. |
| `kv-parity.sh` | That a ring covering the group's context streams nothing and changes no output byte: a dense and a sparse prompt without the key and with `kv-resident: 4096` (the whole `max-model-len x max-num-seqs`), compared byte for byte, with `profile-ops` showing no `kv_resolve` issued. |
| `kv-multiturn-recall.py` | Whether planted facts survive twenty turns whose history outgrows the ring: the same transcript with streaming off and with `kv-resident: 32768` under `max-model-len: 65536`, a code planted at turn 2 and a surname at turn 5 asked at turn 20 (~49k prompt tokens). Fails if the off arm missed the cache on continuing turns or the on arm streamed nothing. |
| `kv-stage-parity-64k.sh` | The prefill stage: streaming off against `kv-resident: 32768` on a ~64k-token document, so every chunk past 32 768 tokens takes the one-layer stage; byte-identical output, the staged copies checked in layer order, and both arms' VRAM split printed. A run that takes the ring instead fails. |
| `statsdump.py` | Records `/stats` to a JSONL file, one row per poll (`--every`, default 1 s), so the dashboard's figures can be read back over time on a machine without a Prometheus scraper. A row is the engine's snapshot verbatim plus the poll's time `t` and the gap since the last good poll `dt_s`; nothing is derived. The file is appended to and rotated at `--max-mib` (default 256, five generations). A failed poll leaves no row; a run that wrote no row, or can no longer write its file, exits 1. The key is taken from `--api-key` or `RADIANCE_API_KEY`. |
| `stampgaps.py` | Reads the CSV that `RADIANCE_AQL_STAMP=N` writes (every dispatch of one recorded pass in N on card 0, start and end) and prints per kind of pass (told apart by tape length) the median wall, the busy time as the union over the queues, the idle share, the gap before an ordered start (p50, p90, sum) and the kernels by share of the dispatch time. The idle share is what chained launches could win at most, the gaps what they would remove. Stamping costs throughput of its own when passes are short (one in 50: 0.3 % at one GLM-5.3 stream, 4 % at eight), so take N larger at high concurrency. |
| `oracle.sh` | Every op compared against libref on the operands the model issued, which rad-kbench cannot do: its operands are its own (dense, rank 2), while the engine's are arena slices and weights loaded from a file. Starts its own server on :8302. Read it for `MISMATCH` lines, and for `NOT CHECKED` lines naming rows whose weight layout has no published inverse and so cannot be compared. |
| `expert_stats_report.py` | Reads the file `--expert-stats` writes and prints, per routed layer, the share of selections taken by the top 5/10/20 % of experts, the Gini coefficient, the experts never selected, and decode against prefill: each one's top-20 % share, the share of decode selections landing on prefill's top-20 % experts, the Jaccard overlap and the total-variation distance. The self-check line compares each layer's selections with its observed tokens × top_k, which is exact unless the drain lost histograms. Read it before spending expert bits or pinning a hot set: a layer's total is the same at every layer (top-k routing), so the totals rank nothing — the concentration and the decode/prefill disagreement do. Two layers with the same total can need opposite spending. |
## Regression checks against a live server
+4 -4
View File
@@ -1,15 +1,15 @@
#!/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. The output
# (minicpm5-2b-iq8r.rad): the bf16 checkpoint with the drafter merged in, every linear made
# rotated int8 by data/recipes/minicpm5-2b-iq8r.recipe, served by arch/llama_dense_fp8. The output
# is removed before conversion starts, so it is a .new.rad beside the served container.
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BUILD="${BUILD:-$ROOT/build}"
cd "$BUILD" || exit 1
RECIPE=${RECIPE:-$ROOT/data/recipes/minicpm5-2b-dspark.recipe}
RECIPE=${RECIPE:-$ROOT/data/recipes/minicpm5-2b-iq8r.recipe}
SRC=$HOME/models/openbmb/MiniCPM5-2B
DRAFT=$HOME/models/openbmb/MiniCPM5-2B-DSpark
OUT=$HOME/models/rad/minicpm5-2b-dspark.new.rad
OUT=$HOME/models/rad/minicpm5-2b-iq8r.new.rad
[ -d "$DRAFT" ] || { echo "no drafter checkpoint at $DRAFT"; exit 1; }
rm -f "$OUT"
./bin/rad-convert "$SRC" -o "$OUT" \
-4
View File
@@ -12,10 +12,6 @@
# (docs/MOE-W4.md, "Calibration"). Grams from another checkpoint do not transfer, and a layer with
# no file is packed without error feedback.
#
# A recipe that does not name $CALIB (e.g. RECIPE=data/recipes/qwen4exp-w4.recipe) rounds experts
# to nearest with absmax scales; setting CALIB=<dir> then applies int4 GPTQ through the --quant
# rule that recipe's header names, which takes precedence over the recipe's own rule.
#
# OUT is removed before conversion starts, so it defaults to a .new.rad beside the served
# container.
#
+1 -1
View File
@@ -17,7 +17,7 @@ cd "$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"
GPU_MAX_ALLOC_PERCENT=100 GPU_MAX_HEAP_SIZE=100 RADIANCE_PROFILE_EVERY="$EVERY" \
./bin/radiance --model "${M:-$HOME/models/rad/qwen3.8-27b-fp8.rad}" \
"$ROOT/scripts/radiance-flags" ./bin/radiance --model "${M:-$HOME/models/rad/qwen3.8-27b-iq8r-dflash.rad}" \
--radiance-home 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 \
+231
View File
@@ -0,0 +1,231 @@
#!/usr/bin/env python3
"""expert_stats_report.py FILE.json [--kinds prefill,decode,...] [--json OUT] [--top N]
Reads the file `radiance --expert-stats FILE` writes (format radiance-expert-stats/1) and prints, per routed layer:
the share of selections taken by the top 5 / 10 / 20 % of experts, the Gini coefficient, the experts never selected,
and decode vs prefill: each one's top-20 % share, the share of decode selections landing on prefill's top-20 %
experts, the Jaccard overlap of the two top-20 % sets, and the total-variation distance between the two.
Then a combined skew verdict (what PLAN-experts.md E3/E4/E5 need to decide on).
The counts are model-wide expert ids (the engine merges the ranks' slices). `--kinds` picks what "all" sums (default
prefill,decode,mixed; the draft head is reported apart). The self-check line compares each layer's selections with
its observed tokens x top_k (exact unless the drain lost histograms).
"""
import argparse
import json
import math
import signal
import sys
KINDS = ("prefill", "decode", "mixed", "draft")
def safe(s):
"""A string for display. A stats file can come from someone else's run, and its model,
arch and map strings reach the operator's terminal: ESC there starts an OSC sequence that
could retitle the window or worse, so control characters print as '?' and never raw."""
return "".join("?" if (c < " " or c == "\x7f" or 0x80 <= ord(c) <= 0x9F) else c for c in str(s))
def gini(xs):
"""Gini coefficient of non-negative counts: 0 flat, (n-1)/n when one expert takes everything."""
n = len(xs)
s = sum(xs)
if n == 0 or s == 0:
return 0.0
v = sorted(xs)
cum = 0.0
for i, x in enumerate(v, 1):
cum += i * x
return (2.0 * cum) / (n * s) - (n + 1.0) / n
def top_share(xs, frac):
"""Share of all selections taken by the top ceil(frac * n) experts."""
n = len(xs)
s = sum(xs)
if n == 0 or s == 0:
return float("nan")
k = max(1, int(math.ceil(frac * n)))
return sum(sorted(xs, reverse=True)[:k]) / s
def top_set(xs, frac):
n = len(xs)
k = max(1, int(math.ceil(frac * n)))
order = sorted(range(n), key=lambda e: (-xs[e], e))
return set(e for e in order[:k] if xs[e] > 0)
def tvd(a, b):
sa, sb = sum(a), sum(b)
if sa == 0 or sb == 0:
return float("nan")
return 0.5 * sum(abs(x / sa - y / sb) for x, y in zip(a, b))
def summed(counts, kinds, layer, n):
row = [0] * n
for k in kinds:
for e, c in enumerate(counts.get(k, [[]] * (layer + 1))[layer]):
row[e] += c
return row
def fmt_pct(x):
return " - " if x != x else f"{100 * x:5.1f}%"
def main():
signal.signal(signal.SIGPIPE, signal.SIG_DFL) # quiet under | head
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("file")
ap.add_argument("--kinds", default="prefill,decode,mixed", help="what the 'all' columns sum")
ap.add_argument("--json", help="also write the per-layer metrics and the verdict here")
ap.add_argument("--top", type=int, default=0, help="also list each layer's N hottest experts (all kinds)")
a = ap.parse_args()
d = json.load(open(a.file))
if d.get("format") != "radiance-expert-stats/1":
sys.exit(f"{a.file}: not a radiance-expert-stats/1 file (format {d.get('format')!r})")
kinds = [k for k in a.kinds.split(",") if k]
for k in kinds:
if k not in KINDS:
sys.exit(f"unknown kind {k!r}; one of {', '.join(KINDS)}")
counts = d["counts"]
L = d["n_layers"]
n_trunk = d.get("n_trunk_layers", L)
lex = d["layer_experts"]
topk = d["top_k"]
up = d.get("uptime_s", 0.0)
print(f"{a.file}: {safe(d.get('model', '?'))} ({safe(d.get('arch', '?'))}), TP{d.get('tp', '?')}, "
f"{'final' if d.get('final') else 'periodic'} write after {up / 60:.1f} min")
tok = d.get("tokens", {})
stp = d.get("steps", {})
print(" issued: " + ", ".join(f"{k} {tok.get(k, 0)} tokens / {stp.get(k, 0)} {'passes' if k == 'draft' else 'steps'}"
for k in KINDS) + f" (mixed: {d.get('mixed_decode_tokens', 0)} decode tokens)")
ranks = d.get("ranks", {})
print(f" drain: {sum(ranks.get('credited', []))} histograms credited, {sum(ranks.get('dropped', []))} lost by the "
f"ring, {sum(ranks.get('unmapped', []))} unmapped selections, {sum(ranks.get('unclassified', []))} unclassified")
maps = sorted(set(safe(m) for m, n in zip(d.get("map", []), lex) if n > 0))
print(f" ids: {', '.join(maps)}; summing {'+'.join(kinds)} as 'all'")
# Self-check: selections == observed tokens x top_k, per kind and layer.
bad = []
for k in KINDS:
sel = d["selections"][k]
ot = d["observed_tokens"][k]
for l in range(L):
if lex[l] == 0 or (sel[l] == 0 and ot[l] == 0):
continue
if sel[l] != ot[l] * topk[l]:
bad.append(f"{k} L{l}: {sel[l]} selections vs {ot[l]} tokens x top-{topk[l]}")
print(" self-check: " + ("every layer's selections == observed tokens x top_k" if not bad else
f"{len(bad)} mismatches, e.g. " + "; ".join(bad[:4])))
print()
hdr = (f"{'layer':>5} {'n':>4} {'k':>3} {'sel(all)':>11} {'top5%':>6} {'top10%':>6} {'top20%':>6} {'gini':>5} "
f"{'never':>5} | {'dec top20':>9} {'pf top20':>8} {'d@pfTop':>7} {'jacc':>5} {'tvd':>5} {'dec never':>9}")
print(hdr)
rows = []
for l in range(L):
n = lex[l]
if n == 0:
continue
head = l >= n_trunk
allk = ["draft"] if head else kinds
x = summed(counts, allk, l, n)
dec = summed(counts, ["decode"], l, n)
pf = summed(counts, ["prefill"], l, n)
r = {"layer": l, "head": head, "n": n, "top_k": topk[l], "selections": sum(x),
"top5": top_share(x, 0.05), "top10": top_share(x, 0.10), "top20": top_share(x, 0.20),
"gini": gini(x), "never": sum(1 for c in x if c == 0),
"dec_top20": top_share(dec, 0.20), "pf_top20": top_share(pf, 0.20),
"dec_never": sum(1 for c in dec if c == 0) if sum(dec) else None}
if sum(dec) and sum(pf):
pt = top_set(pf, 0.20)
dt = top_set(dec, 0.20)
r["dec_on_pf_top20"] = sum(dec[e] for e in pt) / sum(dec)
r["jaccard_top20"] = len(pt & dt) / max(1, len(pt | dt))
r["tvd"] = tvd(dec, pf)
else:
r["dec_on_pf_top20"] = r["jaccard_top20"] = r["tvd"] = float("nan")
rows.append(r)
print(f"{('H' if head else 'L') + str(l):>5} {n:>4} {topk[l]:>3} {r['selections']:>11} {fmt_pct(r['top5'])} "
f"{fmt_pct(r['top10'])} {fmt_pct(r['top20'])} {r['gini']:5.3f} {r['never']:>5} | "
f"{fmt_pct(r['dec_top20']):>9} {fmt_pct(r['pf_top20']):>8} {fmt_pct(r['dec_on_pf_top20']):>7} "
f"{r['jaccard_top20']:5.2f} {r['tvd']:5.3f} {('-' if r['dec_never'] is None else r['dec_never']):>9}")
if a.top:
hot = sorted(range(n), key=lambda e: -x[e])[:a.top]
print(" hottest: " + " ".join(f"e{e}:{x[e] / max(1, sum(x)) * 100:.1f}%" for e in hot))
trunk = [r for r in rows if not r["head"] and r["selections"] > 0]
verdict = {"layers": len(trunk)}
print()
if not trunk:
print("verdict: no trunk selections recorded")
else:
def mean(key):
v = [r[key] for r in trunk if r[key] == r[key]]
return sum(v) / len(v) if v else float("nan")
m20, m10, mg = mean("top20"), mean("top10"), mean("gini")
never = sum(r["never"] for r in trunk)
experts = sum(r["n"] for r in trunk)
mdec = mean("dec_on_pf_top20")
mtvd = mean("tvd")
mdt, mpt = mean("dec_top20"), mean("pf_top20")
# How much of decode's concentration sits on prefill's hot set: (share on prefill's top 20 % - 20 %) over
# (decode's own top-20 % share - 20 %); 1 = the same hot experts, 0 = no better than chance.
shr = [(r["dec_on_pf_top20"] - 0.2) / (r["dec_top20"] - 0.2) for r in trunk
if r["dec_on_pf_top20"] == r["dec_on_pf_top20"] and r["dec_top20"] - 0.2 > 0.05]
shared = sum(shr) / len(shr) if shr else float("nan")
# Uniform routing puts 20 % of selections on the top 20 % (plus sampling noise); thresholds are judgement
# calls for the E3/E4/E5 decision, stated so they can be argued with.
if m20 >= 0.50 or mg >= 0.45:
skew = "SKEWED"
act = ("worth per-expert types (E4: hot/cold tables) and REAP-style pruning of the cold tail (E5); "
"per-layer reallocation (E3) too")
elif m20 >= 0.35 or mg >= 0.25:
skew = "MODERATE"
act = "per-layer reallocation (E3) first; E4/E5 only for the most skewed layers"
else:
skew = "FLAT"
act = "usage is near uniform: per-layer reallocation (E3) only; pruning would cut used experts"
if mdec != mdec:
dp = "no decode/prefill comparison (one of them has no selections)"
elif mdt < 0.3 and mpt < 0.3:
dp = "decode and prefill are both near flat, so there is no hot set to share"
elif shared != shared:
dp = "decode is near flat; prefill is not"
elif shared >= 0.6:
dp = f"decode's hot experts are mostly prefill's (shared {shared:.2f})"
elif shared < 0.3:
dp = f"decode and prefill favour different experts (shared {shared:.2f})"
else:
dp = f"decode and prefill partly share their hot experts (shared {shared:.2f})"
verdict.update({"skew": skew, "mean_top10": m10, "mean_top20": m20, "mean_gini": mg,
"never_selected": never, "experts": experts, "mean_decode_on_prefill_top20": mdec,
"mean_tvd": mtvd, "mean_decode_top20": mdt, "mean_prefill_top20": mpt,
"hot_set_shared": shared, "decode_vs_prefill": dp, "action": act})
sel = sum(r["selections"] for r in trunk)
print(f"verdict: {skew} -- over {len(trunk)} trunk layers ({sel} selections): top 10 % of experts take "
f"{fmt_pct(m10).strip()}, top 20 % take {fmt_pct(m20).strip()} (uniform: 20 %), mean Gini {mg:.3f}; "
f"{never} of {experts} experts never selected")
print(f" {dp}: top 20 % take {fmt_pct(mdt).strip()} of decode, {fmt_pct(mpt).strip()} of prefill; "
f"decode puts {fmt_pct(mdec).strip()} of its selections on prefill's top 20 %; mean TVD {mtvd:.3f}")
print(f" -> {act}")
if sel < 100 * experts:
print(f" caution: {sel / experts:.0f} selections an expert on average; rank tails are noisy below ~100")
if a.json:
with open(a.json, "w") as f:
json.dump({"layers": rows, "verdict": verdict}, f, indent=1, default=lambda o: None)
if __name__ == "__main__":
try:
main()
except (TypeError, ValueError, KeyError, IndexError, AttributeError) as e:
# A file that passes the format check but has the wrong shape underneath is untrusted
# data too: name the fault on one line rather than print a traceback to read past.
sys.exit(f"expert_stats_report: malformed stats file: {e}")
+4 -4
View File
@@ -17,7 +17,7 @@
# context (0% prefix hit, minutes per turn). Watch kv_util; the hit rate drops sharply as the pool
# fills.
#
# Defaults are the production shape (gpu-headroom-mib 96, kv-cache-dtype fp8,
# Defaults are the production shape (gpu-headroom-mib 96, kv-cache-dtype i8,
# max-num-batched-tokens 2048, tp 2, speculation depth 3), with the prefix cache on and
# --checkpoint-slots at its default, as multi-turn chat needs both.
#
@@ -75,12 +75,12 @@ BUILD="${BUILD:-$ROOT/build}"
cd "$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" \
nohup "$ROOT/scripts/radiance-flags" ./bin/radiance --model "$M" \
--radiance-home 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} --kv-cache-dtype ${KVD:-fp8} \
--tp ${TP:-2} --placement expert_tiered --host-pool-mib ${HOSTPOOL:-24576} \
--gpu-headroom-mib ${HR:-96} --kv-cache-dtype ${KVD:-i8} \
--prefix-cache-mib ${KVHOST:-4096} \
--num-speculative-tokens ${NS:-3} \
--max-num-batched-tokens ${MNBT:-2048} \
+3 -3
View File
@@ -35,12 +35,12 @@ pkill -f "bin/radianc[e]"; while pgrep -f "bin/radianc[e]" >/dev/null; do sleep
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" \
"$ROOT/scripts/radiance-flags" ./bin/radiance --model "$M" \
--radiance-home 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} --kv-cache-dtype ${KVD:-fp8} \
--tp ${TP:-2} --placement expert_tiered --host-pool-mib ${HOSTPOOL:-24576} \
--gpu-headroom-mib ${HR:-96} --kv-cache-dtype ${KVD:-i8} \
--num-speculative-tokens ${NS:-3} \
--max-num-batched-tokens ${MNBT:-2048} \
$EXTRA > "$HOME/fntrace.log" 2>&1 &
+12 -6
View File
@@ -44,9 +44,11 @@ set -e
if [ -n "$HFGET_CHILD" ]; then
size=${1%% *}; rest=${1#* }; oid=${rest%% *}; path=${rest#* }
# The parent has vetted every name; this holds anyway, because $out is written straight
# from it and an escape writes outside the directory the operator named.
# from it and an escape writes outside the directory the operator named. The `*/..` arm
# closes the trailing-segment gap (../.. is the prefix arm, a/../b the interior one), and
# the quoted `?` is literal, where a bare one would be the single-character wildcard.
case "$path" in
""|/*|*/|.|..|../*|*/../*)
""|/*|*/|.|..|../*|*/../*|*/..|*'#'*|*'?'*)
echo "hfget: refusing a file named '$path', which does not land inside the destination" >&2
exit 1;;
esac
@@ -137,17 +139,21 @@ done
echo "hfget: $page page(s) of listing"
# A file name that does not land inside the destination is not a listing oddity: an absolute
# path, a `..` segment, a control character (a tab splices one entry into two fields of the
# transfer list), or a name shadowing hfget's own manifest, which the next run would read back
# as its record of verified content. Name the entry and stop; skipping silently would leave a
# directory that reads as complete and is not.
# transfer list), a `#` or `?` (curl ends the path there and requests the fragment- or query-
# stripped object, which for a listing chosen to match is a real object with the listed size
# and oid -- the bytes arrive, the name never asked for lands, and no check can tell), or a
# name shadowing hfget's own manifest, which the next run would read back as its record of
# verified content. Name the entry and stop; skipping silently would leave a directory that
# reads as complete and is not.
bad=$(printf '%s' "$listing" | jq -r '[.[] | select(.type == "file")
| select((.path | test("(^/|(^|/)\\.\\.(/|$))"))
or (.path | test("[[:cntrl:]]"))
or (.path | test("[#?]"))
or (.path | test("(^|/)[.]hfget-manifest")))] | map(.path) | join(", ")')
[ -n "$bad" ] && { echo "hfget: the listing names '$bad', which does not land inside the destination" >&2; exit 1; }
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|msgpack|h5|onnx|onnx_data|gguf)$") or test("(^|/)(pytorch_model|consolidated)[^/]*\\.pth$")) | not)'
[ "$have_st" -gt 0 ] && sel="$sel"' | select((.path | test("\\.(bin|msgpack|h5|onnx|onnx_data|gguf|rad)$") or test("(^|/)(pytorch_model|consolidated)[^/]*\\.pth$")) | not)'
list=$(mktemp "${TMPDIR:-/tmp}/hfget.XXXXXX")
trap 'rm -f "$list" "$dest/.hfget-manifest.tmp"' EXIT INT TERM
+1 -2
View File
@@ -13,8 +13,7 @@
#
# The rest of the pipeline directory (model_index.json, scheduler/, text_encoder/, tokenizer/, vae/,
# transformer/config.json) is the release's: Raw and Turbo ship identical parts but for
# model_index.json, whose `is_distilled` selects Turbo's sampling (8 steps, no guidance). A finetune
# stored as plain fp8 converts with data/recipes/krea-2-fp8-unscaled.recipe.
# model_index.json, whose `is_distilled` selects Turbo's sampling (8 steps, no guidance).
#
# Needs only python3; the data is copied, never decoded.
import json
+3 -3
View File
@@ -32,8 +32,8 @@ MODEL = os.environ.get("MODEL", "/models/qwen3.8-next-flash-fp8-iq4r-moe.rad")
OUT = os.environ.get("OUT", "/tmp/radiance-kv-multiturn")
BASE = ["--model", MODEL, "--tp", "2", "--tp-wire", "exact", "--max-num-seqs", "2",
"--max-model-len", "65536",
"--placement", "expert_tiered", "--host-pool-mib", "23652", "--gpu-headroom-mib", "96",
"--kv-cache-dtype", "fp8", "--prefix-cache-mib", "1024", "--prefix-cache-ttl", "0",
"--placement", "expert_tiered", "--host-pool-mib", "47304", "--gpu-headroom-mib", "96",
"--kv-cache-dtype", "i8", "--prefix-cache-mib", "1024", "--prefix-cache-ttl", "0",
"--vision-tower-placement", "ram", "--num-speculative-tokens", "0", "--deterministic",
"--host", "127.0.0.1", "--api-key", "test"]
@@ -120,7 +120,7 @@ class Server:
"--device", "/dev/kfd", "--device", "/dev/dri", "--group-add", "990", "--group-add", "44",
"--security-opt", "seccomp=unconfined", "--network", "host",
"-v", f"{ROOT}:/src", "-v", f"{MODELS}:/models", "-w", "/src", "rad-toolchain:latest",
"bash", "-lc", f"RADIANCE_HOME={BUILD}/radiance_home {BUILD}/bin/radiance " + " ".join(self.flags)],
"bash", "-lc", f"RADIANCE_HOME={BUILD}/radiance_home /src/scripts/radiance-flags {BUILD}/bin/radiance " + " ".join(self.flags)],
stdout=open(self.logf, "w"), stderr=subprocess.STDOUT)
t0 = time.time()
while time.time() - t0 < 300:
+3 -3
View File
@@ -96,10 +96,10 @@ content_of() {
run_arm() { local arm="$1" prompt="$2"; shift 2
local log="$OUT/$arm.log" req="$OUT/$arm.req.json" resp="$OUT/$arm.json"
echo "== $arm: $* =="
( exec "$BIN" --model "$MODEL" \
( exec "$ROOT/scripts/radiance-flags" "$BIN" --model "$MODEL" \
--tp 2 --tp-wire exact \
--max-num-seqs 1 --max-model-len 4096 --placement expert_tiered --host-pool-mib 23652 \
--kv-cache-dtype fp8 --prefix-cache-mib 4096 --vision-tower-placement ram \
--max-num-seqs 1 --max-model-len 4096 --placement expert_tiered --host-pool-mib 47304 \
--kv-cache-dtype i8 --prefix-cache-mib 4096 --vision-tower-placement ram \
--num-speculative-tokens 0 --deterministic \
"$@" --host 127.0.0.1 --port "$PORT" --api-key test ) > "$log" 2>&1 &
SERVER_PID=$!
+3 -3
View File
@@ -194,8 +194,8 @@ printf '{"model":"qwen4exp","temperature":0,"seed":%s,"max_tokens":%s,"ignore_eo
# --max-num-seqs 2 and SPEC 3 that ceiling is 2 x 4 x 513 = 4 104 blocks, under 8 192, so 32 768
# tokens is not raised.
FLAGS=(--model "$MODEL_IN" --tp 2 --tp-wire exact --max-num-seqs 2 --max-model-len 204800
--placement expert_tiered --host-pool-mib 23652 --gpu-headroom-mib 96
--kv-cache-dtype fp8 --prefix-cache-mib 1024 --prefix-cache-ttl 0
--placement expert_tiered --host-pool-mib 47304 --gpu-headroom-mib 96
--kv-cache-dtype i8 --prefix-cache-mib 1024 --prefix-cache-ttl 0
--vision-tower-placement ram --num-speculative-tokens "$SPEC" --deterministic
--host 127.0.0.1 --port "$PORT" --api-key test)
@@ -209,7 +209,7 @@ start_arm() { # $1 arm, $2 tag; sets RUN_NAME and writes $OUT/$2.server.log
--security-opt seccomp=unconfined --network host \
-v "$ROOT:/src" -v "$(dirname "$MODEL"):/models" \
-w /src "$TOOLCHAIN" \
bash -lc "RADIANCE_HOME=$BUILD/radiance_home exec $BUILD/bin/radiance ${FLAGS[*]} --kv-resident $RESIDENT" \
bash -lc "RADIANCE_HOME=$BUILD/radiance_home exec /src/scripts/radiance-flags $BUILD/bin/radiance ${FLAGS[*]} --kv-resident $RESIDENT" \
> "$OUT/$tag.server.log" 2>&1 &
;;
stock)
+3 -3
View File
@@ -86,10 +86,10 @@ run_arm() {
local log="$OUT/$arm.log" req="$OUT/$arm.req.json" resp="$OUT/$arm.json"
local envs=("$@")
echo "== $arm: $flags ${envs[*]:-} =="
( exec env "${envs[@]}" "$BIN" --model "$MODEL" \
( exec env "${envs[@]}" "$ROOT/scripts/radiance-flags" "$BIN" --model "$MODEL" \
--tp 2 --tp-wire exact \
--max-num-seqs 1 --max-model-len "$MAXLEN" --placement expert_tiered --host-pool-mib 23652 \
--kv-cache-dtype fp8 --prefix-cache-mib 4096 --vision-tower-placement ram \
--max-num-seqs 1 --max-model-len "$MAXLEN" --placement expert_tiered --host-pool-mib 47304 \
--kv-cache-dtype i8 --prefix-cache-mib 4096 --vision-tower-placement ram \
--num-speculative-tokens 0 --deterministic \
$flags --host 127.0.0.1 --port "$PORT" --api-key test ) > "$log" 2>&1 &
SERVER_PID=$!
+3 -3
View File
@@ -99,10 +99,10 @@ stream_line() {
run_arm() { local arm="$1" prompt="$2" ctx="$3" maxtok="$4"; shift 4
local log="$OUT/$arm.log" req="$OUT/$arm.req.json" resp="$OUT/$arm.json"
echo "== $arm: max-model-len $ctx, max_tokens $maxtok, $* =="
( exec "$BIN" --model "$MODEL" \
( exec "$ROOT/scripts/radiance-flags" "$BIN" --model "$MODEL" \
--tp 2 --tp-wire exact \
--max-num-seqs 1 --max-model-len "$ctx" --placement expert_tiered --host-pool-mib 23652 \
--kv-cache-dtype fp8 --prefix-cache-mib 4096 --vision-tower-placement ram \
--max-num-seqs 1 --max-model-len "$ctx" --placement expert_tiered --host-pool-mib 47304 \
--kv-cache-dtype i8 --prefix-cache-mib 4096 --vision-tower-placement ram \
--num-speculative-tokens 0 --deterministic \
"$@" --host 127.0.0.1 --port "$PORT" --api-key test ) > "$log" 2>&1 &
SERVER_PID=$!
+7 -7
View File
@@ -1,25 +1,25 @@
#!/bin/sh
# Start MiniCPM5-2B (fp8) as a long-lived server, like scripts/fnserve.sh: wait for /health, print
# Start MiniCPM5-2B (IQ8R) as a long-lived server, like scripts/fnserve.sh: wait for /health, print
# the endpoints and exit with the server still up. Stop it with scripts/fnstop.sh.
#
# Context is 131072, this checkpoint's n_ctx_train (the 200K of fnserve.sh is Flash-Next's).
#
# 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.
# KV is 21.3 KiB a token at int8 (42 layers x 2 kv heads x (128 x 2 planes of codes + 4 bytes of
# scales)), halved per rank at tp 2, so a full-length sequence costs 1.40 GiB a rank and 8 of them
# do not fit. The pool is a capacity, not a per-request reservation.
P="${P:-8100}"
M="${M:-$HOME/models/rad/minicpm5-2b-dspark.v2.rad}"
M="${M:-$HOME/models/rad/minicpm5-2b-iq8r.rad}"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BUILD="${BUILD:-$ROOT/build}"
cd "$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" \
nohup "$ROOT/scripts/radiance-flags" ./bin/radiance --model "$M" \
--radiance-home 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} \
--gpu-headroom-mib ${HR:-160} --kv-cache-dtype ${KVD:-i8} \
--max-num-batched-tokens ${MNBT:-512} \
$EXTRA > "$HOME/mcserve.log" 2>&1 &
echo "starting, log: ~/mcserve.log"
+2 -2
View File
@@ -14,10 +14,10 @@ pkill -f "bin/radianc[e]"; while pgrep -f "bin/radianc[e]" >/dev/null; do sleep
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" \
"$ROOT/scripts/radiance-flags" ./bin/radiance --model "$M" \
--radiance-home 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 \
--gpu-headroom-mib 160 --kv-cache-dtype i8 --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
+1 -1
View File
@@ -82,7 +82,7 @@ env GPU_MAX_ALLOC_PERCENT=100 GPU_MAX_HEAP_SIZE=100 \
RADIANCE_OP_ORACLE_FROM="${FROM:-0}" \
RADIANCE_OP_ORACLE_TOL="${TOL:-0.02}" \
${TO:+RADIANCE_OP_ORACLE_TO=$TO} \
nohup ./bin/radiance --model "$M" \
nohup "$ROOT/scripts/radiance-flags" ./bin/radiance --model "$M" \
--radiance-home radiance_home \
--host 127.0.0.1 --port "$P" \
--max-num-seqs 1 --max-model-len "${MLEN:-8192}" --tp "${TP:-1}" \
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
# radiance-flags BIN FLAGS... -- run the radiance binary BIN configured by a pre-2.0 command line.
#
# The server reads only a YAML file (radiance --config, docs/MULTIMODEL.md §4). This writes FLAGS
# as that file with rad-yaml (the tool beside BIN), then replaces itself with `BIN --config FILE`,
# so the process a script waits on, signals or greps for is the server itself. The file goes to
# $TMPDIR and is left there for the run's record.
set -euo pipefail
bin="$1"; shift
cfg="$(mktemp "${TMPDIR:-/tmp}/radiance.XXXXXX.yaml")"
"$(dirname "$bin")/rad-yaml" "$@" > "$cfg"
exec "$bin" --config "$cfg"