Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

Merge the shared expert tier for every MoE engine into the dense chain

JustVugg7b20dc7f5fc8
diff --cc .github/workflows/ci.yml
index a6373cee,036a071f..0efc3695
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@@ -168,14 -168,11 +168,17 @@@ jobs
# the routed-expert tier of qwen36 and qwen38 under ASan and UBSan
- family: qwen-sanitize
req: c/tools/requirements-qwen38-tiny.txt
+ # the dense chain (COLI_VK_CHAIN=1) of qwen36 and qwen38, and the same under
+ # ASan and UBSan
+ - family: qwen-chain
+ req: c/tools/requirements-qwen38-tiny.txt
+ - family: qwen-chain-sanitize
+ req: c/tools/requirements-qwen38-tiny.txt
- family: inkling-olmoe
req: c/tools/oracle-requirements.txt
+ # the routed-expert tier of inkling and olmoe under ASan and UBSan
+ - family: inkling-olmoe-sanitize
+ req: c/tools/oracle-requirements.txt
- family: mimo-qwenimage
req: c/tools/requirements-qwenimage-tiny.txt
- family: deepseek
diff --cc c/Makefile
index 58ff051a,1110a0a0..f374f148
--- a/c/Makefile
+++ b/c/Makefile
@@@ -708,13 -707,8 +708,14 @@@ endi
# that does not call it links nothing from it.
VK_OBJ = backend_vulkan.o vk_tier.o
VK_SPV = shaders/qmatmul.spv shaders/qmatmul_gate_up.spv shaders/attention_absorb.spv shaders/rmsnorm.spv \
- shaders/qmatmul_gemm.spv shaders/qmatmul_coop.spv shaders/expert_act.spv
+ shaders/qmatmul_gemm.spv shaders/qmatmul_coop.spv shaders/expert_act.spv \
+ shaders/expert_act_v4.spv
+# vk_chain.o: a layer's dense chain recorded into one submission (vk_chain.h), and
+# its shaders; an engine that does not call it links nothing from it.
+VK_OBJ += vk_chain.o
+VK_SPV += shaders/chain_norm.spv shaders/chain_rope.spv shaders/chain_attn.spv shaders/chain_dnconv.spv \
+ shaders/chain_dnrec.spv shaders/chain_ew.spv shaders/chain_qsa.spv shaders/chain_ple.spv \
+ shaders/chain_gemv.spv
endif
# Optional AMD XDNA2 (Ryzen AI NPU) lane, Windows. Same opt-in shape as VK=1:
diff --cc c/tests/vulkan_engines.sh
index 1e2358d1,62bf31a2..a403e809
--- a/c/tests/vulkan_engines.sh
+++ b/c/tests/vulkan_engines.sh
@@@ -2,9 -2,10 +2,11 @@@
# Every engine's Vulkan path against its own CPU run, on Lavapipe (Mesa's software
# Vulkan), one family per call so CI can run them side by side:
#
- # bash tests/vulkan_engines.sh qwen | qwen-sanitize | inkling-olmoe | mimo-qwenimage | deepseek
+ # bash tests/vulkan_engines.sh qwen | qwen-sanitize | inkling-olmoe | inkling-olmoe-sanitize
+ # bash tests/vulkan_engines.sh mimo-qwenimage | kimi | kimi-mimo-sanitize | deepseek | deepseek-sanitize
+ # bash tests/vulkan_engines.sh glm | glm-sanitize # GLM-5.2 (colibri) and GLM-5.3 Flash (glm53)
# bash tests/vulkan_engines.sh shader # the qmatmul formats, the expert batch and the tier, no engine
+# bash tests/vulkan_engines.sh qwen-chain | qwen-chain-sanitize # the dense chain (COLI_VK_CHAIN=1)
#
# Needs libvulkan-dev, glslc and mesa-vulkan-drivers, plus the Python packages of
# the family's tiny fixtures (see the vulkan-engines job in .github/workflows/ci.yml).
@@@ -464,204 -703,457 +704,646 @@@ print("OK deepseek_v4 session: ids = CP
sys.exit(0 if ok else 1)
PY
need_gpu deepseek_v4 v4-vk.err "deepseek_v4 session"
- echo "OK deepseek_v4: $(vk_count deepseek_v4 v4-vk.err) matmuls on the GPU"
+ echo "OK deepseek_v4: $(vk_count deepseek_v4 v4-vk.err) matmuls on the GPU, $(grep -a -o 'device [0-9]* of [0-9]* routed experts' v4-vk.err | tail -1)"
+
+ # The routed-expert tier on deepseek_v4's fp4 experts (fmt 7) with its own
+ # activation (VKT_ACT_SWIGLU_V4: the CPU kernel's bf16 and E4M3 roundings and the
+ # route weight before down, on the device). Every oracle case against the CPU run:
+ # ids equal to the CPU's and the reference's, teacher-forced predictions equal,
+ # routed experts served by the device. The history is the store's own .coli_usage
+ # in the fixture, removed before each run unless WARM=1 (the tier then warm-starts
+ # from the CPU run's): the runs use a copy of the fixture, whose committed history
+ # stays as it is. An 8-expert variant of the fixture has room for pinned hot
+ # experts, which the store keeps in its rows16 layout: the tier gets them unpacked.
+ rm -rf deepseek_v4_tiny_t && cp -r deepseek_v4_tiny deepseek_v4_tiny_t
+ $PY - tools/make_deepseek_v4_tiny.py deepseek_v4_tiny_e8 <<'PY'
+ import importlib.util, sys
+ spec = importlib.util.spec_from_file_location("gen", sys.argv[1])
+ gen = importlib.util.module_from_spec(spec); spec.loader.exec_module(gen)
+ gen.EXPERTS = 8 # 8 routed experts a layer: two cache slots a layer for pins
+ sys.argv = ["make_deepseek_v4_tiny.py", "--output", sys.argv[2], "--force"]
+ gen.main()
+ PY
+ v4_tier() { # <tag> <fixture> <case> <env...>
+ local tag=$1 fx=$2 c=$3; shift 3
+ local p mt
+ p=$($PY -c 'import json,sys; c=json.load(open(sys.argv[1]+"/ref.json"))["cases"][sys.argv[2]]; print("".join("<t%03d>" % t for t in c["prompt_ids"]))' $fx $c)
+ mt=$($PY -c 'import json,sys; print(json.load(open(sys.argv[1]+"/ref.json"))["cases"][sys.argv[2]]["max_new_tokens"])' $fx $c)
+ rm -f $fx/.coli_usage
+ env "$@" ./deepseek_v4 ./$fx "$p" --raw-prompt --max-tokens $mt --record-oracle v4-cpu.json > /dev/null 2> v4-cpu.err ||
+ { cat v4-cpu.err; fail "deepseek_v4 tier $tag: CPU run"; }
+ [ "${WARM:-0}" = 1 ] || rm -f $fx/.coli_usage
+ env "$@" COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 ./deepseek_v4 ./$fx "$p" --raw-prompt --max-tokens $mt --record-oracle v4-vk.json > /dev/null 2> v4-vk.err ||
+ { cat v4-vk.err; fail "deepseek_v4 tier $tag: Vulkan run"; }
+ rm -f $fx/.coli_usage
+ $PY - $fx $c <<'PY' || fail "deepseek_v4 tier $tag: the Vulkan session differs from the CPU's"
+ import json, sys
+ a, b = json.load(open("v4-cpu.json")), json.load(open("v4-vk.json"))
+ ref = json.load(open(sys.argv[1] + "/ref.json"))["cases"][sys.argv[2]]["greedy_full_ids"]
+ ok = a["full_ids"] == b["full_ids"] == ref and a["tf_pred"] == b["tf_pred"]
+ if not ok: print("CPU", a, "VK", b, "ref", ref)
+ sys.exit(0 if ok else 1)
+ PY
+ [ "$(tier_count deepseek_v4 v4-vk.err)" -gt 0 ] || { cat v4-vk.err; fail "deepseek_v4 tier $tag: no routed expert ran on the device"; }
+ if [ "${EVICT:-0}" = 1 ]; then
+ [ "$(tier_evictions deepseek_v4 v4-vk.err)" -gt 0 ] || { grep '\[VK\] tier' v4-vk.err; fail "deepseek_v4 tier $tag: the budget forced no eviction"; }
+ [ "$(tier_failed deepseek_v4 v4-vk.err)" = 0 ] || { grep '\[VK\] tier' v4-vk.err; fail "deepseek_v4 tier $tag: an upload failed (the budget shrank)"; }
+ fi
+ if [ "${WARM:-0}" = 1 ]; then
+ grep -q '^\[VK\] tier deepseek_v4: warm start' v4-vk.err || { grep '\[VK\] tier' v4-vk.err; fail "deepseek_v4 tier $tag: no warm start"; }
+ fi
+ echo "OK deepseek_v4 tier $tag ($c): ids = CPU = reference, $(grep -a -o 'device [0-9]* of [0-9]* routed experts' v4-vk.err | tail -1), $(grep -a -o 'evictions [0-9]*' v4-vk.err | tail -1), $(grep -a -o 'packed_slots=[0-9]*' v4-vk.err) rows16"
+ }
+ for c in short compressed long; do
+ v4_tier "4 experts" deepseek_v4_tiny_t $c
+ v4_tier "8 experts, pinned rows16" deepseek_v4_tiny_e8 $c
+ done
+ EVICT=1 v4_tier "a budget of three experts" deepseek_v4_tiny_e8 long COLI_VK_TIER_GB=0.00009
+ v4_tier "trunk on the device too" deepseek_v4_tiny_t long COLI_VK_DENSE=1
+ v4_tier "the GEMM route from 2 rows" deepseek_v4_tiny_t long COLI_VK_TIER_GEMM_ROWS=2
+ WARM=1 v4_tier "warm start from the CPU run's history" deepseek_v4_tiny_e8 long
+ # A served prompt with every routed expert on the device (warm start from the CPU
+ # run's history): its per-position logprob echoes against the CPU's. Measured on
+ # Lavapipe they are the same bytes; the gate allows 1e-3, for an exp() that rounds
+ # one hidden value to the other bf16 neighbour on another driver.
+ $PY - deepseek_v4_tiny_e8 <<'PY' || fail "deepseek_v4 tier: served logprobs differ from the CPU's"
+ import json, os, sys
+ from pathlib import Path
+ sys.path.insert(0, "tests")
+ import test_deepseek_v4_brio as b
+ fx = Path(sys.argv[1])
+ case = json.load(open(fx / "ref.json"))["cases"]["long"]
+ def echoes(vk):
+ os.environ.pop("COLI_VULKAN", None)
+ if vk: os.environ.update(COLI_VULKAN="1", COLI_VK_TIER_SYNC="1")
+ else:
+ try: os.remove(fx / ".coli_usage")
+ except FileNotFoundError: pass
+ s = b.Serve(Path("deepseek_v4").resolve(), fx)
+ try: return s.submit(b.token_prompt(case["prompt_ids"]), 0, logprobs=5).echoes
+ finally:
+ s.close()
+ tier = [l for l in s.process.stderr.read().decode(errors="replace").splitlines() if "tier deepseek_v4 turn:" in l]
+ if vk: print(" ", tier[-1][:90] if tier else "no tier line")
+ cpu, dev = echoes(False), echoes(True)
+ os.environ.pop("COLI_VULKAN", None)
+ same = sum(cpu[p] == dev.get(p) for p in cpu)
+ worst = max(abs(cpu[p]["lp"] - dev[p]["lp"]) for p in cpu) if len(cpu) == len(dev) else 1.0
+ print(f"OK deepseek_v4 tier served: {same} of {len(cpu)} positions' logprob echoes identical to the CPU's, worst |delta| {worst:.2e}")
+ sys.exit(0 if len(cpu) == len(dev) and worst <= 1e-3 else 1)
+ PY
+ rm -rf deepseek_v4_tiny_t deepseek_v4_tiny_e8
+ }
+
+ # The routed-expert tier of both deepseek engines under ASan and UBSan: sanitized VK=1
+ # builds, the tier's configurations on Lavapipe (decode and prefill, eviction, DSpark,
+ # pinned rows16 experts, the warm start, the trunk on the device). Memory safety is
+ # the gate; each run must still put experts on the device.
+ family_deepseek_sanitize() {
+ local SAN="-fsanitize=address,undefined -fno-omit-frame-pointer -g"
+ make clean >/dev/null 2>&1 || true
+ make deepseek_v41 VK=1 EXTRA_CFLAGS="$SAN"
+ make deepseek-v4 VK=1 LTO=0 EXTRA_CFLAGS="$SAN" EXTRA_LDFLAGS="$SAN"
+ $PY tools/make_dsv41_tiny.py --out dsv41_tiny --emit-ref dsv41_tiny/ref.json
+ $PY tools/make_dsv41_tiny.py --out dsv41_long --emit-ref dsv41_long/ref.json --prompt-len 40 --max-new 6
+ $PY tools/make_deepseek_v4_tiny.py --output deepseek_v4_tiny_t --force
+ $PY - tools/make_deepseek_v4_tiny.py deepseek_v4_tiny_e8 <<'PY'
+ import importlib.util, sys
+ spec = importlib.util.spec_from_file_location("gen", sys.argv[1])
+ gen = importlib.util.module_from_spec(spec); spec.loader.exec_module(gen)
+ gen.EXPERTS = 8
+ sys.argv = ["make_deepseek_v4_tiny.py", "--output", sys.argv[2], "--force"]
+ gen.main()
+ PY
+ san() { # <engine> <tag> <env and argv...>
+ local eng=$1 tag=$2; shift 2
+ rm -f tier.usage deepseek_v4_tiny_t/.coli_usage deepseek_v4_tiny_e8/.coli_usage
+ env ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=print_stacktrace=1 OMP_NUM_THREADS=2 \
+ COLI_USAGE=tier.usage COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 "$@" > san.log 2>&1 || true
+ if grep -qE "ERROR: AddressSanitizer|runtime error:" san.log; then cat san.log; fail "$tag: sanitizer diagnostic"; fi
+ [ "$(tier_count "$eng" san.log)" -gt 0 ] || { cat san.log; fail "$tag: no routed expert ran on the device"; }
+ echo "OK $tag: sanitizers clean, $(grep -a -o 'device [0-9]* of [0-9]* routed experts' san.log | tail -1), $(grep -a -o 'evictions [0-9]*' san.log | tail -1)"
+ }
+ local cap force p
+ for cap in 1 8; do san deepseek_v41 "asan deepseek_v41 cap=$cap" SNAP=dsv41_long ./deepseek_v41 $cap dsv41_long/ref.json; done
+ for force in 2 4; do san deepseek_v41 "asan deepseek_v41 DSpark spec=$force" SNAP=dsv41_tiny V41_DSPARK=1 V41_SPEC_FORCE=$force ./deepseek_v41 1 dsv41_tiny/ref.json; done
+ san deepseek_v41 "asan deepseek_v41 eviction" COLI_VK_TIER_GB=0.00005 SNAP=dsv41_long ./deepseek_v41 8 dsv41_long/ref.json
+ san deepseek_v41 "asan deepseek_v41 trunk on the device" COLI_VK_DENSE=1 SNAP=dsv41_tiny ./deepseek_v41 2 dsv41_tiny/ref.json
+ p=$($PY -c 'import json; c=json.load(open("deepseek_v4_tiny_t/ref.json"))["cases"]["long"]; print("".join("<t%03d>" % t for t in c["prompt_ids"]))')
+ san deepseek_v4 "asan deepseek_v4" ./deepseek_v4 ./deepseek_v4_tiny_t "$p" --raw-prompt --max-tokens 4 --record-oracle san.json
+ san deepseek_v4 "asan deepseek_v4 pinned rows16" ./deepseek_v4 ./deepseek_v4_tiny_e8 "$p" --raw-prompt --max-tokens 4 --record-oracle san.json
+ san deepseek_v4 "asan deepseek_v4 eviction" COLI_VK_TIER_GB=0.00009 ./deepseek_v4 ./deepseek_v4_tiny_e8 "$p" --raw-prompt --max-tokens 4 --record-oracle san.json
+ san deepseek_v4 "asan deepseek_v4 trunk on the device" COLI_VK_DENSE=1 ./deepseek_v4 ./deepseek_v4_tiny_t "$p" --raw-prompt --max-tokens 4
+ # the warm start: a run that leaves its history, then one that starts from it
+ ./deepseek_v4 ./deepseek_v4_tiny_e8 "$p" --raw-prompt --max-tokens 4 > /dev/null 2>&1 || true
+ env ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=print_stacktrace=1 OMP_NUM_THREADS=2 COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 \
+ ./deepseek_v4 ./deepseek_v4_tiny_e8 "$p" --raw-prompt --max-tokens 4 > san.log 2>&1 || true
+ if grep -qE "ERROR: AddressSanitizer|runtime error:" san.log; then cat san.log; fail "asan deepseek_v4 warm start: sanitizer diagnostic"; fi
+ grep -q '^\[VK\] tier deepseek_v4: warm start' san.log || { cat san.log; fail "asan deepseek_v4 warm start: no warm start"; }
+ echo "OK asan deepseek_v4 warm start: sanitizers clean, $(grep -a -o 'device [0-9]* of [0-9]* routed experts' san.log | tail -1)"
+ rm -rf deepseek_v4_tiny_t deepseek_v4_tiny_e8 san.json
+ make clean >/dev/null 2>&1 || true
+ make deepseek-v4-clean >/dev/null 2>&1 || true
+ }
+
+ # Kimi K3: the routed experts on the shared tier (MXFP4 with ue8m0 scales, fmt 7,
+ # SiTU-GLU in the latent space), against Moonshot's vendor oracle and the CPU run.
+ # K3_IDOT=0 everywhere: the CPU's default int8-activation expert kernel is an
+ # approximation the device does not make (the oracle's engine_env sets it too).
+ family_kimi() {
+ make kimi_k3 VK=1
+ $PY tools/make_kimi_k3_tiny.py --output ./kimi_k3_tiny --force
+ # Moonshot's oracle (greedy, teacher forcing at every position, determinism, the
+ # bite) with the tier on, the shared experts where the default puts them (the CPU
+ # on Lavapipe) and on the device
+ COLI_USAGE=$PWD/k3.usage USAGE_SAVE=0 COLI_VULKAN=1 COLI_VK_TIER_SYNC=1 \
+ $PY tests/test_kimi_k3_tiny.py --binary ./kimi_k3 --fixture ./kimi_k3_tiny
+ COLI_USAGE=$PWD/k3.usage USAGE_SAVE=0 COLI_VULKAN=1 COLI_VK_TIER_SYNC=1 COLI_VK_DENSE=1 \
+ $PY tests/test_kimi_k3_tiny.py --binary ./kimi_k3 --fixture ./kimi_k3_tiny
+ k3ids() { $PY -c "import json,sys;print(' '.join(map(str,json.load(open('kimi_k3_tiny/ref.json'))['cases'][sys.argv[1]]['prompt_ids'])))" "$1"; }
+ # k3_gate <tag> <env...>: the tokens of the CPU run, the tier served some experts,
+ # the shared experts where they were asked to be (dense_where); EVICT=1: it evicted
+ k3_gate() {
+ local tag=$1 c; shift
+ for c in short chunk long; do
+ rm -f k3.usage
+ env "$@" COLI_USAGE=$PWD/k3.usage USAGE_SAVE=0 ./kimi_k3 kimi_k3_tiny --ids "$(k3ids $c)" --ngen 8 2>/dev/null | sed 's/ *TUNE.*//' > cpu.tok
+ env "$@" COLI_USAGE=$PWD/k3.usage USAGE_SAVE=0 COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 \
+ ./kimi_k3 kimi_k3_tiny --ids "$(k3ids $c)" --ngen 8 2> vk.log | sed 's/ *TUNE.*//' > vk.tok
+ { [ -s cpu.tok ] && cmp -s cpu.tok vk.tok; } || { cat cpu.tok vk.tok vk.log; fail "$tag $c: Vulkan tokens differ from the CPU"; }
+ [ "$(tier_count kimi_k3 vk.log)" -gt 0 ] || { cat vk.log; fail "$tag $c: no routed expert ran on the device"; }
+ if [ "${EVICT:-0}" = 1 ]; then
+ [ "$(tier_evictions kimi_k3 vk.log)" -gt 0 ] || { grep '\[VK\] tier' vk.log; fail "$tag $c: the budget forced no eviction"; }
+ grep -q ' failed 0 ' vk.log || { grep '\[VK\] tier' vk.log; fail "$tag $c: an upload failed"; }
+ fi
+ local where; where=$(dense_where kimi_k3 vk.log "$tag $c" "$@") || { echo "$where"; exit 1; }
+ echo "OK $tag $c: tokens = CPU, $(grep -a -o 'device [0-9]* of [0-9]* routed experts' vk.log | tail -1), $(grep -a -o 'evictions [0-9]*' vk.log | tail -1), shared experts on the $where"
+ done
+ }
+ local O="K3_BITS=32 K3_MLA_BITS=32 K3_HEAD_BITS=32 K3_IDOT=0 COLI_TEMP=0" b
+ k3_gate "kimi_k3 tier f32" $O
+ k3_gate "kimi_k3 tier f32, shared experts on the device" $O COLI_VK_DENSE=1
+ for b in 8 4; do # the shared experts as int8 rows (fmt 1) and int4-g64 (fmt 4) on the device
+ k3_gate "kimi_k3 tier K3_BITS=$b, shared experts on the device" K3_BITS=$b K3_MLA_BITS=$b K3_HEAD_BITS=$b K3_IDOT=0 COLI_TEMP=0 COLI_VK_DENSE=1
+ done
+ k3_gate "kimi_k3 tier, prefill one token at a time" $O K3_CHUNK=1
+ k3_gate "kimi_k3 tier, loads not pipelined" $O K3_PIPE=0
+ EVICT=1 k3_gate "kimi_k3 tier, a budget of two experts" $O COLI_VK_TIER_GB=0.000005
+ # the old switches: K3_VK=1 opens the device as COLI_VULKAN=1 does and K3_VK_GB caps
+ # the tier; K3_VK=0 keeps it closed whatever COLI_VULKAN says
+ rm -f k3.usage
+ env $O COLI_USAGE=$PWD/k3.usage USAGE_SAVE=0 ./kimi_k3 kimi_k3_tiny --ids "$(k3ids long)" --ngen 8 2>/dev/null | sed 's/ *TUNE.*//' > cpu.tok
+ env $O COLI_USAGE=$PWD/k3.usage USAGE_SAVE=0 COLI_VK_TIER_SYNC=1 K3_VK=1 K3_VK_GB=0.000005 \
+ ./kimi_k3 kimi_k3_tiny --ids "$(k3ids long)" --ngen 8 2> vk.log | sed 's/ *TUNE.*//' > vk.tok
+ cmp -s cpu.tok vk.tok || { cat vk.log; fail "kimi_k3 K3_VK=1: tokens differ from the CPU"; }
+ grep -q 'K3_VK=1 read as COLI_VULKAN=1' vk.log && grep -q 'budget [0-9.]* KiB = 2 experts' vk.log &&
+ [ "$(tier_count kimi_k3 vk.log)" -gt 0 ] || { cat vk.log; fail "kimi_k3 K3_VK=1 K3_VK_GB: not the tier it asked for"; }
+ env $O COLI_USAGE=$PWD/k3.usage USAGE_SAVE=0 K3_VK=0 COLI_VULKAN=1 \
+ ./kimi_k3 kimi_k3_tiny --ids "$(k3ids long)" --ngen 8 2> vk.log | sed 's/ *TUNE.*//' > vk.tok
+ cmp -s cpu.tok vk.tok && ! grep -q '^\[VK\]' vk.log || { cat vk.log; fail "kimi_k3 K3_VK=0: the device opened"; }
+ echo "OK kimi_k3 K3_VK=1 / K3_VK_GB / K3_VK=0: the shared tier's switches"
+ # a warm start from the history of the run before: the tier starts full, serves
+ # every routed expert of the same prompt, and the tokens stay the CPU's
+ rm -f k3.usage
+ env $O COLI_USAGE=$PWD/k3.usage COLI_VULKAN=1 COLI_VK_TIER_SYNC=1 ./kimi_k3 kimi_k3_tiny --ids "$(k3ids long)" --ngen 8 > /dev/null 2>&1
+ env $O COLI_USAGE=$PWD/k3.usage USAGE_SAVE=0 COLI_VULKAN=1 COLI_VK_TIER_SYNC=1 \
+ ./kimi_k3 kimi_k3_tiny --ids "$(k3ids long)" --ngen 8 2> vk.log | sed 's/ *TUNE.*//' > vk.tok
+ cmp -s cpu.tok vk.tok || { cat vk.log; fail "kimi_k3 warm start: tokens differ from the CPU"; }
+ grep -q 'tier kimi_k3: warm start, [1-9]' vk.log || { cat vk.log; fail "kimi_k3: no warm start from the history"; }
+ echo "OK kimi_k3 warm start: tokens = CPU, $(grep -a -o 'warm start, [0-9]* experts' vk.log), $(grep -a -o 'device [0-9]* of [0-9]* routed experts' vk.log | tail -1)"
+ # COLI_VK_TIER=0: the shared experts alone on the device, as before the tier
+ env $O COLI_USAGE=$PWD/k3.usage USAGE_SAVE=0 COLI_VK_TIER=0 COLI_VULKAN=1 \
+ ./kimi_k3 kimi_k3_tiny --ids "$(k3ids long)" --ngen 8 2> vk.log | sed 's/ *TUNE.*//' > vk.tok
+ cmp -s cpu.tok vk.tok || { cat vk.log; fail "kimi_k3 COLI_VK_TIER=0: tokens differ from the CPU"; }
+ ! grep -q '^\[VK\] tier' vk.log || { cat vk.log; fail "kimi_k3 COLI_VK_TIER=0: the tier started"; }
+ need_gpu kimi_k3 vk.log "kimi_k3 COLI_VK_TIER=0"
+ echo "OK kimi_k3 COLI_VK_TIER=0: tokens = CPU, no tier, $(vk_count kimi_k3 vk.log) matmuls on the GPU"
+ }
+
+ # The Kimi K3 and MiMo expert tiers under ASan and UBSan, as qwen-sanitize does for
+ # the qwen engines: memory safety is the gate, and each run must still put routed
+ # experts on the device.
+ family_kimi_mimo_sanitize() {
+ make clean >/dev/null 2>&1 || true
+ make kimi_k3 mimo VK=1 EXTRA_CFLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -g"
+ $PY tools/make_kimi_k3_tiny.py --output ./kimi_k3_tiny --force
+ $PY tools/make_mimo_tiny.py --output ./mimo_tiny --force --vision
+ ksan() { # <engine> <tag> <env and argv...>
+ local eng=$1 tag=$2; shift 2
+ env ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=print_stacktrace=1 OMP_NUM_THREADS=2 \
+ COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 "$@" > san.log 2>&1 || true
+ if grep -qE "ERROR: AddressSanitizer|runtime error:" san.log; then cat san.log; fail "$tag: sanitizer diagnostic"; fi
+ [ "$(tier_count "$eng" san.log)" -gt 0 ] || { cat san.log; fail "$tag: no routed expert ran on the device"; }
+ echo "OK $tag: sanitizers clean, $(grep -a -o 'device [0-9]* of [0-9]* routed experts' san.log | tail -1), $(grep -a -o 'evictions [0-9]*' san.log | tail -1)"
+ }
+ local O="K3_BITS=32 K3_MLA_BITS=32 K3_HEAD_BITS=32 K3_IDOT=0 COLI_TEMP=0" K3IDS MIDS IMG GRID
+ K3IDS=$($PY -c "import json;print(' '.join(map(str,json.load(open('kimi_k3_tiny/ref.json'))['cases']['long']['prompt_ids'])))")
+ MIDS=$($PY -c "import json;print(' '.join(map(str,json.load(open('mimo_tiny/ref.json'))['cases']['long']['prompt_ids'])))")
+ IMG=$($PY -c "import json;print(' '.join(map(str,json.load(open('mimo_tiny/ref.json'))['image']['prompt_ids'])))")
+ GRID=$($PY -c "import json;i=json.load(open('mimo_tiny/ref.json'))['image'];print(i['grid_h'],i['grid_w'])")
+ rm -f k3.usage
+ ksan kimi_k3 "asan kimi_k3 tier" $O COLI_USAGE=$PWD/k3.usage ./kimi_k3 kimi_k3_tiny --ids "$K3IDS" --ngen 8
+ ksan kimi_k3 "asan kimi_k3 warm start, shared experts on the device" $O COLI_USAGE=$PWD/k3.usage COLI_VK_DENSE=1 ./kimi_k3 kimi_k3_tiny --ids "$K3IDS" --ngen 8
+ ksan kimi_k3 "asan kimi_k3 eviction, int8 shared experts" K3_BITS=8 K3_IDOT=0 COLI_USAGE=$PWD/k3e.usage USAGE_SAVE=0 COLI_VK_TIER_GB=0.000005 COLI_VK_DENSE=1 ./kimi_k3 kimi_k3_tiny --ids "$K3IDS" --ngen 8
+ ksan kimi_k3 "asan kimi_k3 prefill one token at a time, no pipeline" $O COLI_USAGE=$PWD/k3e.usage USAGE_SAVE=0 K3_CHUNK=1 K3_PIPE=0 ./kimi_k3 kimi_k3_tiny --ids "$K3IDS" --ngen 8
+ ksan mimo "asan mimo tier" MIMO_DENSE_BITS=32 COLI_TEMP=0 ./mimo mimo_tiny --ids "$MIDS" --ngen 6
+ ksan mimo "asan mimo eviction (MIMO_VK_EXPERTS=2)" MIMO_DENSE_BITS=32 COLI_TEMP=0 MIMO_VK_EXPERTS=2 ./mimo mimo_tiny --ids "$MIDS" --ngen 6
+ ksan mimo "asan mimo picture, native dense on the device" MIMO_DENSE_BITS=0 COLI_TEMP=0 COLI_VK_DENSE=1 ./mimo mimo_tiny --ids "$IMG" --ngen 6 --image mimo_tiny/patches.f32 --grid $GRID
+ ksan mimo "asan mimo prefill blocks of 3, cache 4" MIMO_DENSE_BITS=32 COLI_TEMP=0 MIMO_CHUNK=3 MIMO_CAP=4 ./mimo mimo_tiny --ids "$MIDS" --ngen 6
+ make clean >/dev/null 2>&1 || true
+ }
+
+ # GLM-5.2 (colibri) and GLM-5.3 Flash (glm53) on the routed-expert tier: the fixtures.
+ # colibri: the bf16 oracle, whose experts the loader quantizes to the bits asked for
+ # (16: f32, fmt 10 on the device; 8: int8, fmt 1; 4: int4 per row, fmt 2; 3: int3-g64,
+ # fmt 5), the int4-g64 and E8/IQ3 containers of the parity gate, and the FP8 oracle
+ # converted to int4-g64 (its 32-wide down rows stay per row), int4 per row, int3-g64 and
+ # int4-g64 with an int3-g64 down. glm53: the int4-gs64 streaming container.
+ glm_fixtures() {
+ $PY tools/make_glm_oracle.py > /dev/null
+ $PY tools/make_glm_oracle.py --fmt4 > /dev/null
+ $PY tools/make_glm_oracle.py --fmt6 > /dev/null
+ mkdir -p glm_fp8 && (cd glm_fp8 && $PY ../tools/make_glm_oracle.py --fp8 > /dev/null)
+ local v
+ for v in "i4:" "i4r:--group-size 0" "i3:--xbits 3" "d3:--down-bits 3"; do
+ # shellcheck disable=SC2086
+ $PY tools/convert_fp8_to_int4.py --indir glm_fp8/glm_tiny --outdir glm_tiny_${v%%:*} \
+ --ebits 4 --io-bits 4 --n-layers 5 --min-free-gb 0 ${v#*:} > /dev/null
+ cp glm_fp8/ref_glm.json glm_tiny_${v%%:*}/
+ done
+ $PY tools/make_glm53_tiny.py --output glm53_tiny --force > /dev/null
+ $PY tools/make_glm53_streaming_pair.py --fixture glm53_tiny --output glm53_stream > /dev/null
+ }
+
+ # glm_tier <tag> <snap> <ref> <env...> -- <argv...>
+ # colibri with the tier against its CPU run: the same greedy tokens (or teacher-forced
+ # predictions, TF=1, mismatches included) and a "[VK] tier colibri run: device N" with
+ # N > 0; EVICT=1: evictions too. The history the tier warms from is <snap>/.coli_usage:
+ # none by default (the tier fills as experts pass by), HIST=1 writes one first from a
+ # greedy run (the warm start, and the device in a teacher-forced prefill). DEV2=1: the
+ # second device's registry served experts ("+ N vk" in the hit-rate line).
+ glm_tier() {
+ local tag=$1 snap=$2 ref=$3; shift 3
+ local envs=() pre=() e; while [ "$1" != "--" ]; do envs+=("$1"); shift; done; shift
+ for e in "${envs[@]}"; do [ "${e%%=*}" = TF ] || pre+=("$e"); done
+ rm -f "$snap/.coli_usage"
+ [ "${HIST:-0}" = 1 ] && { env "${pre[@]}" SNAP=$snap REF=$ref STATS=$snap/.coli_usage ./colibri "$@" > /dev/null 2>&1 || true; }
+ env "${envs[@]}" SNAP=$snap REF=$ref ./colibri "$@" > cpu.log 2>&1 || true
+ env "${envs[@]}" SNAP=$snap REF=$ref COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 ./colibri "$@" > vk.log 2>&1 || true
+ rm -f "$snap/.coli_usage"
+ grep -aE '^GLM C engine|^PREFILL|^\[ORACLE\] mismatch' cpu.log | sed 's/ | [0-9.]* pos\/s//' > cpu.tok || true
+ grep -aE '^GLM C engine|^PREFILL|^\[ORACLE\] mismatch' vk.log | sed 's/ | [0-9.]* pos\/s//' > vk.tok || true
+ { [ -s cpu.tok ] && cmp -s cpu.tok vk.tok; } || { cat cpu.tok vk.tok; tail -20 vk.log; fail "$tag: the tier's tokens differ from the CPU"; }
+ if [ "${DEV2:-0}" = 1 ]; then
+ grep -qaE 'lru \+ [1-9][0-9]* vk /' vk.log || { cat vk.log; fail "$tag: the second device served no expert"; }
+ else
+ [ "$(tier_count colibri vk.log)" -gt 0 ] || { cat vk.log; fail "$tag: no routed expert ran on the device"; }
+ fi
+ if [ "${EVICT:-0}" = 1 ]; then
+ [ "$(tier_evictions colibri vk.log)" -gt 0 ] || { grep '\[VK\] tier' vk.log; fail "$tag: the budget forced no eviction"; }
+ [ "$(tier_failed colibri vk.log)" = 0 ] || { grep '\[VK\] tier' vk.log; fail "$tag: an upload failed (the budget shrank)"; }
+ fi
+ echo "OK $tag: tokens = CPU, $(grep -a -o 'device [0-9]* of [0-9]* routed experts' vk.log | tail -1)$(grep -a -o ' + [0-9]* vk' vk.log | tail -1), $(grep -a -o 'evictions [0-9]*' vk.log | tail -1), $(grep -a -o '(fmt [^)]*)' vk.log | head -1)"
+ }
+
+ # g53_tier <tag> <model dir> <env...> -- <argv...>: glm53, the same gate on its
+ # teacher_forcing and greedy lines; the history is a fresh COLI_USAGE file (HIST=1: one
+ # greedy run writes it first).
+ g53_tier() {
+ local tag=$1 model=$2; shift 2
+ local envs=(); while [ "$1" != "--" ]; do envs+=("$1"); shift; done; shift
+ rm -f g53.usage
+ [ "${HIST:-0}" = 1 ] && { env "${envs[@]}" COLI_USAGE=g53.usage ./glm53 --model $model "$@" > /dev/null 2>&1 || true; }
+ env "${envs[@]}" COLI_USAGE=g53.usage USAGE_SAVE=0 ./glm53 --model $model "$@" > cpu.log 2>&1 || true
+ env "${envs[@]}" COLI_USAGE=g53.usage USAGE_SAVE=0 COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 ./glm53 --model $model "$@" > vk.log 2>&1 || true
+ rm -f g53.usage
+ grep -aE '^teacher_forcing|^greedy' cpu.log > cpu.tok || true
+ grep -aE '^teacher_forcing|^greedy' vk.log > vk.tok || true
+ { [ -s cpu.tok ] && cmp -s cpu.tok vk.tok; } || { cat cpu.tok vk.tok; tail -20 vk.log; fail "$tag: the tier's tokens differ from the CPU"; }
+ [ "$(tier_count glm53 vk.log)" -gt 0 ] || { cat vk.log; fail "$tag: no routed expert ran on the device"; }
+ if [ "${EVICT:-0}" = 1 ]; then
+ [ "$(tier_evictions glm53 vk.log)" -gt 0 ] || { grep '\[VK\] tier' vk.log; fail "$tag: the budget forced no eviction"; }
+ [ "$(tier_failed glm53 vk.log)" = 0 ] || { grep '\[VK\] tier' vk.log; fail "$tag: an upload failed (the budget shrank)"; }
+ fi
+ local where; where=$(dense_where glm53 vk.log "$tag" "${envs[@]}") || { echo "$where"; exit 1; }
+ echo "OK $tag: tokens = CPU, $(grep -a -o 'device [0-9]* of [0-9]* routed experts' vk.log | tail -1), $(grep -a -o 'evictions [0-9]*' vk.log | tail -1), trunk on the $where"
+ }
+
+ # GLM-5.2 and GLM-5.3 Flash on the routed-expert tier, in every expert format the two
+ # engines read, warm and cold, decode and teacher-forced prefill, under eviction (a
+ # budget of two experts, by COLI_VK_TIER_GB and by the deprecated COLI_VK_EXPERTS), with
+ # the trunk and the attention core on the device, beside COLI_VK_DEV2's second
+ # (logical) device, and with the tier off. IDOT=0 gives the CPU's int8 and int4-per-row
+ # experts the f32 activations the device uses (the CPU default rounds them to int8 on
+ # some ISAs), so the two sides differ by summation order only.
+ family_glm() {
+ make colibri glm53 VK=1
+ glm_fixtures
+ export OMP_NUM_THREADS=2 CAP_RAISE=0
+ local cap b
+ # the oracle with f32 experts (fmt 10): decode cold at a one-slot and a full cache,
+ # the teacher-forced prefill from a warm start
+ for cap in 1 64; do glm_tier "colibri f32 experts cap=$cap" glm_tiny ref_glm.json -- $cap 16 16; done
+ HIST=1 glm_tier "colibri f32 experts, prefill from a warm start" glm_tiny ref_glm.json TF=1 -- 64 16 16
+ # quantized at load: int8 (fmt 1), int4 per row (fmt 2), int3-g64 (fmt 5)
+ for b in 8 4 3; do
+ glm_tier "colibri ${b}-bit experts cap=2" glm_tiny ref_glm.json IDOT=0 -- 2 $b 4
+ HIST=1 glm_tier "colibri ${b}-bit experts, prefill warm" glm_tiny ref_glm.json IDOT=0 TF=1 -- 2 $b 4
+ done
+ # the containers: int4-g64 gate/up/down, int4-g64 with a per-row down, int4 per row,
+ # int3-g64, int4-g64 with an int3-g64 down
+ HIST=1 glm_tier "colibri int4-g64 container" glm_tiny_fmt4 glm_tiny_fmt4/ref_glm.json -- 2 16 16
+ HIST=1 glm_tier "colibri int4-g64 container, prefill" glm_tiny_fmt4 glm_tiny_fmt4/ref_glm.json TF=1 -- 2 16 16
+ local fx
+ for fx in i4 i4r i3 d3; do
+ HIST=1 glm_tier "colibri $fx container cap=1" glm_tiny_$fx glm_tiny_$fx/ref_glm.json IDOT=0 -- 1 4 4
+ HIST=1 glm_tier "colibri $fx container, prefill" glm_tiny_$fx glm_tiny_$fx/ref_glm.json IDOT=0 TF=1 -- 2 4 4
+ done
+ # PIPE's asynchronous loads and the PILOT prefetcher beside the tier
+ glm_tier "colibri PIPE=1" glm_tiny_i4 glm_tiny_i4/ref_glm.json IDOT=0 PIPE=1 -- 1 4 4
+ glm_tier "colibri PILOT=1" glm_tiny_i4 glm_tiny_i4/ref_glm.json IDOT=0 PILOT=1 -- 2 4 4
+ # the trunk and the MLA attention core on the device too
+ HIST=1 glm_tier "colibri tier + COLI_VK_DENSE=1 COLI_VK_ATTN=1" glm_tiny_i4 glm_tiny_i4/ref_glm.json IDOT=0 COLI_VK_DENSE=1 COLI_VK_ATTN=1 -- 2 4 4
+ # a budget of two experts must evict as the routing moves: COLI_VK_TIER_GB, and the
+ # deprecated COLI_VK_EXPERTS mapped onto the tier as a cap
+ EVICT=1 glm_tier "colibri, a budget of two experts" glm_tiny ref_glm.json COLI_VK_TIER_GB=0.0001 -- 64 16 16
+ EVICT=1 glm_tier "colibri, COLI_VK_EXPERTS=2" glm_tiny ref_glm.json COLI_VK_EXPERTS=2 -- 64 16 16
+ # COLI_VK_DEV2: a second logical device on Lavapipe holds what the capped tier does not
+ HIST=1 glm_tier "colibri tier + COLI_VK_DEV2" glm_tiny_i4r glm_tiny_i4r/ref_glm.json IDOT=0 COLI_VK_EXPERTS=4 COLI_VK_DEV2=0 -- 64 4 4
+ HIST=1 DEV2=1 glm_tier "colibri COLI_VK_DEV2 alone (COLI_VK_TIER=0)" glm_tiny_i4r glm_tiny_i4r/ref_glm.json IDOT=0 COLI_VK_TIER=0 COLI_VK_DEV2=0 -- 64 4 4
+ # E8/IQ3 (fmt 6) has no device form: the tier declines, the CPU computes them
+ SNAP=glm_tiny_fmt6 REF=glm_tiny_fmt6/ref_glm.json ./colibri 2 16 16 > cpu.log 2>&1 || true
+ SNAP=glm_tiny_fmt6 REF=glm_tiny_fmt6/ref_glm.json COLI_VULKAN=1 ./colibri 2 16 16 > vk.log 2>&1 || true
+ cmp -s <(grep -a '^GLM C engine' cpu.log) <(grep -a '^GLM C engine' vk.log) || { cat vk.log; fail "colibri fmt 6: tokens differ"; }
+ grep -qa 'tier colibri: experts in fmt 6/6/6' vk.log || { cat vk.log; fail "colibri fmt 6: the tier did not decline"; }
+ echo "OK colibri E8/IQ3 (fmt 6): the tier declines, tokens = CPU"
+ # COLI_VK_TIER=0: no tier, the trunk and the attention core on the device as before
+ SNAP=glm_tiny REF=ref_glm.json COLI_VK_DENSE=1 COLI_VK_ATTN=1 ./colibri 2 16 16 > cpu.log 2>&1 || true
+ SNAP=glm_tiny REF=ref_glm.json COLI_VK_DENSE=1 COLI_VK_ATTN=1 COLI_VK_TIER=0 COLI_VULKAN=1 ./colibri 2 16 16 > vk.log 2>&1 || true
+ cmp -s <(grep -a '^GLM C engine' cpu.log) <(grep -a '^GLM C engine' vk.log) || { cat vk.log; fail "colibri COLI_VK_TIER=0: tokens differ"; }
+ ! grep -qa '^\[VK\] tier colibri' vk.log || { cat vk.log; fail "colibri COLI_VK_TIER=0: the tier started"; }
+ echo "OK colibri COLI_VK_TIER=0: tokens = CPU, no tier"
+
+ # glm53: its int4-gs64 streaming container (swiglu_limit 10), dense matrices f32 and int4
+ local ids
+ ids=$($PY -c "print(','.join(str((i*37+5)%120+2) for i in range(100)))")
+ g53_tier "glm53 decode, cold" glm53_stream-i4 GLM53_BITS=32 -- --ids 5,7,9,11,13,17,19,23 --greedy 8
+ HIST=1 g53_tier "glm53 100-token prompt, warm (two blocks of rows)" glm53_stream-i4 GLM53_BITS=32 -- --ids $ids --greedy 4
+ HIST=1 g53_tier "glm53 prefill chunks of 7, one cache slot" glm53_stream-i4 GLM53_BITS=4 GLM53_PREFILL_CHUNK=7 GLM53_EXPERT_GB=0.000001 -- --ids $ids --greedy 4
+ HIST=1 g53_tier "glm53 trunk on the device (COLI_VK_DENSE=1)" glm53_stream-i4 GLM53_BITS=4 COLI_VK_DENSE=1 -- --ids $ids --greedy 4
+ EVICT=1 g53_tier "glm53, a budget of two experts" glm53_stream-i4 GLM53_BITS=32 COLI_VK_TIER_GB=0.00006 -- --ids $ids --greedy 6
+ # COLI_VK_TIER=0: the trunk alone, on the device by default, Lavapipe included
+ GLM53_BITS=4 COLI_USAGE=g53.usage USAGE_SAVE=0 ./glm53 --model glm53_stream-i4 --ids 5,7,9,11 --greedy 4 > cpu.log 2>&1 || true
+ GLM53_BITS=4 COLI_USAGE=g53.usage USAGE_SAVE=0 COLI_VK_TIER=0 COLI_VULKAN=1 ./glm53 --model glm53_stream-i4 --ids 5,7,9,11 --greedy 4 > vk.log 2>&1 || true
+ cmp -s <(grep -aE '^teacher_forcing|^greedy' cpu.log) <(grep -aE '^teacher_forcing|^greedy' vk.log) || { cat vk.log; fail "glm53 COLI_VK_TIER=0: tokens differ"; }
+ ! grep -qa '^\[VK\] tier glm53' vk.log || { cat vk.log; fail "glm53 COLI_VK_TIER=0: the tier started"; }
+ need_gpu glm53 vk.log "glm53 COLI_VK_TIER=0"
+ echo "OK glm53 COLI_VK_TIER=0: tokens = CPU, no tier, $(vk_count glm53 vk.log) matmuls on the GPU"
+ unset OMP_NUM_THREADS CAP_RAISE
+ }
+
+ # The same engines under ASan and UBSan with the tier on: memory safety is the gate, and
+ # each run must still put experts on the device.
+ family_glm_sanitize() {
+ make clean >/dev/null 2>&1 || true
+ make colibri glm53 VK=1 EXTRA_CFLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -g"
+ glm_fixtures
+ export OMP_NUM_THREADS=2 CAP_RAISE=0
+ gsan() { # <engine> <tag> <history: colibri snap, or - for glm53's COLI_USAGE> <env and argv...>
+ local eng=$1 tag=$2 snap=$3; shift 3
+ rm -f g53.usage; [ "$snap" = - ] || rm -f "$snap/.coli_usage"
+ if [ "${HIST:-0}" = 1 ]; then # a history from a greedy run (TF=1 writes none)
+ local a=() x; for x in "$@"; do [ "$x" = TF=1 ] || a+=("$x"); done
+ if [ "$snap" = - ]; then env COLI_USAGE=g53.usage "${a[@]}" > /dev/null 2>&1 || true
+ else env STATS=$snap/.coli_usage "${a[@]}" > /dev/null 2>&1 || true; fi
+ fi
+ env ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=print_stacktrace=1 COLI_USAGE=g53.usage \
+ COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 "$@" > san.log 2>&1 || true
+ rm -f g53.usage; [ "$snap" = - ] || rm -f "$snap/.coli_usage"
+ if grep -qE "ERROR: AddressSanitizer|runtime error:" san.log; then cat san.log; fail "$tag: sanitizer diagnostic"; fi
+ [ "$(tier_count $eng san.log)" -gt 0 ] || { cat san.log; fail "$tag: no routed expert ran on the device"; }
+ echo "OK $tag: sanitizers clean, $(grep -a -o 'device [0-9]* of [0-9]* routed experts' san.log | tail -1), $(grep -a -o 'evictions [0-9]*' san.log | tail -1)"
+ }
+ gsan colibri "asan colibri f32 cap=1" glm_tiny SNAP=glm_tiny REF=ref_glm.json ./colibri 1 16 16
+ HIST=1 gsan colibri "asan colibri prefill, warm" glm_tiny SNAP=glm_tiny REF=ref_glm.json TF=1 ./colibri 64 16 16
+ gsan colibri "asan colibri eviction" glm_tiny SNAP=glm_tiny REF=ref_glm.json COLI_VK_EXPERTS=2 ./colibri 64 16 16
+ HIST=1 gsan colibri "asan colibri int4-g64, trunk + attention on the device" glm_tiny_i4 SNAP=glm_tiny_i4 REF=glm_tiny_i4/ref_glm.json COLI_VK_DENSE=1 COLI_VK_ATTN=1 ./colibri 2 4 4
+ HIST=1 gsan colibri "asan colibri int3-g64 prefill" glm_tiny_i3 SNAP=glm_tiny_i3 REF=glm_tiny_i3/ref_glm.json TF=1 ./colibri 2 4 4
+ HIST=1 gsan colibri "asan colibri int3-g64 down, cap=1" glm_tiny_d3 SNAP=glm_tiny_d3 REF=glm_tiny_d3/ref_glm.json ./colibri 1 4 4
+ HIST=1 gsan colibri "asan colibri tier + COLI_VK_DEV2" glm_tiny_i4r SNAP=glm_tiny_i4r REF=glm_tiny_i4r/ref_glm.json COLI_VK_EXPERTS=4 COLI_VK_DEV2=0 ./colibri 64 4 4
+ gsan colibri "asan colibri int4 at load, PIPE=1" glm_tiny SNAP=glm_tiny REF=ref_glm.json PIPE=1 ./colibri 1 4 4
+ gsan colibri "asan colibri int8 at load, PILOT=1" glm_tiny SNAP=glm_tiny REF=ref_glm.json PILOT=1 ./colibri 2 8 8
+ local ids
+ ids=$($PY -c "print(','.join(str((i*37+5)%120+2) for i in range(100)))")
+ gsan glm53 "asan glm53 decode" - GLM53_BITS=32 ./glm53 --model glm53_stream-i4 --ids 5,7,9,11,13,17,19,23 --greedy 20
+ HIST=1 gsan glm53 "asan glm53 100-token prompt, warm" - GLM53_BITS=32 ./glm53 --model glm53_stream-i4 --ids $ids --greedy 4
+ HIST=1 gsan glm53 "asan glm53 one slot, trunk on the device" - GLM53_BITS=4 GLM53_EXPERT_GB=0.000001 COLI_VK_DENSE=1 ./glm53 --model glm53_stream-i4 --ids $ids --greedy 4
+ gsan glm53 "asan glm53 eviction" - GLM53_BITS=32 COLI_VK_TIER_GB=0.00006 ./glm53 --model glm53_stream-i4 --ids $ids --greedy 6
+ unset OMP_NUM_THREADS CAP_RAISE
+ make clean >/dev/null 2>&1 || true
}
+# The dense chain (vk_chain.c, COLI_VK_CHAIN=1): every layer recorded into one
+# submission, the residual stream, the KV mirrors and the recurrent state on the device.
+# Gates, per configuration: the CPU run's tokens (and its oracle, where the CPU passes
+# it); the last logits within 1e-4 of the largest one where both runs multiply f32
+# activations (tol 1); a "[VK] <engine> chain: N forwards" line with N > 0. Beside them:
+# the chain's ops against CPU references (tests/test_vk_chain), qwen38's oracle targets
+# with the chain on, the prefix-reuse contract, and serve sessions (pins, the prompt
+# cache, the prefill read-out, MTP drafts) frame for frame against the CPU.
+chain_count() {
+ local n
+ n=$(sed -n "s/^\[VK\] $1 chain: \([0-9][0-9]*\) forwards.*/\1/p" "$2" | tail -1)
+ echo "${n:-0}"
+}
+logits_close() { # <cpu.f32> <vk.f32>: max |diff| within 1e-4 of the largest |logit|
+ $PY - "$1" "$2" <<'PY'
+import array, sys
+a = array.array("f", open(sys.argv[1], "rb").read()); b = array.array("f", open(sys.argv[2], "rb").read())
+d = max(abs(x - y) for x, y in zip(a, b)) if a and len(a) == len(b) else float("inf")
+m = max(abs(x) for x in a) if a else 0.0
+print(f"max |logit diff| {d:.2e} of {m:.2e}")
+sys.exit(0 if d <= 1e-4 * m else 1)
+PY
+}
+chain_gate() { # <engine> <tag> <tol 0|1> <env...> -- <argv...> (CPUENV: the CPU arm's own settings)
+ local eng=$1 tag=$2 tol=$3; shift 3
+ local envs=(); while [ "$1" != "--" ]; do envs+=("$1"); shift; done; shift
+ rm -f chain.usage cpu.f32 vk.f32
+ local rc_cpu=0
+ env "${envs[@]}" ${CPUENV:-} DUMP=cpu.f32 ./"$eng" "$@" > cpu.log 2>&1 || rc_cpu=$?
+ env "${envs[@]}" DUMP=vk.f32 COLI_USAGE=chain.usage COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 COLI_VK_CHAIN=${CHAINMODE:-1} \
+ ./"$eng" "$@" > vk.log 2>&1 || { [ $rc_cpu != 0 ] || { cat vk.log; fail "$tag: the chain misses the oracle the CPU passes"; }; }
+ same_tokens cpu.log vk.log "$tag"
+ [ "$(chain_count "$eng" vk.log)" -gt 0 ] || { cat vk.log; fail "$tag: the chain never ran"; }
+ local lg=""
+ if [ "$tol" = 1 ]; then lg=$(logits_close cpu.f32 vk.f32) || { echo "$lg"; fail "$tag: logits"; }; lg=", $lg"; fi
+ echo "OK $tag: tokens = CPU$lg, $(chain_count "$eng" vk.log) chain forwards"
+}
+
+# lost_gate <engine> <tag> <frame> <env...> -- <argv...>: the device "lost" at the given
+# chain frame (COLI_VK_CHAIN_FAULT); the engine rebuilds the recurrent state on the CPU
+# from the prefix record and continues there: the CPU run's tokens all the same.
+lost_gate() {
+ local eng=$1 tag=$2 k=$3; shift 3
+ local envs=(); while [ "$1" != "--" ]; do envs+=("$1"); shift; done; shift
+ rm -f chain.usage
+ env "${envs[@]}" ./"$eng" "$@" > cpu.log 2>&1 || true
+ env "${envs[@]}" COLI_VK_CHAIN_FAULT=$k COLI_USAGE=chain.usage COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 COLI_VK_CHAIN=1 \
+ ./"$eng" "$@" > vk.log 2>&1 || true
+ same_tokens cpu.log vk.log "$tag"
+ grep -q "rebuilding the state of [1-9]" vk.log || { cat vk.log; fail "$tag: no state was rebuilt"; }
+ echo "OK $tag: tokens = CPU, $(grep -o 'rebuilding the state of [0-9]* positions' vk.log)"
+}
+
+family_qwen_chain() {
+ make qwen36 qwen38 tests/test_vk_chain VK=1
+ ./tests/test_vk_chain shaders/qmatmul.spv | tee vk_chain.log
+ tail -1 vk_chain.log | grep -qx PASS || fail "the chain's ops"
+ $PY tools/make_qwen36_tiny.py --out qwen36_tiny --ref-mode full --emit-ref qwen36_tiny/ref_full.json
+ $PY tools/make_qwen36_tiny.py --geometry qwen3-coder-30b --out qwen3_coder_tiny --ref-mode full --emit-ref qwen3_coder_tiny/ref_full.json
+ $PY tools/make_qwen36_tiny.py --geometry qwen38-27b-dense --out qwen38_27b_tiny --ref-mode full --emit-ref qwen38_27b_tiny/ref_full.json
+ $PY tools/make_qwen36_tiny.py --geometry qwen38-2p4t --seed 3 --out qwen38_2p4t_tiny --ref-mode full --emit-ref qwen38_2p4t_tiny/ref_full.json
+ local fx cap caps
+ # qwen36: the hybrid, Qwen3-Coder (attention only, no gate, no shared expert), the
+ # 27B dense geometry (no routed experts: no host step at all) and the 2.4T one
+ for fx in qwen36_tiny qwen3_coder_tiny qwen38_27b_tiny qwen38_2p4t_tiny; do
+ $PY tools/convert_qwen36.py --model $fx --out ${fx}_c --ebits 8
+ caps="1 8"; [ $fx = qwen38_2p4t_tiny ] && caps=8
+ for cap in $caps; do
+ chain_gate qwen36 "chain qwen36 $fx f32 cap=$cap" 1 COLI_DENSE_I8=0 SNAP=${fx}_c -- $cap 8 $fx/ref_full.json
+ done
+ # int8 dense rows (fmt 1): the CPU arm with f32 activations (COLI_DENSE_IDOT=0), as the device
+ CPUENV=COLI_DENSE_IDOT=0 chain_gate qwen36 "chain qwen36 $fx int8" 1 SNAP=${fx}_c -- 8 8 $fx/ref_full.json
+ done
+ # the expert containers the tier reads, the tier off, prefill in chunks of 3 rows,
+ # the tiled GEMM inside the chain from S = 2
+ $PY tools/make_qwen36_tiny.py --out qwen36_tiny64 --ref-mode full --inter 64 --emit-ref qwen36_tiny64/ref_full.json
+ $PY tools/convert_qwen36.py --model qwen36_tiny64 --out qwen36_tiny64_c --ebits 4 --gs 64
+ $PY tools/convert_qwen36.py --model qwen36_tiny64 --out qwen36_tiny64_d8 --ebits 4 --gs 64 --down-bits 8
+ $PY tools/convert_qwen36.py --model qwen36_tiny --out qwen36_tiny_i4r --ebits 4
+ chain_gate qwen36 "chain qwen36 int4-g64 planar" 1 QWEN_EXPERT_ACT=f32 COLI_DENSE_I8=0 SNAP=qwen36_tiny64_c -- 8 4 qwen36_tiny64/ref_full.json
+ chain_gate qwen36 "chain qwen36 int4-g64 int8 activations" 0 COLI_DENSE_I8=0 SNAP=qwen36_tiny64_c -- 1 4 qwen36_tiny64/ref_full.json
+ chain_gate qwen36 "chain qwen36 mixed int4/int8" 1 COLI_DENSE_I8=0 SNAP=qwen36_tiny64_d8 -- 8 4 qwen36_tiny64/ref_full.json
+ chain_gate qwen36 "chain qwen36 int4 per row" 1 COLI_DENSE_I8=0 SNAP=qwen36_tiny_i4r -- 8 4 qwen36_tiny/ref_full.json
+ chain_gate qwen36 "chain qwen36 tier off" 1 COLI_VK_TIER=0 COLI_DENSE_I8=0 SNAP=qwen36_tiny_c -- 8 8 qwen36_tiny/ref_full.json
+ chain_gate qwen36 "chain qwen36 prefill in chunks of 3" 1 COLI_VK_CHAIN_ROWS=3 COLI_DENSE_I8=0 SNAP=qwen36_tiny_c -- 8 8 qwen36_tiny/ref_full.json
+ chain_gate qwen36 "chain qwen36 tiled GEMM" 1 COLI_VK_GEMM_MIN_S=2 COLI_DENSE_I8=0 SNAP=qwen36_tiny_c -- 8 8 qwen36_tiny/ref_full.json
+ chain_gate qwen36 "chain qwen36 the per-row GEMV" 1 COLI_VK_CHAIN_GEMV=0 COLI_DENSE_I8=0 SNAP=qwen36_tiny_c -- 8 8 qwen36_tiny/ref_full.json
+ # an image: the M-RoPE positions reach the chain as the host's cos/sin table,
+ # token-exact against transformers, on the CLI and through the IMAGE frame
+ $PY tools/make_qwen36_vl_tiny.py --out qwen38_27b_vl_tiny
+ $PY tools/convert_qwen36.py --model qwen38_27b_vl_tiny --out qwen38_27b_vl_tiny_c --ebits 8
+ chain_gate qwen36 "chain qwen36 vision" 1 COLI_DENSE_I8=0 SNAP=qwen38_27b_vl_tiny_c -- 8 8 qwen38_27b_vl_tiny/ref.json
+ QWEN36_VL_TINY=qwen38_27b_vl_tiny_c QWEN36_VL_REF=qwen38_27b_vl_tiny/ref.json COLI_VULKAN=1 COLI_VK_CHAIN=1 \
+ COLI_USAGE=$PWD/chain.usage $PY -m unittest tests.test_qwen36_vision_serve
+ # the device lost mid-decode: the state rebuilt on the CPU, the run finishes there
+ lost_gate qwen36 "chain qwen36 device lost" 40 COLI_DENSE_I8=0 SNAP=qwen36_tiny_c -- 8 8 qwen36_tiny/ref_full.json
+ # the prefix-reuse contract with the state on the device, and a serve session
+ QWEN36_TINY=$PWD/qwen36_tiny_c COLI_VULKAN=1 COLI_VK_CHAIN=1 COLI_USAGE=$PWD/chain.usage $PY tests/test_qwen36_prefix_serve.py
+ $PY tests/vulkan_chain_serve.py ./qwen36 qwen36_tiny_c COLI_DENSE_I8=0
+ # COLI_VK_CHAIN=2, prompts on the device and decode on the CPU: the state crosses
+ # between them at every turn's first decode step and next prompt
+ CHAINMODE=2 chain_gate qwen36 "chain qwen36 prompts only" 1 COLI_DENSE_I8=0 SNAP=qwen36_tiny_c -- 8 8 qwen36_tiny/ref_full.json
+ COLI_VK_CHAIN=2 $PY tests/vulkan_chain_serve.py ./qwen36 qwen36_tiny_c COLI_DENSE_I8=0
+
+ # qwen38: every resident format, prefill batching, every expert form, MTP
+ $PY tools/make_qwen38_tiny.py --out qwen38_tiny
+ $PY tools/make_qwen38_tiny.py --out qwen38_tiny_fp8 --fp8-experts
+ $PY tools/make_qwen38_tiny.py --out qwen38_tiny_int4 --fp8-experts --int4-experts --expert-gain 3
+ local trunk batch bf16 fx ref f
+ for batch in 0 1; do for bf16 in 0 1; do
+ chain_gate qwen38 "chain qwen38 bf16=$bf16 batch=$batch" 1 OMP_NUM_THREADS=2 Q38_PREFILL_BATCH=$batch Q38_NATIVE_BF16=$bf16 SNAP=qwen38_tiny -- 4 8 qwen38_tiny/ref.json
+ done; done
+ # the int8 trunk (fmt 1): the CPU's integer kernel rounds activations, so tokens only
+ chain_gate qwen38 "chain qwen38 int8 trunk" 0 OMP_NUM_THREADS=2 Q38_TRUNK_MIN_KB=0 SNAP=qwen38_tiny -- 4 8 qwen38_tiny/ref.json
+ for fx in qwen38_tiny_fp8 qwen38_tiny_int4; do
+ ref=$fx/ref.json; [ $fx = qwen38_tiny_int4 ] && ref=$fx/ref_int4.json
+ for batch in 0 1; do chain_gate qwen38 "chain qwen38 $fx batch=$batch" 1 OMP_NUM_THREADS=2 Q38_PREFILL_BATCH=$batch SNAP=$fx -- 2 8 $ref; done
+ done
+ chain_gate qwen38 "chain qwen38 tier off" 1 OMP_NUM_THREADS=2 COLI_VK_TIER=0 SNAP=qwen38_tiny -- 4 8 qwen38_tiny/ref.json
+ chain_gate qwen38 "chain qwen38 prefill in chunks of 3" 1 OMP_NUM_THREADS=2 COLI_VK_CHAIN_ROWS=3 SNAP=qwen38_tiny -- 4 8 qwen38_tiny/ref.json
+ $PY tools/make_qwen38_tiny.py --out qwen38_tiny_mtp --mtp
+ $PY tools/make_edge_tiny_tokenizer.py --vocab-size 64 ./qwen38_tiny_mtp # serve speaks text
+ $PY tools/make_qwen38_tiny.py --out qwen38_tiny_fp8_mtp --fp8-experts --mtp
+ $PY tools/make_qwen38_tiny.py --out qwen38_tiny_int4_mtp --fp8-experts --int4-experts --expert-gain 3 --mtp
+ # MTP verify (S = 2) with the device's snapshot and rollback: drafts as they come,
+ # every draft rejected (a rollback per token), every one accepted, alternating
+ for fx in qwen38_tiny_mtp qwen38_tiny_fp8_mtp qwen38_tiny_int4_mtp; do for f in "" reject accept mixed; do
+ chain_gate qwen38 "chain qwen38 MTP $fx ${f:-drafting}" 1 OMP_NUM_THREADS=2 Q38_MTP=1 Q38_MTP_FORCE=$f SNAP=$fx -- 2 8 $fx/ref.json
+ done; done
+ # the device lost mid-decode, once between steps and once inside an MTP verify
+ lost_gate qwen38 "chain qwen38 device lost" 20 OMP_NUM_THREADS=2 SNAP=qwen38_tiny -- 4 8 qwen38_tiny/ref.json
+ lost_gate qwen38 "chain qwen38 device lost in a verify" 45 OMP_NUM_THREADS=2 Q38_MTP=1 Q38_MTP_FORCE=mixed SNAP=qwen38_tiny_mtp -- 2 8 qwen38_tiny_mtp/ref.json
+ # the oracle targets with the chain on (COLI_VK_TIER_BALANCE=0: the int4 target wants
+ # the same last logits from every expert path, and the balancer moves experts between
+ # the device and the CPU by measured times); the MTP harness, whose prompt-cache and pin
+ # checks compare a warm session's draft logits bit for bit with a fresh one's, with the
+ # tier off: the tier's residency differs between two sessions, with or without the chain
+ COLI_VULKAN=1 COLI_VK_CHAIN=1 COLI_VK_TIER_SYNC=1 COLI_VK_TIER_BALANCE=0 \
+ make qwen38-tiny-check qwen38-tiny-fp8-check qwen38-tiny-int4-check VK=1
+ COLI_VULKAN=1 COLI_VK_CHAIN=1 COLI_VK_TIER=0 make qwen38-tiny-mtp-check VK=1
+ $PY tests/vulkan_chain_serve.py ./qwen38 qwen38_tiny_mtp OMP_NUM_THREADS=2 Q38_MTP=1
+ $PY tests/vulkan_chain_serve.py ./qwen38 qwen38_tiny_mtp OMP_NUM_THREADS=2
+ CHAINMODE=2 chain_gate qwen38 "chain qwen38 prompts only, MTP" 1 OMP_NUM_THREADS=2 Q38_MTP=1 Q38_MTP_FORCE=mixed SNAP=qwen38_tiny_mtp -- 2 8 qwen38_tiny_mtp/ref.json
+ COLI_VK_CHAIN=2 $PY tests/vulkan_chain_serve.py ./qwen38 qwen38_tiny_mtp OMP_NUM_THREADS=2 Q38_MTP=1
+}
+
+# The chain under ASan and UBSan: memory safety is the gate (a sanitized build
+# vectorizes differently, so tokens are not compared); each run must have run the chain.
+family_qwen_chain_sanitize() {
+ make clean >/dev/null 2>&1 || true
+ make qwen36 qwen38 tests/test_vk_chain VK=1 EXTRA_CFLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -g"
+ export ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=print_stacktrace=1
+ ./tests/test_vk_chain shaders/qmatmul.spv > san.log 2>&1 || true
+ if grep -qE "ERROR: AddressSanitizer|runtime error:" san.log || ! tail -1 san.log | grep -qx PASS; then cat san.log; fail "asan: the chain's ops"; fi
+ echo "OK asan: the chain's ops"
+ $PY tools/make_qwen36_tiny.py --out qwen36_tiny --ref-mode full --emit-ref qwen36_tiny/ref_full.json
+ $PY tools/convert_qwen36.py --model qwen36_tiny --out qwen36_tiny_c --ebits 8
+ $PY tools/make_qwen36_tiny.py --geometry qwen38-27b-dense --out qwen38_27b_tiny --ref-mode full --emit-ref qwen38_27b_tiny/ref_full.json
+ $PY tools/convert_qwen36.py --model qwen38_27b_tiny --out qwen38_27b_tiny_c --ebits 8
+ $PY tools/make_qwen36_tiny.py --out qwen36_tiny64 --ref-mode full --inter 64 --emit-ref qwen36_tiny64/ref_full.json
+ $PY tools/convert_qwen36.py --model qwen36_tiny64 --out qwen36_tiny64_c --ebits 4 --gs 64
+ $PY tools/make_qwen38_tiny.py --out qwen38_tiny
+ $PY tools/make_qwen38_tiny.py --out qwen38_tiny_int4_mtp --fp8-experts --int4-experts --expert-gain 3 --mtp
+ $PY tools/make_qwen38_tiny.py --out qwen38_tiny_mtp --mtp
+ $PY tools/make_edge_tiny_tokenizer.py --vocab-size 64 ./qwen38_tiny_mtp # serve speaks text
+ csan() { # <engine> <tag> <env and argv...>
+ local eng=$1 tag=$2; shift 2
+ rm -f chain.usage
+ env OMP_NUM_THREADS=2 COLI_USAGE=chain.usage COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 COLI_VK_CHAIN=1 "$@" > san.log 2>&1 || true
+ if grep -qE "ERROR: AddressSanitizer|runtime error:" san.log; then cat san.log; fail "$tag: sanitizer diagnostic"; fi
+ [ "$(chain_count "$eng" san.log)" -gt 0 ] || { cat san.log; fail "$tag: the chain never ran"; }
+ echo "OK $tag: sanitizers clean, $(chain_count "$eng" san.log) chain forwards"
+ }
+ csan qwen36 "asan chain qwen36 int8 experts" COLI_DENSE_I8=0 SNAP=qwen36_tiny_c ./qwen36 1 8 qwen36_tiny/ref_full.json
+ csan qwen36 "asan chain qwen36 int8 dense, chunks of 3" COLI_VK_CHAIN_ROWS=3 SNAP=qwen36_tiny_c ./qwen36 8 8 qwen36_tiny/ref_full.json
+ csan qwen36 "asan chain qwen36 int4-g64 planar" COLI_DENSE_I8=0 SNAP=qwen36_tiny64_c ./qwen36 8 4 qwen36_tiny64/ref_full.json
+ csan qwen36 "asan chain qwen36 dense model" COLI_DENSE_I8=0 SNAP=qwen38_27b_tiny_c ./qwen36 8 8 qwen38_27b_tiny/ref_full.json
+ csan qwen38 "asan chain qwen38 batch=0" Q38_PREFILL_BATCH=0 SNAP=qwen38_tiny ./qwen38 4 8 qwen38_tiny/ref.json
+ csan qwen38 "asan chain qwen38 int8 trunk, chunks of 3" Q38_TRUNK_MIN_KB=0 COLI_VK_CHAIN_ROWS=3 SNAP=qwen38_tiny ./qwen38 4 8 qwen38_tiny/ref.json
+ csan qwen38 "asan chain qwen38 MTP reject" Q38_MTP=1 Q38_MTP_FORCE=reject SNAP=qwen38_tiny_int4_mtp ./qwen38 2 8 qwen38_tiny_int4_mtp/ref.json
+ csan qwen38 "asan chain qwen38 MTP mixed" Q38_MTP=1 Q38_MTP_FORCE=mixed SNAP=qwen38_tiny_int4_mtp ./qwen38 2 8 qwen38_tiny_int4_mtp/ref.json
+ $PY tests/vulkan_chain_serve.py ./qwen38 qwen38_tiny_mtp Q38_MTP=1 > san.log 2>&1 || { cat san.log; fail "asan chain qwen38 serve"; }
+ if grep -qE "ERROR: AddressSanitizer|runtime error:" san.log; then cat san.log; fail "asan chain qwen38 serve: sanitizer diagnostic"; fi
+ echo "OK asan chain qwen38 serve: $(tail -1 san.log)"
+ make clean >/dev/null 2>&1 || true
+}
+
case "${1:-}" in
shader) shader_formats ;;
qwen) family_qwen ;;
qwen-sanitize) family_qwen_sanitize ;;
inkling-olmoe) family_inkling_olmoe ;;
+ inkling-olmoe-sanitize) family_inkling_olmoe_sanitize ;;
mimo-qwenimage) family_mimo_qwenimage ;;
deepseek) family_deepseek ;;
+ deepseek-sanitize) family_deepseek_sanitize ;;
+ kimi) family_kimi ;;
+ kimi-mimo-sanitize) family_kimi_mimo_sanitize ;;
+ glm) family_glm ;;
+ glm-sanitize) family_glm_sanitize ;;
- *) echo "usage: $0 shader|qwen|qwen-sanitize|inkling-olmoe|inkling-olmoe-sanitize|mimo-qwenimage|deepseek|deepseek-sanitize|kimi|kimi-mimo-sanitize|glm|glm-sanitize" >&2; exit 2 ;;
+ qwen-chain) family_qwen_chain ;;
+ qwen-chain-sanitize) family_qwen_chain_sanitize ;;
- *) echo "usage: $0 shader|qwen|qwen-sanitize|inkling-olmoe|mimo-qwenimage|deepseek" >&2; exit 2 ;;
++ *) echo "usage: $0 shader|qwen|qwen-sanitize|inkling-olmoe|inkling-olmoe-sanitize|mimo-qwenimage|deepseek|deepseek-sanitize|kimi|kimi-mimo-sanitize|glm|glm-sanitize|qwen-chain|qwen-chain-sanitize" >&2; exit 2 ;;
esac
diff --cc docs/ENVIRONMENT.md
index 47df11a7,0fa0b675..d39b5c8e
--- a/docs/ENVIRONMENT.md
+++ b/docs/ENVIRONMENT.md
@@@ -244,13 -244,7 +244,13 @@@ With `COLI_VULKAN=1` every MoE engine (
| `COLI_VK_TIER_BALANCE` | on | `0`: the device takes every resident expert of a step. On, when a join keeps waiting for the device, the step's resident experts the CPU also holds in RAM go back to the CPU beyond the device's share, which moves with every join (down when the CPU waited more than a tenth of its own time, up when the device finished before 80% of it). |
| `COLI_VK_TIER_GEMM_ROWS` | `16` | Rows from which an expert of a step takes the tiled GEMM (prefill) instead of the per-row GEMV; `0` never. Below it a row's bits do not depend on how many rows share the dispatch. |
| `COLI_VK_TIER_QUEUE` | a second queue | `0`: the tier's batches share the main queue with the dense matmuls (they then serialize). Unset: a second queue of the main family, else a compute-only family's (RADV), else shared (Lavapipe). |
- | `COLI_VK_DENSE` | on; off on a device sharing the CPU's RAM while the tier is on | Where the dense (non-expert) matrices of qwen36, qwen38, inkling, olmoe, mimo, deepseek_v41, deepseek_v4 and qwenimage run. `0`: on the CPU (with the tier on, the device takes the routed experts only); `1`: on the device whatever the device. Unset: on the device, except on an integrated GPU or a CPU device (Lavapipe) while the engine runs the expert tier (today qwen36 and qwen38), where they stay on the CPU: there the dense matmuls cost more than the tier gains (measured on a Radeon 780M). The `[VK] <engine>: device ready, dense matrices on the ...` line says which and why. The GLM engine reads it through the same rule with its own default, off (see above). |
+ | `COLI_VK_DENSE` | on; off on a device sharing the CPU's RAM while the tier is on | Where the dense (non-expert) matrices of qwen36, qwen38, inkling, olmoe, kimi_k3 (its shared experts), mimo, deepseek_v41, deepseek_v4, glm53 and qwenimage run. `0`: on the CPU (with the tier on, the device takes the routed experts only); `1`: on the device whatever the device. Unset: on the device, except on an integrated GPU or a CPU device (Lavapipe) while the engine runs the expert tier (every one of them but qwenimage, which has no routed experts), where they stay on the CPU: there the dense matmuls cost more than the tier gains (measured on a Radeon 780M). The `[VK] <engine>: device ready, dense matrices on the ...` line says which and why. The GLM engine reads it through the same rule with its own default, off (see above). |
+| `COLI_VK_CHAIN` | on for a discrete GPU; qwen36 on, qwen38 off on an integrated GPU with the tier; off on a CPU device | qwen36 and qwen38: every layer's dense chain recorded into one submission per layer, the residual stream and the recurrent and KV state on the device (see [vulkan.md](vulkan.md#the-dense-chain-vk_chainc)). `0` off, `1` on, `2` on for prompts only (decode on the CPU). The `[VK] <engine>: dense chain ...` line says which and why. |
+| `COLI_VK_CHAIN_ROWS` | `512` | Prompt rows per chunk of the chain's prefill. |
+| `COLI_VK_CHAIN_GEMV` | on | `0`: the chain's decode matrices take `qmatmul.comp`'s GEMV instead of `chain_gemv.comp`'s. |
+| `COLI_VK_CHAIN_SPIN_US` | `2000` | How long a wait on a chain frame polls before blocking. |
+| `COLI_VK_CHAIN_PROF` | off | `1`: device time per kind of chain op, one line per run. |
+| `COLI_VK_CHAIN_FAULT` | off | Tests: the n-th chain frame fails as a lost device would; the engine rebuilds the state on the CPU. |
### Second Vulkan device (opt-in)
diff --cc docs/vulkan.md
index 32e4709f,b2bee264..4977814f
--- a/docs/vulkan.md
+++ b/docs/vulkan.md
@@@ -512,205 -663,11 +663,207 @@@ converts `expert_ffn.h`'s planar int4 a
backend enables the extension when the device has it; nothing outside the harness
uses it.
+## The dense chain (`vk_chain.c`)
+
+With the dense matrices on the device one `coli_vk_matmul` at a time, each matrix is
+a submit and a host round trip: about 726 of them per Qwen3.8 decode token. On an
+integrated GPU that made the dense part slower on the device than on the CPU (see
+[the other engines](#the-other-engines)). The chain records a whole layer into one
+command buffer instead, and keeps the residual stream on the device from one layer
+to the next. qwen36 (Qwen3.6, Qwen3-Coder, Qwen3.8-27B) and qwen38 (Qwen3.8 Flash
+Next) run it: by default on a discrete GPU, and for qwen36 on an integrated one with
+the expert tier (see [the default](#the-chain-on-a-radeon-780m)); `COLI_VK_CHAIN=1`
+anywhere.
+
+**What runs where, per layer** (S rows: one at decode, a prompt chunk at prefill):
+
+| | qwen36 | qwen38 adds |
+|---|---|---|
+| device, frame A1 | the previous layer's MoE output joining the residual (in the CPU's order: routed experts in rank order, then the gated shared expert, then the add); the input RMSNorm; the gated attention (q/k/v, per-head q/k norm, RoPE, the new K/V rows into the device cache, attention with the output gate, o_proj) or the Gated DeltaNet (qkv/z/b/a, the causal convolution with its ring, the recurrence with its state, the gated norm, out_proj); the residual add; the post-attention norm; the router logits | the four hyper-connection streams: each block's gated-residual read (per-stream norm, the low-rank pair, the stream mix, the inject weights) and its write-back; the PLE layer's projections, gate and dilated convolution (the n-gram table rows come up from the host); QSA with its indexer: each block's pooled key computed once on the device when a step completes it, and the top-k selection per query row |
+| host | the router's softmax and top-k; the routed experts (the expert tier's device batch and the CPU's share, joined in rank order); the new K/V rows copied into the host's cache | the new index-key rows too |
+| device, frame A2 (not waited for) | the shared expert and its gate, while the host computes the routed experts | |
+| last frame | the final norm and lm_head on the last row | the final mixer; lm_head on the last one or two rows (an MTP verify) |
+
+Per layer the host gets the normalized rows the routed experts read (D floats a row)
+and the router logits (E floats a row), and the new K/V (and index-key) rows of an
+attention layer; it sends the routed sum back (D floats a row). A model without
+routed experts (Qwen3.8-27B) has no host step: its whole forward is one frame.
+
+**The state, and who owns it.**
+- The residual stream: on the device for the whole forward.
+- The attention KV cache (and Qwen3.8's index keys): the host's copy stays canonical,
+ as with the GLM engine's KV mirror. The device holds a mirror per layer with a
+ watermark: rows below it equal the host's. A step from `pos_base` first uploads
+ the rows between the watermark and `pos_base`; a step that runs on the CPU lowers
+ the watermark to its `pos_base`; a cache that grows is mirrored again. Qwen3.8's
+ pooled block keys have a watermark of their own, lowered to the first block a step
+ rewrites (a rejected draft's block is recomputed when a step completes it again).
+- The DeltaNet recurrent state and conv rings, and Qwen3.8's PLE ring: on the device
+ while the chain runs (60 MB on Qwen3.6-35B, too much to copy per token). The host's
+ copy is brought back before anything reads it there (a pinned snapshot, the prompt
+ cache, a CPU step) and pushed up after anything writes it there (a reset: a fill
+ with zeros on the device; a restored snapshot: an upload).
+- An MTP verify (S = 2) snapshots the DeltaNet states, the conv rings and the PLE ring
+ after its first row on the device (the shaders write the snapshot as they pass
+ that row); a rejected draft swaps the device buffers, as the CPU swaps its own.
+ Its matrices take the per-row GEMV, so its rows get a decode step's bits.
+
+Prompt-cache and prefix reuse need nothing else: a reused prefix is rows below the
+watermark and a recurrent state that already sits where the next step expects it.
+The serve and prefix tests run with the chain on (below).
+
+**What stays on the CPU.** The routed experts the tier does not hold, the router's
+top-k, the embedding gather and the vision tower's rows, Qwen3.8's n-gram table reads
+and the MTP head (its experts are FP8 beside the int4 sidecar, two rows per draft).
+The chain declines, and the per-matrix path runs with the state synced first, under
+the CUDA expert tier (CUDA keeps its priority), a qpack container, PILOT prefetch, or
+a geometry outside its shaders (head dim above 256, a DeltaNet value head above 128 or
+key head above 256, a conv kernel above 9). A device lost while the chain holds the
+recurrent state does not stop the engine: it rebuilds that state on the CPU from the
+prefix record (the ids the state was built from; the KV rows are the host's already),
+a prefill's worth of CPU work, and runs on the CPU from there. Only a state the ids do
+not describe (a turn with an image) cannot be rebuilt: that stops the engine with a
+message. `COLI_VK_CHAIN_FAULT=n` fakes the loss at the n-th frame (the tests use it).
+
+**The shaders** (`shaders/chain_*.comp`, each documented at its top): RMSNorm over
+segments (rows, heads with a gate between them, streams with a weight slice each,
+zero-centred or not, L2); RoPE from a host table (the CPU's own cosf/sinf at the CPU's
+angles, so M-RoPE is just another table); grouped-query attention with an online
+softmax over tiles of 128 positions, the output gate and an optional selection list;
+the DeltaNet convolution and the recurrence (one workgroup per value head, a column of
+the state in registers per thread, the gated norm fused); the element-wise steps; the
+QSA block keys and selection; the PLE gate and convolution; and a decode GEMV for the
+trunk's formats (int8 rows, int4-g64, bf16, f32) that reads 16 bytes per lane per step
+and spreads a row over a cluster of lanes. The matrices of a prefill chunk take the
+backend's fp32 tiled GEMM from its threshold (S ≥ 2 and S·O ≥ 4096). Activations are
+f32 throughout, as the CPU's f32 path.
+
+| Variable | Default | Effect |
+|---|---|---|
+| `COLI_VK_CHAIN` | on for a discrete GPU; on an integrated GPU with the expert tier, what the engine measured (qwen36 on, qwen38 off); off on a CPU device | `1`: every layer's dense chain on the device; `2`: prompts only (forwards of more than two rows; decode and MTP verifies on the per-matrix path, the state moving between the two); `0`: the per-matrix path. The `[VK] <engine>: dense chain ...` line says which and why. |
+| `COLI_VK_CHAIN_ROWS` | `512` | Prompt rows per chunk: a longer prompt runs every layer chunk by chunk (the device's scratch is sized for one chunk). |
+| `COLI_VK_CHAIN_GEMV` | on | `0`: the decode matrices take `qmatmul.comp`'s GEMV instead of `chain_gemv.comp`'s. |
+| `COLI_VK_CHAIN_SPIN_US` | `2000` | How long a wait on a chain frame polls the fence before blocking. |
+| `COLI_VK_CHAIN_PROF` | off | `1`: one `[VK] chain profile` line of device time per kind of op (timestamps). |
+
+Each run and serve turn prints `[VK] <engine> chain: N forwards, F frames (ops,
+matmuls, tiled GEMM), the time spent waiting for the device, the routed experts' host
+time and the device memory the chain holds`.
+
+### The chain on a Radeon 780M
+
+The box and the method of [the tier's measurements](#measured-on-a-radeon-780m): Ryzen
+7 PRO 8700GE, RADV, `OMP_NUM_THREADS=8`, every run after the model files were dropped
+from the page cache, 1-min load under 2, every tier arm from the same history of one
+unrelated conversation, the same binary for every arm; Qwen3.8 runs the int4-g64
+sidecar at cap 96, Qwen3.6 the int4 gs64 container at cap 64. Decode is 100 tokens
+after a 25-token prompt (the rate the engine reports; in brackets the whole process),
+prefill a 512-token prompt (`N_NEW=1`; Qwen3.8 with `Q38_PREFILL_BATCH_ROWS=512`).
+Where a cell lists two or three numbers, they are separate rounds.
+
+| Decode | Qwen3.8 Flash Next, int4 | Qwen3.6-35B-A3B |
+|---|---|---|
+| CPU | 3.49 tok/s (36.5 s) | 6.01 tok/s (23.6 s) |
+| tier, trunk on the CPU | 3.81, 3.81, 3.84 tok/s (36.8 s) | 8.03, 8.06 tok/s (22.5 s) |
+| tier and chain (`COLI_VK_CHAIN=1`) | 3.18, 3.18 tok/s (41.7 s) | 9.94, 9.92, 9.97 tok/s (20.2 s) |
+| tier and chain on prompts only (`COLI_VK_CHAIN=2`) | 3.64 tok/s | |
+
+| Prefill, 512 tokens | Qwen3.8 Flash Next, int4 | Qwen3.6-35B-A3B |
+|---|---|---|
+| CPU | 43.6 s (51.5 s) | 35.7 s (42.8 s) |
+| tier, trunk on the CPU | 38.7, 38.6 s (49.4 s) | 12.2 s (22.3 s) |
+| tier and chain (prompts: `COLI_VK_CHAIN=1` or `2`) | 30.1, 30.1, 30.1 s (40.5 s) | 9.5, 9.5 s (19.7 s) |
+
+What the numbers say:
+
+- **Qwen3.6: the chain wins both.** Decode 24% over the tier alone, 65% over the CPU;
+ the first token 22% sooner than the tier alone. A decode token is 82 frames (two a
+ layer and the head) where the trunk on the device took about 290 synchronous
+ submits; the host waited 53 ms a token for the device's frames and spent 40 on the
+ routed experts (the tier's batch, the CPU's share, their join).
+- **Qwen3.8: prefill wins, decode loses.** The first token comes 22% sooner, but
+ decode is 17% slower than the tier alone. Its trunk is 3.6 G weights in the layers
+ and 0.6 G in lm_head, int8 rows, read whole every token (more than its routed
+ experts); the device's decode GEMV, at the 800 MHz floor the GPU mostly sits at,
+ reads int8 at 30 to 43 GB/s back to back, where the CPU's integer kernel takes the
+ trunk in about 84 ms a token (73 ms of resident matmuls and 11 of lm_head in the tier
+ arm's timers), about 50 GB/s. `COLI_VK_CHAIN_PROF=1` put 77% of the chain's device
+ time in those GEMVs. Running only the prompts on the device (`COLI_VK_CHAIN=2`) keeps the prefill
+ gain and still loses 5% of decode: on shared RAM the trunk's device copy (1.1 GiB of
+ the budget here) is taken from the tier.
+- **The clock.** With the trunk on the CPU the GPU sat at its 800 MHz floor in 97 to
+ 100% of the samples during decode. The chain keeps it busy enough to leave the floor
+ part of the time: 53% of the samples at 800 MHz on Qwen3.6's decode, 39% on
+ Qwen3.8's, 60% and 84% on the prefills. Nothing here pinned the clock.
+- **The text.** Qwen3.6's chain printed the CPU's 100 decode tokens word for word (the
+ tier alone left them at the 22nd word in this round); Qwen3.8's left them at the
+ 59th word of 78 (the tier alone at the 43rd). The chain multiplies f32 activations
+ where the CPU's int8 kernels round them (see Arithmetic above); after the 512-token
+ prompts every arm gave the CPU's first token.
+- **Memory.** The chain holds 160 to 290 MiB on the device for Qwen3.6 and 350 to
+ 720 MiB for Qwen3.8 (state, mirrors and scratch for a 512-row chunk), beside the
+ trunk's device copy (1.9 GiB of int8 for Qwen3.6). On an integrated GPU both come
+ out of the tier's budget: 12.05 instead of 12.48 GiB on Qwen3.6, 8.4 instead of
+ 9.6 GiB on Qwen3.8.
+
+**The default** (`coli_vk_chain_decide`, next to `coli_vk_dense_decide`): on a discrete
+GPU the chain is on. On an integrated GPU with the expert tier on, each engine passes
+what it measured here: qwen36 on, qwen38 off (decode, a chat's steady state, is slower
+in both modes; `COLI_VK_CHAIN=2` is the choice for long prompts). Without the tier, and
+on a CPU device such as Lavapipe, it is off. The startup line says which and why:
+
+```
+[VK] qwen36: dense chain on (an integrated GPU with the expert tier: measured faster on decode and prefill; COLI_VK_CHAIN=0 off, 1 on, 2 prompts only)
+```
+
+**What was not measured.** No discrete GPU was available. On one the trunk sits in
+VRAM, read at several times the CPU's bandwidth, the clock is not held at a floor
+between bursts, and the host round trip per layer crosses PCIe (a few KB a row each
+way); that is the case the chain's default is set for, and nothing above is a
+prediction of it. Not timed either: contexts past 2048 tokens (where Qwen3.8's QSA
+selects blocks instead of attending to all of them), serve sessions, Qwen3-Coder and
+Qwen3.8-27B (no checkpoints on the box); their correctness is the Lavapipe gates'.
+
+### Adding an engine to the chain
+
+The recipe qwen36_chain.h and qwen38_chain.h follow, for the engines still on the
+per-matrix path:
+
+1. **Parameters and tensors once.** Pack every norm weight and small parameter vector
+ into one device buffer (`vkc_buf` + one `vkc_write`) and pass offsets; resolve every
+ matrix to the device copy the per-matrix path already uploads (`coli_vk_tensor_ensure`
+ into the engine's own `vk` field), so the two paths never hold a matrix twice.
+2. **Own the state explicitly.** Attention caches: keep the host's canonical, copy each
+ step's new rows back (a few KB a layer), mirror on the device behind a watermark
+ lowered by every CPU write. Recurrent state too large to copy per token: on the
+ device, with a "who holds the newest copy" flag synced at every host read (snapshots,
+ prompt caches) and every host write (resets, restores). A speculative verify writes a
+ snapshot of the recurrent state at its first row in the shader that walks the rows,
+ and a rejection swaps buffers.
+3. **One frame per layer up to the first thing the host must decide** (the router's
+ top-k for the routed experts), the CPU-independent tail (the shared expert) in a
+ frame nobody waits for, and the join (routed sum + shared, in the CPU's order) at the
+ head of the next layer's frame.
+4. **The CPU's arithmetic order wherever it is cheap to keep** (the conv sum order, the
+ MoE combine, the RoPE angles from a host table), f32 activations, and a gate per
+ configuration in `tests/vulkan_engines.sh` against the CPU's tokens and logits.
+
+What each remaining architecture needs on top of today's shaders:
+
+| Engine | Attention / mixer | New pieces |
+|---|---|---|
+| colibri.c (GLM-5.2), glm53, deepseek_v41, kimi_k3 (MLA layers) | MLA: q_a/kv_a, the latent norms, q_b, RoPE on the rope dims, a latent + rope cache | the absorb core (`attention_absorb.comp`) already reads a device KV mirror with GLM's watermark (`vk_kv_valid`): record it as a chain op with the o-projection fused (the universal layout's eight bindings hold its seven); DSA's index keys and top-k are `chain_qsa.comp`'s selection with blocks of one position, and the absorb shader takes the selection list as `chain_attn.comp` does; GLM's MTP layer stays on the CPU like qwen38's head, or runs in the chain (MLA has no recurrent state: a rejected draft is a lowered watermark) |
+| deepseek_v4 | MLA with compressed (CSA) and hierarchical (HCA) KV, mHC | the manifold hyper-connections are qwen38's stream read/apply with a Sinkhorn normalization (an element-wise op that iterates); the compressors' rolling windows are rings like the conv's, snapshotted the same way; the CPU rounds activations to E4M3 before its fp8 matmuls, so the chain needs that rounding as an element-wise op to keep the same arithmetic |
+| kimi_k3 (KDA layers) | Kimi Delta Attention: a gated delta rule whose decay is a vector over the key channels | `chain_dnrec.comp` with the decay per key row (one `exp(g_k)` per row of the column, loaded beside q and k in shared memory) instead of one per head; the short convolution is `chain_dnconv.comp`; its output gate and norm as the gated norm |
+| mimo | sliding-window attention (and full layers) | `chain_attn.comp` with a window (positions from `max(0, pos - W + 1)`: one more push constant), the cache optionally a ring of W rows (the host mirror then indexes `t % W`) |
+| inkling | grouped attention, MoE with a shared expert | qwen36's attention and combine as they are; its per-position heads are matmuls of the residual rows |
+| olmoe | attention with q/k norm, MoE without a shared expert | qwen36's Qwen3-Coder geometry (all attention, no gate, no shared expert) is the same chain |
+
## Adding an engine to the tier
- The integration steps are in [`c/vk_tier.h`](../c/vk_tier.h); in short:
+ Every MoE engine here is on the tier ([the table above](#the-routed-expert-tier-vk_tierc));
+ these are the steps the next one takes. They are in [`c/vk_tier.h`](../c/vk_tier.h);
+ in short:
1. **Describe the experts** (`VktConfig`): geometry, how RAM holds gate/up and down
(`VktSrc`: int8 per row or grouped, the int8 copy of an int4 container, int4
@@@ -767,14 -719,24 +915,32 @@@
in flight. `tests/vulkan_engines.sh qwen` gives the CPU's tokens with the tier on
in every qwen36 and qwen38 expert format, under eviction, with MTP and with the
trunk on the CPU; `qwen-sanitize` runs the same under ASan and UBSan.
+ `tests/vulkan_engines.sh inkling-olmoe` does the same for inkling (every expert
+ format above, under the f32, bf16 and dense-int4g64 snapshots, `TOPP`) and olmoe
+ (with `PILOT`'s worker), under eviction, with a warm start, and through both
+ engines' serve tests (prefix reuse, the dashboard, Brio); `inkling-olmoe-sanitize`
+ runs them under ASan and UBSan. `kimi` and the mimo half of `mimo-qwenimage` do it
+ for Kimi K3 and MiMo: their vendor oracles with the tier on, the CPU's
+ tokens in every dense format with the trunk on the device and on the CPU, a budget
+ of two experts that must evict, the old switches, Kimi K3's warm start;
+ `kimi-mimo-sanitize` runs the tier's configurations under ASan and UBSan.
+ `tests/vulkan_engines.sh deepseek` does it for deepseek_v41 (every tiny oracle, the
+ 40-token prompt, DSpark, eviction) and deepseek_v4 (the three oracle cases on a 4-
+ and an 8-expert fixture with pinned rows16 experts, eviction, the warm start, the
+ served logprobs), and `deepseek-sanitize` under ASan and UBSan. DeepSeek V4's
+ activation has a case of its own in the harness, checked bit for bit, and in
+ `vk-tier-check`.
+ `tests/vulkan_engines.sh glm` does the same for colibri and glm53 (every expert
+ format, warm and cold, prefill, eviction, the trunk and attention core on the
+ device, `COLI_VK_DEV2`), `glm-sanitize` under ASan and UBSan.
+- The dense chain: `make vk-chain-check VK=1` (`tests/test_vk_chain.c`) runs every chain
+ op against a CPU reference; `tests/vulkan_engines.sh qwen-chain` gives the CPU's tokens
+ with the chain in every qwen36 geometry and expert container and every qwen38 format,
+ the last logits within 1e-4 of the largest one where both sides use f32 activations
+ (measured 2e-7 and below on the fixtures), prefill in chunks, an image, MTP drafts
+ rejected, accepted and alternating, a device lost mid-run, the qwen38 oracle targets,
+ the prefix-reuse contract and serve sessions frame for frame; `qwen-chain-sanitize`
+ runs the chain under ASan and UBSan.
- int4 weights decode as offset-binary (nibble−8), byte-identical layout to
the CPU path — no repacking.
- Khronos validation layers: the backend never enables them, so the loader