Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
vulkan: DeepSeek V4.1 and V4's attention on the chain
JustVuggd61fd94724d6
diff --git a/c/Makefile b/c/Makefileindex a60020f5..6b65660b 100644--- a/c/Makefile+++ b/c/Makefile@@ -721,6 +721,8 @@ VK_SPV += shaders/chain_norm.spv shaders/chain_rope.spv shaders/chain_attn.spvVK_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.spvendif# Optional AMD XDNA2 (Ryzen AI NPU) lane, Windows. Same opt-in shape as VK=1:diff --git a/c/shaders/chain_dsv4.comp b/c/shaders/chain_dsv4.compnew file mode 100644index 00000000..1e210b19--- /dev/null+++ b/c/shaders/chain_dsv4.comp@@ -0,0 +1,406 @@+#version 450+// DeepSeek V4.1 Flash's (and DeepSeek V4's) attention on the dense chain (vk_chain.c,+// chain_dsv4; vk_chain.h: vkc_dsv4_*). The model is MQA over one KV row per position:+// a sliding window of raw rows plus compressed rows a DSA indexer picks. Seven modes:+//+// mode 0, sparse attention with a sink (sparse_attn.h, coli_sparse_attend): one+// workgroup per (head h, row s). The row's list is list[l_off + s*l_row + j], j < cnt:+// an entry e < 0 is skipped, e < nwin reads the window ring's row e (win at w_off ++// e*hd), any other the compressed row e - nwin (cmp at c_off + ...). Per entry+// score = (q . k) * scale (the dot in the CPU scalar path's order), best = the largest+// score (-1e30 when none), w = exp(score - best), denom = exp(sink[h] - best) + the w in+// list order, out = (sum of w * k in list order) / denom. A row with no entry gives 0.+// flags 1 (DeepSeek V4): w rounds to bf16 before the value sum (the denominator keeps it+// whole), and the output rounds to bf16.+// mode 1, RoPE on interleaved pairs in place (deepseek_v41.c rope_apply): segment g at+// x_off + row*x_row + j*x_seg (row = g / per_row, j = g % per_row), its first rd floats;+// pair i: a = x[2i], b = x[2i+1], (cos, sin) = cs[cs_off + row*cs_row + 2i, +1], the+// sine negated when inverse; x[2i] = a*cos - b*sin, x[2i+1] = a*sin + b*cos. flags 1:+// both round to bf16 after (DeepSeek V4).+// mode 2, the compressor's rolling group (model.py Compressor, its decode form, which a+// prefill reproduces): one workgroup; the S rows in order, row s at position pos =+// pos_base + s writes its kv and score rows (P floats each; score + ape[slot] when+// ape_off >= 0) into ring row slot = pos % ratio (ratio + slot when overlap), and when+// (pos + 1) % ratio == 0 pools channel d < D over the ring rows (with overlap, the+// first ratio rows read column d and the next ratio rows column D + d):+// best = max score, out[pos / ratio][d] = sum(exp(score - best) * kv) / sum(exp(...)),+// the sums in ring-row order; with overlap the second half of the ring then moves to+// the first. The ring: kv rows at ring_off, score rows after them ((1+overlap)*ratio+// rows of P each).+// mode 3, the indexer's scores (deepseek_v41.c indexer_run): one workgroup per row s,+// position pos = pos_base + s, lens = (pos + 1) / ratio. For j < width: j < lens (and+// mask[mask_off + s*mask_row + j] != 0 when mask_row > 0) scores sum_h [dot > 0] dot *+// w_h, dot = q_h . key[j] (k_off + j*k_row), w_h = hw[w_off + s*w_row + h] * wscale; any+// other j scores -inf. Into sc[sc_off + s*sc_row + j]. Limits: IH <= 64, IH*ID <= 4096.+// mode 4, the candidate blocks (model.py select_candidate_blocks): one workgroup per row+// s: the best score of each block of `block` columns of the row's first `width`, the+// block holding column lens - 1 pinned (+inf), then min(topb, blocks) times the best+// block above -inf (the lower block on a tie), each kept whole: mask[s*mask_row + j] =+// 1 for its columns, 0 elsewhere. Limit: 4096 blocks.+// mode 5, the top-k: one workgroup per row s: keep = min(topk, the scores above -inf);+// the keep largest, ties to the lower column (the CPU's selection), written as base + j+// to list[l_off + s*l_row + k], k < keep, in ascending column order (order 0) or by+// rank, score then column (order 1); -1 in the slots after them up to topk. The+// threshold is found by bisection on order-keeping integer keys (-0 counts as +0).+// mode 6, the engram gate (deepseek_v41.c engram_run): one workgroup per (stream c, row+// s): x = the stream (x_off + s*x_row + c*D), key = kv[s][c*D..], value = kv[s][H*D..];+// r = 1/sqrt(mean(x^2) + eps) * 1/sqrt(mean(key^2) + eps), t = sum(x * qw * kw * key)+// * r / sqrt(D), g = sigmoid(sign(t) * sqrt(max(|t|, 1e-6))); x += g * value.+// Offsets and strides in floats (ints for lists and masks).+#extension GL_KHR_shader_subgroup_basic : enable+layout(local_size_x = 256) in;++layout(std430, binding = 0) readonly buffer B0 { float b0[]; }; // q, kv rows, iq, scores, engram kv+layout(std430, binding = 1) readonly buffer B1 { float b1[]; }; // window ring, score rows, hw, prm+layout(std430, binding = 2) readonly buffer B2 { float b2[]; }; // compressed rows, index keys+layout(std430, binding = 3) readonly buffer L3 { int l3[]; }; // attention list, score mask+layout(std430, binding = 4) readonly buffer B4 { float b4[]; }; // sinks, ape, cos/sin+layout(std430, binding = 5) buffer Y5 { float y5[]; }; // outputs (in place for 1, 6)+layout(std430, binding = 6) buffer I6 { int i6[]; }; // top-k list, candidate mask+layout(std430, binding = 7) buffer R7 { float r7[]; }; // the compressor's ring++layout(push_constant) uniform P { int v[32]; } p;+#define MODE p.v[0]++shared float sm[4160];+shared float red[256];+shared uint cnt[256];++#define NEG_INF uintBitsToFloat(0xff800000u)+#define POS_INF uintBitsToFloat(0x7f800000u)++float bf16r(float f) { // round to nearest even, as coli_bf16_round+ uint u = floatBitsToUint(f);+ if ((u & 0x7f800000u) != 0x7f800000u) u += 0x7fffu + ((u >> 16) & 1u);+ return uintBitsToFloat(u & 0xffff0000u);+}+float sig(float v) {+ if (v >= 0.0) { float d = exp(-v); return 1.0 / (1.0 + d); }+ float g = exp(v);+ return g / (1.0 + g);+}+uint okey(float f) {+ uint u = floatBitsToUint(f);+ if (u == 0x80000000u) u = 0u;+ return (u & 0x80000000u) != 0u ? ~u : (u | 0x80000000u);+}+uint wsum(uint v, int tid) {+ cnt[tid] = v;+ barrier();+ for (int off = 128; off > 0; off >>= 1) {+ if (tid < off) cnt[tid] += cnt[tid + off];+ barrier();+ }+ uint t = cnt[0];+ barrier();+ return t;+}+uint wscan(uint v, int tid) { // exclusive, in thread order+ cnt[tid] = v;+ barrier();+ for (int off = 1; off < 256; off <<= 1) {+ uint a = tid >= off ? cnt[tid - off] : 0u;+ barrier();+ cnt[tid] += a;+ barrier();+ }+ uint incl = cnt[tid];+ barrier();+ return incl - v;+}++// ---- mode 0 ------------------------------------------------------------------------+void attend() {+ int h = int(gl_WorkGroupID.x), s = int(gl_WorkGroupID.y), tid = int(gl_LocalInvocationID.x);+ int S = p.v[1], H = p.v[2], hd = p.v[3], n = p.v[4];+ if (s >= S || h >= H) return;+ int lb = p.v[5] + s * p.v[6], nwin = p.v[7], woff = p.v[8], coff = p.v[9];+ int qb = p.v[10] + s * p.v[11] + h * hd, ob = p.v[12] + s * p.v[13] + h * hd;+ float sink = b4[p.v[14] + h];+ int flags = p.v[15];+ float scale = intBitsToFloat(p.v[16]);+ for (int i = tid; i < hd; i += 256) sm[i] = b0[qb + i];+ barrier();+ float best = -1.0e30;+ for (int j = tid; j < n; j += 256) {+ int e = l3[lb + j];+ float sc = NEG_INF;+ if (e >= 0) {+ float d = 0.0;+ if (e < nwin) { int kb = woff + e * hd; for (int i = 0; i < hd; i++) d += sm[i] * b1[kb + i]; }+ else { int kb = coff + (e - nwin) * hd; for (int i = 0; i < hd; i++) d += sm[i] * b2[kb + i]; }+ sc = d * scale;+ if (sc > best) best = sc;+ }+ sm[1024 + j] = sc;+ }+ red[tid] = best;+ barrier();+ for (int off = 128; off > 0; off >>= 1) {+ if (tid < off && red[tid + off] > red[tid]) red[tid] = red[tid + off];+ barrier();+ }+ best = red[0];+ barrier();+ for (int j = tid; j < n; j += 256) {+ float sc = sm[1024 + j];+ sm[1024 + j] = sc > NEG_INF ? exp(sc - best) : 0.0;+ }+ barrier();+ if (tid == 0) { // the denominator in list order, from the sink+ float den = exp(sink - best);+ for (int j = 0; j < n; j++) if (l3[lb + j] >= 0) den += sm[1024 + j];+ red[0] = den;+ }+ barrier();+ float den = red[0];+ for (int i = tid; i < hd; i += 256) {+ float acc = 0.0;+ for (int j = 0; j < n; j++) {+ int e = l3[lb + j];+ if (e < 0) continue;+ float w = sm[1024 + j];+ if ((flags & 1) != 0) w = bf16r(w);+ float k = e < nwin ? b1[woff + e * hd + i] : b2[coff + (e - nwin) * hd + i];+ acc += w * k;+ }+ float o = acc / den;+ y5[ob + i] = (flags & 1) != 0 ? bf16r(o) : o;+ }+}++// ---- mode 1 ------------------------------------------------------------------------+void rope() {+ int t = int(gl_GlobalInvocationID.x + gl_GlobalInvocationID.y * gl_NumWorkGroups.x * 256u);+ int nseg = p.v[1], per_row = p.v[2], half_ = p.v[3] / 2;+ if (t >= nseg * half_) return;+ int g = t / half_, i = t - g * half_;+ int row = g / per_row, j = g - row * per_row;+ int xb = p.v[4] + row * p.v[5] + j * p.v[6] + 2 * i;+ int cb = p.v[7] + row * p.v[8] + 2 * i;+ float c = b4[cb], sn = b4[cb + 1];+ if (p.v[9] != 0) sn = -sn;+ float a = y5[xb], b = y5[xb + 1];+ float x0 = a * c - b * sn, x1 = a * sn + b * c;+ if ((p.v[10] & 1) != 0) { x0 = bf16r(x0); x1 = bf16r(x1); }+ y5[xb] = x0; y5[xb + 1] = x1;+}++// ---- mode 2 ------------------------------------------------------------------------+void compress() {+ int tid = int(gl_LocalInvocationID.x);+ int S = p.v[1], pb = p.v[2], R = p.v[3], P = p.v[4], D = p.v[5], ov = p.v[6];+ int kvo = p.v[7], kvr = p.v[8], sco = p.v[9], scr = p.v[10], ape = p.v[11];+ int oo = p.v[12], orow = p.v[13], ro = p.v[14];+ int rows = ov != 0 ? 2 * R : R, so = ro + rows * P;+ for (int s = 0; s < S; s++) {+ int pos = pb + s, slot = pos % R, srow = ov != 0 ? R + slot : slot;+ for (int c = tid; c < P; c += 256) {+ r7[ro + srow * P + c] = b0[kvo + s * kvr + c];+ float v = b1[sco + s * scr + c];+ if (ape >= 0) v = v + b4[ape + slot * P + c];+ r7[so + srow * P + c] = v;+ }+ if ((pos + 1) % R != 0) continue;+ memoryBarrierBuffer();+ barrier();+ int g = pos / R;+ for (int d = tid; d < D; d += 256) {+ float best = NEG_INF;+ for (int k = 0; k < rows; k++) {+ int col = (ov != 0 && k >= R) ? D + d : d;+ float v = r7[so + k * P + col];+ if (v > best) best = v;+ }+ float tot = 0.0, mix = 0.0;+ for (int k = 0; k < rows; k++) {+ int col = (ov != 0 && k >= R) ? D + d : d;+ float w = exp(r7[so + k * P + col] - best);+ tot += w;+ mix += w * r7[ro + k * P + col];+ }+ y5[oo + g * orow + d] = mix / tot;+ }+ memoryBarrierBuffer();+ barrier();+ if (ov != 0) {+ for (int c = tid; c < R * P; c += 256) {+ r7[ro + c] = r7[ro + R * P + c];+ r7[so + c] = r7[so + R * P + c];+ }+ memoryBarrierBuffer();+ barrier();+ }+ }+}++// ---- mode 3 ------------------------------------------------------------------------+void score() {+ int s = int(gl_WorkGroupID.x), tid = int(gl_LocalInvocationID.x);+ int pos = p.v[2] + s, lens = (pos + 1) / p.v[3];+ int IH = p.v[4], ID = p.v[5], width = p.v[6];+ int qb = p.v[7] + s * p.v[8], wb = p.v[9] + s * p.v[10];+ int ko = p.v[11], kr = p.v[12], mr = p.v[13], sb = p.v[16] + s * p.v[14], mb = p.v[17] + s * mr;+ float wscale = intBitsToFloat(p.v[15]);+ for (int i = tid; i < IH * ID; i += 256) sm[i] = b0[qb + i];+ for (int h = tid; h < IH; h += 256) sm[4096 + h] = b1[wb + h] * wscale;+ barrier();+ for (int j = tid; j < width; j += 256) {+ float v = NEG_INF;+ if (j < lens && (mr <= 0 || l3[mb + j] != 0)) {+ int kb = ko + j * kr;+ float tot = 0.0;+ for (int h = 0; h < IH; h++) {+ float d = 0.0;+ for (int i = 0; i < ID; i++) d += sm[h * ID + i] * b2[kb + i];+ if (d > 0.0) tot += d * sm[4096 + h];+ }+ v = tot;+ }+ y5[sb + j] = v;+ }+}++// ---- mode 4 ------------------------------------------------------------------------+void candidates() {+ int s = int(gl_WorkGroupID.x), tid = int(gl_LocalInvocationID.x);+ int pos = p.v[2] + s, lens = (pos + 1) / p.v[3];+ int width = p.v[4], blk = p.v[5], topb = p.v[6], sb = s * p.v[7], mb = s * p.v[8];+ int blocks = (width + blk - 1) / blk;+ for (int b = tid; b < blocks; b += 256) {+ float top = NEG_INF;+ for (int i = b * blk; i < (b + 1) * blk && i < width; i++) { float v = b0[sb + i]; if (v > top) top = v; }+ sm[b] = top;+ }+ for (int i = tid; i < width; i += 256) i6[mb + i] = 0;+ memoryBarrierBuffer();+ barrier();+ // C's (lens - 1) / block, which truncates toward zero+ int last = lens >= 1 ? (lens - 1) / blk : (blk == 1 ? -1 : 0);+ if (tid == 0 && last >= 0 && last < blocks) sm[last] = POS_INF;+ barrier();+ int wanted = min(topb, blocks);+ for (int pick = 0; pick < wanted; pick++) {+ // the best block above -inf, the lower one on a tie+ float bv = NEG_INF; int bi = -1;+ for (int b = tid; b < blocks; b += 256) {+ float v = sm[b];+ if (v > NEG_INF && (bi < 0 || v > bv)) { bv = v; bi = b; }+ }+ red[tid] = bv; cnt[tid] = uint(bi < 0 ? 0x7fffffff : bi);+ barrier();+ for (int off = 128; off > 0; off >>= 1) {+ if (tid < off) {+ float ov = red[tid + off]; uint oi = cnt[tid + off];+ if (oi != 0x7fffffffu && (cnt[tid] == 0x7fffffffu || ov > red[tid] || (ov == red[tid] && oi < cnt[tid]))) {+ red[tid] = ov; cnt[tid] = oi;+ }+ }+ barrier();+ }+ uint chosen = cnt[0];+ barrier();+ if (chosen == 0x7fffffffu) break;+ int cb = int(chosen);+ for (int i = cb * blk + tid; i < (cb + 1) * blk && i < width; i += 256) i6[mb + i] = 1;+ if (tid == 0) sm[cb] = NEG_INF;+ barrier();+ }+}++// ---- mode 5 ------------------------------------------------------------------------+void topk() {+ int s = int(gl_WorkGroupID.x), tid = int(gl_LocalInvocationID.x);+ int width = p.v[2], topk_ = p.v[3], sb = s * p.v[4], lb = p.v[5] + s * p.v[6], base = p.v[7], order = p.v[8];+ uint nv = 0u;+ for (int j = tid; j < width; j += 256) if (b0[sb + j] > NEG_INF) nv++;+ int valid = int(wsum(nv, tid));+ int keep = min(topk_, valid);+ for (int k = keep + tid; k < topk_; k += 256) i6[lb + k] = -1;+ if (keep == 0) return;+ // the keep-th largest key among the valid scores, bit by bit from the top+ uint K = 0u;+ for (int bit = 31; bit >= 0; bit--) {+ uint cand = K | (1u << uint(bit));+ uint c = 0u;+ for (int j = tid; j < width; j += 256) { float v = b0[sb + j]; if (v > NEG_INF && okey(v) >= cand) c++; }+ if (wsum(c, tid) >= uint(keep)) K = cand;+ }+ uint ab = 0u;+ for (int j = tid; j < width; j += 256) { float v = b0[sb + j]; if (v > NEG_INF && okey(v) > K) ab++; }+ int above = int(wsum(ab, tid)), need = keep - above;+ // walk the columns in order: the selected ones (above K, or equal to it while ties are+ // still needed, lower columns first)+ uint seen_eq = 0u, placed = 0u;+ for (int j0 = 0; j0 < width; j0 += 256) {+ int j = j0 + tid;+ float v = j < width ? b0[sb + j] : NEG_INF;+ bool ok = v > NEG_INF;+ uint key = ok ? okey(v) : 0u;+ uint eq = ok && key == K ? 1u : 0u;+ uint eq_before = wscan(eq, tid) + seen_eq;+ bool sel = ok && (key > K || (eq == 1u && eq_before < uint(need)));+ uint sv = sel ? 1u : 0u;+ uint at = wscan(sv, tid) + placed;+ if (sel) {+ if (order == 0) i6[lb + int(at)] = base + j;+ else sm[int(at)] = float(j); // ranked below+ }+ seen_eq += wsum(eq, tid);+ placed += wsum(sv, tid);+ }+ if (order == 0) return;+ // rank order: score, then the lower column (keep <= 4096)+ barrier();+ for (int a = tid; a < keep; a += 256) {+ int ja = int(sm[a]); float va = b0[sb + ja];+ int r = 0;+ for (int b = 0; b < keep; b++) {+ int jb = int(sm[b]); float vb = b0[sb + jb];+ if (vb > va || (vb == va && jb < ja)) r++;+ }+ i6[lb + r] = base + ja;+ }+}++// ---- mode 6 ------------------------------------------------------------------------+void engram() {+ int c = int(gl_WorkGroupID.x), s = int(gl_WorkGroupID.y), tid = int(gl_LocalInvocationID.x);+ int S = p.v[1], H = p.v[2], D = p.v[3];+ if (s >= S || c >= H) return;+ int kb = p.v[4] + s * p.v[5], xb = p.v[6] + s * p.v[7] + c * D;+ int qw = p.v[8] + c * D, kw = p.v[9] + c * D;+ float eps = intBitsToFloat(p.v[10]);+ float xs = 0.0, ks = 0.0, dt = 0.0;+ for (int i = tid; i < D; i += 256) {+ float xv = y5[xb + i], kv = b0[kb + c * D + i];+ xs += xv * xv; ks += kv * kv; dt += xv * b1[qw + i] * b1[kw + i] * kv;+ }+ sm[tid] = xs; sm[256 + tid] = ks; sm[512 + tid] = dt;+ barrier();+ for (int off = 128; off > 0; off >>= 1) {+ if (tid < off) { sm[tid] += sm[tid + off]; sm[256 + tid] += sm[256 + tid + off]; sm[512 + tid] += sm[512 + tid + off]; }+ barrier();+ }+ float r = (1.0 / sqrt(sm[0] / float(D) + eps)) * (1.0 / sqrt(sm[256] / float(D) + eps));+ float t = sm[512] * r / sqrt(float(D));+ float mag = abs(t);+ if (mag < 1.0e-6) mag = 1.0e-6;+ float sr = sqrt(mag);+ if (t < 0.0) sr = -sr;+ float g = sig(sr);+ barrier();+ int vb = kb + H * D;+ for (int i = tid; i < D; i += 256) y5[xb + i] = y5[xb + i] + g * b0[vb + i];+}++void main() {+ int m = MODE;+ if (m == 0) attend();+ else if (m == 1) rope();+ else if (m == 2) compress();+ else if (m == 3) score();+ else if (m == 4) candidates();+ else if (m == 5) topk();+ else if (m == 6) engram();+}diff --git a/c/shaders/chain_dsv4.spv b/c/shaders/chain_dsv4.spvnew file mode 100644index 00000000..cd2546b6Binary files /dev/null and b/c/shaders/chain_dsv4.spv differdiff --git a/c/tests/test_vk_chain.c b/c/tests/test_vk_chain.cindex a17d1626..2b4a98bc 100644--- a/c/tests/test_vk_chain.c+++ b/c/tests/test_vk_chain.c@@ -32,6 +32,10 @@* decay, beta, output norm and gate* mhc hyper_connections.h's split, collapse and write back, the mean, and the* clamped SwiGLU+ * 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** make vk-chain-check VK=1 (VK_ICD_FILENAMES=.../lvp_icd.json for Lavapipe) */#include <stdio.h>@@ -44,6 +48,7 @@#include "../delta_attention.h" /* the KDA step the KDA ops follow */#include "../hyper_connections.h" /* the mHC arithmetic */#include "../sparse_index.h" /* GLM-5.3's k-pooled indexer */+#include "../sparse_attn.h" /* DeepSeek V4.1's attention kernel */static int fails;#define CHECK(c, ...) do { if (!(c)) { fails++; printf("FAIL %s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0)@@ -976,6 +981,270 @@ static void test_kpool(int S, int pos_base, int IH, int ID, int pool, int topk,free(keys); free(gates); free(ape); free(q); free(hw); free(valid); free(ref); free(hwd); free(rk); free(gk);}+/* ---- 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[64];+ 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);+}+/* ---- frames: many ops, frames in flight, ordering ---------------------------------------- */static void test_frames(void) {int n = 1000;@@ -1093,6 +1362,18 @@ int main(int argc, char **argv) {test_mhc(2, 64, 3); test_mhc(4, 96, 20); test_mhc(3, 40, 1);printf("mhc done\n");}+ 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);+ printf("dsv4 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 --git a/c/vk_chain.c b/c/vk_chain.cindex ee112a1d..2d487f69 100644--- a/c/vk_chain.c+++ b/c/vk_chain.c@@ -247,6 +247,8 @@ static VkPipeline make_pipe(VkShaderModule m, const VkSpecializationInfo *si) {return p;}+static void dsv4_init(void); /* chain_dsv4.comp (DeepSeek V4.1 / V4), below */+static void dsv4_shutdown(void);int vkc_init(void) {if (K.ready) return !K.lost;if (!coli_vk_core(&K.core)) return 0;@@ -299,6 +301,7 @@ int vkc_init(void) {if (f && (K.mmod[i] = load_module(K.core.spv_path, mla_file[i]))) K.mpipe[i] = make_pipe(K.mmod[i], NULL);}K.mla_ok = K.mpipe[PM_MLA] && K.mpipe[PM_HGEMV] && K.mpipe[PM_DSA];+ dsv4_init();/* the fp32 tiled GEMM at the backend's tiles; none = every S on the GEMV */K.mod_gemm = K.core.gemm_tiles ? load_module(K.core.spv_path, "qmatmul_gemm.spv") : VK_NULL_HANDLE;for (int k = 0; K.mod_gemm && k < K.core.gemm_tiles && k < VKC_GEMM_MAX; k++) {@@ -1031,6 +1034,84 @@ void vkc_shutdown(void) {if (K.mod_dnrec) vkDestroyShaderModule(K.dev, K.mod_dnrec, NULL);if (K.pl) vkDestroyPipelineLayout(K.dev, K.pl, NULL);if (K.dsl) vkDestroyDescriptorSetLayout(K.dev, K.dsl, NULL);+ dsv4_shutdown();memset(&K, 0, sizeof K);K.cur = -1; K.gemm_rows = -1;}++/* ---- DeepSeek V4.1 Flash and DeepSeek V4 attention (chain_dsv4.comp) ------------------+ * Its own optional pipeline: without the shader only these ops decline. */+static struct { VkShaderModule mod; VkPipeline pipe; } D4;+static void dsv4_init(void) {+ char path[1200];+ const char *sl = strrchr(K.core.spv_path, '/');+ size_t pre = sl ? (size_t)(sl - K.core.spv_path) + 1 : 0;+ const char *file = "chain_dsv4.spv";+ if (pre + strlen(file) + 1 >= sizeof path) return;+ memcpy(path, K.core.spv_path, pre); strcpy(path + pre, file);+ FILE *f = fopen(path, "rb");+ if (!f) return;+ fclose(f);+ if ((D4.mod = load_module(K.core.spv_path, file))) D4.pipe = make_pipe(D4.mod, NULL);+}+static void dsv4_shutdown(void) {+ if (D4.pipe) vkDestroyPipeline(K.dev, D4.pipe, NULL);+ if (D4.mod) vkDestroyShaderModule(K.dev, D4.mod, NULL);+ memset(&D4, 0, sizeof D4);+}+int vkc_dsv4_ready(void) { return vkc_ready() && D4.pipe; }++/* the shader reads one block of 32 words: the mode, then the op's fields */+typedef struct { int mode; int w[31]; } Dsv4PC;+static int dsv4_rec(int kind, int mode, const void *b, size_t bytes, VkcBind *bd, int nb, uint32_t gx, uint32_t gy) {+ if (!D4.pipe || !open_frame() || K.lost || bytes > sizeof(int) * 31) return 0;+ Dsv4PC pc; memset(&pc, 0, sizeof pc);+ pc.mode = mode; memcpy(pc.w, b, bytes);+ K.kind = kind;+ return record(D4.pipe, bd, nb, &pc, sizeof pc, gx, gy, 1);+}+int vkc_dsv4_attn(VkcBuf *q, VkcBuf *win, VkcBuf *cmp, VkcBuf *list, VkcBuf *prm, VkcBuf *out, const VkcDsAttn *p) {+ if (p->S < 1 || p->S > 65535 || p->H < 1 || p->H > 65535 || p->hd < 1 || p->hd > 1024 || p->cnt < 0 || p->cnt > 3072)+ return 0;+ if (p->cnt == 0) return 0;+ VkcBind bd[6] = {B(q, 0), B(win, 0), B(cmp ? cmp : win, 0), B(list, 0), B(prm, 0), B(out, 1)};+ return dsv4_rec(PK_ATTN, 0, p, sizeof *p, bd, 6, (uint32_t)p->H, (uint32_t)p->S);+}+int vkc_dsv4_rope(VkcBuf *x, VkcBuf *cs, const VkcDsRope *p) {+ if (p->nseg < 0 || p->per_row < 1 || p->rd < 2 || (p->rd & 1)) return 0;+ if (p->nseg == 0) return open_frame() && !K.lost;+ VkcBind bd[6] = {B(NULL, 0), B(NULL, 0), B(NULL, 0), B(NULL, 0), B(cs, 0), B(x, 1)};+ uint32_t gx, gy; grid(((uint64_t)p->nseg * (p->rd / 2) + 255) / 256, &gx, &gy);+ return dsv4_rec(PK_ROPE, 1, p, sizeof *p, bd, 6, gx, gy);+}+int vkc_dsv4_compress(VkcBuf *kv, VkcBuf *sc, VkcBuf *ring, VkcBuf *prm, VkcBuf *out, const VkcDsComp *p) {+ if (p->S < 0 || p->ratio < 1 || p->P < 1 || p->D < 1 || p->D > p->P || (p->overlap && p->P < 2 * p->D)) return 0;+ if (p->S == 0) return open_frame() && !K.lost;+ VkcBind bd[8] = {B(kv, 0), B(sc, 0), B(NULL, 0), B(NULL, 0), B(p->ape_off >= 0 ? prm : NULL, 0), B(out, 1), B(NULL, 0),+ B(ring, 1)};+ return dsv4_rec(PK_DSA, 2, p, sizeof *p, bd, 8, 1, 1);+}+int vkc_dsv4_score(VkcBuf *iq, VkcBuf *hw, VkcBuf *keys, VkcBuf *mask, VkcBuf *sc, const VkcDsScore *p) {+ if (p->S < 1 || p->S > 65535 || p->IH < 1 || p->IH > 64 || p->ID < 1 || p->IH * p->ID > 4096 || p->ratio < 1 ||+ p->width < 0 || p->sc_row < p->width || (p->mask_row > 0 && !mask)) return 0;+ if (p->width == 0) return open_frame() && !K.lost;+ VkcBind bd[6] = {B(iq, 0), B(hw, 0), B(keys, 0), B(p->mask_row > 0 ? mask : NULL, 0), B(NULL, 0), B(sc, 1)};+ return dsv4_rec(PK_DSA, 3, p, sizeof *p, bd, 6, (uint32_t)p->S, 1);+}+int vkc_dsv4_cand(VkcBuf *sc, VkcBuf *mask, const VkcDsCand *p) {+ if (p->S < 1 || p->S > 65535 || p->block < 1 || p->ratio < 1 || p->width < 0 ||+ (p->width + p->block - 1) / p->block > 4096 || p->mask_row < p->width) return 0;+ VkcBind bd[7] = {B(sc, 0), B(NULL, 0), B(NULL, 0), B(NULL, 0), B(NULL, 0), B(NULL, 0), B(mask, 1)};+ return dsv4_rec(PK_DSA, 4, p, sizeof *p, bd, 7, (uint32_t)p->S, 1);+}+int vkc_dsv4_topk(VkcBuf *sc, VkcBuf *list, const VkcDsTopk *p) {+ if (p->S < 1 || p->S > 65535 || p->topk < 0 || p->width < 0 || (p->order && p->topk > 4096)) return 0;+ if (p->topk == 0) return open_frame() && !K.lost;+ VkcBind bd[7] = {B(sc, 0), B(NULL, 0), B(NULL, 0), B(NULL, 0), B(NULL, 0), B(NULL, 0), B(list, 1)};+ return dsv4_rec(PK_DSA, 5, p, sizeof *p, bd, 7, (uint32_t)p->S, 1);+}+int vkc_dsv4_engram(VkcBuf *kv, VkcBuf *prm, VkcBuf *x, const VkcDsEngram *p) {+ if (p->S < 1 || p->S > 65535 || p->H < 1 || p->D < 1) return 0;+ VkcBind bd[6] = {B(kv, 0), B(prm, 0), B(NULL, 0), B(NULL, 0), B(NULL, 0), B(x, 1)};+ return dsv4_rec(PK_EW, 6, p, sizeof *p, bd, 6, (uint32_t)p->H, (uint32_t)p->S);+}diff --git a/c/vk_chain.h b/c/vk_chain.hindex 784b3d2b..c21c9104 100644--- a/c/vk_chain.h+++ b/c/vk_chain.h@@ -286,6 +286,62 @@ typedef struct { int S, H, D, iters, x_off, x_row, m_off, m_row, hp_off, hp_row,float eps, hc_eps, lim; } VkcMhc;int vkc_mhc(int mode, VkcBuf *x, VkcBuf *m, VkcBuf *hp, VkcBuf *prm, VkcBuf *y, const VkcMhc *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 <= 64, IH*ID <= 4096.+ * 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);+/* counters, for the engines' [VK] lines */typedef struct {unsigned long long frames, waits, ops, matmuls, gemms, barriers, bytes_up, bytes_down;diff --git a/docs/vulkan.md b/docs/vulkan.mdindex 8dda85a9..fd1d13aa 100644--- a/docs/vulkan.md+++ b/docs/vulkan.md@@ -971,6 +971,32 @@ way, the KDA layer against `delta_attention.h` over two submissions (the state awindow carried between them, inputs small enough that the l2 eps counts), the mHC opsagainst `hyper_connections.h`; each within 3e-7 on Lavapipe and on the Iris Xe.+### DeepSeek V4.1 Flash and DeepSeek V4's attention (`vkc_dsv4`)++DeepSeek's attention is not the absorbed MLA above: it is MQA over one KV row per+position, the same row key and value, read from a sliding window of raw rows and from+compressed rows (a compressor pools `ratio` positions into one) that a DSA indexer picks+per query, with an attention sink. Its ops are in `vk_chain.h` (`vkc_dsv4_*`), one shader+of their own (`chain_dsv4.comp`), optional like the MLA ones:++| Op | What it does |+|---|---|+| `vkc_dsv4_attn` | the sparse attention of `sparse_attn.h`: per row a list of window rows, compressed rows and skipped entries; the sink in the denominator only, the value sum and the denominator in list order; optionally DeepSeek V4's roundings (the weights and the output to bf16) |+| `vkc_dsv4_rope` | RoPE on interleaved pairs in place from a host table, forward or inverse (the attention output's un-rotation) |+| `vkc_dsv4_compress` | the compressor's rolling group: each row's kv and score rows into the ring slot of its position, the per-channel softmax pooling when a group completes; DeepSeek V4's overlapping form (two halves, a position bias per slot) too |+| `vkc_dsv4_score` | the indexer's scores: the relu-gated, head-weighted dot of each reachable compressed row, a candidate mask, -inf past the row's reach |+| `vkc_dsv4_cand` | DeepSeek V4.1's candidate blocks: each block's best score, the newest block pinned, the best blocks kept whole |+| `vkc_dsv4_topk` | the top-k of the CPU's selection (ties to the lower column), in column order (V4.1) or by rank (V4), padded with skipped entries |+| `vkc_dsv4_engram` | DeepSeek V4.1's engram gate on the residual streams |++`make vk-chain-check VK=1` checks them against references transcribed from+`deepseek_v41.c` (and V4's rounding variant): the attention over lists of window and+compressed rows with skipped entries and a row with none (within 1.1e-6 of the largest+output on Lavapipe), RoPE both ways, the compressor over three calls with its ring+carried (ratios 1 to 4, the overlapping form with its bias, within 2e-6), the scores,+the candidate mask and the top-k list slot for slot on scores exact in float on both+sides, ties included, with and without a mask, and the engram gate (within 2e-6).+## Adding an engine to the tierEvery MoE engine here is on the tier ([the table above](#the-routed-expert-tier-vk_tierc));