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

tests: the GLM engines' dense chain on Lavapipe, and under ASan and UBSan

JustVugg69faa75f1b82
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 005cf6aa..8cced225 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -200,6 +200,12 @@ jobs:
req: c/tools/requirements-glm53-tiny.txt
- family: glm-sanitize
req: c/tools/requirements-glm53-tiny.txt
+ # the dense chain (COLI_VK_CHAIN=1) of colibri and glm53: the MLA, KDA and mHC
+ # ops, and the same under ASan and UBSan
+ - family: glm-chain
+ req: c/tools/requirements-glm53-tiny.txt
+ - family: glm-chain-sanitize
+ req: c/tools/requirements-glm53-tiny.txt
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
diff --git a/c/tests/vulkan_chain_serve.py b/c/tests/vulkan_chain_serve.py
index e760e72d..48ff5748 100644
--- a/c/tests/vulkan_chain_serve.py
+++ b/c/tests/vulkan_chain_serve.py
@@ -11,7 +11,13 @@ device sums in another order), so numbers compare within 1e-4.
usage: vulkan_chain_serve.py <engine> <snapshot> [KEY=VALUE ...] (extra environment)
COLI_VK_CHAIN in the caller's environment picks the chain's mode (default 1; 2 runs
-prompts on the device and decode on the CPU, the state moving between them)
+prompts on the device and decode on the CPU, the state moving between them).
+CHAIN_SERVE_DIALECT picks the SUBMIT header: unset, ids r0, r1, ... and the options
+straight after top_p (what the qwen engines have always been sent); "numeric", ids 1,
+2, ... (glm53); "colibri", numeric ids and the grammar-bytes field (0) before the
+options (colibri's multiplexed serve). CHAIN_SERVE_SLOTS=n sends request i to KV slot
+i % n (the engine needs KV_SLOTS=n): the turns move between sessions, and with them
+whatever state the chain keeps on the device.
"""
import os
import subprocess
@@ -46,7 +52,11 @@ def session(engine, snap, extra, chain):
(base + b"QRSk", 4, "")]
out = []
for i, (prompt, max_tok, ext) in enumerate(turns):
- hdr = f"SUBMIT r{i} 0 {len(prompt)} {max_tok} 0 1" + (f" {ext}" if ext else "") + "\n"
+ dialect = os.environ.get("CHAIN_SERVE_DIALECT", "")
+ rid = f"{i + 1}" if dialect in ("numeric", "colibri") else f"r{i}"
+ slot = i % int(os.environ.get("CHAIN_SERVE_SLOTS", "1"))
+ hdr = (f"SUBMIT {rid} {slot} {len(prompt)} {max_tok} 0 1" + (" 0" if dialect == "colibri" else "") +
+ (f" {ext}" if ext else "") + "\n")
p.stdin.write(hdr.encode() + prompt + b"\n")
p.stdin.flush()
while True:
diff --git a/c/tests/vulkan_engines.sh b/c/tests/vulkan_engines.sh
index ab4f9ff7..197017b7 100755
--- a/c/tests/vulkan_engines.sh
+++ b/c/tests/vulkan_engines.sh
@@ -7,6 +7,7 @@
# 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)
+# bash tests/vulkan_engines.sh glm-chain | glm-chain-sanitize # the same for colibri and glm53
#
# 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).
@@ -1340,6 +1341,183 @@ family_qwen_chain_sanitize() {
make clean >/dev/null 2>&1 || true
}
+# The dense chain of the MLA engines: GLM-5.2 (colibri) and GLM-5.3 Flash (glm53).
+# mla_gate <engine> <tag> <tol 0|1> <env...> -- <argv...>: the CPU run's token lines
+# (colibri: the generated tokens, the teacher-forced predictions and the oracle's
+# mismatches; glm53: teacher_forcing and greedy), every logits row within 1e-4 of the
+# largest |logit| (tol 1; DUMP= writes them), and a "[VK] <engine> chain: N forwards"
+# line with N > 0. LOST=1: COLI_VK_CHAIN_FAULT is set, and the run must say the device
+# was lost (and, for glm53 with REBUILD=1, rebuild the KDA state of some positions).
+mla_toks() { # <engine> <log>
+ if [ "$1" = colibri ]; then grep -aE '^GLM C engine|^PREFILL|^\[ORACLE\] mismatch' "$2" | sed 's/ | [0-9.]* pos\/s//'
+ else grep -aE '^teacher_forcing|^greedy' "$2"; fi
+}
+mla_gate() {
+ 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
+ env "${envs[@]}" COLI_USAGE=chain.usage USAGE_SAVE=0 DUMP=cpu.f32 ./"$eng" "$@" > cpu.log 2>&1 || true
+ rm -f chain.usage
+ env "${envs[@]}" COLI_USAGE=chain.usage USAGE_SAVE=0 DUMP=vk.f32 COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 \
+ COLI_VK_CHAIN=${CHAINMODE:-1} ./"$eng" "$@" > vk.log 2>&1 || true
+ mla_toks "$eng" cpu.log > cpu.tok; mla_toks "$eng" vk.log > vk.tok
+ { [ -s cpu.tok ] && cmp -s cpu.tok vk.tok; } || { cat cpu.tok vk.tok; tail -20 vk.log; fail "$tag: the chain's tokens differ from the CPU"; }
+ if [ "${LOST:-0}" = 1 ]; then
+ grep -q "$eng chain: the device was lost" vk.log || { cat vk.log; fail "$tag: no loss was handled"; }
+ if [ "${REBUILD:-0}" = 1 ]; then grep -q "rebuilding the state of [1-9]" vk.log || { cat vk.log; fail "$tag: no state was rebuilt"; }; fi
+ else
+ [ "$(chain_count "$eng" vk.log)" -gt 0 ] || { cat vk.log; fail "$tag: the chain never ran"; }
+ fi
+ 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$(grep -o 'rebuilding the state of [0-9]* positions' vk.log | sed 's/^/, /')"
+}
+glm_chain_fixtures() {
+ glm_fixtures
+ $PY tools/make_glm_mtp_tiny.py --src glm_tiny --out glm_tiny_mtp > /dev/null && cp ref_glm.json glm_tiny_mtp/
+ rm -rf glm_tiny_serve && cp -r glm_tiny glm_tiny_serve
+ $PY tools/make_edge_tiny_tokenizer.py --vocab-size 256 ./glm_tiny_serve > /dev/null # serve speaks text
+ rm -rf glm53_serve && cp -r glm53_stream-i4 glm53_serve
+ $PY tools/make_edge_tiny_tokenizer.py --vocab-size 128 ./glm53_serve > /dev/null
+ $PY tools/make_glm53_multimodal_tiny.py --output glm53_mm_tiny > /dev/null
+ rm -rf glm53_lim0 && cp -r glm53_stream-i4 glm53_lim0 # swiglu_limit 0: the tier declines, the chain does not
+ $PY - <<'PY'
+import json
+p = "glm53_lim0/config.json"; c = json.load(open(p))
+(c["text_config"] if "text_config" in c else c)["swiglu_limit"] = 0.0
+json.dump(c, open(p, "w"))
+PY
+}
+
+# Every configuration the chain takes: colibri in every expert format (IDOT=0 where the
+# CPU would round activations to int8: the device matches IDOT=0, as for the tier),
+# decode and teacher-forced prefill in chunks, the DSA indexer's selection active
+# (DSA_TOPK=4 on the 12-token prompt, and DSA_FORCE), n-gram and MTP drafts accepted and
+# rejected (the MTP fixture's head is the last layer's copy), the tier off, the per-matrix
+# trunk and attention core beside it, prompts only, a device lost mid-decode and in a
+# prompt, serve sessions (pins, the prompt cache, two KV slots, the prefill read-out);
+# glm53 with f32, int8 and int4 trunks, streamed and resident experts, an image, prefill
+# chunks and chain chunks, swiglu_limit 0, a lost device whose KDA state is rebuilt on
+# the CPU, serve sessions, and its pin-branch harness with the chain on.
+family_glm_chain() {
+ make colibri glm53 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"
+ glm_chain_fixtures
+ export OMP_NUM_THREADS=2 CAP_RAISE=0
+ local cap b fx d
+ for cap in 1 64; do mla_gate colibri "chain colibri f32 cap=$cap" 1 SNAP=glm_tiny REF=ref_glm.json -- $cap 16 16; done
+ mla_gate colibri "chain colibri f32 prefill" 1 SNAP=glm_tiny REF=ref_glm.json TF=1 -- 64 16 16
+ mla_gate colibri "chain colibri prefill in chunks of 3" 1 SNAP=glm_tiny REF=ref_glm.json TF=1 COLI_VK_CHAIN_ROWS=3 -- 64 16 16
+ for b in 8 4 3; do
+ mla_gate colibri "chain colibri ${b}-bit trunk and experts" 1 SNAP=glm_tiny REF=ref_glm.json IDOT=0 -- 2 $b $b
+ done
+ mla_gate colibri "chain colibri int4-g64 experts" 1 SNAP=glm_tiny_fmt4 REF=glm_tiny_fmt4/ref_glm.json -- 2 16 16
+ mla_gate colibri "chain colibri E8/IQ3 experts on the CPU" 1 SNAP=glm_tiny_fmt6 REF=glm_tiny_fmt6/ref_glm.json -- 2 16 16
+ for fx in i4 i4r i3 d3; do
+ mla_gate colibri "chain colibri $fx container" 1 SNAP=glm_tiny_$fx REF=glm_tiny_$fx/ref_glm.json IDOT=0 -- 1 4 4
+ done
+ mla_gate colibri "chain colibri i4 container, prefill" 1 SNAP=glm_tiny_i4 REF=glm_tiny_i4/ref_glm.json IDOT=0 TF=1 -- 2 4 4
+ # the DSA indexer's selection on the device: index_topk 4 against a 32-token context
+ mla_gate colibri "chain colibri DSA top-4" 1 SNAP=glm_tiny REF=ref_glm.json DSA_TOPK=4 -- 64 16 16
+ mla_gate colibri "chain colibri DSA top-4, prefill in chunks of 5" 1 SNAP=glm_tiny REF=ref_glm.json DSA_TOPK=4 TF=1 COLI_VK_CHAIN_ROWS=5 -- 64 16 16
+ mla_gate colibri "chain colibri DSA_FORCE" 1 SNAP=glm_tiny REF=ref_glm.json DSA_FORCE=1 -- 64 16 16
+ # drafts: n-gram, and the MTP head at depths 1 to 3 (accepted and rejected)
+ mla_gate colibri "chain colibri n-gram drafts" 1 SNAP=glm_tiny REF=ref_glm.json DRAFT=3 -- 64 16 16
+ for d in 1 2 3; do mla_gate colibri "chain colibri MTP depth $d" 1 SNAP=glm_tiny_mtp REF=glm_tiny_mtp/ref_glm.json DRAFT=$d -- 64 16 16; done
+ mla_gate colibri "chain colibri MTP with DSA top-4" 1 SNAP=glm_tiny_mtp REF=glm_tiny_mtp/ref_glm.json DSA_TOPK=4 -- 64 16 16
+ mla_gate colibri "chain colibri MTP, 4-bit" 1 SNAP=glm_tiny_mtp REF=glm_tiny_mtp/ref_glm.json IDOT=0 DRAFT=2 -- 2 4 4
+ # around the chain: the tier off, the per-matrix trunk and core, the GEMM and GEMV choices
+ mla_gate colibri "chain colibri tier off" 1 SNAP=glm_tiny REF=ref_glm.json COLI_VK_TIER=0 -- 64 16 16
+ mla_gate colibri "chain colibri beside COLI_VK_DENSE=1 COLI_VK_ATTN=1" 1 SNAP=glm_tiny_i4 REF=glm_tiny_i4/ref_glm.json IDOT=0 COLI_VK_DENSE=1 COLI_VK_ATTN=1 -- 2 4 4
+ # COLI_VK_DEV2 beside the chain: a second logical device holds what the capped tier does not
+ SNAP=glm_tiny_i4r REF=glm_tiny_i4r/ref_glm.json IDOT=0 STATS=glm_tiny_i4r/.coli_usage ./colibri 64 4 4 > /dev/null 2>&1 || true
+ mla_gate colibri "chain colibri beside COLI_VK_DEV2" 1 SNAP=glm_tiny_i4r REF=glm_tiny_i4r/ref_glm.json IDOT=0 COLI_VK_EXPERTS=4 COLI_VK_DEV2=0 -- 64 4 4
+ grep -qaE 'lru \+ [1-9][0-9]* vk /' vk.log || { cat vk.log; fail "chain colibri beside COLI_VK_DEV2: no expert on the devices"; }
+ rm -f glm_tiny_i4r/.coli_usage
+ mla_gate colibri "chain colibri tiled GEMM from 2 rows" 1 SNAP=glm_tiny REF=ref_glm.json TF=1 COLI_VK_GEMM_MIN_S=2 -- 64 16 16
+ mla_gate colibri "chain colibri the per-row GEMV" 1 SNAP=glm_tiny REF=ref_glm.json COLI_VK_CHAIN_GEMV=0 -- 64 16 16
+ CHAINMODE=2 mla_gate colibri "chain colibri prompts only, drafts" 1 SNAP=glm_tiny REF=ref_glm.json DRAFT=3 -- 64 16 16
+ # the device lost: mid-decode, in the prompt, between MTP drafts
+ LOST=1 mla_gate colibri "chain colibri device lost mid-decode" 1 SNAP=glm_tiny REF=ref_glm.json COLI_VK_CHAIN_FAULT=30 -- 64 16 16
+ LOST=1 mla_gate colibri "chain colibri device lost in the prompt" 1 SNAP=glm_tiny REF=ref_glm.json COLI_VK_CHAIN_FAULT=3 -- 64 16 16
+ LOST=1 mla_gate colibri "chain colibri device lost with MTP" 1 SNAP=glm_tiny_mtp REF=glm_tiny_mtp/ref_glm.json COLI_VK_CHAIN_FAULT=40 -- 64 16 16
+ # serve sessions frame for frame: pins, the prompt cache, the prefill read-out, two KV slots
+ CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0
+ CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 DSA_TOPK=4 DRAFT=3
+ CHAIN_SERVE_SLOTS=2 CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 KV_SLOTS=2
+ COLI_VK_CHAIN=2 CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 DSA_TOPK=4
+
+ # glm53
+ local ids bits
+ ids=$($PY -c "print(','.join(str((i*37+5)%120+2) for i in range(100)))")
+ mla_gate glm53 "chain glm53 decode" 1 GLM53_BITS=32 -- --model glm53_stream-i4 --ids 5,7,9,11,13,17,19,23 --greedy 8
+ for bits in 32 8 4; do
+ mla_gate glm53 "chain glm53 100-token prompt, ${bits}-bit trunk" 1 GLM53_BITS=$bits -- --model glm53_stream-i4 --ids $ids --greedy 4
+ done
+ mla_gate glm53 "chain glm53 prefill chunks of 7, one cache slot" 1 GLM53_BITS=4 GLM53_PREFILL_CHUNK=7 GLM53_EXPERT_GB=0.000001 -- --model glm53_stream-i4 --ids $ids --greedy 4
+ mla_gate glm53 "chain glm53 chain chunks of 3" 1 GLM53_BITS=32 COLI_VK_CHAIN_ROWS=3 -- --model glm53_stream-i4 --ids $ids --greedy 4
+ mla_gate glm53 "chain glm53 resident experts" 1 GLM53_BITS=32 -- --model glm53_tiny --ids $ids --greedy 6
+ mla_gate glm53 "chain glm53 tier off" 1 GLM53_BITS=32 COLI_VK_TIER=0 -- --model glm53_stream-i4 --ids $ids --greedy 6
+ mla_gate glm53 "chain glm53 an image" 1 GLM53_BITS=32 -- --model glm53_mm_tiny --ids 103,117,268,268,268,268,120,121 --patches glm53_mm_tiny/patches.f32 --grid 4x4 --greedy 4
+ mla_gate glm53 "chain glm53 swiglu_limit 0" 1 GLM53_BITS=32 -- --model glm53_lim0 --ids $ids --greedy 4
+ grep -qa 'tier glm53: swiglu_limit is 0' vk.log || { cat vk.log; fail "chain glm53 swiglu_limit 0: the tier did not decline"; }
+ CHAINMODE=2 mla_gate glm53 "chain glm53 prompts only" 1 GLM53_BITS=32 GLM53_PREFILL_CHUNK=16 -- --model glm53_stream-i4 --ids $ids --greedy 6
+ LOST=1 REBUILD=1 mla_gate glm53 "chain glm53 device lost, the KDA state rebuilt" 1 GLM53_BITS=32 GLM53_PREFILL_CHUNK=16 COLI_VK_CHAIN_FAULT=20 -- --model glm53_stream-i4 --ids $ids --greedy 6
+ LOST=1 REBUILD=1 mla_gate glm53 "chain glm53 device lost after an image" 1 GLM53_BITS=32 COLI_VK_CHAIN_FAULT=6 -- --model glm53_mm_tiny --ids 103,117,268,268,268,268,120,121 --patches glm53_mm_tiny/patches.f32 --grid 4x4 --greedy 4
+ CHAIN_SERVE_DIALECT=numeric $PY tests/vulkan_chain_serve.py ./glm53 glm53_serve GLM53_BITS=32
+ CHAIN_SERVE_DIALECT=numeric $PY tests/vulkan_chain_serve.py ./glm53 glm53_serve GLM53_BITS=4 COLI_VK_CHAIN_ROWS=3
+ CHAIN_SERVE_SLOTS=2 CHAIN_SERVE_DIALECT=numeric $PY tests/vulkan_chain_serve.py ./glm53 glm53_serve GLM53_BITS=32 KV_SLOTS=2
+ COLI_VK_CHAIN=2 CHAIN_SERVE_DIALECT=numeric $PY tests/vulkan_chain_serve.py ./glm53 glm53_serve GLM53_BITS=32
+ # a pin restored over rows another branch rewrote: the KDA state goes up from the pin,
+ # the MLA rows' watermark comes down
+ COLI_VULKAN=1 COLI_VK_CHAIN=1 COLI_USAGE=$PWD/chain.usage $PY tests/glm53_pin_branch_harness.py --binary ./glm53 --fixture glm53_mm_tiny
+ unset OMP_NUM_THREADS CAP_RAISE
+}
+
+# The same chains under ASan and UBSan: memory safety is the gate; each run must have run
+# the chain (or handled the loss). detect_stack_use_after_return=0 as in every sanitized
+# family (ASan's fake stack breaks 64-byte aligned AVX-512 locals).
+family_glm_chain_sanitize() {
+ make clean >/dev/null 2>&1 || true
+ make colibri glm53 tests/test_vk_chain VK=1 EXTRA_CFLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -g"
+ export ASAN_OPTIONS=detect_leaks=0:detect_stack_use_after_return=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"
+ glm_chain_fixtures
+ export OMP_NUM_THREADS=2 CAP_RAISE=0
+ msan() { # <engine> <tag> <env and argv...>
+ local eng=$1 tag=$2; shift 2
+ rm -f chain.usage
+ env COLI_USAGE=chain.usage USAGE_SAVE=0 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
+ grep -q "$eng chain: \([1-9][0-9]* forwards\|the device was lost\)" san.log || { cat san.log; fail "$tag: the chain never ran"; }
+ echo "OK $tag: sanitizers clean, $(chain_count "$eng" san.log) chain forwards"
+ }
+ local ids
+ ids=$($PY -c "print(','.join(str((i*37+5)%120+2) for i in range(100)))")
+ msan colibri "asan chain colibri f32 decode" SNAP=glm_tiny REF=ref_glm.json ./colibri 1 16 16
+ msan colibri "asan chain colibri DSA top-4 prefill, chunks of 3" SNAP=glm_tiny REF=ref_glm.json TF=1 DSA_TOPK=4 COLI_VK_CHAIN_ROWS=3 ./colibri 64 16 16
+ msan colibri "asan chain colibri i4 container" SNAP=glm_tiny_i4 REF=glm_tiny_i4/ref_glm.json IDOT=0 ./colibri 2 4 4
+ msan colibri "asan chain colibri MTP depth 2" SNAP=glm_tiny_mtp REF=glm_tiny_mtp/ref_glm.json DRAFT=2 ./colibri 64 16 16
+ msan colibri "asan chain colibri device lost" SNAP=glm_tiny REF=ref_glm.json COLI_VK_CHAIN_FAULT=30 ./colibri 64 16 16
+ msan glm53 "asan chain glm53 decode" GLM53_BITS=32 ./glm53 --model glm53_stream-i4 --ids 5,7,9,11,13,17,19,23 --greedy 8
+ msan glm53 "asan chain glm53 int4 trunk, chain chunks of 3" GLM53_BITS=4 COLI_VK_CHAIN_ROWS=3 ./glm53 --model glm53_stream-i4 --ids $ids --greedy 4
+ msan glm53 "asan chain glm53 an image" GLM53_BITS=32 ./glm53 --model glm53_mm_tiny --ids 103,117,268,268,268,268,120,121 --patches glm53_mm_tiny/patches.f32 --grid 4x4 --greedy 4
+ msan glm53 "asan chain glm53 device lost, rebuilt" GLM53_BITS=32 GLM53_PREFILL_CHUNK=16 COLI_VK_CHAIN_FAULT=20 ./glm53 --model glm53_stream-i4 --ids $ids --greedy 6
+ local args
+ for args in "./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 KV_SLOTS=2" "./glm53 glm53_serve GLM53_BITS=32 KV_SLOTS=2"; do
+ # shellcheck disable=SC2086
+ CHAIN_SERVE_SLOTS=2 CHAIN_SERVE_DIALECT=$([ "${args%% *}" = ./colibri ] && echo colibri || echo numeric) \
+ $PY tests/vulkan_chain_serve.py $args > san.log 2>&1 || { cat san.log; fail "asan chain serve $args"; }
+ if grep -qE "ERROR: AddressSanitizer|runtime error:" san.log; then cat san.log; fail "asan chain serve $args: sanitizer diagnostic"; fi
+ echo "OK asan chain serve ${args%% *}: $(tail -1 san.log)"
+ done
+ unset OMP_NUM_THREADS CAP_RAISE
+ make clean >/dev/null 2>&1 || true
+}
+
case "${1:-}" in
shader) shader_formats ;;
qwen) family_qwen ;;
@@ -1355,5 +1533,7 @@ case "${1:-}" in
glm-sanitize) family_glm_sanitize ;;
qwen-chain) family_qwen_chain ;;
qwen-chain-sanitize) family_qwen_chain_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|qwen-chain|qwen-chain-sanitize" >&2; exit 2 ;;
+ glm-chain) family_glm_chain ;;
+ glm-chain-sanitize) family_glm_chain_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|qwen-chain|qwen-chain-sanitize|glm-chain|glm-chain-sanitize" >&2; exit 2 ;;
esac
diff --git a/c/tools/make_glm_mtp_tiny.py b/c/tools/make_glm_mtp_tiny.py
new file mode 100644
index 00000000..6bd3f0ae
--- /dev/null
+++ b/c/tools/make_glm_mtp_tiny.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python3
+"""Give a GLM-5.2 tiny fixture (make_glm_oracle.py's glm_tiny) an MTP head, for the
+engine's speculative decode in tests.
+
+colibri.c turns MTP on when layer n_layers carries the head's tensors (eh_proj, enorm,
+hnorm, shared_head.norm and a full attention + MoE block). The oracle's transformers
+model has none, so this writes them: the block is a copy of the last layer's tensors,
+eh_proj passes the normalized hidden state through (its embedding half is zero), the
+three norms are ones and the model's final norm. The drafts it makes are a model of
+the model, not trained ones: some are accepted, most are not, and both paths run.
+
+Greedy decode with speculation verifies every draft, so the tokens are the oracle's
+whatever the head proposes: the fixture tests the draft/verify machinery, not the head.
+
+usage: make_glm_mtp_tiny.py --src glm_tiny --out glm_tiny_mtp
+"""
+import argparse
+import json
+import shutil
+from pathlib import Path
+
+import torch
+from safetensors.torch import load_file, save_file
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ ap.add_argument("--src", default="glm_tiny")
+ ap.add_argument("--out", default="glm_tiny_mtp")
+ args = ap.parse_args()
+ src, out = Path(args.src), Path(args.out)
+ cfg = json.loads((src / "config.json").read_text())
+ L, D = cfg["num_hidden_layers"], cfg["hidden_size"]
+ sd = load_file(str(src / "model.safetensors"))
+ last = f"model.layers.{L - 1}."
+ head = f"model.layers.{L}."
+ for name, t in list(sd.items()):
+ if name.startswith(last) and ".indexer." not in name:
+ sd[head + name[len(last):]] = t.clone()
+ eh = torch.zeros(D, 2 * D, dtype=torch.float32)
+ eh[:, D:] = torch.eye(D)
+ sd[head + "eh_proj.weight"] = eh
+ sd[head + "enorm.weight"] = torch.ones(D)
+ sd[head + "hnorm.weight"] = torch.ones(D)
+ sd[head + "shared_head.norm.weight"] = sd["model.norm.weight"].clone()
+ if out.exists():
+ shutil.rmtree(out)
+ out.mkdir(parents=True)
+ save_file({k: v.contiguous() for k, v in sd.items()}, str(out / "model.safetensors"))
+ for f in src.iterdir():
+ if f.name != "model.safetensors" and f.is_file():
+ shutil.copy(f, out / f.name)
+ print(f"wrote {out}: layer {L} is the MTP head ({sum(1 for k in sd if k.startswith(head))} tensors)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md
index d39b5c8e..3178dfc3 100644
--- a/docs/ENVIRONMENT.md
+++ b/docs/ENVIRONMENT.md
@@ -245,12 +245,13 @@ With `COLI_VULKAN=1` every MoE engine (qwen36, qwen38, inkling, olmoe, kimi_k3,
| `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, 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` | on for a discrete GPU; qwen36 on, qwen38, colibri and glm53 off on an integrated GPU with the tier; off on a CPU device | qwen36, qwen38, colibri (GLM-5.2) and glm53 (GLM-5.3 Flash): 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. |
+| `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 (colibri has none to rebuild) and runs there. |
+| `DUMP` | unset | colibri and glm53 in a `VK=1` build: every logits row the forward computes, appended to this file as raw f32 (the Vulkan gates compare the device's with the CPU's). |
### Second Vulkan device (opt-in)
diff --git a/docs/vulkan.md b/docs/vulkan.md
index 30bd2e67..cc68e245 100644
--- a/docs/vulkan.md
+++ b/docs/vulkan.md
@@ -673,7 +673,8 @@ command buffer instead, and keeps the residual stream on the device from one lay
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.
+anywhere. colibri (GLM-5.2) and glm53 (GLM-5.3 Flash) run it too, with the MLA,
+KDA and hyper-connection ops ([below](#glm-52-and-glm-53-flash-on-the-chain)).
**What runs where, per layer** (S rows: one at decode, a prompt chunk at prefill):
@@ -740,7 +741,7 @@ 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` | on for a discrete GPU; on an integrated GPU with the expert tier, what the engine measured (qwen36 on, qwen38 off; colibri and glm53 off: not measured); 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. |
@@ -824,6 +825,61 @@ prediction of it. Not timed either: contexts past 2048 tokens (where Qwen3.8's Q
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'.
+### GLM-5.2 and GLM-5.3 Flash on the chain
+
+`glm_chain.h` (colibri) and `glm53_chain.h` (glm53) follow the recipe below with the
+[MLA ops](#multi-head-latent-attention-on-the-chain-vkc_mla). What runs where, per
+layer:
+
+| | colibri (GLM-5.2) | glm53 (GLM-5.3 Flash) |
+|---|---|---|
+| device, frame A1 | the previous layer's MoE output joining the residual (routed, then the shared expert, then the add: the CPU's order); the input RMSNorm; the MLA attention: q_a, its norm, q_b, kv_a, the latent norm, interleaved RoPE, the new latent and rope rows into the device cache, on a DSA layer the index key (wk, LayerNorm, RoPE) into its cache and, past `index_topk` (or with `DSA_FORCE`), each row's top-k, reused by the shared layers after it; the absorbed core over the cache or the selection, the value rows, o_proj; the add; the post-attention norm. A dense layer runs its MLP here and has no host step | the previous layer's FFN branch (the routed sum plus the shared expert) written back into the hc_mult streams; every site through mHC (the mix, the split with Sinkhorn, the collapse, the write back); the input RMSNorm; a KDA layer (its projections, the short convolution with its window, the delta rule with its state, the output norm and gate, o) or an MLA layer (the projections into the cache, the k-pooled indexer: index keys and pool gates into their caches, each completed pool's key, every row's pools; the absorbed core over the selection, the values, o); the FFN site's entry and norm; a dense layer's MLP (clamped SwiGLU) |
+| host | moe() on the normalized rows without the shared expert: the f32 router with every routing option, the routed experts (the tier's batch and the CPU's share); the new KV rows copied into the host's cache | the router and the routed experts (the tier's batch and the CPU's share); the new MLA rows copied into the host's cache |
+| device, frame A2 (not waited for) | the shared expert | the shared expert (clamped SwiGLU) |
+| after the last layer | the final rows back to the host, which runs the final norm and lm_head as before | the final streams back to the host, which collapses them and runs the final norm and the head as before |
+
+**The state.** The KV caches (GLM-5.2's latent, rope keys and index keys; GLM-5.3's
+latent, index keys and pool gates) stay the host's: each step copies its new rows back,
+and the device mirror has a watermark that every host write lowers (the CPU's attention,
+`kv_alloc`, a slot adopting another slot's rows, another KV state or session bound, a
+pin restored). GLM-5.3's pool keys have a watermark of their own. MLA has no recurrent
+state, so a rejected draft is rows the next step rewrites. GLM-5.3's KDA state and
+convolution windows stay on the device while the chain runs, for one session at a time:
+the host's copy is brought back before a pin or a state capture reads it, before a CPU
+forward of the session and when another session takes the device, and goes up after a
+pin or a state is restored.
+
+**Drafts and the MTP head.** colibri's speculative decode runs as before: the verify
+rows go through the chain, the MTP head stays on the CPU and reads the chain's final
+rows, and n-gram drafts work the same way. glm53 has no draft path.
+
+**A lost device.** The forward that failed runs again on the CPU from its input (the
+chain keeps the caller's rows untouched until its last chunk is through), and the CPU
+runs from there. colibri has nothing to rebuild (its cache is the host's). glm53
+rebuilds the KDA state on the CPU from the input rows the chain records since the host's
+copy was last current (embedding rows, or the vision tower's), a prefill's worth of CPU
+work.
+
+**Declined** (the CPU path runs, the state synced first): a ragged multi-slot decode
+batch (a single-slot serve's one-row batch takes the chain), a layer range (a segment),
+a quantized KV cache (KV8, KV_TQ), PILOT, LOOKA, the exact verify of
+`COLI_EXACT_VERIFY`, the CUDA backend, matrices with no device form (int2, E8/IQ3, fp8
+dense matrices), and geometries past the ops' limits. With the chain on, the per-matrix
+switches (`COLI_VK_DENSE`, `COLI_VK_ATTN`, `COLI_VK_DEV2`) keep working beside it: the
+chain's tensors are their device copies where they made one.
+
+**Arithmetic.** f32 activations throughout, as the CPU's f32 paths: colibri's CPU int8
+dot (`IDOT`, on by default for int8 and, from two rows, int4 rows) rounds activations,
+so the tests set `IDOT=0` for those trunks, as for the tier. On the fixtures every
+configuration gives the CPU's tokens, and every logits row is within 2e-6 of the largest
+logit (Lavapipe: 1.9e-6 at worst, colibri's int4-g64 experts on the tier, 6.3e-7 and
+below everywhere else).
+
+**The default** is off on an integrated GPU (`COLI_VK_CHAIN=1` turns it on, `2` for
+prompts only) and on a discrete GPU follows the rule above. No GLM checkpoint was run:
+the 780M box has none, and both models are hundreds of GB. Speed is not measured; the
+tests prove the tokens on the tiny fixtures.
+
### Adding an engine to the chain
The recipe qwen36_chain.h and qwen38_chain.h follow, for the engines still on the
@@ -852,9 +908,9 @@ 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 |
+| 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 [MLA ops](#multi-head-latent-attention-on-the-chain-vkc_mla) take any geometry (q_lora or none, NoPE, the scale and cos/sin table from the engine, a gate on the values for Kimi K3); colibri and glm53 run them ([above](#glm-52-and-glm-53-flash-on-the-chain)). DeepSeek V4.1's attention has sinks and its own sparse selection: those are not in the ops yet |
+| deepseek_v4 | MLA with compressed (CSA) and hierarchical (HCA) KV, mHC | the manifold hyper-connections are `vkc_mhc` (GLM-5.3's, the same arithmetic) and the clamped SwiGLU too; 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 | `vkc_kda_conv` and `vkc_kda_rec` (GLM-5.3's KDA, `delta_attention.h`'s step); Kimi K3 builds its decay and output gate its own way (a full g_proj, not a low-rank one), which the recurrence's prologue and epilogue would take as options |
| 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 |
@@ -988,7 +1044,12 @@ in short:
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`
+ the prefix-reuse contract and serve sessions frame for frame; `glm-chain` does the
+ same for colibri and glm53: every expert format and trunk, prefill in chunks, the DSA
+ selection active, n-gram and MTP drafts accepted and rejected, glm53's image, KDA state
+ and swiglu_limit 0, a device lost (glm53's KDA state rebuilt), serve sessions with pins
+ and two KV slots, and glm53's pin-branch harness; `glm-chain-sanitize` runs them under
+ ASan and UBSan; `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.
@@ -1039,15 +1100,18 @@ hit-rate line is the tier-effectiveness number.
## Limits and future work
-- GLM-5.2 (this section's engine): the attention core serves `S<=4`; prefill uses the
- CPU/batched attention paths (dense projections do run on VK at prefill). Its routed
- experts are on the shared expert tier, which serves prefill too.
+- GLM-5.2 (this section's engine): the per-matrix attention core serves `S<=4`; prefill
+ uses the CPU/batched attention paths (dense projections do run on VK at prefill),
+ except with the dense chain (`COLI_VK_CHAIN=1`), which runs the whole layer, prefill
+ and the DSA selection included. Its routed experts are on the shared expert tier,
+ which serves prefill too.
- The expert tier's uploads are host writes into host-visible device memory: a
discrete card needs Resizable BAR for them (above). A staging copy on a transfer
queue, for cards without it, is not written.
-- DSA top-k selection, ragged multi-slot serving, and quantized-KV caches
- fall back to the CPU attention path.
-- Not yet done: a fully resident-layer pipeline for the engines other than qwen36 and
- qwen38 ([the dense chain](#the-dense-chain-vk_chainc) is theirs), Polaris/gfx803 validation on real
+- Without the dense chain, DSA top-k selection, ragged multi-slot serving, and
+ quantized-KV caches fall back to the CPU attention path; with it, the DSA selection
+ runs on the device.
+- Not yet done: a fully resident-layer pipeline for the engines other than qwen36,
+ qwen38, colibri and glm53 ([the dense chain](#the-dense-chain-vk_chainc) is theirs), Polaris/gfx803 validation on real
hardware (the shaders use dynamic subgroup sizes and are wave64-safe by
construction). The cooperative-matrix GEMM is measured on RDNA3 only.