Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
Merge the Kimi K3 chain and dev into the DeepSeek chain
JustVugg9564b60afaf7
diff --cc .github/workflows/ci.ymlindex d2548451,298dd324..586acb88--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@@ -206,14 -217,12 +217,20 @@@ jobsreq: c/tools/requirements-glm53-tiny.txt- family: glm-chain-sanitizereq: c/tools/requirements-glm53-tiny.txt+ # the dense chain (COLI_VK_CHAIN=1) of deepseek_v41 and deepseek_v4, and the same+ # under ASan and UBSan+ - family: deepseek-chain+ req: c/tools/requirements-deepseek-v4-tiny.txt+ extra: sympy pillow+ - family: deepseek-chain-sanitize+ req: c/tools/requirements-deepseek-v4-tiny.txt+ extra: sympy pillow+ # the dense chain (COLI_VK_CHAIN=1) of Kimi K3: its attention residuals, KDA+ # and gated MLA layers on the device, and the same under ASan and UBSan+ - family: kimi-chain+ req: c/tools/requirements-kimi-k3-tiny.txt+ - family: kimi-chain-sanitize+ req: c/tools/requirements-kimi-k3-tiny.txtsteps:- uses: actions/checkout@v4- uses: actions/setup-python@v5diff --cc c/Makefileindex 6b65660b,33e247ac..cc016a1d--- a/c/Makefile+++ b/c/Makefile@@@ -721,8 -721,11 +721,13 @@@ VK_SPV += shaders/chain_norm.spv shadVK_SPV += shaders/chain_mla.spv shaders/chain_hgemv.spv shaders/chain_dsa.spv# Kimi Delta Attention and manifold-constrained hyper-connections (vk_chain.h)VK_SPV += shaders/chain_kda.spv shaders/chain_mhc.spv+# DeepSeek V4.1 Flash and DeepSeek V4 attention (vk_chain.h: vkc_dsv4_*)+VK_SPV += shaders/chain_dsv4.spv+ # Kimi K3's attention residuals and SiTU-GLU (vk_chain.h)+ VK_SPV += shaders/chain_ares.spv+ # inkling's chain ops (made on first use): the short convolution and the attention+ # with its relative-position bias+ VK_SPV += shaders/chain_sconv.spv shaders/chain_relattn.spvendif# Optional AMD XDNA2 (Ryzen AI NPU) lane, Windows. Same opt-in shape as VK=1:diff --cc c/deepseek_v4.cindex 7f3b38df,757863cc..60484576--- a/c/deepseek_v4.c+++ b/c/deepseek_v4.c@@@ -12846,21 -12730,9 +12846,21 @@@ static int head_argmax(ColiV4Engine *en}/* Every head score of one hidden row, in vocabulary order. head_argmax used* to run this matmul and keep only the maximum; the numeric channel (SUBMIT- * logprobs=k, docs/brio.md) needs the whole row, so the row is computed here+ * logprobs=k, docs/systemone.md) needs the whole row, so the row is computed here* once and the argmax is a scan over it. Same head_bf16_dot per row, same scan* order: the token picked and its logit do not change. */+#ifdef COLI_VULKAN+/* DUMP=<path> (VK=1 builds): every logits row the head computes, for the Vulkan gates */+static void v4_dump_logits(const float *scores, size_t count) {+ static FILE *dump;+ static int dump_init;+ if (!dump_init) { const char *d = getenv("DUMP"); dump_init = 1; if (d && *d) dump = fopen(d, "wb"); }+ if (dump) { fwrite(scores, sizeof(float), count, dump); fflush(dump); }+}+#define V4_DUMP_LOGITS(scores, count) v4_dump_logits((scores), (count))+#else+#define V4_DUMP_LOGITS(scores, count) ((void)0)+#endifstatic int head_scores_impl(ColiV4Engine *engine, const float *hidden,const ColiSafetensorsIndex *index,const ColiDeepSeekV4Config *config, float *scores) {diff --cc c/tests/test_vk_chain.cindex 979b53b2,7153efbf..53142cea--- a/c/tests/test_vk_chain.c+++ b/c/tests/test_vk_chain.c@@@ -32,12 -34,16 +34,22 @@@* decay, beta, output norm and gate* mhc hyper_connections.h's split, collapse and write back, the mean, and the* clamped SwiGLU+ * kda k3 Kimi K3's KDA layer (kimi_k3.c's kda_forward): exp(A_log) as the engine+ * keeps it, its order of the l2 norms and the update, over two submissions+ * ares Kimi K3's attention residuals (res_mix) over 0 to 15 block snapshots, and+ * SiTU-GLU on values both sides of its two constants+ * sconv inkling's short convolution (residual inside, the ring carried across+ * calls) and its scalar multiply and divide+ * relattn inkling's attention: the relative-position bias, tau, a sliding window+ * over a ring the step wraps, the step's rows read from its own K/V, and a+ * global layer; the shared experts' weighted add (HC_APPLY over one stream)+ * inkling's hidden size: the GEMV and the norm at D = 6144, the GEMV at I = 24576+ * dsv4 DeepSeek V4.1 / V4 (deepseek_v41.c): the sparse attention with a sink over+ * window and compressed rows (V4's bf16 roundings too), interleaved RoPE+ * both ways, the compressor's ring (V4's overlapping form), the indexer's+ * scores, candidate blocks and top-k slot for slot, the engram gate+ * dsv4 rounding DeepSeek V4's roundings (deepseek_v4.c): bf16, E4M3 and E2M1 per block,+ * the Hadamard transform, bit for bit; its SwiGLU within one bf16 step** make vk-chain-check VK=1 (VK_ICD_FILENAMES=.../lvp_icd.json for Lavapipe) */#include <stdio.h>@@@ -983,443 -1174,122 +1181,559 @@@ static void test_kpool(int S, int pos_bfree(keys); free(gates); free(ape); free(q); free(hw); free(valid); free(ref); free(hwd); free(rk); free(gk);}+ /* Kimi K3's KDA layer, kimi_k3.c's kda_forward row by row (its scalar path): the window+ * shifted and the taps summed in order, silu; q and k l2-normalized with the eps after+ * the squares, q then scaled; alpha from A = exp(A_log) as the engine keeps it; the+ * recurrence k * ((v - kS) * beta); the output RMSNorm (its sum in double) and gate.+ * S rows over two calls (the state and the window carried on the device). */+ static void test_kda_k3(int H, int KD, int CK, float xs) {+ int VD = KD, P = H * KD, C = 3 * P, S = 6;+ float lb = -5.f, neps = 1e-6f, eps = 1e-5f, qscale = 1.f / sqrtf((float)KD);+ float *qkv = fvec((size_t)S * C, xs), *f = fvec((size_t)S * P, 1.f), *b = fvec((size_t)S * H, 2.f), *g = fvec((size_t)S * P, 2.f);+ float *taps = fvec((size_t)C * CK, 0.7f), *win = fvec((size_t)C * CK, 1.f), *state = fvec((size_t)H * KD * VD, 0.3f);+ float *prm = malloc((size_t)(H + P + VD) * 4);+ for (int i = 0; i < H; i++) prm[i] = expf(frnd() * 0.5f); /* A = exp(A_log), as kimi_k3.c keeps it */+ for (int i = 0; i < P; i++) prm[H + i] = frnd() * 0.5f;+ for (int i = 0; i < VD; i++) prm[H + P + i] = 0.5f + (rnd() % 100) / 100.f;+ float *rs = malloc((size_t)H * KD * VD * 4), *rw = malloc((size_t)C * CK * 4), *ref = malloc((size_t)S * P * 4);+ memcpy(rs, state, (size_t)H * KD * VD * 4); memcpy(rw, win, (size_t)C * CK * 4);+ float *vec = malloc((size_t)C * 4), *kS = malloc((size_t)VD * 4), *oh = malloc((size_t)VD * 4);+ float *qn = malloc((size_t)KD * 4), *kn = malloc((size_t)KD * 4), *al = malloc((size_t)KD * 4);+ for (int s = 0; s < S; s++) {+ for (int c = 0; c < C; c++) { /* the short convolution, the window oldest first */+ float *wd = rw + (size_t)c * CK;+ for (int j = 0; j < CK - 1; j++) wd[j] = wd[j + 1];+ wd[CK - 1] = qkv[(size_t)s * C + c];+ float acc = 0; for (int j = 0; j < CK; j++) acc += taps[(size_t)c * CK + j] * wd[j];+ vec[c] = acc / (1.f + expf(-acc));+ }+ for (int h = 0; h < H; h++) {+ const float *qh = vec + h * KD, *kh = vec + P + h * KD, *vh = vec + 2 * P + h * VD;+ float sq = 0, sk = 0;+ for (int i = 0; i < KD; i++) { sq += qh[i] * qh[i]; sk += kh[i] * kh[i]; }+ sq = 1.f / sqrtf(sq + neps); sk = 1.f / sqrtf(sk + neps);+ for (int i = 0; i < KD; i++) { qn[i] = qh[i] * sq * qscale; kn[i] = kh[i] * sk; }+ for (int i = 0; i < KD; i++) al[i] = expf(lb * sigm(prm[h] * (f[(size_t)s * P + h * KD + i] + prm[H + h * KD + i])));+ float beta = sigm(b[(size_t)s * H + h]);+ float *St = rs + (size_t)h * KD * VD;+ memset(kS, 0, (size_t)VD * 4);+ for (int k = 0; k < KD; k++) { float *row = St + (size_t)k * VD; for (int v = 0; v < VD; v++) { row[v] *= al[k]; kS[v] += kn[k] * row[v]; } }+ for (int v = 0; v < VD; v++) kS[v] = (vh[v] - kS[v]) * beta;+ memset(oh, 0, (size_t)VD * 4);+ for (int k = 0; k < KD; k++) { float *row = St + (size_t)k * VD; for (int v = 0; v < VD; v++) { row[v] += kn[k] * kS[v]; oh[v] += qn[k] * row[v]; } }+ double ms = 0; for (int v = 0; v < VD; v++) ms += (double)oh[v] * oh[v];+ float r = 1.f / sqrtf((float)(ms / VD) + eps);+ for (int v = 0; v < VD; v++) ref[(size_t)s * P + h * VD + v] = oh[v] * r * prm[H + P + v] * sigm(g[(size_t)s * P + h * VD + v]);+ }+ }+ /* the device: q, k, v in three blocks [3][S][P] (in_part = S*P), as an engine's three matmuls leave them */+ float *blk = malloc((size_t)3 * S * P * 4);+ for (int s = 0; s < S; s++) for (int part = 0; part < 3; part++)+ memcpy(blk + (size_t)part * S * P + (size_t)s * P, qkv + (size_t)s * C + (size_t)part * P, (size_t)P * 4);+ VkcBuf *ib = up(blk, (size_t)3 * S * P), *tb = up(taps, (size_t)C * CK), *wb = up(win, (size_t)C * CK), *sb = up(state, (size_t)H * KD * VD);+ VkcBuf *fb = up(f, (size_t)S * P), *bb = up(b, (size_t)S * H), *gb = up(g, (size_t)S * P), *pb = up(prm, (size_t)H + P + VD);+ VkcBuf *mb = vkc_buf((size_t)S * C * 4, VKC_DEV), *yb = vkc_buf((size_t)S * P * 4, VKC_DEV);+ int ok = 1, s0 = 0;+ for (int part = 0; part < 2 && ok; part++) {+ int n = part ? S - 1 : 1;+ VkcKdaConv cp = {n, C, CK, P, s0 * P, P, S * P, 0, C, 0, 0};+ VkcKdaRec rp = {n, H, VD, P, 0, C, s0 * P, P, s0 * H, H, s0 * P, P, s0 * P, P, 0, 0, lb, neps, eps};+ ok = vkc_begin() && vkc_kda_conv(ib, tb, wb, mb, &cp) &&+ vkc_kda_rec_flags(KD, mb, fb, bb, gb, pb, sb, yb, &rp, VKC_KDA_EXP_A | VKC_KDA_K3) && vkc_submit(part);+ s0 += n;+ }+ float *y = down(yb, 0, (size_t)S * P), *st2 = down(sb, 0, (size_t)H * KD * VD), *w2 = down(wb, 0, (size_t)C * CK);+ double e = relerr(y, ref, (size_t)S * P, 1e-3), es = relerr(st2, rs, (size_t)H * KD * VD, 1e-3), ew = relerr(w2, rw, (size_t)C * CK, 1e-3);+ CHECK(ok && e < 1e-5 && es < 1e-5 && ew == 0 && !bad(y, (size_t)S * P), "kda k3 H %d KD %d K %d: ok %d out %.2e state %.2e window %.2e",+ H, KD, CK, ok, e, es, ew);+ if (getenv("VKC_TEST_VERBOSE")) printf("kda k3 H %d KD %d: out %.2e state %.2e\n", H, KD, e, es);+ vkc_free(ib); vkc_free(tb); vkc_free(wb); vkc_free(sb); vkc_free(fb); vkc_free(bb); vkc_free(gb); vkc_free(pb); vkc_free(mb); vkc_free(yb);+ free(qkv); free(f); free(b); free(g); free(taps); free(win); free(state); free(prm); free(rs); free(rw); free(ref);+ free(vec); free(kS); free(oh); free(qn); free(kn); free(al); free(blk); free(y); free(st2); free(w2);+ }++ /* kimi_k3.c's res_mix for S rows over nb block snapshots at a row stride, and SiTU-GLU */+ static void test_ares(int S, int D, int nb) {+ int nbmax = nb > 0 ? nb + 1 : 1, xrow = D + 3, brow = nbmax * D, yrow = D + 5;+ float eps = 1e-5f;+ float *x = fvec((size_t)S * xrow, 2.f), *bl = fvec((size_t)S * brow, 1.5f), *w = fvec((size_t)D + 7, 0.3f);+ for (int s = 0; s < S; s++) for (int d = 0; d < D; d++) x[(size_t)s * xrow + d] *= 1.f + (float)s; /* rows of different sizes */+ float *ref = calloc((size_t)S * yrow, 4);+ for (int s = 0; s < S; s++) {+ const float *v[16]; float sc[16];+ for (int e = 0; e < nb; e++) v[e] = bl + (size_t)s * brow + (size_t)e * D;+ v[nb] = x + (size_t)s * xrow;+ for (int e = 0; e <= nb; e++) {+ double ms = 0, dot = 0;+ for (int d = 0; d < D; d++) { double a = v[e][d]; ms += a * a; dot += a * (double)w[7 + d]; }+ sc[e] = (float)(dot / sqrt(ms / D + eps));+ }+ float m = sc[0]; for (int e = 1; e <= nb; e++) if (sc[e] > m) m = sc[e];+ float sum = 0; for (int e = 0; e <= nb; e++) { sc[e] = expf(sc[e] - m); sum += sc[e]; }+ for (int e = 0; e <= nb; e++) sc[e] /= sum;+ for (int d = 0; d < D; d++) { float a = 0; for (int e = 0; e <= nb; e++) a += sc[e] * v[e][d]; ref[(size_t)s * yrow + d] = a; }+ }+ VkcBuf *xb = up(x, (size_t)S * xrow), *bb = up(bl, (size_t)S * brow), *wb = up(w, (size_t)D + 7), *yb = vkc_buf((size_t)S * yrow * 4, VKC_DEV);+ VkcAres ap = {S, D, nb, 0, xrow, 0, brow, 7, 0, yrow, eps};+ int ok = vkc_begin() && vkc_ares_mix(xb, bb, wb, yb, &ap) && vkc_submit(1);+ float *y = down(yb, 0, (size_t)S * yrow);+ for (int s = 0; s < S; s++) for (int d = D; d < yrow; d++) y[(size_t)s * yrow + d] = 0.f; /* the gaps are not written */+ double e = relerr(y, ref, (size_t)S * yrow, 1e-3);+ CHECK(ok && e < 2e-6 && !bad(y, (size_t)S * yrow), "ares S %d D %d nb %d: ok %d err %.2e", S, D, nb, ok, e);+ if (getenv("VKC_TEST_VERBOSE")) printf("ares S %d D %d nb %d: %.2e\n", S, D, nb, e);+ vkc_free(xb); vkc_free(bb); vkc_free(wb); vkc_free(yb);+ free(x); free(bl); free(w); free(ref); free(y);+ }+ static void test_situ(float b1, float b2) {+ int n = 777;+ float *ga = fvec(n, 3.f * b1), *ua = fvec(n, 3.f * b2), *rr = malloc((size_t)n * 4);+ for (int i = 0; i < n; i++) rr[i] = b1 * tanhf(ga[i] / b1) * sigm(ga[i]) * b2 * tanhf(ua[i] / b2);+ VkcBuf *gb = up(ga, n), *ub = up(ua, n), *yb = vkc_buf((size_t)n * 4 + 64, VKC_DEV);+ VkcSitu sp = {n, 0, 0, 16, b1, b2};+ int ok = vkc_begin() && vkc_situ(gb, ub, yb, &sp) && vkc_submit(1);+ float *y = down(yb, 16, n);+ double e = relerr(y, rr, n, 1e-3);+ CHECK(ok && e < 1e-6 && !bad(y, n), "situ b1 %g b2 %g: ok %d err %.2e", b1, b2, ok, e);+ vkc_free(gb); vkc_free(ub); vkc_free(yb); free(ga); free(ua); free(rr); free(y);+ }++/* ---- DeepSeek V4.1 / V4 attention (chain_dsv4.comp) ------------------------------------- */+static float bf16r(float f) { uint32_t u; memcpy(&u, &f, 4); if ((u & 0x7f800000u) != 0x7f800000u) u += 0x7fffu + ((u >> 16) & 1u);+ u &= 0xffff0000u; memcpy(&f, &u, 4); return f; }+/* sparse_attn.h's scalar kernel (and DeepSeek V4's: the weights and the output to bf16)+ * over lists of window rows (e < nwin), compressed rows (nwin + j) and skipped entries */+static void test_ds_attn(int S, int H, int hd, int nwin, int ncmp, int cnt, int flags) {+ int qrow = H * hd + 3, lrow = cnt + 2, orow = H * hd + 3;+ float *q = fvec((size_t)S * qrow, 1.f), *win = fvec((size_t)(nwin * hd + 5), 1.f), *cmp = fvec((size_t)(ncmp * hd + 7), 1.f);+ float *sink = fvec((size_t)H + 2, 2.f), *ref = calloc((size_t)S * orow, 4), *sc = malloc((size_t)cnt * 4);+ int *list = malloc((size_t)S * lrow * 4);+ float *kvall = malloc((size_t)(nwin + ncmp) * hd * 4);+ memcpy(kvall, win + 5, (size_t)nwin * hd * 4); memcpy(kvall + (size_t)nwin * hd, cmp + 7, (size_t)ncmp * hd * 4);+ for (int s = 0; s < S; s++)+ for (int j = 0; j < lrow; j++) {+ int r = (int)(rnd() % 5);+ list[s * lrow + j] = s == S - 1 && S > 1 ? -1 /* a row with nothing to read */+ : r == 0 ? -1 : r < 3 ? (int)(rnd() % (unsigned)nwin) : nwin + (int)(rnd() % (unsigned)ncmp);+ }+ for (int s = 0; s < S; s++)+ for (int h = 0; h < H; h++) {+ const float *qq = q + (size_t)s * qrow + 1 + h * hd;+ float *o = ref + (size_t)s * orow + 2 + h * hd;+ const int *idx = list + s * lrow + 1;+ if (!(flags & 1)) { coli_sparse_attend_scalar(o, qq, kvall, idx, cnt, hd, sink[1 + h], 1.f / sqrtf((float)hd), sc); continue; }+ float best = -1e30f; /* DeepSeek V4's reference: w to bf16 before the value sum, the output to bf16 */+ for (int j = 0; j < cnt; j++) {+ if (idx[j] < 0) { sc[j] = -INFINITY; continue; }+ float d = 0; for (int i = 0; i < hd; i++) d += qq[i] * kvall[(size_t)idx[j] * hd + i];+ sc[j] = d * (1.f / sqrtf((float)hd)); if (sc[j] > best) best = sc[j];+ }+ float den = expf(sink[1 + h] - best);+ for (int i = 0; i < hd; i++) o[i] = 0;+ for (int j = 0; j < cnt; j++) {+ if (idx[j] < 0) continue;+ float w = expf(sc[j] - best); den += w; w = bf16r(w);+ for (int i = 0; i < hd; i++) o[i] += w * kvall[(size_t)idx[j] * hd + i];+ }+ for (int i = 0; i < hd; i++) o[i] = bf16r(o[i] / den);+ }+ VkcBuf *qb = up(q, (size_t)S * qrow), *wb = up(win, (size_t)nwin * hd + 5), *cb = up(cmp, (size_t)ncmp * hd + 7);+ VkcBuf *sb = up(sink, (size_t)H + 2), *ob = vkc_buf((size_t)S * orow * 4, VKC_DEV), *lb = vkc_buf((size_t)S * lrow * 4, VKC_DEV);+ vkc_begin(); vkc_write(lb, 0, list, (size_t)S * lrow * 4); vkc_submit(1);+ VkcDsAttn p = {S, H, hd, cnt, 1, lrow, nwin, 5, 7, 1, qrow, 2, orow, 1, flags, 1.f / sqrtf((float)hd)};+ vkc_begin(); int ok = vkc_dsv4_attn(qb, wb, cb, lb, sb, ob, &p); vkc_submit(1);+ float *got = down(ob, 0, (size_t)S * orow);+ double e = 0;+ for (int s = 0; s < S; s++) { double r = relerr(got + (size_t)s * orow + 2, ref + (size_t)s * orow + 2, (size_t)H * hd, 1e-3); if (r > e) e = r; }+ double tol = (flags & 1) ? 8e-3 : 2e-5;+ CHECK(ok && e < tol && !bad(got, (size_t)S * orow), "dsv4 attn S %d H %d hd %d cnt %d flags %d: rel err %.2e", S, H, hd, cnt, flags, e);+ if (!(flags & 1) && S > 1) { /* the empty row is exactly zero */+ int z = 1; for (int i = 0; i < H * hd; i++) z &= got[(size_t)(S - 1) * orow + 2 + i] == 0.f;+ CHECK(z, "dsv4 attn: a row with no entry is not zero");+ }+ printf(" dsv4 attn S %d H %d hd %d cnt %d flags %d: rel err %.2e\n", S, H, hd, cnt, flags, e);+ vkc_free(qb); vkc_free(wb); vkc_free(cb); vkc_free(sb); vkc_free(ob); vkc_free(lb);+ free(q); free(win); free(cmp); free(sink); free(ref); free(sc); free(list); free(kvall); free(got);+}++/* deepseek_v41.c's rope_apply: interleaved pairs, forward and inverse, segments at a stride */+static void test_ds_rope(int flags) {+ int rows = 3, per = 4, seg = 40, rd = 16, xrow = per * seg + 2, csrow = rd + 1;+ float *x = fvec((size_t)rows * xrow + 3, 1.f), *ref = malloc(((size_t)rows * xrow + 3) * 4), *cs = malloc(((size_t)rows * csrow + 2) * 4);+ for (int r = 0; r < rows; r++) for (int i = 0; i < rd / 2; i++) {+ float a = (r * 7 + 3) * powf(10000.f, -2.f * i / rd);+ cs[2 + r * csrow + 2 * i] = cosf(a); cs[2 + r * csrow + 2 * i + 1] = sinf(a);+ }+ for (int inv = 0; inv < 2; inv++) {+ memcpy(ref, x, ((size_t)rows * xrow + 3) * 4);+ for (int r = 0; r < rows; r++) for (int j = 0; j < per; j++) {+ float *v = ref + 3 + r * xrow + j * seg + (seg - rd);+ for (int i = 0; i < rd / 2; i++) {+ float c = cs[2 + r * csrow + 2 * i], sn = cs[2 + r * csrow + 2 * i + 1];+ if (inv) sn = -sn;+ float a = v[2 * i], b = v[2 * i + 1];+ v[2 * i] = a * c - b * sn; v[2 * i + 1] = a * sn + b * c;+ if (flags & 1) { v[2 * i] = bf16r(v[2 * i]); v[2 * i + 1] = bf16r(v[2 * i + 1]); }+ }+ }+ VkcBuf *xb = up(x, (size_t)rows * xrow + 3), *cb = up(cs, (size_t)rows * csrow + 2);+ VkcDsRope p = {rows * per, per, rd, 3 + seg - rd, xrow, seg, 2, csrow, inv, flags};+ vkc_begin(); int ok = vkc_dsv4_rope(xb, cb, &p); vkc_submit(1);+ float *got = down(xb, 0, (size_t)rows * xrow + 3);+ double e = relerr(got, ref, (size_t)rows * xrow + 3, 1e-3);+ CHECK(ok && e < ((flags & 1) ? 8e-3 : 1e-6), "dsv4 rope inverse %d flags %d: rel err %.2e", inv, flags, e);+ vkc_free(xb); vkc_free(cb); free(got);+ }+ free(x); free(ref); free(cs);+}++/* deepseek_v41.c's compressor_run (its decode form; the prefill form gives the same groups)+ * and DeepSeek V4's overlapping one (ratio 4: the previous group's rows in the first half,+ * a channel of its own each, the ape bias), the ring carried over three calls */+static void test_ds_compress(int ratio, int overlap, int ape) {+ int D = 24, P = overlap ? 2 * D : D, rows = overlap ? 2 * ratio : ratio, T = 23, pb0 = 3;+ float *kv = fvec((size_t)T * P, 1.f), *sc = fvec((size_t)T * P, 2.f), *ap = fvec((size_t)ratio * P + 4, 1.f);+ float *rk = calloc((size_t)rows * P, 4), *rs = malloc((size_t)rows * P * 4);+ for (int i = 0; i < rows * P; i++) rs[i] = -INFINITY;+ int G = (pb0 + T) / ratio + 1;+ float *ref = calloc((size_t)G * D, 4);+ for (int t = 0; t < T; t++) {+ int pos = pb0 + t, slot = pos % ratio, sr = overlap ? ratio + slot : slot;+ for (int c = 0; c < P; c++) { rk[sr * P + c] = kv[t * P + c]; rs[sr * P + c] = sc[t * P + c] + (ape ? ap[4 + slot * P + c] : 0.f); }+ if ((pos + 1) % ratio) continue;+ for (int d = 0; d < D; d++) {+ float best = -INFINITY;+ for (int k = 0; k < rows; k++) { int col = overlap && k >= ratio ? D + d : d; if (rs[k * P + col] > best) best = rs[k * P + col]; }+ float tot = 0, mix = 0;+ for (int k = 0; k < rows; k++) { int col = overlap && k >= ratio ? D + d : d; float w = expf(rs[k * P + col] - best); tot += w; mix += w * rk[k * P + col]; }+ ref[(size_t)(pos / ratio) * D + d] = mix / tot;+ }+ if (overlap) { memcpy(rk, rk + (size_t)ratio * P, (size_t)ratio * P * 4); memcpy(rs, rs + (size_t)ratio * P, (size_t)ratio * P * 4); }+ }+ VkcBuf *kb = up(kv, (size_t)T * P), *sb = up(sc, (size_t)T * P), *ab = up(ap, (size_t)ratio * P + 4);+ VkcBuf *ring = vkc_buf((size_t)(2 * rows * P + 5) * 4, VKC_DEV), *ob = vkc_buf((size_t)G * D * 4, VKC_DEV);+ float *init = malloc((size_t)(2 * rows * P + 5) * 4);+ for (int i = 0; i < 2 * rows * P + 5; i++) init[i] = i >= 5 + rows * P ? -INFINITY : 0.f;+ vkc_begin(); vkc_write(ring, 0, init, (size_t)(2 * rows * P + 5) * 4); vkc_submit(1);+ int cuts[4] = {0, 5, 6, T}, ok = 1;+ for (int k = 0; k < 3; k++) {+ int n = cuts[k + 1] - cuts[k];+ VkcDsComp p = {n, pb0 + cuts[k], ratio, P, D, overlap, cuts[k] * P, P, cuts[k] * P, P, ape ? 4 : -1, 0, D, 5};+ vkc_begin(); ok &= vkc_dsv4_compress(kb, sb, ring, ab, ob, &p); vkc_submit(k == 2);+ }+ float *got = down(ob, 0, (size_t)G * D);+ int g0 = (pb0 + 1 + ratio - 1) / ratio; /* the first group completed by a row here */+ double e = relerr(got + (size_t)g0 * D, ref + (size_t)g0 * D, (size_t)(G - 1 - g0) * D, 1e-3);+ CHECK(ok && e < 2e-6, "dsv4 compress ratio %d overlap %d ape %d: rel err %.2e", ratio, overlap, ape, e);+ vkc_free(kb); vkc_free(sb); vkc_free(ab); vkc_free(ring); vkc_free(ob);+ free(kv); free(sc); free(ap); free(rk); free(rs); free(ref); free(got); free(init);+}++/* deepseek_v41.c's indexer_run and candidate_blocks: the scores with the reach and the+ * mask, the candidate blocks, and the top-k list slot for slot. Inputs on a grid of 0.25+ * (weights 0.5, a power-of-two scale) so every score is exact in float on both sides,+ * with equal keys for ties. */+static void ds_topk_ref(const float *score, int width, int topk, int base, int order, int *row) {+ int taken = 0;+ for (int k = 0; k < topk; k++) row[k] = -1;+ for (int k = 0; k < topk; k++) {+ int best = -1;+ for (int j = 0; j < width; j++) {+ if (score[j] == -INFINITY) continue;+ int already = 0; for (int u = 0; u < taken; u++) if (row[u] == j) { already = 1; break; }+ if (already) continue;+ if (best < 0 || score[j] > score[best]) best = j;+ }+ if (best < 0) break;+ row[taken++] = best;+ }+ if (order == 0)+ for (int a = 0; a < taken; a++) for (int b = a + 1; b < taken; b++) if (row[b] < row[a]) { int t = row[a]; row[a] = row[b]; row[b] = t; }+ for (int k = 0; k < taken; k++) row[k] += base;+}+static void ds_cand_ref(const float *score, int width, int lens, int block, int topb, int *keep) {+ int blocks = (width + block - 1) / block;+ float *best = malloc((size_t)(blocks + 1) * 4);+ for (int b = 0; b < blocks; b++) { float top = -INFINITY; for (int i = b * block; i < (b + 1) * block && i < width; i++) if (score[i] > top) top = score[i]; best[b] = top; }+ int last = (lens - 1) / block;+ if (last >= 0 && last < blocks) best[last] = INFINITY;+ int wanted = topb < blocks ? topb : blocks;+ for (int i = 0; i < width; i++) keep[i] = 0;+ for (int pick = 0; pick < wanted; pick++) {+ int chosen = -1;+ for (int b = 0; b < blocks; b++) if (best[b] > -INFINITY && (chosen < 0 || best[b] > best[chosen])) chosen = b;+ if (chosen < 0) break;+ for (int i = chosen * block; i < (chosen + 1) * block && i < width; i++) keep[i] = 1;+ best[chosen] = -INFINITY;+ }+ free(best);+}+static void test_ds_index(int S, int pos_base, int ratio, int IH, int ID, int topk, int block, int topb, int order) {+ int width = (pos_base + S) / ratio, krow = ID + 3, qrow = IH * ID + 1, wrow = IH + 2, scrow = width + 3, lrow = topk + 5, base = 11;+ if (width < 1) width = 1;+ float *q = malloc((size_t)(S * qrow + 1) * 4), *k = malloc((size_t)(width * krow + 3) * 4), *w = malloc((size_t)(S * wrow + 2) * 4);+ for (int i = 0; i < S * qrow + 1; i++) q[i] = ((int)(rnd() % 17) - 8) * 0.25f;+ for (int i = 0; i < width * krow + 3; i++) k[i] = ((int)(rnd() % 17) - 8) * 0.25f;+ for (int i = 0; i < S * wrow + 2; i++) w[i] = ((int)(rnd() % 9) - 3) * 0.5f;+ for (int t = 0; t < width; t += 4) for (int i = 0; i < ID; i++) k[3 + t * krow + i] = k[3 + (t / 4) * krow + i]; /* ties */+ float wscale = 0.25f;+ float *ref = malloc((size_t)S * scrow * 4), *refm = malloc((size_t)S * scrow * 4);+ int *keep = calloc((size_t)S * scrow, 4), *lst = malloc((size_t)S * lrow * 4), *lstm = malloc((size_t)S * lrow * 4);+ for (int s = 0; s < S; s++) {+ int lens = (pos_base + s + 1) / ratio;+ float wt[128];+ for (int h = 0; h < IH; h++) { wt[h] = w[2 + s * wrow + h]; wt[h] *= wscale; }+ for (int j = 0; j < width; j++) {+ if (j >= lens) { ref[s * scrow + j] = -INFINITY; continue; }+ float total = 0;+ for (int h = 0; h < IH; h++) {+ float dot = 0; for (int i = 0; i < ID; i++) dot += q[1 + s * qrow + h * ID + i] * k[3 + j * krow + i];+ if (dot > 0.f) total += dot * wt[h];+ }+ ref[s * scrow + j] = total;+ }+ ds_cand_ref(ref + s * scrow, width, lens, block, topb, keep + s * scrow);+ for (int j = 0; j < width; j++) refm[s * scrow + j] = keep[s * scrow + j] ? ref[s * scrow + j] : -INFINITY;+ ds_topk_ref(ref + s * scrow, width, topk, base, order, lst + s * lrow + 2);+ ds_topk_ref(refm + s * scrow, width, topk, base, order, lstm + s * lrow + 2);+ }+ VkcBuf *qb = up(q, (size_t)S * qrow + 1), *kb = up(k, (size_t)width * krow + 3), *wb = up(w, (size_t)S * wrow + 2);+ VkcBuf *scb = vkc_buf((size_t)S * scrow * 4, VKC_DEV), *mb = vkc_buf((size_t)S * scrow * 4, VKC_DEV);+ VkcBuf *lb = vkc_buf((size_t)S * lrow * 4, VKC_DEV), *lb2 = vkc_buf((size_t)S * lrow * 4, VKC_DEV), *scb2 = vkc_buf((size_t)S * scrow * 4, VKC_DEV);+ VkcDsScore sp = {S, pos_base, ratio, IH, ID, width, 1, qrow, 2, wrow, 3, krow, 0, scrow, wscale, 0, 0};+ VkcDsCand cp = {S, pos_base, ratio, width, block, topb, scrow, scrow};+ VkcDsTopk tp = {S, width, topk, scrow, 2, lrow, base, order};+ VkcDsScore sm = sp; sm.mask_row = scrow;+ vkc_begin();+ int ok = vkc_dsv4_score(qb, wb, kb, NULL, scb, &sp) && vkc_dsv4_cand(scb, mb, &cp) && vkc_dsv4_topk(scb, lb, &tp);+ if (S > 1) /* the masked scores one row at a time, at offsets (a speculative step's rows read different keys) */+ for (int s = 0; s < S && ok; s++) {+ VkcDsScore r1 = sm; r1.S = 1; r1.pos_base = pos_base + s; r1.q_off = 1 + s * qrow; r1.w_off = 2 + s * wrow;+ r1.sc_off = s * scrow; r1.mask_off = s * scrow;+ ok = vkc_dsv4_score(qb, wb, kb, mb, scb2, &r1);+ }+ else ok = ok && vkc_dsv4_score(qb, wb, kb, mb, scb2, &sm);+ ok = ok && vkc_dsv4_topk(scb2, lb2, &tp);+ vkc_submit(1);+ float *gs = down(scb, 0, (size_t)S * scrow);+ int *gm = (int *)down(mb, 0, (size_t)S * scrow), *gl = (int *)down(lb, 0, (size_t)S * lrow), *gl2 = (int *)down(lb2, 0, (size_t)S * lrow);+ int same_sc = 1, same_m = 1, same_l = 1, same_l2 = 1;+ for (int s = 0; s < S; s++) {+ for (int j = 0; j < width; j++) {+ same_sc &= gs[s * scrow + j] == ref[s * scrow + j];+ same_m &= gm[s * scrow + j] == keep[s * scrow + j];+ }+ for (int t = 0; t < topk; t++) { same_l &= gl[s * lrow + 2 + t] == lst[s * lrow + 2 + t]; same_l2 &= gl2[s * lrow + 2 + t] == lstm[s * lrow + 2 + t]; }+ }+ CHECK(ok && same_sc && same_m && same_l && same_l2, "dsv4 index S %d pos %d ratio %d IH %d ID %d topk %d block %d/%d order %d: "+ "scores %d mask %d list %d masked list %d", S, pos_base, ratio, IH, ID, topk, block, topb, order, same_sc, same_m, same_l, same_l2);+ vkc_free(qb); vkc_free(kb); vkc_free(wb); vkc_free(scb); vkc_free(mb); vkc_free(lb); vkc_free(lb2); vkc_free(scb2);+ free(q); free(k); free(w); free(ref); free(refm); free(keep); free(lst); free(lstm); free(gs); free(gm); free(gl); free(gl2);+}++/* deepseek_v41.c's engram_run gate, in place on the streams */+static void test_ds_engram(int S, int H, int D) {+ int kvrow = (H + 1) * D + 2, xrow = H * D + 3;+ float *kv = fvec((size_t)S * kvrow + 1, 1.f), *x = fvec((size_t)S * xrow + 4, 1.f), *prm = fvec((size_t)2 * H * D + 6, 1.f);+ float *ref = malloc(((size_t)S * xrow + 4) * 4), eps = 1e-6f;+ memcpy(ref, x, ((size_t)S * xrow + 4) * 4);+ for (int s = 0; s < S; s++) {+ const float *k0 = kv + 1 + (size_t)s * kvrow, *value = k0 + (size_t)H * D;+ for (int c = 0; c < H; c++) {+ const float *key = k0 + (size_t)c * D, *qw = prm + 6 + (size_t)c * D, *kw = prm + 6 + (size_t)H * D + (size_t)c * D;+ float *st = ref + 4 + (size_t)s * xrow + (size_t)c * D;+ double ss = 0, ks = 0, dot = 0;+ for (int i = 0; i < D; i++) { ss += (double)st[i] * st[i]; ks += (double)key[i] * key[i]; dot += (double)st[i] * qw[i] * kw[i] * key[i]; }+ float rstd = (1.0f / sqrtf((float)(ss / D) + eps)) * (1.0f / sqrtf((float)(ks / D) + eps));+ float scaled = (float)dot * rstd / sqrtf((float)D);+ float mag = fabsf(scaled); if (mag < 1e-6f) mag = 1e-6f;+ float sr = sqrtf(mag); if (scaled < 0) sr = -sr;+ float g = sigm(sr);+ for (int i = 0; i < D; i++) st[i] += g * value[i];+ }+ }+ VkcBuf *kb = up(kv, (size_t)S * kvrow + 1), *xb = up(x, (size_t)S * xrow + 4), *pb = up(prm, (size_t)2 * H * D + 6);+ VkcDsEngram p = {S, H, D, 1, kvrow, 4, xrow, 6, 6 + H * D, eps};+ vkc_begin(); int ok = vkc_dsv4_engram(kb, pb, xb, &p); vkc_submit(1);+ float *got = down(xb, 0, (size_t)S * xrow + 4);+ double e = relerr(got, ref, (size_t)S * xrow + 4, 1e-3);+ CHECK(ok && e < 2e-6, "dsv4 engram S %d H %d D %d: rel err %.2e", S, H, D, e);+ vkc_free(kb); vkc_free(xb); vkc_free(pb);+ free(kv); free(x); free(prm); free(ref); free(got);+}++/* ---- DeepSeek V4's roundings (chain_dsv4.comp modes 7, 8) ------------------------------+ * References transcribed from deepseek_v4.c (COLI_V4_UNIT_NATIVE_QUANT, the MATH unit's+ * coli_v4_swiglu): the device must give their bits. */+static float ds_e4m3_decode(uint8_t v) {+ int sign = v >> 7, exponent = (v >> 3) & 15, mantissa = v & 7;+ if (exponent == 15 && mantissa == 7) return NAN;+ float n = !exponent ? ldexpf((float)mantissa, -9) : ldexpf(1.0f + (float)mantissa / 8.0f, exponent - 7);+ return sign ? -n : n;+}+static uint8_t ds_e4m3_encode(float value) {+ if (isnan(value)) return 0x7f;+ int negative = signbit(value) != 0;+ float magnitude = fabsf(value);+ if (!magnitude) return negative ? 0x80 : 0;+ if (magnitude >= 448.0f) return (uint8_t)((negative ? 0x80 : 0) | 0x7e);+ uint8_t best;+ if (magnitude < 0.015625f) {+ float scaled = magnitude * 512.0f;+ uint8_t rounded = (uint8_t)scaled;+ float fraction = scaled - rounded;+ if (fraction > 0.5f || (fraction == 0.5f && (rounded & 1))) rounded++;+ best = rounded;+ } else {+ uint32_t bits; memcpy(&bits, &magnitude, 4);+ int exponent = (int)((bits >> 23) & 0xff) - 127;+ uint32_t significand = 0x800000u | (bits & 0x7fffffu), rounded = significand >> 20, remainder = significand & 0xfffffu;+ if (remainder > 0x80000u || (remainder == 0x80000u && (rounded & 1u))) rounded++;+ if (rounded == 16u) { rounded = 8u; exponent++; }+ best = (uint8_t)((exponent + 7) * 8 + (int)rounded - 8);+ }+ return (uint8_t)(best | (negative ? 0x80 : 0));+}+static int ds_ceil_log2(float value) { int e; float f = frexpf(value, &e); return f == 0.5f ? e - 1 : e; }+static void ds_fp8_qdq(float *out, const float *in, size_t n, size_t block) {+ for (size_t base = 0; base < n; base += block) {+ size_t count = n - base < block ? n - base : block;+ float maximum = 0.0f;+ for (size_t i = 0; i < count; i++) maximum = fmaxf(maximum, fabsf(in[base + i]));+ maximum = fmaxf(maximum, 1e-4f);+ int e = ds_ceil_log2(maximum / 448.0f);+ if (e < -127) e = -127;+ if (e > 127) e = 127;+ float scale = ldexpf(1.0f, e);+ for (size_t i = 0; i < count; i++)+ out[base + i] = ds_e4m3_decode(ds_e4m3_encode(fmaxf(-448.0f, fminf(448.0f, in[base + i] / scale)))) * scale;+ }+}+static float ds_e2m1_decode(int n) {+ static const float v[16] = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f, 0.0f, -0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f};+ return v[n & 15];+}+static void ds_fp4_qdq(float *out, const float *in, size_t n, size_t block) {+ for (size_t base = 0; base < n; base += block) {+ size_t count = n - base < block ? n - base : block;+ float maximum = 0.0f;+ for (size_t i = 0; i < count; i++) maximum = fmaxf(maximum, fabsf(in[base + i]));+ maximum = fmaxf(maximum, 6.0f * ldexpf(1.0f, -126));+ int e = ds_ceil_log2(maximum / 6.0f);+ if (e < -127) e = -127;+ if (e > 127) e = 127;+ float scale = ldexpf(1.0f, e);+ for (size_t i = 0; i < count; i++) {+ float value = fmaxf(-6.0f, fminf(6.0f, in[base + i] / scale));+ int best = 0; float distance = fabsf(value - ds_e2m1_decode(0));+ for (int code = 1; code < 16; code++) {+ float c = fabsf(value - ds_e2m1_decode(code));+ if (c < distance) { distance = c; best = code; }+ }+ out[base + i] = ds_e2m1_decode(best) * scale;+ }+ }+}+static void ds_hadamard(float *v, size_t n) {+ for (size_t w = 1; w < n; w *= 2)+ for (size_t base = 0; base < n; base += 2 * w)+ for (size_t i = 0; i < w; i++) { float l = v[base + i], r = v[base + w + i]; v[base + i] = l + r; v[base + w + i] = l - r; }+ float scale = 1.0f / sqrtf((float)n);+ for (size_t i = 0; i < n; i++) v[i] = bf16r(v[i] * scale);+}+static float ds_sigmoid(float v) { if (v >= 0.0f) { float d = expf(-v); return 1.0f / (1.0f + d); } float g = expf(v); return g / (1.0f + g); }++/* A block's values: random magnitudes over 40 binades, and blocks built on purpose:+ * all zero, the amax on the scale's boundary (1.75 * 2^E for E4M3, 1.5 * 2^E for E2M1)+ * and one step above it, exact ties of the target grid (E4M3 mantissa midpoints and+ * subnormal midpoints; E2M1 midpoints), signed zeros, an amax under E4M3's floor. (The+ * bf16 rounding after E4M3 or E2M1 is the CPU's step but changes nothing: both grids+ * are bf16 values.) */+static void ds_fill(float *v, int n, int kind, int pattern) {+ float s = ldexpf(1.0f, (int)(rnd() % 30) - 15);+ for (int i = 0; i < n; i++) v[i] = frnd() * ldexpf(1.0f, (int)(rnd() % 40) - 20);+ if (pattern == 1) for (int i = 0; i < n; i++) v[i] = 0.0f;+ if (pattern == 2 || pattern == 3) {+ float top = (kind == VKC_DS_E2M1 ? 1.5f : 1.75f) * 4.0f * s;+ if (pattern == 3) { uint32_t u; memcpy(&u, &top, 4); u++; memcpy(&top, &u, 4); }+ v[0] = top;+ }+ if (pattern == 4) {+ float amax = (kind == VKC_DS_E2M1 ? 6.0f : 448.0f) * s;+ static const float ties2[7] = {0.25f, 0.75f, 1.25f, 1.75f, 2.5f, 3.5f, 5.0f};+ v[0] = amax;+ for (int i = 1; i < n; i++) {+ float t;+ if (kind == VKC_DS_E2M1) t = ties2[rnd() % 7];+ else if (rnd() % 3 == 0) t = (float)(2 * (int)(rnd() % 8) + 1) * ldexpf(1.0f, -10); /* subnormal midpoints */+ else t = (1.0f + (float)(2 * (int)(rnd() % 8) + 1) / 16.0f) * ldexpf(1.0f, (int)(rnd() % 14) - 6);+ v[i] = (rnd() & 1 ? -t : t) * s;+ }+ v[n / 2] = -0.0f; if (n > 3) v[3] = 0.0f;+ }+ if (pattern == 5) for (int i = 0; i < n; i++) v[i] = frnd() * ldexpf(1.0f, -20 - (int)(rnd() % 4)); /* under the floor */+}+/* kind, nseg segments of len (per_row a row, at strides), block, flags; in place or not */+static void test_ds_round(int kind, int nseg, int per_row, int len, int block, int flags, int inplace) {+ int rows = (nseg + per_row - 1) / per_row, xseg = len + 3, xrow = per_row * xseg + 5, yseg = len + 1, yrow = per_row * yseg + 2;+ size_t xn = (size_t)rows * xrow + 7, yn = inplace ? xn : (size_t)rows * yrow + 4;+ int xo = 7, yo = inplace ? 7 : 4, ys = inplace ? xseg : yseg, yr = inplace ? xrow : yrow;+ float *x = fvec(xn, 1.f), *ref = malloc(xn > yn ? xn * 4 : yn * 4), *seg = malloc((size_t)len * 4);+ int bl = kind == VKC_DS_E4M3 || kind == VKC_DS_E2M1 ? block : len, nb = (len + bl - 1) / bl;+ for (int g = 0; g < nseg; g++) {+ float *xs = x + xo + (g / per_row) * xrow + (g % per_row) * xseg;+ for (int b = 0; b < nb; b++) ds_fill(xs + b * bl, len - b * bl < bl ? len - b * bl : bl, kind, (g * nb + b) % 6);+ }+ if (inplace) memcpy(ref, x, xn * 4);+ else for (size_t i = 0; i < yn; i++) ref[i] = -7.0f; /* what the op must not touch */+ for (int g = 0; g < nseg; g++) {+ const float *xs = x + xo + (g / per_row) * xrow + (g % per_row) * xseg;+ float *ys2 = ref + yo + (g / per_row) * yr + (g % per_row) * ys;+ memcpy(seg, xs, (size_t)len * 4);+ if (kind == VKC_DS_BF16) for (int i = 0; i < len; i++) seg[i] = bf16r(seg[i]);+ else if (kind == VKC_DS_E4M3) ds_fp8_qdq(seg, xs, (size_t)len, (size_t)block);+ else if (kind == VKC_DS_E2M1) ds_fp4_qdq(seg, xs, (size_t)len, (size_t)block);+ else ds_hadamard(seg, (size_t)len);+ if ((flags & 1) && (kind == VKC_DS_E4M3 || kind == VKC_DS_E2M1)) for (int i = 0; i < len; i++) seg[i] = bf16r(seg[i]);+ memcpy(ys2, seg, (size_t)len * 4);+ }+ VkcBuf *xb = up(x, xn), *yb = inplace ? xb : NULL;+ if (!inplace) { float *init = malloc(yn * 4); for (size_t i = 0; i < yn; i++) init[i] = -7.0f; yb = up(init, yn); free(init); }+ VkcDsRound p = {kind, nseg, per_row, len, block, flags, xo, xrow, xseg, yo, yr, ys, 1.0f / sqrtf((float)len)};+ vkc_begin(); int ok = vkc_dsv4_round(xb, yb, &p); vkc_submit(1);+ float *got = down(yb, 0, yn);+ size_t diff = 0, first = 0;+ for (size_t i = 0; i < yn; i++) if (memcmp(&got[i], &ref[i], 4)) { if (!diff) first = i; diff++; }+ CHECK(ok && !diff, "dsv4 round kind %d nseg %d len %d block %d flags %d inplace %d: %zu of %zu values differ (first at %zu: %a, want %a)",+ kind, nseg, len, block, flags, inplace, diff, yn, first, (double)got[first], (double)ref[first]);+ vkc_free(xb); if (!inplace) vkc_free(yb);+ free(x); free(ref); free(seg); free(got);+}+/* The SwiGLU: within one bf16 step of the CPU (the device's exp is not the CPU's expf),+ * and how many values are the CPU's bits */+static void test_ds_swiglu(int n, float lim) {+ float *a = fvec((size_t)n + 3, 14.f), *b = fvec((size_t)n + 5, 14.f), *ref = malloc((size_t)n * 4);+ for (int i = 0; i < n; i++) {+ float g = bf16r(a[3 + i]), u = bf16r(b[5 + i]);+ if (lim > 0.0f) { g = fminf(g, lim); u = fmaxf(-lim, fminf(u, lim)); }+ ref[i] = bf16r(g * ds_sigmoid(g) * u);+ }+ VkcBuf *ab = up(a, (size_t)n + 3), *bb = up(b, (size_t)n + 5), *yb = vkc_buf((size_t)(n + 2) * 4, VKC_DEV);+ VkcDsSwiglu p = {n, 3, 5, 2, lim};+ vkc_begin(); int ok = vkc_dsv4_swiglu(ab, bb, yb, &p); vkc_submit(1);+ float *got = down(yb, 2, (size_t)n);+ int same = 0, far = 0;+ for (int i = 0; i < n; i++) {+ uint32_t u, v; memcpy(&u, &got[i], 4); memcpy(&v, &ref[i], 4);+ same += u == v;+ long d = (long)(u >> 16) - (long)(v >> 16);+ if ((u & 0xffff) || d > 1 || d < -1) far++;+ }+ CHECK(ok && !far, "dsv4 swiglu n %d lim %g: %d values further than one bf16 step (or not bf16)", n, lim, far);+ printf(" dsv4 swiglu n %d lim %g: %d of %d values the CPU's bits, the rest one bf16 step away\n", n, lim, same, n);+ vkc_free(ab); vkc_free(bb); vkc_free(yb);+ free(a); free(b); free(ref); free(got);+}+/* ---- frames: many ops, frames in flight, ordering ---------------------------------------- */static void test_frames(void) {int n = 1000;@@@ -1536,31 -1415,18 +1859,42 @@@ int main(int argc, char **argv)printf("kda done\n");test_mhc(2, 64, 3); test_mhc(4, 96, 20); test_mhc(3, 40, 1);printf("mhc done\n");+ test_kda_k3(2, 16, 4, 1.f); test_kda_k3(3, 32, 4, 1.f); test_kda_k3(2, 128, 4, 1.f); test_kda_k3(1, 64, 2, 1.f);+ test_kda_k3(2, 16, 4, 0.002f);+ printf("kda k3 done\n");+ }+ if (!vkc_ares_ready()) { fails++; printf("FAIL: the AttnRes shader did not load\n"); }+ else {+ test_ares(1, 128, 0); test_ares(3, 128, 1); test_ares(5, 300, 4); test_ares(2, 7168, 8); test_ares(4, 96, 15);+ test_situ(1.f, 1.f); test_situ(4.f, 25.f);+ printf("ares done\n");}+ if (vkc_sconv_ready() && vkc_relattn_ready()) { test_inkling(); printf("inkling done\n"); }+ else CHECK(0, "inkling's ops: chain_sconv.spv or chain_relattn.spv did not load");+ if (!vkc_dsv4_ready()) { fails++; printf("FAIL: the DeepSeek V4 shader did not load\n"); }+ else {+ test_ds_attn(1, 4, 64, 8, 5, 13, 0); test_ds_attn(3, 2, 512, 128, 40, 300, 0); test_ds_attn(2, 3, 100, 6, 9, 20, 0);+ test_ds_attn(2, 2, 64, 8, 12, 2900, 0); test_ds_attn(3, 4, 64, 8, 5, 13, 1);+ test_ds_rope(0); test_ds_rope(1);+ test_ds_compress(2, 0, 0); test_ds_compress(1, 0, 0); test_ds_compress(4, 0, 0); test_ds_compress(4, 1, 1);+ test_ds_compress(3, 0, 1);+ test_ds_index(1, 30, 1, 4, 32, 4, 2, 2, 0); test_ds_index(5, 40, 2, 4, 32, 4, 2, 2, 0); test_ds_index(3, 0, 1, 2, 16, 8, 2, 3, 0);+ test_ds_index(2, 900, 1, 3, 64, 100, 4, 8, 0); test_ds_index(4, 300, 4, 16, 64, 16, 1, 3, 1); test_ds_index(3, 1, 2, 2, 16, 4, 2, 1, 0);+ test_ds_engram(1, 4, 128); test_ds_engram(3, 2, 300);+ test_ds_index(3, 37, 4, 64, 128, 16, 2, 2, 1); test_ds_index(2, 60, 4, 96, 64, 8, 2, 2, 0); /* DeepSeek V4's 64 x 128, past the staging */+ printf("dsv4 done\n");+ int in;+ for (in = 0; in < 2; in++) {+ test_ds_round(VKC_DS_BF16, 6, 2, 50, 0, 0, in); test_ds_round(VKC_DS_BF16, 300, 1, 1000, 0, 0, in);+ test_ds_round(VKC_DS_E4M3, 6, 2, 300, 128, 0, in); test_ds_round(VKC_DS_E4M3, 9, 3, 448, 64, 1, in);+ test_ds_round(VKC_DS_E4M3, 40, 1, 4096, 128, 0, in); test_ds_round(VKC_DS_E4M3, 5, 1, 70, 256, 1, in);+ test_ds_round(VKC_DS_E2M1, 6, 2, 128, 32, 1, in); test_ds_round(VKC_DS_E2M1, 10, 5, 100, 32, 0, in);+ test_ds_round(VKC_DS_HADAMARD, 6, 2, 128, 0, 0, in); test_ds_round(VKC_DS_HADAMARD, 3, 1, 4096, 0, 0, in);+ test_ds_round(VKC_DS_HADAMARD, 4, 4, 32, 0, 0, in); test_ds_round(VKC_DS_HADAMARD, 2, 1, 1, 0, 0, in);+ }+ test_ds_swiglu(5000, 10.0f); test_ds_swiglu(3000, 0.0f);+ printf("dsv4 rounding done\n");+ }VkcStats st; vkc_stats(&st);printf("chain: %llu frames, %llu ops, %llu matmuls (%llu GEMM), %llu barriers\n", st.frames, st.ops, st.matmuls, st.gemms, st.barriers);vkc_shutdown();diff --cc c/tests/vulkan_engines.shindex ca61374f,c5752324..2f148930--- a/c/tests/vulkan_engines.sh+++ b/c/tests/vulkan_engines.sh@@@ -7,8 -7,10 +7,11 @@@# 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 mimo-chain | mimo-chain-sanitize # MiMo-V2.6's dense chain+ # bash tests/vulkan_engines.sh inkling-olmoe-chain | inkling-olmoe-chain-sanitize# bash tests/vulkan_engines.sh glm-chain | glm-chain-sanitize # the same for colibri and glm53+ # bash tests/vulkan_engines.sh kimi-chain | kimi-chain-sanitize # the same for Kimi K3+# bash tests/vulkan_engines.sh deepseek-chain | deepseek-chain-sanitize # deepseek_v41 and deepseek_v4## 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).@@@ -1530,447 -1884,190 +1885,631 @@@ family_glm_chain_sanitize()make clean >/dev/null 2>&1 || true}+ # Kimi K3's dense chain (kimi_k3_chain.h). The tolerance: the tiny fixture amplifies+ # rounding at a few positions. The CPU against itself, with only its RMSNorm's sum taken+ # in float instead of double, moves the logits by up to 1.4e-4 of the largest one on the+ # f32 trunk and 1.0e-3 on the 8-bit one, and the served logprobs by up to 4.1e-3 (int4+ # trunk), at the positions where the chain moves them most (measured on Lavapipe: 1.8e-4+ # and 4.5e-4; logprobs 6.1e-3): every logits row is held within 2e-3 of the largest+ # |logit|, the logprobs of the serve sessions within 2e-2, the tokens exactly. With the CPU's int8 expert activations+ # (K3_IDOT=1) a rounding that flips an int8 step moves the logits further (8e-3, the+ # tokens unchanged): that configuration gates on its tokens (TOKENS=1).+ k3c_ids() { $PY -c "import json,sys;print(' '.join(map(str,json.load(open('kimi_k3_tiny/ref.json'))['cases'][sys.argv[1]]['prompt_ids'])))" "$1"; }+ k3c_close() { # <cpu.f32> <vk.f32>: max |diff| within 2e-3 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 / m if m else d:.1e} of the largest")+ sys.exit(0 if d <= 2e-3 * m else 1)+ PY+ }+ # k3c_gate <tag> <env...>: for each of the oracle's prompts (K3C_CASES, default all+ # three), the CPU run's tokens, every logits row (K3_VAL_LOGITS: every prefill row and+ # every decode step) within k3c_close (TOKENS=1: reported, not gated), and the chain+ # ran. EVICT=1: the tier evicted.+ # FAULT_BACK=k: the device is lost k frames before the end of the same run without a+ # fault (counted from that run's frames, so on any device the loss lands in the same+ # forward), and the run must say so; REBUILD=1: and rebuild the KDA state of some+ # positions on the CPU.+ k3c_gate() {+ local tag=$1 c frames fault; shift+ for c in ${K3C_CASES:-short chunk long}; do+ rm -f k3c.usage cpu.f32 vk.f32+ env "$@" COLI_USAGE=$PWD/k3c.usage USAGE_SAVE=0 K3_VAL_LOGITS=cpu.f32 ./kimi_k3 kimi_k3_tiny --ids "$(k3c_ids $c)" --ngen 8 \+ 2> cpu.log | sed 's/ *TUNE.*//' > cpu.tok+ fault=""+ if [ -n "${FAULT_BACK:-}" ]; then+ env "$@" COLI_USAGE=$PWD/k3c.usage USAGE_SAVE=0 COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 COLI_VK_CHAIN=1 \+ ./kimi_k3 kimi_k3_tiny --ids "$(k3c_ids $c)" --ngen 8 2> vk.log > /dev/null+ frames=$(sed -n 's/^\[VK\] kimi_k3 chain: [0-9]* forwards, \([0-9]*\) frames.*/\1/p' vk.log | tail -1)+ [ -n "$frames" ] && [ "$frames" -gt "$FAULT_BACK" ] || { cat vk.log; fail "$tag $c: no fault-free run to count frames from"; }+ fault="COLI_VK_CHAIN_FAULT=$((frames - FAULT_BACK + 1))"+ fi+ env "$@" $fault COLI_USAGE=$PWD/k3c.usage USAGE_SAVE=0 K3_VAL_LOGITS=vk.f32 COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 \+ COLI_VK_CHAIN=${CHAINMODE:-1} ./kimi_k3 kimi_k3_tiny --ids "$(k3c_ids $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; tail -20 vk.log; fail "$tag $c: the chain's tokens differ from the CPU"; }+ if [ -n "$fault" ]; then+ grep -q "kimi_k3 chain: the device was lost" vk.log || { cat vk.log; fail "$tag $c: no loss was handled"; }+ if [ "${REBUILD:-0}" = 1 ]; then grep -q "rebuilding the state of [1-9]" vk.log || { cat vk.log; fail "$tag $c: no state was rebuilt"; }; fi+ else+ [ "$(chain_count kimi_k3 vk.log)" -gt 0 ] || { cat vk.log; fail "$tag $c: the chain never ran"; }+ fi+ 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 lg; lg=$(k3c_close cpu.f32 vk.f32) || { echo "$lg"; [ "${TOKENS:-0}" = 1 ] || fail "$tag $c: logits"; }+ echo "OK $tag $c: tokens = CPU, $lg, $(chain_count kimi_k3 vk.log) chain forwards$(grep -o 'rebuilding the state of [0-9]* positions\|the host.s state is current' vk.log | sed 's/^/, /')"+ done+ }+ k3c_serve_fixture() { # the tiny fixture with the tokenizer the serve tests speak through+ rm -rf kimi_k3_serve && mkdir kimi_k3_serve+ cp kimi_k3_tiny/config.json kimi_k3_tiny/model.safetensors kimi_k3_serve/+ cp tests/tok_kimi_tiny.json kimi_k3_serve/tokenizer.json+ }++ # Every configuration the chain takes: Moonshot's oracle with the chain on (the tier on,+ # off, the shared experts on the device), every dense format (f32, int8 rows, int4-g64,+ # mixed), the CPU's int8 expert activations with the tier off, prefill a token at a+ # time and in chain chunks of 3, the tiled GEMM and the per-row GEMV, K3_TOPP, a tier+ # budget that evicts, prompts only (the KDA state crossing between the device and the+ # CPU at every decode), a device lost mid-decode (the KDA state rebuilt on the CPU), in+ # the first prompt chunk (the host's state current) and in a later one (rebuilt); serve+ # sessions frame for frame (pins, the prompt cache, prefix reuse, a prompt that diverges+ # and one that starts over, the prefill read-out), with recurrent-state checkpoints+ # (COLI_K3_CKPT: photos taken from the device's state and restored to it), in chain+ # chunks, on prompts only, with a device lost mid-session; the checkpoint and dashboard+ # harnesses with the chain on.+ family_kimi_chain() {+ make kimi_k3 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_kimi_k3_tiny.py --output ./kimi_k3_tiny --force+ k3c_serve_fixture+ export OMP_NUM_THREADS=2+ local e b out frames+ for e in COLI_VK_TIER=1 COLI_VK_TIER=0 COLI_VK_DENSE=1; do+ env $e COLI_USAGE=$PWD/k3c.usage USAGE_SAVE=0 COLI_VULKAN=1 COLI_VK_CHAIN=1 COLI_VK_TIER_SYNC=1 \+ $PY tests/test_kimi_k3_tiny.py --binary ./kimi_k3 --fixture ./kimi_k3_tiny+ echo "OK chain kimi_k3 vendor oracle ($e)"+ done+ local O="K3_BITS=32 K3_MLA_BITS=32 K3_HEAD_BITS=32 K3_IDOT=0 COLI_TEMP=0"+ k3c_gate "chain kimi_k3 f32" $O+ k3c_gate "chain kimi_k3 f32, tier off" $O COLI_VK_TIER=0+ k3c_gate "chain kimi_k3 f32, shared experts by COLI_VK_DENSE=1" $O COLI_VK_DENSE=1+ for b in 8 4; do # int8 rows (fmt 1); int4-g64 (fmt 4) where a row is whole groups, int8 elsewhere+ k3c_gate "chain kimi_k3 ${b}-bit trunk" K3_BITS=$b K3_MLA_BITS=$b K3_HEAD_BITS=$b K3_IDOT=0 COLI_TEMP=0+ done+ k3c_gate "chain kimi_k3 int4 KDA and MoE, int8 MLA and head" K3_BITS=4 K3_IDOT=0 COLI_TEMP=0+ TOKENS=1 k3c_gate "chain kimi_k3 int8 expert activations, tier off" K3_BITS=32 K3_MLA_BITS=32 K3_HEAD_BITS=32 COLI_TEMP=0 COLI_VK_TIER=0+ k3c_gate "chain kimi_k3 prefill one token at a time" $O K3_CHUNK=1+ k3c_gate "chain kimi_k3 chain chunks of 3" $O COLI_VK_CHAIN_ROWS=3+ k3c_gate "chain kimi_k3 tiled GEMM from 2 rows" $O COLI_VK_GEMM_MIN_S=2+ k3c_gate "chain kimi_k3 the per-row GEMV" $O COLI_VK_CHAIN_GEMV=0+ k3c_gate "chain kimi_k3 K3_TOPP=0.6" $O K3_TOPP=0.6+ EVICT=1 k3c_gate "chain kimi_k3 a tier budget of two experts" $O COLI_VK_TIER_GB=0.000005+ CHAINMODE=2 k3c_gate "chain kimi_k3 prompts only" $O+ # the device lost: 9 frames a forward on this fixture (two per sparse layer and the+ # head); the long prompt is three forwards (32, 32 and 8 rows), then 7 decode steps+ FAULT_BACK=3 REBUILD=1 k3c_gate "chain kimi_k3 device lost mid-decode" $O+ K3C_CASES=long FAULT_BACK=86 k3c_gate "chain kimi_k3 device lost in the first prompt chunk" $O+ K3C_CASES=long FAULT_BACK=77 REBUILD=1 k3c_gate "chain kimi_k3 device lost in a later prompt chunk" $O+ # in chain chunks of 5 rows (seven chunks a 32-row forward), the loss in the third+ # chunk of the second forward: the state its first chunks advanced is not used+ K3C_CASES=long FAULT_BACK=124 REBUILD=1 k3c_gate "chain kimi_k3 device lost inside a chunked forward" $O COLI_VK_CHAIN_ROWS=5+ # serve sessions frame for frame, the KDA state across turns+ local S="K3_BITS=32 K3_MLA_BITS=32 K3_HEAD_BITS=32 K3_IDOT=0 K3_PREFIX_LOG=1 USAGE_SAVE=0"+ export CHAIN_SERVE_TOL=2e-2+ rm -rf k3c_photos && mkdir k3c_photos+ # shellcheck disable=SC2086+ {+ $PY tests/vulkan_chain_serve.py ./kimi_k3 kimi_k3_serve $S+ out=$($PY tests/vulkan_chain_serve.py ./kimi_k3 kimi_k3_serve $S COLI_K3_CKPT=4); echo "$out"+ $PY tests/vulkan_chain_serve.py ./kimi_k3 kimi_k3_serve $S COLI_K3_CKPT=2 COLI_K3_CKPT_DIR=$PWD/k3c_photos+ $PY tests/vulkan_chain_serve.py ./kimi_k3 kimi_k3_serve K3_BITS=4 K3_IDOT=0 K3_PREFIX_LOG=1 USAGE_SAVE=0 COLI_VK_CHAIN_ROWS=3+ COLI_VK_CHAIN=2 $PY tests/vulkan_chain_serve.py ./kimi_k3 kimi_k3_serve $S COLI_K3_CKPT=4+ # a device lost mid-session, 134 frames before the end of the same session without a+ # fault (on Lavapipe frame 200 of 334: after a photo brought the state to the host,+ # the state of the 3 positions since then is rebuilt from it)+ frames=$(echo "$out" | sed -n 's/.*kimi_k3 chain: [0-9]* forwards, \([0-9]*\) frames.*/\1/p')+ [ -n "$frames" ] && [ "$frames" -gt 134 ] || fail "chain kimi_k3 serve: no fault-free session to count frames from"+ CHAIN_SERVE_EXPECT='kimi_k3 chain: the device was lost' \+ $PY tests/vulkan_chain_serve.py ./kimi_k3 kimi_k3_serve $S COLI_K3_CKPT=4 COLI_VK_CHAIN_FAULT=$((frames - 134))+ }+ unset CHAIN_SERVE_TOL+ # recurrent-state checkpoints and the dashboard's lines with the chain on+ COLI_USAGE=$PWD/k3c.usage USAGE_SAVE=0 COLI_VULKAN=1 COLI_VK_CHAIN=1 COLI_VK_TIER_SYNC=1 \+ $PY tests/test_kimi_k3_ckpt.py --binary ./kimi_k3 --fixture ./kimi_k3_tiny+ COLI_USAGE=$PWD/k3c.usage USAGE_SAVE=0 COLI_VULKAN=1 COLI_VK_CHAIN=1 COLI_VK_TIER_SYNC=1 \+ $PY tests/test_kimi_k3_dashboard.py --binary ./kimi_k3 --fixture ./kimi_k3_tiny+ unset OMP_NUM_THREADS+ }++ # The same chain under ASan and UBSan: memory safety is the gate; each run must have+ # run the chain (or handled the loss).+ family_kimi_chain_sanitize() {+ make clean >/dev/null 2>&1 || true+ make kimi_k3 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"+ $PY tools/make_kimi_k3_tiny.py --output ./kimi_k3_tiny --force+ k3c_serve_fixture+ export OMP_NUM_THREADS=2+ k3san() { # <tag> <env and argv...>+ local tag=$1; shift+ rm -f k3c.usage+ env COLI_USAGE=$PWD/k3c.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 "kimi_k3 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 kimi_k3 san.log) chain forwards"+ }+ local O="K3_BITS=32 K3_MLA_BITS=32 K3_HEAD_BITS=32 K3_IDOT=0 COLI_TEMP=0" ids frames+ ids=$(k3c_ids long)+ # shellcheck disable=SC2086+ {+ k3san "asan chain kimi_k3 f32" env $O ./kimi_k3 kimi_k3_tiny --ids "$ids" --ngen 8+ frames=$(sed -n 's/^\[VK\] kimi_k3 chain: [0-9]* forwards, \([0-9]*\) frames.*/\1/p' san.log | tail -1)+ k3san "asan chain kimi_k3 int4 trunk, chain chunks of 3" env K3_BITS=4 K3_IDOT=0 COLI_VK_CHAIN_ROWS=3 ./kimi_k3 kimi_k3_tiny --ids "$ids" --ngen 8+ k3san "asan chain kimi_k3 tier off, every logits row" env $O COLI_VK_TIER=0 K3_VAL_LOGITS=san.f32 ./kimi_k3 kimi_k3_tiny --ids "$ids" --ngen 8+ k3san "asan chain kimi_k3 prompts only" env $O COLI_VK_CHAIN=2 ./kimi_k3 kimi_k3_tiny --ids "$ids" --ngen 8+ # the device lost mid-decode: 3 frames before the end of the run above (a fixed frame+ # number can land in the buffers' setup on a device whose memory is not mapped)+ k3san "asan chain kimi_k3 device lost, rebuilt" env $O COLI_VK_CHAIN_FAULT=$((frames - 2)) ./kimi_k3 kimi_k3_tiny --ids "$ids" --ngen 8+ grep -q "rebuilding the state of [1-9]" san.log || { cat san.log; fail "asan chain kimi_k3 device lost: no state was rebuilt"; }+ }+ CHAIN_SERVE_TOL=2e-2 $PY tests/vulkan_chain_serve.py ./kimi_k3 kimi_k3_serve K3_BITS=32 K3_MLA_BITS=32 K3_HEAD_BITS=32 K3_IDOT=0 \+ K3_PREFIX_LOG=1 USAGE_SAVE=0 COLI_K3_CKPT=4 > san.log 2>&1 || { cat san.log; fail "asan chain kimi_k3 serve"; }+ if grep -qE "ERROR: AddressSanitizer|runtime error:" san.log; then cat san.log; fail "asan chain kimi_k3 serve: sanitizer diagnostic"; fi+ echo "OK asan chain kimi_k3 serve: $(tail -1 san.log)"+ unset OMP_NUM_THREADS+ make clean >/dev/null 2>&1 || true+ }++# DeepSeek V4.1 Flash (deepseek_v41) and DeepSeek V4 (deepseek_v4) on the dense chain+# (COLI_VK_CHAIN=1). v41_gate runs the CPU and then the chain with the same settings:+# the same exit code (the engine fails on a token off its reference), the same printed+# token stream, every logits row (DUMP) within 1e-4 of the largest, the chain ran (or,+# with FAULT_BACK=k, the device was lost k frames before the end of a fault-free run and+# the CPU took over).+v41_gate() { # <tag> <env...> -- <argv...>+ local tag=$1; shift+ local envs=(); while [ "$1" != "--" ]; do envs+=("$1"); shift; done; shift+ local rc_cpu=0 rc_vk=0+ rm -f chain.usage cpu.f32 vk.f32+ env "${envs[@]}" DUMP=cpu.f32 ./deepseek_v41 "$@" > cpu.txt 2> cpu.log || rc_cpu=$?+ if [ -n "${FAULT_BACK:-}" ]; then+ env "${envs[@]}" COLI_USAGE=chain.usage COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 COLI_VK_CHAIN=1 \+ ./deepseek_v41 "$@" > /dev/null 2> vk.log || true+ local frames; frames=$(sed -n 's/^\[VK\] deepseek_v41 chain: [0-9]* forwards, \([0-9]*\) frames.*/\1/p' vk.log | tail -1)+ [ -n "$frames" ] && [ "$frames" -gt "$FAULT_BACK" ] || { cat vk.log; fail "$tag: no fault-free run to count frames from"; }+ envs+=("COLI_VK_CHAIN_FAULT=$((frames - FAULT_BACK + 1))")+ rm -f chain.usage+ fi+ env "${envs[@]}" DUMP=vk.f32 COLI_USAGE=chain.usage COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 \+ COLI_VK_CHAIN=${CHAINMODE:-1} ./deepseek_v41 "$@" > vk.txt 2> vk.log || rc_vk=$?+ [ "$rc_cpu" = "$rc_vk" ] || { tail -20 vk.log; fail "$tag: exit $rc_vk, the CPU's $rc_cpu"; }+ { [ -s cpu.txt ] && cmp -s cpu.txt vk.txt; } || { cat cpu.txt vk.txt; tail -20 vk.log; fail "$tag: the chain's tokens differ from the CPU"; }+ if [ -n "${FAULT_BACK:-}" ]; then+ grep -q "deepseek_v41 chain: the device was lost" vk.log || { cat vk.log; fail "$tag: no loss was handled"; }+ else+ [ "$(chain_count deepseek_v41 vk.log)" -gt 0 ] || { cat vk.log; fail "$tag: the chain never ran"; }+ fi+ local lg; lg=$(logits_close cpu.f32 vk.f32) || { echo "$lg"; fail "$tag: logits"; }+ echo "OK $tag: tokens = CPU (exit $rc_cpu), $lg, $(chain_count deepseek_v41 vk.log) chain forwards$(grep -q 'the device was lost' vk.log && echo ', the device lost and the CPU on')"+}+v41_chain_fixtures() {+ $PY tools/make_dsv41_tiny.py --out dsv41_tiny --emit-ref dsv41_tiny/ref.json > /dev/null+ $PY tools/make_dsv41_tiny.py --out dsv41_long --emit-ref dsv41_long/ref.json --prompt-len 40 --max-new 6 > /dev/null+}++# DeepSeek V4 (deepseek_v4) on the dense chain: the deepseek-chain family's V4 half. The+# functions use $PY, fail and chain_count from tests/vulkan_engines.sh and run from c/.+#+# v4_chain_gate <tag> <fixture> <case> <env...>: the CPU run (no COLI_VULKAN) and the+# chain run of one oracle case of the fixture (or ids:a,b,...:n, those ids and n new+# tokens), with the same settings and --record-oracle: the generated ids equal to the+# CPU's (and to the reference's greedy stream), every logits row (DUMP) within+# V4_CHAIN_TOL (5e-1) of its largest |logit|, the same draft attempts and acceptances as+# the CPU (V4_DRAFT), the chain ran, and, on the chain throughout, each decode row equal+# bit for bit to the teacher-forced row at its position. The teacher-forced argmaxes that+# moved are counted, not gated (the logits bound already covers them). FAULT_BACK=k: the+# device is lost k frames before the end of a fault-free run (counted without+# --record-oracle) and the CPU takes over; CHAINMODE=2: prompts only. Each run starts+# from no expert history (the fixture's .coli_usage removed), the tier's uploads awaited.+# Why 0.5: DeepSeek V4 rounds to bf16 after nearly every step and the input of every fp8+# matrix to E4M3 per block; a value the device's sums put on the other side of a bf16+# boundary can move a whole E4M3 block by a step and the indexer's top-k to another row.+# Measured worst on Lavapipe and a Radeon 780M: 0.32 (deepseek_v4_tiny_g2, long). The+# check that no driver blurs is v4_chain_same (and the decode-row check above).+v4_chain_prompt() { # <fixture> <case>: the case's prompt as the tiny vocabulary's text (ids:a,b,...: those ids)+ $PY -c 'import json,sys; c=sys.argv[2]; ids=[int(t) for t in c[4:].split(":")[0].split(",")] if c.startswith("ids:") else json.load(open(sys.argv[1]+"/ref.json"))["cases"][c]["prompt_ids"]; print("".join("<t%03d>" % t for t in ids))' "$1" "$2"+}+v4_chain_logits() { # <cpu.f32> <vk.f32> <vocab>: the worst row's |diff| over its largest |logit|+ $PY - "$1" "$2" "$3" "${V4_CHAIN_TOL:-5e-1}" <<'PY'+import array, sys+a = array.array("f", open(sys.argv[1], "rb").read()); b = array.array("f", open(sys.argv[2], "rb").read())+V, tol = int(sys.argv[3]), float(sys.argv[4])+if not a or len(a) != len(b): print(f"logits: {len(a)} and {len(b)} values"); sys.exit(1)+worst, same = 0.0, 0+for r in range(len(a) // V):+ ra, rb = a[r * V:(r + 1) * V], b[r * V:(r + 1) * V]+ d = max(abs(x - y) for x, y in zip(ra, rb)); m = max(abs(x) for x in ra)+ same += d == 0+ worst = max(worst, d / m if m else d)+print(f"logits: {same} of {len(a) // V} rows identical, worst row {worst:.2e} of its largest")+sys.exit(0 if worst <= tol else 1)+PY+}+# v4_chain_same <tag> <fixture> <case> <A> <B> <env...>: the chain twice, with the settings+# A and then B (space-separated KEY=VALUE lists) on top of env: the same ids and every+# logits row the same bits. The chain's arithmetic does not depend on how the rows are+# cut (every matrix takes the per-row GEMV, every other op is per row or in the CPU's+# row order) nor on which side of the tier computed an expert, so chunks of 1 or 3, the+# tier off or a draft's rows cut differently give the default run's bits; a state the+# device kept stale across forwards (a rejected draft longer than a chunk) shows here+# even where its logits stay within the CPU's tolerance.+v4_chain_same() {+ local tag=$1 fx=$2 c=$3 A=$4 B=$5; shift 5+ local p mt side+ p=$(v4_chain_prompt "$fx" "$c")+ mt=$($PY -c 'import json,sys; c=sys.argv[2]; print(c.split(":")[2] if c.startswith("ids:") else json.load(open(sys.argv[1]+"/ref.json"))["cases"][c]["max_new_tokens"])' "$fx" "$c")+ for side in a b; do+ rm -f "$fx/.coli_usage" "v4-$side.f32"+ # shellcheck disable=SC2046+ env "$@" $([ $side = a ] && echo "$A" || echo "$B") DUMP=v4-$side.f32 COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 COLI_VK_CHAIN=1 \+ ./deepseek_v4 "./$fx" "$p" --raw-prompt --max-tokens "$mt" --record-oracle v4-$side.json > /dev/null 2> v4-$side.err ||+ { tail -20 v4-$side.err; fail "$tag: run $side"; }+ [ "$(chain_count deepseek_v4 v4-$side.err)" -gt 0 ] || { cat v4-$side.err; fail "$tag: the chain never ran ($side)"; }+ done+ rm -f "$fx/.coli_usage"+ cmp -s v4-a.f32 v4-b.f32 && $PY -c 'import json,sys; sys.exit(json.load(open("v4-a.json"))["full_ids"] != json.load(open("v4-b.json"))["full_ids"])' ||+ { v4_chain_logits v4-a.f32 v4-b.f32 "$($PY -c 'import json,sys; print(json.load(open(sys.argv[1]+"/config.json"))["vocab_size"])' "$fx")"; fail "$tag: $A and $B give different bits"; }+ echo "OK $tag (${c%%:*}): $A and $B: the same ids and the same logits bit for bit ($(($(wc -c < v4-a.f32) / 4)) values), $(chain_count deepseek_v4 v4-b.err) chain forwards"+}+v4_chain_gate() {+ local tag=$1 fx=$2 c=$3; shift 3+ local p mt lg frames fault=()+ p=$(v4_chain_prompt "$fx" "$c")+ mt=$($PY -c 'import json,sys; c=sys.argv[2]; print(c.split(":")[2] if c.startswith("ids:") else json.load(open(sys.argv[1]+"/ref.json"))["cases"][c]["max_new_tokens"])' "$fx" "$c")+ rm -f "$fx/.coli_usage" cpu.f32 vk.f32 v4-cpu.json v4-vk.json+ env "$@" DUMP=cpu.f32 ./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 "$tag: CPU run"; }+ if [ -n "${FAULT_BACK:-}" ]; then+ rm -f "$fx/.coli_usage"+ env "$@" COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 COLI_VK_CHAIN=1 ./deepseek_v4 "./$fx" "$p" --raw-prompt --max-tokens "$mt" > /dev/null 2> v4-vk.err || true+ frames=$(sed -n 's/^\[VK\] deepseek_v4 chain: [0-9]* forwards, \([0-9]*\) frames.*/\1/p' v4-vk.err | tail -1)+ [ -n "$frames" ] && [ "$frames" -gt "$FAULT_BACK" ] || { cat v4-vk.err; fail "$tag: no fault-free run to count frames from"; }+ fault=("COLI_VK_CHAIN_FAULT=$((frames - FAULT_BACK + 1))")+ fi+ rm -f "$fx/.coli_usage"+ env "$@" "${fault[@]}" DUMP=vk.f32 COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 COLI_VK_CHAIN=${CHAINMODE:-1} \+ ./deepseek_v4 "./$fx" "$p" --raw-prompt --max-tokens "$mt" --record-oracle v4-vk.json > /dev/null 2> v4-vk.err ||+ { tail -20 v4-vk.err; fail "$tag: chain run"; }+ rm -f "$fx/.coli_usage"+ $PY - "$fx" "$c" <<'PY' || { tail -20 v4-vk.err; fail "$tag: the chain's session differs from the CPU's"; }+import json, sys+a, b = json.load(open("v4-cpu.json")), json.load(open("v4-vk.json"))+ref = a["full_ids"] if sys.argv[2].startswith("ids:") else json.load(open(sys.argv[1] + "/ref.json"))["cases"][sys.argv[2]]["greedy_full_ids"]+ok = a["full_ids"] == b["full_ids"] == ref and len(a["tf_pred"]) == len(b["tf_pred"])+if not ok: print("CPU", a["full_ids"], "chain", b["full_ids"], "ref", ref)+open("v4-tf.txt", "w").write(str(sum(x != y for x, y in zip(a["tf_pred"], b["tf_pred"]))))+sys.exit(0 if ok else 1)+PY+ if [ "${EVICT:-0}" = 1 ]; then # the budget forced evictions+ [ "$(tier_evictions deepseek_v4 v4-vk.err)" -gt 0 ] || { grep '\[VK\] tier' v4-vk.err; fail "$tag: the budget forced no eviction"; }+ fi+ # drafts (V4_DRAFT): the same attempts, drafted and accepted tokens as the CPU's+ [ "$(grep -ao 'v4_dspark attempts=[0-9]* drafted=[0-9]* accepted=[0-9]*' v4-cpu.err)" = \+ "$(grep -ao 'v4_dspark attempts=[0-9]* drafted=[0-9]* accepted=[0-9]*' v4-vk.err)" ] || { grep -a v4_dspark v4-cpu.err v4-vk.err; fail "$tag: the drafts went otherwise"; }+ if [ -n "${FAULT_BACK:-}" ]; then+ grep -q "deepseek_v4 chain: the device was lost" v4-vk.err || { cat v4-vk.err; fail "$tag: no loss was handled"; }+ else+ [ "$(chain_count deepseek_v4 v4-vk.err)" -gt 0 ] || { cat v4-vk.err; fail "$tag: the chain never ran"; }+ fi+ lg=$(v4_chain_logits cpu.f32 vk.f32 "$($PY -c 'import json,sys; print(json.load(open(sys.argv[1]+"/config.json"))["vocab_size"])' "$fx")") ||+ { echo "$lg"; fail "$tag: logits"; }+ # an oracle case on the chain throughout: its decode rows are the teacher-forced+ # forward's rows at the same positions, bit for bit (as on the CPU)+ if [ "${c#ids:}" = "$c" ] && [ "${CHAINMODE:-1}" = 1 ] && [ -z "${FAULT_BACK:-}" ] && [ "${*#*V4_DRAFT}" = "$*" ]; then+ $PY - vk.f32 "$fx" "$c" <<'PY' || fail "$tag: a decode row differs from the teacher-forced row at its position"+import array, json, sys+v = array.array("f", open(sys.argv[1], "rb").read())+V = json.load(open(sys.argv[2] + "/config.json"))["vocab_size"]+case = json.load(open(sys.argv[2] + "/ref.json"))["cases"][sys.argv[3]]+P, mt = len(case["prompt_ids"]), case["max_new_tokens"]+row = lambda r: v[r * V:(r + 1) * V]+for j in range(mt): # session rows: the prompt's last position, then each decode step+ if row(j) != row(mt + P - 1 + j): sys.exit(1)+PY+ lg="$lg, decode rows = teacher-forced rows"+ fi+ echo "OK $tag (${c%%:*}): ids = CPU$(case $c in ids:*) ;; *) echo ' = reference';; esac), $(cat v4-tf.txt) teacher-forced argmaxes moved, $lg, $(chain_count deepseek_v4 v4-vk.err) chain forwards$(grep -q 'the device was lost' v4-vk.err && echo ', the device lost and the CPU on')$(grep -ao 'v4_dspark attempts=[0-9]* drafted=[0-9]* accepted=[0-9]*' v4-vk.err | tail -1 | sed 's/^/, /')$([ "${EVICT:-0}" = 1 ] && grep -ao 'evictions [0-9]*' v4-vk.err | tail -1 | sed 's/^/, /')"+}+# v4_chain_fixtures: the 4-expert fixture (a copy), the 8-expert one (pinned rows16+# experts), and three more geometries: 8 heads in 2 output groups (wo_a per group), a+# window of 4 with ratios 4 and 2 (the window and the rings roll over more often), and+# DeepSeek V4's indexer of 64 heads of 128 (the scores past the shared staging).+v4_chain_fixtures() {+ $PY tools/make_deepseek_v4_tiny.py --output deepseek_v4_tiny_t --force > /dev/null+ local spec+ for spec in "deepseek_v4_tiny_e8 EXPERTS=8" "deepseek_v4_tiny_g2 HEADS=8 O_GROUPS=2" \+ "deepseek_v4_tiny_w4 SLIDING=4 COMPRESS_RATIOS=[0,4,2] HCA=2" "deepseek_v4_tiny_ix INDEX_HEADS=64 INDEX_DIM=128"; do+ # shellcheck disable=SC2086+ $PY - tools/make_deepseek_v4_tiny.py $spec <<'PY' > /dev/null+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)+for kv in sys.argv[3:]:+ k, v = kv.split("=", 1)+ if k != "HCA": setattr(gen, k, eval(v)); continue+ hf = gen.make_hf_config # the heavily compressed layers' ratio+ def patched(C, hf=hf, r=int(v)):+ cfg = hf(C); cfg.compress_rates["heavily_compressed_attention"] = r; return cfg+ gen.make_hf_config = patched+sys.argv = ["make_deepseek_v4_tiny.py", "--output", sys.argv[2], "--force"]+gen.main()+PY+ done+}+# v4_chain_serve: the brio served prompt's per-position logprob echoes with the chain+# against the CPU's (pinned, then a prompt that extends the pin, then max_tokens 0),+# and the prefix-reuse contract (tests/test_deepseek_v4_prefix.py) with the chain on.+v4_chain_serve() { # <fixture>+ $PY - "$1" <<'PY' || fail "deepseek_v4 chain served: the chain's echoes 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"]+ids = case["prompt_ids"]+def turns(chain):+ for k in ("COLI_VULKAN", "COLI_VK_CHAIN", "COLI_VK_TIER_SYNC"): os.environ.pop(k, None)+ try: os.remove(fx / ".coli_usage")+ except FileNotFoundError: pass+ if chain: os.environ.update(COLI_VULKAN="1", COLI_VK_CHAIN=os.environ.get("V4_CHAIN_MODE", "1"), COLI_VK_TIER_SYNC="1")+ s = b.Serve(Path("deepseek_v4").resolve(), fx)+ out = []+ try:+ out.append(s.submit(b.token_prompt(ids[:40]), 3, logprobs=4, pin=True))+ out.append(s.submit(b.token_prompt(ids[:40] + ids[40:60]), 4, logprobs=4))+ out.append(s.submit(b.token_prompt(ids), 0, logprobs=5))+ out.append(s.submit(b.token_prompt(ids[:30]), 4))+ finally:+ s.close()+ err = s.process.stderr.read().decode(errors="replace")+ return out, err+cpu, err_cpu = turns(False)+dev, err = turns(True)+for text in (err_cpu, err): # a sanitized build reports into the engine's stderr+ if "ERROR: AddressSanitizer" in text or "runtime error:" in text: print(text[-4000:]); sys.exit("sanitizer diagnostic")+if "deepseek_v4 chain:" not in err or " forwards" not in err:+ print(err[-3000:]); sys.exit("the chain never ran")+worst, n, same = 0.0, 0, 0+for x, y in zip(cpu, dev):+ if [d[0] for d in x.data] != [d[0] for d in y.data] or sorted(x.echoes) != sorted(y.echoes) or x.reuse != y.reuse:+ print("CPU", x.data, x.echoes.keys(), x.reuse, "chain", y.data, y.echoes.keys(), y.reuse); sys.exit(1)+ for p in x.echoes:+ n += 1; same += x.echoes[p] == y.echoes[p]+ if x.echoes[p]["token"] != y.echoes[p]["token"]: sys.exit(1)+ worst = max(worst, abs(x.echoes[p]["lp"] - y.echoes[p]["lp"]))+fw = [l for l in err.splitlines() if "deepseek_v4 chain:" in l and "forwards" in l][-1]+print(f"OK deepseek_v4 chain served: the pin, its extension, a read-only prompt and a shorter one: texts and reuse = CPU, "+ f"{same} of {n} logprob echoes identical, worst |delta| {worst:.2e}; {fw.split('] ', 1)[1][:48]}")+sys.exit(0 if worst <= 0.5 else 1)+PY+}+# v4_chain_san <tag> <env and argv...>: a sanitized build's chain run (FAULT_BACK=k: the+# loss k frames before the end of a fault-free run): no sanitizer diagnostic, and the+# chain ran (or handled the loss).+v4_chain_san() {+ local tag=$1; shift+ local fault=() frames+ if [ -n "${FAULT_BACK:-}" ]; then+ rm -f deepseek_v4_tiny_*/.coli_usage+ env COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 COLI_VK_CHAIN=1 "$@" > san.log 2>&1 || true+ frames=$(sed -n 's/^\[VK\] deepseek_v4 chain: [0-9]* forwards, \([0-9]*\) frames.*/\1/p' san.log | tail -1)+ [ -n "$frames" ] && [ "$frames" -gt "$FAULT_BACK" ] || { cat san.log; fail "$tag: no fault-free run to count frames from"; }+ fault=("COLI_VK_CHAIN_FAULT=$((frames - FAULT_BACK + 1))")+ fi+ rm -f deepseek_v4_tiny_*/.coli_usage+ env COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 COLI_VK_CHAIN=1 "${fault[@]}" "$@" > san.log 2>&1 || true+ rm -f deepseek_v4_tiny_*/.coli_usage+ if grep -qE "ERROR: AddressSanitizer|runtime error:" san.log; then cat san.log; fail "$tag: sanitizer diagnostic"; fi+ grep -q "deepseek_v4 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 deepseek_v4 san.log) chain forwards$(grep -q 'the device was lost' san.log && echo ', the device lost')"+}++# The V4 half of the family: the engine, its fixtures, then every configuration: 4 and 8+# experts (pinned rows16), the three oracle cases (the long one rolls the window of 8 and+# both compressors over many times), 2 output groups, a window of 4 with ratios 4 and 2,+# V4's indexer of 64 heads of 128, eviction, the tier off, the per-matrix trunk beside,+# prefill and chain chunks, the per-row GEMV, V4_IDX_IDENTITY, prompts only, n-gram+# drafts accepted and rejected (V4_MTP on a one-layer MTP checkpoint runs target-only),+# the chain against itself, a device lost mid-decode, in the prompt and between drafts,+# served turns (a pin, its extension, a read-only prompt), and the engine's own serve+# tests with the chain on.+v4_chain_family() {+ make deepseek-v4 VK=1+ v4_chain_fixtures+ local c fx+ for c in short compressed long; do+ v4_chain_gate "chain deepseek_v4 4 experts" deepseek_v4_tiny_t $c+ v4_chain_gate "chain deepseek_v4 8 experts, pinned rows16" deepseek_v4_tiny_e8 $c+ done+ for c in short long; do+ v4_chain_gate "chain deepseek_v4 2 output groups" deepseek_v4_tiny_g2 $c+ v4_chain_gate "chain deepseek_v4 a window of 4, ratios 4 and 2" deepseek_v4_tiny_w4 $c+ v4_chain_gate "chain deepseek_v4 an indexer of 64 heads of 128" deepseek_v4_tiny_ix $c+ done+ EVICT=1 v4_chain_gate "chain deepseek_v4 a budget of three experts" deepseek_v4_tiny_e8 long COLI_VK_TIER_GB=0.00009+ v4_chain_gate "chain deepseek_v4 tier off" deepseek_v4_tiny_t long COLI_VK_TIER=0 COLI_VK_DENSE=0+ v4_chain_gate "chain deepseek_v4 beside the per-matrix trunk" deepseek_v4_tiny_t long COLI_VK_DENSE=1+ v4_chain_gate "chain deepseek_v4 prefill chunks of 7" deepseek_v4_tiny_t long V4_PREFILL_CHUNK=7+ v4_chain_gate "chain deepseek_v4 chain chunks of 3" deepseek_v4_tiny_e8 long COLI_VK_CHAIN_ROWS=3+ v4_chain_gate "chain deepseek_v4 chunks of 5, a window of 4" deepseek_v4_tiny_w4 long COLI_VK_CHAIN_ROWS=5+ v4_chain_gate "chain deepseek_v4 the per-row GEMV" deepseek_v4_tiny_t long COLI_VK_CHAIN_GEMV=0+ v4_chain_gate "chain deepseek_v4 V4_IDX_IDENTITY=1" deepseek_v4_tiny_t long V4_IDX_IDENTITY=1+ CHAINMODE=2 v4_chain_gate "chain deepseek_v4 prompts only" deepseek_v4_tiny_t long+ # n-gram drafts on prompts whose tails repeat: accepted and rejected (A), every one+ # rejected (R), a mix over three attempts (M)+ local A=ids:20,21,22,23,24,25,26,27,28,29,20,21,22:12 R=ids:20,21,22,23,50,51,52,20,21,22:12+ local M=ids:30,31,32,33,34,35,60,61,30,31,32,33,34,35,36,37,38,39,40,41,30,31,32:12+ v4_chain_gate "chain deepseek_v4 n-gram drafts accepted and rejected" deepseek_v4_tiny_t $A V4_DRAFT=4 V4_NGRAM_PARTIAL_KEEP=1+ v4_chain_gate "chain deepseek_v4 an n-gram draft rejected" deepseek_v4_tiny_t $R V4_DRAFT=4 V4_NGRAM_PARTIAL_KEEP=1+ v4_chain_gate "chain deepseek_v4 n-gram drafts, a window of 4" deepseek_v4_tiny_w4 $M V4_DRAFT=4 V4_NGRAM_PARTIAL_KEEP=1+ v4_chain_gate "chain deepseek_v4 n-gram drafts, 8 experts" deepseek_v4_tiny_e8 $M V4_DRAFT=4 V4_NGRAM_PARTIAL_KEEP=1+ CHAINMODE=2 v4_chain_gate "chain deepseek_v4 prompts only, drafts" deepseek_v4_tiny_w4 $M V4_DRAFT=4 V4_NGRAM_PARTIAL_KEEP=1+ v4_chain_gate "chain deepseek_v4 V4_MTP=1 (one MTP layer: target only)" deepseek_v4_tiny_t long V4_MTP=1 V4_DRAFT=3+ # the chain against itself+ for fx in deepseek_v4_tiny_t deepseek_v4_tiny_w4 deepseek_v4_tiny_g2; do+ v4_chain_same "chain deepseek_v4 chunks, $fx" $fx long "X=1" "COLI_VK_CHAIN_ROWS=1"+ v4_chain_same "chain deepseek_v4 prefill chunks, $fx" $fx long "X=1" "V4_PREFILL_CHUNK=3"+ done+ v4_chain_same "chain deepseek_v4 the tier off" deepseek_v4_tiny_e8 long "X=1" "COLI_VK_TIER=0 COLI_VK_DENSE=0"+ v4_chain_same "chain deepseek_v4 a draft rejected, chunks of 2" deepseek_v4_tiny_w4 $R "X=1" "COLI_VK_CHAIN_ROWS=2" V4_DRAFT=4 V4_NGRAM_PARTIAL_KEEP=1+ v4_chain_same "chain deepseek_v4 drafts, chunks of 1" deepseek_v4_tiny_w4 $M "X=1" "COLI_VK_CHAIN_ROWS=1" V4_DRAFT=4 V4_NGRAM_PARTIAL_KEEP=1+ v4_chain_same "chain deepseek_v4 drafts, chunks of 3, 8 experts" deepseek_v4_tiny_e8 $A "X=1" "COLI_VK_CHAIN_ROWS=3" V4_DRAFT=4 V4_NGRAM_PARTIAL_KEEP=1+ FAULT_BACK=3 v4_chain_gate "chain deepseek_v4 device lost mid-decode" deepseek_v4_tiny_t long+ FAULT_BACK=40 v4_chain_gate "chain deepseek_v4 device lost in the prompt" deepseek_v4_tiny_t long COLI_VK_CHAIN_ROWS=7+ FAULT_BACK=10 v4_chain_gate "chain deepseek_v4 device lost between drafts" deepseek_v4_tiny_w4 $M V4_DRAFT=4 V4_NGRAM_PARTIAL_KEEP=1+ v4_chain_serve deepseek_v4_tiny_t+ V4_CHAIN_MODE=2 v4_chain_serve deepseek_v4_tiny_t+ local t+ for t in test_deepseek_v4_prefix test_deepseek_v4_brio test_deepseek_v4_tiny; do+ COLI_VULKAN=1 COLI_VK_CHAIN=1 COLI_VK_TIER_SYNC=1 COLI_USAGE=$PWD/chain.usage \+ $PY tests/$t.py --binary "$PWD/deepseek_v4" --fixture "$PWD/deepseek_v4_tiny_t" > v4-test.log 2>&1 ||+ { cat v4-test.log; fail "deepseek_v4 $t with the chain"; }+ echo "OK deepseek_v4 $t with the chain: $(tail -1 v4-test.log)"+ done+ rm -rf deepseek_v4_tiny_t deepseek_v4_tiny_e8 deepseek_v4_tiny_g2 deepseek_v4_tiny_w4 deepseek_v4_tiny_ix chain.usage+ rm -f cpu.f32 vk.f32 v4-*.f32 v4-*.json v4-*.err v4-tf.txt v4-test.log+}++# The same under ASan and UBSan (LTO off, as family_deepseek_sanitize builds it): no+# diagnostic, and each run ran the chain (or handled the loss); the serve tests with+# UBSan halting on its first report.+v4_chain_sanitize_runs() {+ local p t+ p=$(v4_chain_prompt deepseek_v4_tiny_t long)+ mk() { v4_chain_prompt x "ids:$1"; }+ v4_chain_san "asan chain deepseek_v4 long, 4 experts" ./deepseek_v4 ./deepseek_v4_tiny_t "$p" --raw-prompt --max-tokens 4 --record-oracle san.json+ v4_chain_san "asan chain deepseek_v4 8 experts, pinned rows16, eviction" COLI_VK_TIER_GB=0.00009 ./deepseek_v4 ./deepseek_v4_tiny_e8 "$p" --raw-prompt --max-tokens 4 --record-oracle san.json+ v4_chain_san "asan chain deepseek_v4 chunks of 3, a window of 4" COLI_VK_CHAIN_ROWS=3 ./deepseek_v4 ./deepseek_v4_tiny_w4 "$(v4_chain_prompt deepseek_v4_tiny_w4 long)" --raw-prompt --max-tokens 4 --record-oracle san.json+ v4_chain_san "asan chain deepseek_v4 2 output groups" ./deepseek_v4 ./deepseek_v4_tiny_g2 "$(v4_chain_prompt deepseek_v4_tiny_g2 long)" --raw-prompt --max-tokens 4+ v4_chain_san "asan chain deepseek_v4 an indexer of 64 heads of 128" ./deepseek_v4 ./deepseek_v4_tiny_ix "$(v4_chain_prompt deepseek_v4_tiny_ix long)" --raw-prompt --max-tokens 4+ v4_chain_san "asan chain deepseek_v4 drafts rejected, chunks of 2" V4_DRAFT=4 V4_NGRAM_PARTIAL_KEEP=1 COLI_VK_CHAIN_ROWS=2 ./deepseek_v4 ./deepseek_v4_tiny_w4 "$(mk 20,21,22,23,50,51,52,20,21,22)" --raw-prompt --max-tokens 12+ v4_chain_san "asan chain deepseek_v4 drafts" V4_DRAFT=4 V4_NGRAM_PARTIAL_KEEP=1 ./deepseek_v4 ./deepseek_v4_tiny_w4 "$(mk 30,31,32,33,34,35,60,61,30,31,32,33,34,35,36,37,38,39,40,41,30,31,32)" --raw-prompt --max-tokens 12+ FAULT_BACK=10 v4_chain_san "asan chain deepseek_v4 device lost" ./deepseek_v4 ./deepseek_v4_tiny_t "$p" --raw-prompt --max-tokens 4+ v4_chain_serve deepseek_v4_tiny_t > san.log 2>&1 || { cat san.log; fail "asan chain deepseek_v4 served"; }+ echo "OK asan chain deepseek_v4 served: $(tail -1 san.log | cut -c1-120)"+ for t in test_deepseek_v4_prefix test_deepseek_v4_brio; do+ UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 COLI_VULKAN=1 COLI_VK_CHAIN=1 COLI_VK_TIER_SYNC=1 $PY tests/$t.py --binary $PWD/deepseek_v4 --fixture $PWD/deepseek_v4_tiny_t > san.log 2>&1 || { cat san.log; fail "asan $t with the chain"; }+ echo "OK asan $t with the chain: $(tail -1 san.log)"+ done+}+v4_chain_family_sanitize() {+ local SAN="-fsanitize=address,undefined -fno-omit-frame-pointer -g"+ make deepseek-v4-clean >/dev/null 2>&1 || true+ make deepseek-v4 VK=1 LTO=0 EXTRA_CFLAGS="$SAN" EXTRA_LDFLAGS="$SAN"+ v4_chain_fixtures+ export ASAN_OPTIONS=detect_leaks=0:detect_stack_use_after_return=0 UBSAN_OPTIONS=print_stacktrace=1+ v4_chain_sanitize_runs+ rm -rf deepseek_v4_tiny_t deepseek_v4_tiny_e8 deepseek_v4_tiny_g2 deepseek_v4_tiny_w4 deepseek_v4_tiny_ix san.json san.log+ make deepseek-v4-clean >/dev/null 2>&1 || true+}++# deepseek_v41 in every configuration the chain takes: the expert cache from one slot+# to all (cap 1, 2, 8), the 8-token and the 40-token prompt (the window ring of 8 and+# the ratio-2 groups roll over many times; the candidate blocks and the published index+# keys of the ratio-1 group), DSpark drafts accepted (1, 3) and rejected (2, 4, 5:+# undo rows on the device's copies), prompts in chunks of 3 and 7 (the device's ring+# wraps), prompts only (decode on the CPU between them), the tier off, the per-matrix+# trunk beside, the tiled GEMM from two rows, the per-row GEMV, V41_INDEX_OWNER, a+# device lost mid-decode, in a prompt and between drafts; serve sessions frame for+# frame (pins, the prompt cache, the prefill read-out, DSpark, prompts only), images+# on the wire, and the engine's own serve tests with the chain on. Then deepseek_v4+# (v4_chain_family above).+family_deepseek_chain() {+ make deepseek_v41 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"+ v41_chain_fixtures+ export OMP_NUM_THREADS=2+ local cap f+ for cap in 1 2 8; do v41_gate "chain deepseek_v41 cap=$cap" SNAP=dsv41_tiny -- $cap dsv41_tiny/ref.json; done+ for cap in 2 8; do v41_gate "chain deepseek_v41 40-token prompt cap=$cap" SNAP=dsv41_long -- $cap dsv41_long/ref.json; done+ for f in 1 2 3 4 5; do v41_gate "chain deepseek_v41 DSpark spec=$f" SNAP=dsv41_tiny V41_DSPARK=1 V41_SPEC_FORCE=$f -- 8 dsv41_tiny/ref.json; done+ v41_gate "chain deepseek_v41 DSpark spec=5, one cache slot" SNAP=dsv41_tiny V41_DSPARK=1 V41_SPEC_FORCE=5 -- 1 dsv41_tiny/ref.json+ v41_gate "chain deepseek_v41 prompt in chunks of 3" SNAP=dsv41_long COLI_VK_CHAIN_ROWS=3 -- 8 dsv41_long/ref.json+ v41_gate "chain deepseek_v41 prompt in chunks of 7" SNAP=dsv41_long COLI_VK_CHAIN_ROWS=7 -- 2 dsv41_long/ref.json+ CHAINMODE=2 v41_gate "chain deepseek_v41 prompts only" SNAP=dsv41_long -- 8 dsv41_long/ref.json+ CHAINMODE=2 v41_gate "chain deepseek_v41 prompts only, DSpark spec=2" SNAP=dsv41_tiny V41_DSPARK=1 V41_SPEC_FORCE=2 -- 8 dsv41_tiny/ref.json+ v41_gate "chain deepseek_v41 tier off" SNAP=dsv41_long COLI_VK_TIER=0 -- 8 dsv41_long/ref.json+ v41_gate "chain deepseek_v41 beside the per-matrix trunk" SNAP=dsv41_long COLI_VK_DENSE=1 -- 8 dsv41_long/ref.json+ v41_gate "chain deepseek_v41 tiled GEMM from 2 rows" SNAP=dsv41_long COLI_VK_GEMM_MIN_S=2 -- 8 dsv41_long/ref.json+ v41_gate "chain deepseek_v41 the per-row GEMV" SNAP=dsv41_tiny COLI_VK_CHAIN_GEMV=0 -- 8 dsv41_tiny/ref.json+ v41_gate "chain deepseek_v41 V41_INDEX_OWNER=1" SNAP=dsv41_long V41_INDEX_OWNER=1 -- 8 dsv41_long/ref.json+ FAULT_BACK=5 v41_gate "chain deepseek_v41 device lost mid-decode" SNAP=dsv41_long -- 8 dsv41_long/ref.json+ FAULT_BACK=100 v41_gate "chain deepseek_v41 device lost in the prompt" SNAP=dsv41_long COLI_VK_CHAIN_ROWS=7 -- 8 dsv41_long/ref.json+ FAULT_BACK=8 v41_gate "chain deepseek_v41 device lost between drafts" SNAP=dsv41_tiny V41_DSPARK=1 V41_SPEC_FORCE=5 -- 8 dsv41_tiny/ref.json+ $PY tests/vulkan_chain_serve.py ./deepseek_v41 dsv41_tiny V41_DSPARK=0+ $PY tests/vulkan_chain_serve.py ./deepseek_v41 dsv41_tiny V41_DSPARK=1+ COLI_VK_CHAIN=2 $PY tests/vulkan_chain_serve.py ./deepseek_v41 dsv41_tiny V41_DSPARK=1 COLI_VK_CHAIN_ROWS=3+ $PY tests/vulkan_chain_v41_image.py ./deepseek_v41 dsv41_tiny V41_DSPARK=0+ COLI_VULKAN=1 COLI_VK_CHAIN=1 COLI_VK_TIER_SYNC=1 COLI_USAGE=$PWD/chain.usage \+ $PY -m unittest tests.test_dsv41_prefix_serve tests.test_dsv41_dspark_serve+ rm -f chain.usage chain-serve.usage chain-image.usage+ v4_chain_family+ unset OMP_NUM_THREADS+}++# The same chain under ASan and UBSan: memory safety is the gate; each run must have run+# the chain (or handled the loss), with the ASAN_OPTIONS of every sanitized family.+family_deepseek_chain_sanitize() {+ local SAN="-fsanitize=address,undefined -fno-omit-frame-pointer -g"+ make clean >/dev/null 2>&1 || true+ make deepseek_v41 tests/test_vk_chain VK=1 EXTRA_CFLAGS="$SAN"+ 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"+ v41_chain_fixtures+ export OMP_NUM_THREADS=2+ dsan() { # <tag> <env and argv...> (FAULT_BACK=k: the loss k frames before the end of a fault-free run)+ local tag=$1; shift+ local fault=()+ if [ -n "${FAULT_BACK:-}" ]; then+ rm -f chain.usage+ env COLI_USAGE=chain.usage COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 COLI_VK_CHAIN=1 "$@" > san.log 2>&1 || true+ local frames; frames=$(sed -n 's/^\[VK\] deepseek_v41 chain: [0-9]* forwards, \([0-9]*\) frames.*/\1/p' san.log | tail -1)+ [ -n "$frames" ] && [ "$frames" -gt "$FAULT_BACK" ] || { cat san.log; fail "$tag: no fault-free run to count frames from"; }+ fault=("COLI_VK_CHAIN_FAULT=$((frames - FAULT_BACK + 1))")+ fi+ rm -f chain.usage+ env COLI_USAGE=chain.usage COLI_VK_TIER_SYNC=1 COLI_VULKAN=1 COLI_VK_CHAIN=1 "${fault[@]}" "$@" > 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 "deepseek_v41 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 deepseek_v41 san.log) chain forwards"+ }+ dsan "asan chain deepseek_v41 40-token prompt" SNAP=dsv41_long ./deepseek_v41 8 dsv41_long/ref.json+ dsan "asan chain deepseek_v41 DSpark spec=5, one cache slot" SNAP=dsv41_tiny V41_DSPARK=1 V41_SPEC_FORCE=5 ./deepseek_v41 1 dsv41_tiny/ref.json+ dsan "asan chain deepseek_v41 prompt in chunks of 3" SNAP=dsv41_long COLI_VK_CHAIN_ROWS=3 ./deepseek_v41 2 dsv41_long/ref.json+ FAULT_BACK=20 dsan "asan chain deepseek_v41 device lost" SNAP=dsv41_long ./deepseek_v41 8 dsv41_long/ref.json+ $PY tests/vulkan_chain_serve.py ./deepseek_v41 dsv41_tiny V41_DSPARK=1 > san.log 2>&1 || { cat san.log; fail "asan chain deepseek_v41 serve"; }+ echo "OK asan chain serve deepseek_v41: $(tail -1 san.log)"+ $PY tests/vulkan_chain_v41_image.py ./deepseek_v41 dsv41_tiny V41_DSPARK=0 > san.log 2>&1 || { cat san.log; fail "asan chain deepseek_v41 images"; }+ echo "OK asan chain images deepseek_v41: $(tail -1 san.log)"+ rm -f chain.usage chain-serve.usage chain-image.usage+ v4_chain_family_sanitize+ unset OMP_NUM_THREADS+ make clean >/dev/null 2>&1 || true+}+case "${1:-}" inshader) shader_formats ;;qwen) family_qwen ;;@@@ -1986,9 -2085,11 +2527,13 @@@glm-sanitize) family_glm_sanitize ;;qwen-chain) family_qwen_chain ;;qwen-chain-sanitize) family_qwen_chain_sanitize ;;+ inkling-olmoe-chain) family_inkling_olmoe_chain ;;+ inkling-olmoe-chain-sanitize) family_inkling_olmoe_chain_sanitize ;;glm-chain) family_glm_chain ;;glm-chain-sanitize) family_glm_chain_sanitize ;;+ kimi-chain) family_kimi_chain ;;+ kimi-chain-sanitize) family_kimi_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|mimo-chain|mimo-chain-sanitize|inkling-olmoe-chain|inkling-olmoe-chain-sanitize|glm-chain|glm-chain-sanitize|kimi-chain|kimi-chain-sanitize" >&2; exit 2 ;;+ deepseek-chain) family_deepseek_chain ;;+ deepseek-chain-sanitize) family_deepseek_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|deepseek-chain|deepseek-chain-sanitize" >&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|mimo-chain|mimo-chain-sanitize|inkling-olmoe-chain|inkling-olmoe-chain-sanitize|glm-chain|glm-chain-sanitize|kimi-chain|kimi-chain-sanitize|deepseek-chain|deepseek-chain-sanitize" >&2; exit 2 ;;esacdiff --cc c/vk_chain.hindex e645800f,d9e9a71f..c30ab8ba--- a/c/vk_chain.h+++ b/c/vk_chain.h@@@ -285,87 -304,35 +304,115 @@@ int vkc_mhc_ready(void)typedef struct { int S, H, D, iters, x_off, x_row, m_off, m_row, hp_off, hp_row, y_off, y_row, prm_off, n;float eps, hc_eps, lim; } VkcMhc;int vkc_mhc(int mode, VkcBuf *x, VkcBuf *m, VkcBuf *hp, VkcBuf *prm, VkcBuf *y, const VkcMhc *p);+ /* Inkling's ops, their pipelines made on first use (an engine checks *_ready at setup:+ * a build without the shader keeps every other op, and that engine's chain off).+ * chain_sconv.comp (mode 0: the depthwise causal short convolution, residual inside, in+ * place, its ring carried; mode 1: x *= fc over n floats; mode 2: x /= fc) */+ typedef struct { int mode, S, C, CK, x_off, x_row, w_off, ring_off, n; float fc; } VkcSconv;+ int vkc_sconv_ready(void);+ int vkc_sconv(VkcBuf *x, VkcBuf *w, VkcBuf *ring, const VkcSconv *p);+ /* chain_relattn.comp: attention with a relative-position bias bank, a per-row scale+ * tau and a sliding window over a ring cache, the step's own rows read from kvs */+ typedef struct { int S, H, KVH, hd, pos_base, cap, window, ext, d_rel;+ int q_off, q_row, o_off, o_row, k_off, v_off, ks_off, vs_off, kv_row;+ int r_off, r_row, relp_off, tau_off; float scale; } VkcRelAttn;+ int vkc_relattn_ready(void);+ int vkc_relattn(VkcBuf *q, VkcBuf *kc, VkcBuf *vc, VkcBuf *o, VkcBuf *kvs, VkcBuf *r, VkcBuf *relp, VkcBuf *tau,+ const VkcRelAttn *p);++ /* ---- attention residuals and SiTU-GLU (chain_ares.comp) ----------------------------+ * Kimi K3's residual stream (AttnRes) and its activation, for S rows:+ * vkc_ares_mix kimi_k3.c's res_mix: row s mixes the nb block snapshots ([nb][D] at+ * b_off + s*b_row) and the running prefix (x_off + s*x_row) by the+ * softmax of (v . w) / sqrt(mean(v^2) + eps), w at w_off in prm, into+ * y_off + s*y_row; nb <= 15, y apart from x and blk+ * vkc_situ y[i] = b1*tanh(g/b1)*sigmoid(g)*b2*tanh(u/b2), i < n, in the CPU's order */+ int vkc_ares_ready(void);+ typedef struct { int S, D, nb, x_off, x_row, b_off, b_row, w_off, y_off, y_row; float eps; } VkcAres;+ int vkc_ares_mix(VkcBuf *x, VkcBuf *blk, VkcBuf *prm, VkcBuf *y, const VkcAres *p);+ typedef struct { int n, g_off, u_off, y_off; float b1, b2; } VkcSitu;+ int vkc_situ(VkcBuf *g, VkcBuf *u, VkcBuf *y, const VkcSitu *p);+/* ---- DeepSeek V4.1 Flash and DeepSeek V4 attention (chain_dsv4.comp) -----------------+ * The model is MQA over one KV row per position (the same row is key and value): a+ * sliding window of raw rows, plus compressed rows (a compressor pools `ratio`+ * positions into one) that a DSA indexer picks per query. Optional like the MLA ops:+ * vkc_dsv4_ready() says whether the shader is there; a missing one turns off these ops.+ * vkc_dsv4_attn sparse attention with a sink over a per-row list (sparse_attn.h):+ * entry e < 0 skipped, e < nwin the window ring's row e, else the+ * compressed row e - nwin; scores (q . k) * scale, the sink in the+ * denominator only, the value sum and the denominator in list order.+ * flags 1: the weights round to bf16 before the value sum and the+ * output to bf16 (DeepSeek V4). Limits: hd <= 1024, cnt <= 3072.+ * vkc_dsv4_rope RoPE on interleaved pairs in place, the first rd floats of each+ * segment, (cos, sin) pairs from a host table; inverse negates the sine+ * (the attention output's un-rotation). flags 1: round to bf16.+ * vkc_dsv4_compress the compressor's rolling group for S rows in order: each row's kv+ * and score rows (P floats; score + ape[slot] when ape_off >= 0) into+ * the ring row pos % ratio (ratio + that with overlap), and at each+ * completed group the per-channel softmax pooling of the ring rows+ * (overlap: the first ratio rows read channel d, the next ratio rows+ * channel D + d; the second half then moves to the first) into+ * out[pos / ratio]. ring: (1 + overlap) * ratio kv rows of P at+ * ring_off, then as many score rows.+ * vkc_dsv4_score the indexer's scores: row s (position pos_base + s) scores columns+ * j < lens = (pos + 1) / ratio (and mask[mask_off + s*mask_row + j] != 0+ * when mask_row > 0) as sum_h [dot > 0] dot * hw_h * wscale, dot = q_h .+ * key[j]; every other j < width scores -inf; into sc[sc_off + s*sc_row+ * + j]. IH <= 4096; IH <= 64 and IH*ID <= 4096 stage the queries in+ * shared memory, larger ones read them from memory (the same sums).+ * vkc_dsv4_cand the candidate blocks: per row, each block's best score, the block of+ * column lens - 1 pinned, then the best min(topb, blocks) blocks (the+ * lower on a tie), mask 1 on their columns. At most 4096 blocks.+ * vkc_dsv4_topk per row the min(topk, finite scores) largest, ties to the lower+ * column, as base + j into the list, ascending (order 0) or by rank+ * (order 1); -1 in the rest of the topk slots. topk <= 4096 for order 1.+ * vkc_dsv4_engram the engram gate: per (stream c, row s) the stream gains+ * sigmoid(signed sqrt(x . (qw * kw * key) * rms(x)^-1 * rms(key)^-1 /+ * sqrt(D))) * value; kv[s] = H keys of D, then the value.+ * Offsets and strides in floats; lists and masks are int32 buffers. */+int vkc_dsv4_ready(void);+typedef struct { int S, H, hd, cnt, l_off, l_row, nwin, w_off, c_off, q_off, q_row, o_off, o_row, sink_off, flags;+ float scale; } VkcDsAttn;+int vkc_dsv4_attn(VkcBuf *q, VkcBuf *win, VkcBuf *cmp, VkcBuf *list, VkcBuf *prm, VkcBuf *out, const VkcDsAttn *p);+typedef struct { int nseg, per_row, rd, x_off, x_row, x_seg, cs_off, cs_row, inverse, flags; } VkcDsRope;+int vkc_dsv4_rope(VkcBuf *x, VkcBuf *cs, const VkcDsRope *p);+typedef struct { int S, pos_base, ratio, P, D, overlap, kv_off, kv_row, sc_off, sc_row, ape_off, out_off, out_row,+ ring_off; } VkcDsComp;+int vkc_dsv4_compress(VkcBuf *kv, VkcBuf *sc, VkcBuf *ring, VkcBuf *prm, VkcBuf *out, const VkcDsComp *p);+typedef struct { int S, pos_base, ratio, IH, ID, width, q_off, q_row, w_off, w_row, k_off, k_row, mask_row, sc_row;+ float wscale; int sc_off, mask_off; } VkcDsScore;+int vkc_dsv4_score(VkcBuf *iq, VkcBuf *hw, VkcBuf *keys, VkcBuf *mask, VkcBuf *sc, const VkcDsScore *p);+typedef struct { int S, pos_base, ratio, width, block, topb, sc_row, mask_row; } VkcDsCand;+int vkc_dsv4_cand(VkcBuf *sc, VkcBuf *mask, const VkcDsCand *p);+typedef struct { int S, width, topk, sc_row, l_off, l_row, base, order; } VkcDsTopk;+int vkc_dsv4_topk(VkcBuf *sc, VkcBuf *list, const VkcDsTopk *p);+typedef struct { int S, H, D, kv_off, kv_row, x_off, x_row, qw_off, kw_off; float eps; } VkcDsEngram;+int vkc_dsv4_engram(VkcBuf *kv, VkcBuf *prm, VkcBuf *x, const VkcDsEngram *p);+/* DeepSeek V4's roundings, each the engine's C bit for bit (chain_dsv4.comp modes 7, 8):+ * vkc_dsv4_round nseg segments of len floats (segment g at row g / per_row, index+ * g % per_row: x_off + row*x_row + j*x_seg, y likewise) from x into y+ * (y may be x: in place), as `kind`:+ * VKC_DS_BF16 to bf16, nearest even (coli_bf16_round)+ * VKC_DS_E4M3 E4M3 per block of `block` values with one+ * power-of-two scale (coli_fp8_activation_qdq_ref)+ * VKC_DS_E2M1 E2M1 per block (coli_fp4_activation_qdq_ref)+ * VKC_DS_HADAMARD the Hadamard transform times hscale (the host's+ * 1 / sqrtf(len)), to bf16 (coli_hadamard_bf16_ref)+ * flags 1: the E4M3 or E2M1 result to bf16 after. Limits: block <= 256;+ * the Hadamard's len a power of two up to 4096.+ * vkc_dsv4_swiglu y[y_off + i] = bf16(g * sigmoid(g) * u), g = bf16(a[a_off + i]) and+ * u = bf16(b[b_off + i]) clamped by lim when lim > 0, i < n (the shared+ * expert's activation between its roundings; coli_v4_swiglu). */+#define VKC_DS_BF16 0+#define VKC_DS_E4M3 1+#define VKC_DS_E2M1 2+#define VKC_DS_HADAMARD 3+typedef struct { int kind, nseg, per_row, len, block, flags, x_off, x_row, x_seg, y_off, y_row, y_seg; float hscale; } VkcDsRound;+int vkc_dsv4_round(VkcBuf *x, VkcBuf *y, const VkcDsRound *p);+typedef struct { int n, a_off, b_off, y_off; float lim; } VkcDsSwiglu;+int vkc_dsv4_swiglu(VkcBuf *a, VkcBuf *b, VkcBuf *y, const VkcDsSwiglu *p);+/* counters, for the engines' [VK] lines */typedef struct {unsigned long long frames, waits, ops, matmuls, gemms, barriers, bytes_up, bytes_down;diff --cc docs/ENVIRONMENT.mdindex 871ecb49,d4c2de31..c6e2f91a--- a/docs/ENVIRONMENT.md+++ b/docs/ENVIRONMENT.md@@@ -245,13 -245,13 +245,13 @@@ With `COLI_VULKAN=1` every MoE engine (| `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, colibri, glm53, deepseek_v41 and deepseek_v4 off on an integrated GPU with the tier; off on a CPU device | qwen36, qwen38, colibri (GLM-5.2), glm53 (GLM-5.3 Flash), deepseek_v41 (DeepSeek V4.1 Flash) and deepseek_v4: 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 and olmoe on, qwen38 off, and mimo, inkling, colibri, glm53 and kimi_k3 off (not measured) on an integrated GPU with the tier; off on a CPU device | qwen36, qwen38, olmoe, inkling, mimo, colibri (GLM-5.2), glm53 (GLM-5.3 Flash) and kimi_k3: 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 and olmoe on, qwen38 off, and mimo, inkling, colibri, glm53, kimi_k3, deepseek_v41 and deepseek_v4 off (not measured) on an integrated GPU with the tier; off on a CPU device | qwen36, qwen38, olmoe, inkling, mimo, colibri (GLM-5.2), glm53 (GLM-5.3 Flash), kimi_k3, deepseek_v41 (DeepSeek V4.1 Flash) and deepseek_v4: 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 (colibri and the DeepSeek engines have none to rebuild) and runs there. |-| `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 and runs there (colibri and mimo have none to rebuild: the CPU continues from its host caches). |-| `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). |++| `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 and runs there (colibri, mimo and the DeepSeek engines have none to rebuild: the CPU continues from its host caches). |+| `DUMP` | unset | colibri, glm53, deepseek_v41 and deepseek_v4 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 --cc docs/vulkan.mdindex 56ee4473,3d370e2a..c0e78f21--- a/docs/vulkan.md+++ b/docs/vulkan.md@@@ -673,9 -673,9 +673,10 @@@ command buffer instead, and keeps the rto the next. qwen36 (Qwen3.6, Qwen3-Coder, Qwen3.8-27B) and qwen38 (Qwen3.8 FlashNext) run it: by default on a discrete GPU, and for qwen36 on an integrated one withthe expert tier (see [the default](#the-chain-on-a-radeon-780m)); `COLI_VK_CHAIN=1`- anywhere. colibri (GLM-5.2) and glm53 (GLM-5.3 Flash) run it too, with the MLA,+ anywhere. olmoe and inkling run it as well ([OLMoE and Inkling](#olmoe-and-inkling)).+ colibri (GLM-5.2), glm53 (GLM-5.3 Flash) and kimi_k3 run it too, with the MLA,-KDA and hyper-connection ops ([below](#glm-52-and-glm-53-flash-on-the-chain)).+KDA and hyper-connection ops ([below](#glm-52-and-glm-53-flash-on-the-chain)), and+deepseek_v41 and deepseek_v4 with DeepSeek's own ([below](#deepseek-v41-flash-and-deepseek-v4-on-the-chain)).**What runs where, per layer** (S rows: one at decode, a prompt chunk at prefill):@@@ -742,7 -742,7 +743,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; colibri, glm53, deepseek_v41 and deepseek_v4 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` | on for a discrete GPU; on an integrated GPU with the expert tier, what the engine measured (qwen36 and olmoe on, qwen38 off; mimo, inkling, colibri, glm53 and kimi_k3 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` | on for a discrete GPU; on an integrated GPU with the expert tier, what the engine measured (qwen36 and olmoe on, qwen38 off; mimo, inkling, colibri, glm53, kimi_k3, deepseek_v41 and deepseek_v4 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. |@@@ -888,146 -1078,88 +1079,229 @@@ the tiny fixtures, on Lavapipe and on t[VK] colibri: dense chain off (an integrated GPU with the expert tier: not measured; COLI_VK_CHAIN=0 off, 1 on, 2 prompts only)```+### DeepSeek V4.1 Flash and DeepSeek V4 on the chain++`deepseek_v41_chain.h` (deepseek_v41) follows the recipe below with the+[DeepSeek ops](#deepseek-v41-flash-and-deepseek-v4s-attention-vkc_dsv4), the mHC ops and+the per-head blocks of `vkc_mla_hgemv`. The residual is `hc_mult` streams per position,+and V4.1 collapses a site with the mix the site before it computed. What runs where, per+layer:++| | deepseek_v41 (DeepSeek V4.1 Flash) |+|---|---|+| device, frame A1 | the previous layer's FFN branch (the routed sum plus the shared expert) written back into the streams; on an engram layer the engram (`eng_wkv` over the n-gram rows the host looked up, the gate into each stream); on a DSpark target layer the streams' mean for the draft head; the attention site's mix, split with Sinkhorn, collapse and norm; the attention: `wq_a`, its norm, `wq_b`, `wkv`, its norm, RoPE on interleaved pairs, the new rows into the window ring; on a kv_source layer the compressor's rolling group, the pooled latent's norm, the index keys and the compressed rows' RoPE; on an index source the indexer (its queries and RoPE, `weights_proj`, the scores against the keys the CPU would read, the candidate blocks, the top-k); the sparse attention with the sink over the window and the selection, the inverse RoPE, the grouped `wo_a`, `wo_b`; the write back; the FFN site's mix, collapse and norm |+| host | `moe_run_at` without the shared expert: the router and the routed experts (the tier's batch and the CPU's share); an engram layer's n-gram rows are looked up (on disk) as its frame is recorded |+| device, frame A2 (not waited for) | the shared expert (clamped SwiGLU) |+| after the last layer | the final streams and the last site's mix back to the host, which collapses them and runs the final norm and the head as before |++**The state.** The host's stays canonical. What a forward changes there, the window ring+and its position map, the compressed rows and index keys, the compressor's group and the+published index keys, is written back once the forward's last frame is through, exactly+as the CPU would have left it, a speculative verify's undo rows included. The device+mirrors the window ring (window + chunk rows, so a chunk never overwrites a row one of+its earlier rows still reads) behind a watermark, each kv_source layer's compressed rows+and index keys behind one of their own (grown in powers of two), and takes the+compressor's group up at every forward. Every host write lowers the watermarks: a CPU+forward, a rejected draft, a reset. The index keys each layer scores follow the engine's+published-key rule (the released behaviour; per row on a verify) and `V41_INDEX_OWNER=1`.++**Drafts.** DSpark's stages stay on the CPU and read the host's window rings and the+chain's means; a verify's rows go through the chain (its matrices on the per-row GEMV,+so each row gets a decode step's bits), a rejection is the host's rollback and the+watermarks follow.++**A lost device.** The forward that failed runs again on the CPU from its input (the+chain leaves it, and the host's state, untouched until every chunk is through), and the+CPU runs from there. There is nothing to rebuild.++**Declined** (the CPU runs the layers, the watermarks follow): `V41_TRACE`, prompts only+when the forward has two rows or fewer, and a model the ops or the chain do not take: a+head above 1024 floats, a window plus top-k above 3072 entries, an indexer above 64 heads+or 4096 query floats, more than 8 streams, a compressed layer reading the index list of+another ratio (or of none), a candidate mask read across ratios.++**Arithmetic.** V4.1's CPU multiplies f32 activations everywhere, so the chain does the+same arithmetic in another order. On the fixtures every configuration gives the CPU's+tokens, and every logits row is within 1e-6 of the largest logit: 9.3e-7 at worst on+Lavapipe, 1.1e-6 on a Radeon 780M (RADV) and 1.0e-6 on an Intel Iris Xe (Mesa's Dozen,+four configurations).++**The default**: `COLI_VK_CHAIN_UNMEASURED`, so the chain 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 DeepSeek checkpoint was run on the chain: none is on the 780M box, and+V4.1 Flash is 510 GB. Speed is not measured; the tests prove the tokens on the tiny+fixtures, on Lavapipe, the 780M and the Iris Xe:++```+[VK] deepseek_v41: dense chain off (an integrated GPU with the expert tier: not measured; COLI_VK_CHAIN=0 off, 1 on, 2 prompts only)+```++### DeepSeek V4 on the chain++`deepseek_v4_chain.h` runs DeepSeek V4's layers on the dense chain (`make deepseek-v4+VK=1`, `COLI_VK_CHAIN=1`), every forward the engine makes: prompts, decode steps, the+verify of a draft, the teacher-forced pass of `--record-oracle`, serve turns. What runs+where, per layer:++| | deepseek_v4 |+|---|---|+| device, frame A1 | the previous layer's FFN branch (the routed sum from the host plus the shared expert, to bf16) written back into the hc_mult streams; the attention site (hc_attn_fn, the split with Sinkhorn, the collapse with the site's own pre, bf16, the norm, bf16); the attention: the input to E4M3, wq_a, q_norm; on a compressed layer the compressor (wkv and wgate in bf16 on the f32 input, the ring with its position bias, the pooled rows' norm, RoPE at the group's first position with YaRN's table, the no-position part to E4M3 per 64); on a ratio-4 layer the indexer (its own compressor into the keys with the Hadamard transform and E2M1 per 32; the queries from the q latent, RoPE, Hadamard, E2M1; weights_proj; the scores and the top-k in score order); wq_b and the per-head RMS without weight, wkv and kv_norm, RoPE, the key's no-position part to E4M3 per 64, the new rows into the window ring; the sparse attention with the sink over the window and the compressed rows (V4's bf16 weights and output), the inverse RoPE, wo_a per group, wo_b; mHC's exit; the FFN site; every bf16 and E4M3 rounding where the CPU makes it |+| host | the router (bf16, or the hash router on the token ids) and the routed experts: the expert tier's batch and the CPU's share, summed in the CPU block's order (ascending expert, then rank) |+| device, frame A2 (not waited for) | the shared expert: the input to E4M3, w1 and w3, V4's SwiGLU between bf16 roundings, the input to E4M3, w2, bf16 |+| after the last layer | the streams back to the host, which runs the final collapse, the norm and the head as before (and DSpark's taps of the last three layers) |++The matrices are the per-matrix path's device copies, found in the same map (fp8 as+fmt 12, bf16 as fmt 11), and the mHC mixes in f32 (fmt 10), which only the chain+multiplies. Every matrix takes the per-row GEMV, never the tiled GEMM: a row's bits then+do not depend on how a forward is cut into chunks, nor on whether the row is a prompt+row, a decode step or a verify row, which is what the CPU gives (its batched and+per-token kernels agree bit for bit), and what makes a reused prefix give the bits of a+cold prefill. A prompt's matrices are slower for it than they could be.++Four roundings are ops of their own, `vkc_dsv4_round` (bf16 over segments; E4M3 per+block, the scale the smallest power of two that brings the block's maximum under 448;+E2M1 per block, the scale the smallest that brings it under 6; the Hadamard transform+with its bf16), each the engine's C bit for bit, and `vkc_dsv4_swiglu`. The indexer's+scores past 4096 query floats (V4's 64 heads of 128) read the queries from memory instead+of staging them, the same sums.++**The state.** The host's stays canonical. What a forward changes there (the window ring,+the compressed rows and their count, each compressor's ring, the indexer's keys and count+and its compressor's ring) is written back once the forward's last frame is through, as+the CPU would have left it. The device mirrors it: the window ring (window + chunk rows)+behind a watermark, with the position each row holds, so a row a rejected draft longer+than a chunk overwrote goes up again; the compressed rows and the index keys of each layer+behind watermarks of their own; each compressor's ring behind a flag. Every host write+lowers them: a CPU forward, a restored snapshot (a rejected draft), a reset, a prefix+checkpoint or a pin restored, another attention state, a forward that does not start+where the last one ended.++**Drafts.** n-gram drafts (`V4_DRAFT`) verify through the chain and replay the accepted+rows through it after a rejection. The full DSpark drafter (three MTP stages) stays on the+CPU, reading the taps of the target's last three layers that the chain copies back; the+tiny fixture has one MTP layer, so that path ran target-only in every test here.++**A lost device.** The forward that failed runs again on the CPU from its input (the chain+leaves the host's state and the caller's rows untouched until the last frame), and the CPU+runs from there: nothing to rebuild.++**Declined** (the CPU path runs, the device's copies follow): no resident dense layers (a+low-memory plan reloads them per forward, and the `--oracle` path's own copies), the CUDA+tier, prompts only (`COLI_VK_CHAIN=2`) for forwards of two rows or fewer, a forward whose+attention list (the window plus every compressed row of a layer without an indexer) would+pass 3072 entries (from there on in that session), and geometries past the shaders (head+dim above 1024, an indexer head that is not a power of two or above 4096, a top-k above+4096, more than 8 streams).++**Arithmetic.** The device sums in other orders than the CPU (the GEMV, the norms' and+mHC's reductions) and its exp and sqrt are not glibc's, so an intermediate value now and+then lands on the other side of a bf16 rounding. V4 then amplifies it: the next E4M3+rounding of a block that holds that value can move a whole step (one part in 8 to 16),+and the indexer's top-k can pick another compressed row. Measured on Lavapipe: given the+same input, a layer on the chain gives the CPU's output bit for bit apart from such+single-value flips (checked by feeding the CPU the chain's layer output); on the fixtures+51 to 100% of the logits rows are bit-identical to the CPU's, and the worst row moves by+up to 0.32 of its largest logit (the 2-output-group fixture's 72-token case, after one+flipped norm value at layer 0 moved a key row by an E4M3 step); in one of 1,500+teacher-forced positions the argmax moved, never in a generated stream. So the gates+are: the CPU's generated tokens exactly (and the reference's), every logits row within+0.5 of its largest |logit|, and two checks no driver can blur: the chain against itself+(chunks of 1, 2, 3 or the default, prefill chunks of 3, the tier off, drafts rejected and+accepted give the same bits) and each decode row equal to the teacher-forced row at its+position. A stale row in the device's ring after a rejected draft (a bug found while+writing this) moved the logits by 0.39 to 0.53 of the largest, inside what a+rounding flip can do, and failed the self-consistency check at once.++**The default.** `COLI_VK_CHAIN_UNMEASURED`: off on an integrated GPU (`COLI_VK_CHAIN=1`+turns it on, `2` for prompts only), on a discrete GPU the rule above. No DeepSeek V4+checkpoint was run (the 780M box has none; the model is far past its disk), so speed is+not measured; the tests prove the tokens on the tiny fixtures.++```+[VK] deepseek_v4: dense chain off (an integrated GPU with the expert tier: not measured; COLI_VK_CHAIN=0 off, 1 on, 2 prompts only)+++ ### Kimi K3 on the chain++ `kimi_k3_chain.h` (kimi_k3) follows the recipe below with the+ [MLA ops](#multi-head-latent-attention-on-the-chain-vkc_mla), GLM-5.3's KDA ops and three+ of its own. Kimi K3's residual is AttnRes: per row a running prefix and a snapshot every+ `attn_res_block_size` layers, mixed by a softmax before the attention and before the MLP+ of every layer and once at the end. What runs where, per layer:++ | | kimi_k3 |+ |---|---|+ | device, frame A1 | the previous layer's MoE output joining the prefix (the routed sum's RMSNorm and latent up-projection, plus the shared experts, then the add: `moe_forward`'s order); the attention site's residual mix and a block boundary's snapshot; the input RMSNorm; a KDA layer (q, k, v, the full-rank output gate, the decay's two f32 matrices and beta's; the short convolution with its window, the delta rule with its state, the output norm and gate, o_proj) or a gated MLA layer (q_a, its norm, q_b, kv_a, the latent norm, the new rows into the cache; the absorbed core over the cache, the values times the sigmoid gate, o_proj); the prefix update; the MLP site's residual mix and post-attention norm; a dense layer's SiTU-GLU MLP and its add (no host step), or the f32 router's logits and the latent down-projection |+ | host | the router (sigmoid, the top-k with the correction bias, `K3_TOPP`) and the routed experts in the latent: the tier's batch and the CPU's share, added in the union's order; the new MLA rows copied into the host's cache |+ | device, frame A2 (not waited for) | the shared experts (SiTU-GLU at full width) |+ | after the last layer | the output residual mix and the final RMSNorm of every row, lm_head on the last; the normalized rows come back when the host wants the logits of every row (`K3_LOGITS`, `K3_VAL_LOGITS`, a logprobs request) and the host runs lm_head on them |++ Kimi K3's MLA is NoPE: the qk_rope parts of the query and of the shared key are used as+ the projections leave them. `vkc_mla_qkv` rotates them by angle 0 (a table of cos 1 and+ sin 0), which in float is the identity.++ | Op | Shader | What it does |+ |---|---|---|+ | `vkc_ares_mix` | `chain_ares` (mode 0) | `res_mix`: per row, the softmax of `(v . w) / sqrt(mean(v^2) + eps)` over the block snapshots and the prefix, and their weighted sum, in snapshot order (up to 15 snapshots) |+ | `vkc_situ` | `chain_ares` (mode 1) | SiTU-GLU, `b1*tanh(g/b1)*sigmoid(g)*b2*tanh(u/b2)`, in the CPU's order |+ | `vkc_kda_rec_flags` | `chain_kda` | the KDA recurrence with Kimi K3's two differences from GLM-5.3: the decay's `exp(A_log)` given as the engine keeps it (`VKC_KDA_EXP_A`), and `kda_forward`'s order of the l2 norms (the eps after the squares, q normalized, then scaled) and of the update, `k * ((v - mem) * beta)` (`VKC_KDA_K3`). `vkc_kda_rec` is the same op with no flags, unchanged for glm53 |++ `make vk-chain-check VK=1` runs Kimi K3's KDA layer against `kda_forward`'s arithmetic+ over two submissions (the state and the window carried, inputs small enough that the+ l2 eps counts), `res_mix` over 0 to 15 snapshots at row strides (D up to 7168) and+ SiTU-GLU at Kimi K3's constants. The KDA layer within 3.8e-7 of its largest output on+ Lavapipe, 5.0e-7 on the Radeon 780M and 5.4e-7 on the Iris Xe (Dozen); the residual mix+ within 2.4e-7, 3.3e-7 and 3.3e-7; SiTU-GLU within the test's 1e-6 on all three.++ **The state.** The MLA caches (`Lc`, the normalized latent, and `Rc`, the qk_rope part)+ stay the host's: each step copies its new rows back, and the device mirror has a+ watermark per layer that a CPU forward, a reset and a grown cache (`kv_alloc`) lower.+ The KDA state and the three convolution windows of every KDA layer stay on the device+ while the chain runs (96 heads of 128 x 128 floats and three windows of 12288 x 4: 6.9+ MB a layer on the full model): the host's copy is brought back before a recurrent-state+ checkpoint (`COLI_K3_CKPT`, a `pin=1` photo) or a CPU forward reads it, and goes up+ after a reset (a fill with zeros on the device) or a restored photo. Prefix reuse needs+ nothing more: the reused positions are rows below the watermark and a KDA state that+ already sits where the next step expects it.++ **Drafts.** kimi_k3 has no MTP head and no draft path.++ **A lost device.** The forward that failed runs again on the CPU from its input rows+ (the chain never writes them). If the device held the newest KDA state, that state is+ rebuilt on the CPU first: from the host's copy, current at the position where it last+ went up or came back, through the prefix record's ids up to where the device was, a+ prefill's worth of CPU work; from zeros if the loss interrupted a copy of the state to+ the host after part of it had landed. The CPU runs from there. (Both rebuilds were+ checked on the 780M, where that copy takes frames, by faults placed inside it: a serve+ session with checkpoints gave the CPU's frames either way.)++ **Declined** (the CPU path runs, the state synced first): the CUDA expert tier,+ `KIMI_DSA_INDEXER=1` (its index cache is filled on the CPU), the validation dumps that+ read every layer on the host (`K3_TRACE`, `K3_VALIDATE_LAYER`, `K3_DEBUG_OUT`), a model+ without its head (`K3_LAYERS`), a Segment's layer range, and geometries past the ops'+ limits (a KDA head above 128 floats, a convolution above 8 taps, `kv_lora` above 1024,+ `qk_rope` above 128 or odd). The chain's tensors are its own except the shared experts'+ under `COLI_VK_DENSE`, which it shares with the per-matrix path: a forward the chain+ declines (`COLI_VK_CHAIN=2`'s decode) runs on the CPU as before.++ **Arithmetic.** f32 activations, as the CPU's dense kernels (int8 rows and int4-g64+ alike); the routed experts are the tier's or the CPU's, as without the chain. The tiny+ fixture amplifies rounding at a few positions: the CPU against itself, with only its+ RMSNorm's sum taken in float instead of double, moves the logits by up to 1.4e-4 of the+ largest one on the f32 trunk and 1.0e-3 on the 8-bit one, and the served logprobs by up+ to 4.1e-3, at the positions where the chain moves them most (Lavapipe: 1.8e-4, 4.5e-4+ and 6.1e-3; the 780M: 2.3e-4, 9.9e-4 and 3.3e-3). The tests hold every logits row within+ 2e-3 of the largest and the logprobs within 2e-2; the tokens are the CPU's in every+ configuration. With the CPU's int8 expert activations (`K3_IDOT=1`, tier off) a flipped+ int8 step moved the logits by 8.3e-3 on Lavapipe (no step flipped on the 780M), the+ tokens unchanged; that configuration is gated on its tokens.++ **The default**: kimi_k3 passes `COLI_VK_CHAIN_UNMEASURED`: off on an integrated GPU+ (`COLI_VK_CHAIN=1` turns it on, `2` for prompts only), on a discrete GPU the rule above.+ No Kimi K3 checkpoint was run (1.56 TB; the 780M box has none): speed is not measured,+ and the tests prove the tokens on the tiny fixture, on Lavapipe and on the 780M:++ ```+ [VK] kimi_k3: dense chain off (an integrated GPU with the expert tier: not measured; COLI_VK_CHAIN=0 off, 1 on, 2 prompts only)```### Adding an engine to the chain@@@ -1058,13 -1190,12 +1332,12 @@@ What each remaining architecture needs| Engine | Attention / mixer | New pieces ||---|---|---|- | 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_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 |+| deepseek_v41 | MQA over a window ring and compressed rows, a sink, an indexer with candidate blocks | on the chain ([above](#deepseek-v41-flash-and-deepseek-v4-on-the-chain)), with the [DeepSeek ops](#deepseek-v41-flash-and-deepseek-v4s-attention-vkc_dsv4) |+| deepseek_v4 | MQA over a window ring and compressed (CSA, HCA) rows, mHC, bf16 and E4M3 roundings | on the chain ([above](#deepseek-v4-on-the-chain)), with the DeepSeek ops and their rounding modes |- | 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 |+ | kimi_k3 (KDA layers) | Kimi Delta Attention: a gated delta rule whose decay is a vector over the key channels | on the chain ([above](#kimi-k3-on-the-chain)): `vkc_kda_conv` and `vkc_kda_rec_flags` with Kimi K3's options; its full-rank output gate and low-rank decay are matmuls before the op |+ | mimo | sliding-window attention (and full layers) | done: [MiMo-V2.6 on the chain](#mimo-v26-on-the-chain) (`chain_attn.comp` with a window, a ring of W rows, V's own head dim and a sink) |+ | inkling | grouped attention with a relative-position bias, a sliding window and short convolutions; MoE with shared experts | in the chain ([OLMoE and Inkling](#olmoe-and-inkling)): two shaders of its own, `chain_relattn.comp` and `chain_sconv.comp`; the shared experts join through `HC_APPLY` |+ | olmoe | attention with q/k norm, MoE without a shared expert | in the chain ([OLMoE and Inkling](#olmoe-and-inkling)) with qwen36's ops as they are |### Multi-head latent attention on the chain (`vkc_mla`)