Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
vulkan: multi-head latent attention on the dense chain
JustVugg611a65e97989
diff --git a/c/Makefile b/c/Makefileindex f374f148..cd82eb05 100644--- a/c/Makefile+++ b/c/Makefile@@ -716,6 +716,9 @@ VK_OBJ += vk_chain.oVK_SPV += shaders/chain_norm.spv shaders/chain_rope.spv shaders/chain_attn.spv shaders/chain_dnconv.spv \shaders/chain_dnrec.spv shaders/chain_ew.spv shaders/chain_qsa.spv shaders/chain_ple.spv \shaders/chain_gemv.spv+# the MLA ops (vk_chain.h): attention core, RoPE and LayerNorm rows, per-head weight+# blocks, the DSA indexer's selection+VK_SPV += shaders/chain_mla.spv shaders/chain_hgemv.spv shaders/chain_dsa.spvendif# Optional AMD XDNA2 (Ryzen AI NPU) lane, Windows. Same opt-in shape as VK=1:diff --git a/c/shaders/chain_dsa.comp b/c/shaders/chain_dsa.compnew file mode 100644index 00000000..fa55bfdf--- /dev/null+++ b/c/shaders/chain_dsa.comp@@ -0,0 +1,112 @@+#version 450+// A DSA lightning indexer's top-k selection on the dense chain (vk_chain.c,+// VKC_P_DSA), for the attention core's selection list (chain_mla.comp mode 0).+//+// mode 0, per token (GLM-5.2, colibri.c's attention_rows): one workgroup per query row+// s, position pos = pos_base + s, nk = pos + 1 positions. When nk <= topk (and not+// force) the row attends to every position: sel[s*sel_row] = -1. Otherwise each+// position t scores+// score_t = (sum_h [d_h > 0] w_h * d_h) * wscale, d_h = (q_h . k_t) * qscale+// (q the row's IH index queries of ID floats, roped; w its IH head weights; k the+// index-key cache), the CPU's sums in its order, and the row keeps keep = min(nk, topk)+// positions as the CPU does: thr = the keep-th largest score, then the positions+// scoring above thr in position order, then those scoring exactly thr in position+// order until keep. The threshold is found by bisection on the scores' order-keeping+// integer keys (32 counting passes); -0 counts as +0, as the float compare does.+// sel[s*sel_row] = keep, then the positions. Scores live in sc[s*sc_row + t].+// Limits: IH*ID <= 4096.+#extension GL_KHR_shader_subgroup_arithmetic : require+layout(local_size_x = 256) in;++layout(std430, binding = 0) readonly buffer IQ { float iq[]; };+layout(std430, binding = 1) readonly buffer HW { float hw[]; };+layout(std430, binding = 2) readonly buffer KC { float kc[]; };+layout(std430, binding = 3) buffer SC { float sc[]; };+layout(std430, binding = 4) buffer SL { int sel[]; };++layout(push_constant) uniform P {+ int mode, S, pos_base, IH, ID, topk, force;+ int q_off, q_row, w_off, w_row, k_off, k_row, sc_row, sel_row;+ float qscale, wscale;+} p;++shared float qs[4096];+shared float ws[64];+shared uint cnt[256];++uint okey(float f) {+ uint u = floatBitsToUint(f);+ if (u == 0x80000000u) u = 0u;+ return (u & 0x80000000u) != 0u ? ~u : (u | 0x80000000u);+}++// the workgroup's sum of v (every thread passes its own)+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;+}+// exclusive prefix sum of v over the workgroup's threads, in thread order+uint wscan(uint v, int tid) {+ 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;+}++void main() {+ int s = int(gl_WorkGroupID.x), tid = int(gl_LocalInvocationID.x);+ int nk = p.pos_base + s + 1;+ int lb = s * p.sel_row;+ if (nk <= p.topk && p.force == 0) { if (tid == 0) sel[lb] = -1; return; }+ int keep = min(nk, p.topk);+ int nq = p.IH * p.ID, qb = p.q_off + s * p.q_row;+ for (int i = tid; i < nq; i += 256) qs[i] = iq[qb + i];+ for (int h = tid; h < p.IH; h += 256) ws[h] = hw[p.w_off + s * p.w_row + h];+ barrier();+ int sb = s * p.sc_row;+ for (int t = tid; t < nk; t += 256) {+ int kb = p.k_off + t * p.k_row;+ float a = 0.0;+ for (int h = 0; h < p.IH; h++) {+ float d = 0.0;+ for (int i = 0; i < p.ID; i++) d += qs[h * p.ID + i] * kc[kb + i];+ d *= p.qscale;+ if (d > 0.0) a += ws[h] * d;+ }+ sc[sb + t] = a * p.wscale;+ }+ memoryBarrierBuffer();+ barrier();+ // the keep-th largest key, bit by bit from the top+ uint K = 0u;+ for (int b = 31; b >= 0; b--) {+ uint cand = K | (1u << uint(b));+ uint c = 0u;+ for (int t = tid; t < nk; t += 256) if (okey(sc[sb + t]) >= cand) c++;+ if (wsum(c, tid) >= uint(keep)) K = cand;+ }+ // the positions in order: each thread a contiguous chunk, its place from a scan+ int chunk = (nk + 255) / 256, c0 = tid * chunk, c1 = min(nk, c0 + chunk);+ uint above = 0u, at = 0u;+ for (int t = c0; t < c1; t++) { uint k = okey(sc[sb + t]); above += k > K ? 1u : 0u; at += k == K ? 1u : 0u; }+ uint n1 = wsum(above, tid);+ uint o = wscan(above, tid);+ for (int t = c0; t < c1; t++) if (okey(sc[sb + t]) > K) sel[lb + 1 + int(o++)] = t;+ o = n1 + wscan(at, tid);+ for (int t = c0; t < c1 && o < uint(keep); t++) if (okey(sc[sb + t]) == K) sel[lb + 1 + int(o++)] = t;+ if (tid == 0) sel[lb] = keep;+}diff --git a/c/shaders/chain_dsa.spv b/c/shaders/chain_dsa.spvnew file mode 100644index 00000000..53c70bf2Binary files /dev/null and b/c/shaders/chain_dsa.spv differdiff --git a/c/shaders/chain_hgemv.comp b/c/shaders/chain_hgemv.compnew file mode 100644index 00000000..1d7246ba--- /dev/null+++ b/c/shaders/chain_hgemv.comp@@ -0,0 +1,108 @@+#version 450+// Per-head block matmuls of a resident tensor on the dense chain (vk_chain.c,+// VKC_P_HGEMV): the weight halves of multi-head latent attention, where every head+// multiplies its own slice of the activations by its own block of rows. Head h's+// block is the rows h*hstride + hoff + [0, n) of W ([O x I], any resident format).+//+// mode 0, rows: y[s][h][o] = sum_i W[h*hstride + hoff + o][i] * x[s][h][i], o < n,+// i < I (the value rows of kv_b times the latent context; an absorbed query from a+// key matrix stored per head as [K x Q]). One subgroup per output row, its lanes+// split the row. With has_gate, y *= sigmoid(g[g_off + s*g_row + h*n + o]) (an+// output gate on the values).+// mode 1, transposed: y[s][h][i] = sum_d W[h*hstride + hoff + d][i] * x[s][h][d],+// d < n, i < I (the absorbed query from kv_b's key rows: q_nope's n values times+// the head's n rows, into the latent's I columns). One workgroup per (h, s), x's+// slice staged in shared memory (n <= 1024), a thread per column, d in order.+// x[s][h][.] is at x_off + s*x_row + h*x_seg, y[s][h][.] at y_off + s*y_row + h*y_seg.+//+// Formats (the backend's, qmatmul.comp's layout: row r at r*rowWords words):+// 1 int8 rows (scale per row), 2 int4 rows (nibble - 8, scale per row), 4 int4 in+// groups of gs, 5 int3-g64 (24 bytes and one scale per 64), 7 MXFP4 (scale per gs),+// 10 f32, 11 bf16 (low half = even column), 12 fp8 e4m3 (scale per gs), 13 int8 in+// groups of gs.+#extension GL_KHR_shader_subgroup_arithmetic : require+layout(local_size_x = 256) in;++layout(std430, binding = 0) readonly buffer X { float x[]; };+layout(std430, binding = 1) readonly buffer W { uint w[]; };+layout(std430, binding = 2) readonly buffer Sc { float sc[]; };+layout(std430, binding = 3) writeonly buffer Y { float y[]; };+layout(std430, binding = 4) readonly buffer G { float g[]; };++layout(push_constant) uniform P {+ int mode, fmt, I, rowWords, gs;+ int S, H, n, hstride, hoff;+ int x_off, x_row, x_seg, y_off, y_row, y_seg;+ int g_off, g_row, has_gate;+} p;++shared float xs[1024];++float i8(uint word, int lane) { return float(bitfieldExtract(int(word), lane * 8, 8)); }+float i4(uint word, int lane) { return float(bitfieldExtract(word, lane * 4, 4)) - 8.0; }+float mx4(uint word, int lane) {+ uint nb = bitfieldExtract(word, lane * 4, 4);+ const float lut[8] = float[8](0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0);+ float v = lut[nb & 7u];+ return (nb & 8u) != 0u ? -v : v;+}+float e4m3(uint word, int lane) {+ uint b = bitfieldExtract(word, lane * 8, 8);+ if ((b & 0x7fu) == 0x7fu) return uintBitsToFloat(0x7fc00000u);+ uint e = (b >> 3) & 0xfu, m = b & 7u;+ float v = e == 0u ? float(m) * 0.001953125 : ldexp(1.0 + float(m) * 0.125, int(e) - 7);+ return (b & 0x80u) != 0u ? -v : v;+}++// W[row][i], dequantized+float wv(int row, int i) {+ uint rb = uint(row) * uint(p.rowWords);+ int f = p.fmt;+ if (f == 10) return uintBitsToFloat(w[rb + uint(i)]);+ if (f == 11) { uint pk = w[rb + uint(i >> 1)]; return uintBitsToFloat((i & 1) != 0 ? (pk & 0xffff0000u) : (pk << 16)); }+ if (f == 1) return i8(w[rb + uint(i >> 2)], i & 3) * sc[row];+ if (f == 2) return i4(w[rb + uint(i >> 3)], i & 7) * sc[row];+ int ng = (p.I + p.gs - 1) / max(p.gs, 1);+ if (f == 4) return i4(w[rb + uint(i >> 3)], i & 7) * sc[row * ng + i / p.gs];+ if (f == 7) return mx4(w[rb + uint(i >> 3)], i & 7) * sc[row * ng + i / p.gs];+ if (f == 12) return e4m3(w[rb + uint(i >> 2)], i & 3) * sc[row * ng + i / p.gs];+ if (f == 13) return i8(w[rb + uint(i >> 2)], i & 3) * sc[row * ng + i / p.gs];+ // 5: int3-g64, 24 bytes per group: a 16-byte plane of 2-bit lows, an 8-byte plane of high bits+ int gi = i >> 6, j = i & 63, ng64 = (p.I + 63) >> 6;+ uint blo = w[rb + uint(gi * 6 + (j >> 4))], bhi = w[rb + uint(gi * 6 + 4 + (j >> 5))];+ uint u = ((blo >> uint((j & 15) * 2)) & 3u) | (((bhi >> uint(j & 31)) & 1u) << 2);+ return float(int(u) - 4) * sc[row * ng64 + gi];+}++void main() {+ int tid = int(gl_LocalInvocationID.x);+ if (p.mode == 0) {+ int s = int(gl_WorkGroupID.y);+ int lane = int(gl_SubgroupInvocationID), sgs = int(gl_SubgroupSize);+ int nsg = 256 / sgs, total = p.H * p.n;+ int stride = int(gl_NumWorkGroups.x) * nsg;+ for (int og = int(gl_WorkGroupID.x) * nsg + int(gl_SubgroupID); og < total; og += stride) {+ int h = og / p.n, o = og - h * p.n;+ int row = h * p.hstride + p.hoff + o;+ int xb = p.x_off + s * p.x_row + h * p.x_seg;+ float a = 0.0;+ for (int i = lane; i < p.I; i += sgs) a += wv(row, i) * x[xb + i];+ float tot = subgroupAdd(a);+ if (lane == 0) {+ if (p.has_gate != 0) tot *= 1.0 / (1.0 + exp(-g[p.g_off + s * p.g_row + h * p.n + o]));+ y[p.y_off + s * p.y_row + h * p.y_seg + o] = tot;+ }+ }+ return;+ }+ int h = int(gl_WorkGroupID.x), s = int(gl_WorkGroupID.y);+ int xb = p.x_off + s * p.x_row + h * p.x_seg;+ for (int d = tid; d < p.n; d += 256) xs[d] = x[xb + d];+ barrier();+ int r0 = h * p.hstride + p.hoff, yb = p.y_off + s * p.y_row + h * p.y_seg;+ for (int i = tid; i < p.I; i += 256) {+ float a = 0.0;+ for (int d = 0; d < p.n; d++) a += xs[d] * wv(r0 + d, i);+ y[yb + i] = a;+ }+}diff --git a/c/shaders/chain_hgemv.spv b/c/shaders/chain_hgemv.spvnew file mode 100644index 00000000..f3dfdf35Binary files /dev/null and b/c/shaders/chain_hgemv.spv differdiff --git a/c/shaders/chain_mla.comp b/c/shaders/chain_mla.compnew file mode 100644index 00000000..fffef7d9--- /dev/null+++ b/c/shaders/chain_mla.comp@@ -0,0 +1,235 @@+#version 450+// Multi-head latent attention on the dense chain (vk_chain.c, VKC_P_MLA), three modes.+// The weights never reach this shader: the absorbed query and the value rows are+// per-head matmuls of the weights (chain_hgemv.comp); what is left here is the part+// that reads the cache, and the two small row ops MLA needs around it.+//+// mode 0, the attention core. One workgroup per (head h = WorkGroupID.x, row s =+// WorkGroupID.y). With qa the absorbed query (the no-position query times the key+// half of kv_b, in the latent space, K floats) and qr the rotated part (R floats):+// score_t = (qa . L[t] + qr . Rc[t]) * scale over the row's positions+// clat = sum_t softmax(score)_t L[t] (K floats, the latent context)+// L is the latent cache ([cap][lat_row], the normalized latent of every position),+// Rc the rope cache ([cap][rope_row], the rotated shared key). The positions are+// kv_start..pos_base+s (causal), or the row's selection list: sel[sel_off + s*sel_row]+// = count, then the positions (a DSA indexer's choice); a negative count means the+// causal range, a negative entry is skipped. A row with no position gets clat = 0.+// The softmax runs online over tiles of 64 positions (running max and sum, the+// accumulator rescaled when the max grows), so no score row is stored and a context+// of any length costs one pass over the cache. The CPU normalizes first, then sums:+// the two agree to rounding. Limits: K <= 1024, R <= 128.+//+// mode 1, RoPE over segments from a host table, in place or into another buffer.+// Segment g: row g / per_row, j = g % per_row, at x_off + row*x_row + j*x_seg (the+// same for y). Its first rd floats rotate with (c, s) = cs[cs_off + row*cs_row + 2i],+// cs[... + 1] for i < rd/2; the rest of the segment (seg_len - rd floats) is copied+// when y is another buffer (copy_rest). style 0: rotate-half, a = x[i], b = x[i + rd/2];+// style 1: interleaved pairs in, halves out, a = x[2i], b = x[2i+1] (GLM, DeepSeek):+// y[i] = a*c - b*s, y[i + rd/2] = b*c + a*s+// One workgroup per segment, so the pairs can be read before any is written (rd <= 256).+//+// mode 2, LayerNorm over segments (a DSA indexer's key norm): y = (x - mean) * r * w+// + b with r = 1 / sqrt(var + eps), weight at w_off, bias at b_off when has_b. One+// workgroup per segment, laid out as in mode 1. The CPU sums in double (colibri) or in+// float in order (glm53); this is a float tree: they agree to rounding.+#extension GL_KHR_shader_subgroup_arithmetic : require+layout(local_size_x = 256) in;++layout(std430, binding = 0) readonly buffer QA { float qa[]; }; // mode 0: absorbed query; 1, 2: x+layout(std430, binding = 1) readonly buffer QR { float qrb[]; }; // mode 0: q's rotated part; 1: cos/sin; 2: w, b+layout(std430, binding = 2) readonly buffer LC { float lc[]; }; // mode 0: latent cache+layout(std430, binding = 3) readonly buffer RC { float rc[]; }; // mode 0: rope cache+layout(std430, binding = 4) readonly buffer SL { int sel[]; }; // mode 0: selection lists+layout(std430, binding = 5) buffer OB { float ob[]; }; // mode 0: clat; 1, 2: y++// Push constants: one block of 32 words, read per mode (vk_chain.h's VkcMlaCore and+// VkcMlaRow have the same layout).+layout(push_constant) uniform P { int v[32]; } p;+// mode 0+#define S_ p.v[1]+#define H_ p.v[2]+#define K_ p.v[3]+#define R_ p.v[4]+#define POS_BASE p.v[5]+#define KV_START p.v[6]+#define QA_OFF p.v[7]+#define QA_ROW p.v[8]+#define QA_SEG p.v[9]+#define QR_OFF p.v[10]+#define QR_ROW p.v[11]+#define QR_SEG p.v[12]+#define LAT_OFF p.v[13]+#define LAT_ROW p.v[14]+#define ROPE_OFF p.v[15]+#define ROPE_ROW p.v[16]+#define SEL_OFF p.v[17]+#define SEL_ROW p.v[18]+#define O_OFF p.v[19]+#define O_ROW p.v[20]+#define O_SEG p.v[21]+#define SCALE intBitsToFloat(p.v[22])+// modes 1 and 2+#define NSEG p.v[1]+#define PER_ROW p.v[2]+#define RD p.v[3]+#define SEG_LEN p.v[4]+#define STYLE p.v[5]+#define X_OFF p.v[6]+#define X_ROW p.v[7]+#define X_SEG p.v[8]+#define Y_OFF p.v[9]+#define Y_ROW p.v[10]+#define Y_SEG p.v[11]+#define CS_OFF p.v[12]+#define CS_ROW p.v[13]+#define W_OFF p.v[14]+#define B_OFF p.v[15]+#define HAS_B p.v[16]+#define EPS intBitsToFloat(p.v[17])+#define COPY_REST p.v[18] // mode 1: y is not x, the rest of the segment is copied++shared float qs[1024];+shared float qrs[128];+shared float sc[64];+shared int tp[64];+shared float red[256];++void core() {+ int h = int(gl_WorkGroupID.x), s = int(gl_WorkGroupID.y);+ int tid = int(gl_LocalInvocationID.x);+ int lane = int(gl_SubgroupInvocationID), sgs = int(gl_SubgroupSize);+ int sg = int(gl_SubgroupID), nsg = 256 / sgs;+ int qb = QA_OFF + s * QA_ROW + h * QA_SEG, rb = QR_OFF + s * QR_ROW + h * QR_SEG;+ for (int i = tid; i < K_; i += 256) qs[i] = qa[qb + i];+ for (int i = tid; i < R_; i += 256) qrs[i] = qrb[rb + i];+ int n = POS_BASE + s + 1 - KV_START;+ bool list = false;+ int lb = 0;+ if (SEL_ROW > 0) {+ lb = SEL_OFF + s * SEL_ROW;+ int c = sel[lb];+ if (c >= 0) { n = c; list = true; }+ }+ barrier();+ float m = -3.0e38, l = 0.0;+ float acc[4] = float[4](0.0, 0.0, 0.0, 0.0);+ for (int t0 = 0; t0 < n; t0 += 64) {+ int cnt = min(64, n - t0);+ // the tile's positions and scores: one subgroup per position, lanes split the dot+ if (tid < 64) {+ int t = -1;+ if (tid < cnt) t = list ? sel[lb + 1 + t0 + tid] : KV_START + t0 + tid;+ tp[tid] = t;+ }+ barrier();+ for (int j = sg; j < cnt; j += nsg) {+ int t = tp[j];+ float a = 0.0;+ if (t >= 0) {+ int lo = LAT_OFF + t * LAT_ROW, ro = ROPE_OFF + t * ROPE_ROW;+ for (int i = lane; i < K_; i += sgs) a += qs[i] * lc[lo + i];+ for (int i = lane; i < R_; i += sgs) a += qrs[i] * rc[ro + i];+ }+ float tot = subgroupAdd(a);+ if (lane == 0) sc[j] = t >= 0 ? tot * SCALE : -3.0e38;+ }+ barrier();+ // the tile's maximum, then the weights+ red[tid] = tid < cnt ? sc[tid] : -3.0e38;+ barrier();+ for (int off = 128; off > 0; off >>= 1) {+ if (tid < off) red[tid] = max(red[tid], red[tid + off]);+ barrier();+ }+ float mt = red[0];+ barrier();+ if (mt > -1.0e38) { // a tile with a live position (a skipped entry scores -3e38)+ float mn = max(m, mt);+ float corr = m > -1.0e38 ? exp(m - mn) : 0.0;+ if (tid < 64) sc[tid] = tid < cnt && tp[tid] >= 0 ? exp(sc[tid] - mn) : 0.0;+ barrier();+ red[tid] = tid < 64 ? sc[tid] : 0.0;+ barrier();+ for (int off = 128; off > 0; off >>= 1) {+ if (tid < off) red[tid] += red[tid + off];+ barrier();+ }+ l = l * corr + red[0];+ for (int k = 0; k < 4; k++) {+ int i = tid + 256 * k;+ if (i >= K_) break;+ float a = acc[k] * corr;+ for (int j = 0; j < cnt; j++) {+ int t = tp[j];+ if (t >= 0) a += sc[j] * lc[LAT_OFF + t * LAT_ROW + i];+ }+ acc[k] = a;+ }+ m = mn;+ }+ barrier();+ }+ float inv = l > 0.0 ? 1.0 / l : 0.0;+ int ob0 = O_OFF + s * O_ROW + h * O_SEG;+ for (int k = 0; k < 4; k++) {+ int i = tid + 256 * k;+ if (i >= K_) break;+ ob[ob0 + i] = acc[k] * inv;+ }+}++void rope() {+ int g = int(gl_WorkGroupID.x + gl_WorkGroupID.y * gl_NumWorkGroups.x);+ if (g >= NSEG) return;+ int row = g / PER_ROW, j = g - row * PER_ROW;+ int xb = X_OFF + row * X_ROW + j * X_SEG, yb = Y_OFF + row * Y_ROW + j * Y_SEG;+ int tid = int(gl_LocalInvocationID.x), half_ = RD / 2;+ for (int i = tid; i < RD; i += 256) red[i] = qa[xb + i];+ barrier();+ int cb = CS_OFF + row * CS_ROW;+ for (int i = tid; i < half_; i += 256) {+ float c = qrb[cb + 2 * i], sn = qrb[cb + 2 * i + 1];+ float a = STYLE == 1 ? red[2 * i] : red[i], b = STYLE == 1 ? red[2 * i + 1] : red[i + half_];+ ob[yb + i] = a * c - b * sn;+ ob[yb + i + half_] = b * c + a * sn;+ }+ if (COPY_REST != 0) for (int i = RD + tid; i < SEG_LEN; i += 256) ob[yb + i] = qa[xb + i];+}++void lnorm() {+ int g = int(gl_WorkGroupID.x + gl_WorkGroupID.y * gl_NumWorkGroups.x);+ if (g >= NSEG) return;+ int row = g / PER_ROW, j = g - row * PER_ROW;+ int xb = X_OFF + row * X_ROW + j * X_SEG, yb = Y_OFF + row * Y_ROW + j * Y_SEG;+ int tid = int(gl_LocalInvocationID.x), D = SEG_LEN;+ float a = 0.0;+ for (int i = tid; i < D; i += 256) a += qa[xb + i];+ red[tid] = a;+ barrier();+ for (int off = 128; off > 0; off >>= 1) {+ if (tid < off) red[tid] += red[tid + off];+ barrier();+ }+ float mean = red[0] / float(D);+ barrier();+ a = 0.0;+ for (int i = tid; i < D; i += 256) { float d = qa[xb + i] - mean; a += d * d; }+ red[tid] = a;+ barrier();+ for (int off = 128; off > 0; off >>= 1) {+ if (tid < off) red[tid] += red[tid + off];+ barrier();+ }+ float rr = 1.0 / sqrt(red[0] / float(D) + EPS);+ barrier();+ for (int i = tid; i < D; i += 256) {+ float v = (qa[xb + i] - mean) * rr * qrb[W_OFF + i];+ ob[yb + i] = HAS_B != 0 ? v + qrb[B_OFF + i] : v;+ }+}++void main() {+ if (p.v[0] == 0) core();+ else if (p.v[0] == 1) rope();+ else lnorm();+}diff --git a/c/shaders/chain_mla.spv b/c/shaders/chain_mla.spvnew file mode 100644index 00000000..165c753bBinary files /dev/null and b/c/shaders/chain_mla.spv differdiff --git a/c/tests/test_vk_chain.c b/c/tests/test_vk_chain.cindex cf036906..b016afe7 100644--- a/c/tests/test_vk_chain.c+++ b/c/tests/test_vk_chain.c@@ -18,6 +18,13 @@* qsa block keys, and the selection with ties broken as the CPU sorts* ple the gate and the dilated convolution with its ring and snapshot* frames vkc_write, vkc_read, a frame left in flight and one ordered after it+ * mla the per-head weight blocks in every format, both ways, with a gate; RoPE+ * interleaved and rotate-half, in place and into a cache row; LayerNorm;+ * the layer op against colibri.c's absorbed attention over several+ * geometries (q latent or none, NoPE, kv_b or the split halves, selection+ * lists with skipped entries, a gate, prefill rows, a long context from+ * kv_start, latents up to 1024)+ * dsa the indexer's top-k selection bit for bit, ties included** make vk-chain-check VK=1 (VK_ICD_FILENAMES=.../lvp_icd.json for Lavapipe) */#include <stdio.h>@@ -439,6 +446,350 @@ static void test_ple(void) {free(hd); free(rd); free(sd);}+/* ---- MLA: weight blocks, RoPE and LayerNorm rows, the layer op, the DSA selection ------ */+static float e4m3f(uint8_t b) { /* the CPU's E4M3_LUT */+ int e = (b >> 3) & 15, m = b & 7;+ float v = e == 0 ? m * 0.001953125f : ldexpf(1.f + m * 0.125f, e - 7);+ return (b & 0x80) ? -v : v;+}+/* A resident [O x I] tensor in fmt with random codes (values about `scale`); W gets the+ * dequantized weights. Groups of 64 for the grouped formats. */+static ColiVkTensor *mk_tensor(int fmt, int O, int I, float scale, float *W) {+ void *codes = NULL; float *sc = NULL; int gs = 0, ng64 = (I + 63) / 64;+ size_t n = (size_t)O * I;+ if (fmt == 1 || fmt == 13) {+ int8_t *q = malloc(n); gs = fmt == 13 ? 64 : 0;+ int ns = fmt == 13 ? O * ng64 : O;+ sc = malloc((size_t)ns * sizeof *sc);+ for (int k = 0; k < ns; k++) sc[k] = scale * (0.5f + (rnd() % 100) / 100.f) / 127.f;+ for (int o = 0; o < O; o++) for (int i = 0; i < I; i++) {+ q[(size_t)o * I + i] = (int8_t)((int)(rnd() % 255) - 127);+ W[(size_t)o * I + i] = q[(size_t)o * I + i] * sc[fmt == 13 ? o * ng64 + i / 64 : o];+ }+ codes = q;+ } else if (fmt == 2 || fmt == 4) {+ size_t rb = (size_t)(I + 1) / 2; uint8_t *q = calloc((size_t)O * rb, 1); gs = fmt == 4 ? 64 : 0;+ int ns = fmt == 4 ? O * ng64 : O;+ sc = malloc((size_t)ns * sizeof *sc);+ for (int k = 0; k < ns; k++) sc[k] = scale * (0.5f + (rnd() % 100) / 100.f) / 7.f;+ for (int o = 0; o < O; o++) for (int i = 0; i < I; i++) {+ int v = (int)(rnd() % 16);+ q[(size_t)o * rb + i / 2] |= (uint8_t)(v << ((i & 1) * 4));+ W[(size_t)o * I + i] = (v - 8) * sc[fmt == 4 ? o * ng64 + i / 64 : o];+ }+ codes = q;+ } else if (fmt == 5) { /* int3-g64: 16 bytes of 2-bit lows, 8 of high bits, a scale per 64 */+ size_t rb = (size_t)ng64 * 24; uint8_t *q = calloc((size_t)O * rb, 1);+ sc = malloc((size_t)O * ng64 * sizeof *sc);+ for (int k = 0; k < O * ng64; k++) sc[k] = scale * (0.5f + (rnd() % 100) / 100.f) / 4.f;+ for (int o = 0; o < O; o++) for (int i = 0; i < I; i++) {+ int u = (int)(rnd() % 8), g = i / 64, j = i % 64;+ uint8_t *gb = q + (size_t)o * rb + (size_t)g * 24;+ gb[j / 4] |= (uint8_t)((u & 3) << ((j & 3) * 2));+ gb[16 + j / 8] |= (uint8_t)(((u >> 2) & 1) << (j & 7));+ W[(size_t)o * I + i] = (u - 4) * sc[o * ng64 + g];+ }+ codes = q;+ } else if (fmt == 12) { /* fp8 e4m3, a scale per 64 */+ uint8_t *q = malloc(n); gs = 64;+ sc = malloc((size_t)O * ng64 * sizeof *sc);+ for (int k = 0; k < O * ng64; k++) sc[k] = scale * (0.5f + (rnd() % 100) / 100.f) / 8.f;+ for (int o = 0; o < O; o++) for (int i = 0; i < I; i++) {+ uint8_t b; do b = (uint8_t)rnd(); while ((b & 0x7f) == 0x7f || ((b >> 3) & 15) > 10);+ q[(size_t)o * I + i] = b; W[(size_t)o * I + i] = e4m3f(b) * sc[o * ng64 + i / 64];+ }+ codes = q;+ } else if (fmt == 10) {+ float *w = fvec(n, scale); memcpy(W, w, n * sizeof *W); codes = w;+ } else { /* 11 bf16 */+ uint16_t *w = malloc(n * 2);+ for (size_t i = 0; i < n; i++) { w[i] = f2bf(frnd() * scale); W[i] = bf2f(w[i]); }+ codes = w;+ }+ ColiVkTensor *t = NULL;+ int ok = coli_vk_tensor_ensure(&t, codes, sc, fmt, I, O, gs);+ free(codes); free(sc);+ return ok ? t : NULL;+}++/* the per-head weight blocks, both directions, every format, a gate */+static void test_hgemv(int fmt, int trans) {+ int S = 3, H = 3, n = trans ? 24 : 20, I = 128, hstride = n + 9, hoff = 5, O = (H - 1) * hstride + hoff + n + 2;+ float *W = malloc((size_t)O * I * sizeof *W);+ ColiVkTensor *t = mk_tensor(fmt, O, I, 0.1f, W);+ if (!t) { CHECK(0, "hgemv fmt %d: upload", fmt); free(W); return; }+ int xin = trans ? n : I, xseg = xin + 3, xrow = H * xseg + 1, yout = trans ? I : n, yseg = yout + 2, yrow = H * yseg;+ float *x = fvec((size_t)S * xrow + 7, 1.f), *g = fvec((size_t)S * H * n, 2.f);+ float *ref = calloc((size_t)S * yrow, sizeof *ref);+ for (int s = 0; s < S; s++) for (int h = 0; h < H; h++) {+ const float *xs = x + 7 + (size_t)s * xrow + h * xseg;+ float *ys = ref + (size_t)s * yrow + h * yseg;+ if (trans) for (int i = 0; i < I; i++) {+ double a = 0; for (int d = 0; d < n; d++) a += (double)W[(size_t)(h * hstride + hoff + d) * I + i] * xs[d];+ ys[i] = (float)a;+ } else for (int o = 0; o < n; o++) {+ double a = 0; for (int i = 0; i < I; i++) a += (double)W[(size_t)(h * hstride + hoff + o) * I + i] * xs[i];+ ys[o] = (float)a * sigm(g[(size_t)s * H * n + h * n + o]);+ }+ }+ VkcBuf *xb = up(x, (size_t)S * xrow + 7), *gb = up(g, (size_t)S * H * n), *yb = vkc_buf((size_t)S * yrow * 4, VKC_DEV);+ VkcHgemv p = {trans, S, H, n, hstride, hoff, 7, xrow, xseg, 0, yrow, yseg, 0, H * n, !trans};+ vkc_begin(); int ok = vkc_mla_hgemv(t, xb, yb, trans ? NULL : gb, &p); vkc_submit(1);+ float *y = down(yb, 0, (size_t)S * yrow);+ double e = relerr(y, ref, (size_t)S * yrow, 1e-3);+ CHECK(ok && e < 2e-5, "hgemv fmt %d trans %d: ok %d err %.2e", fmt, trans, ok, e);+ vkc_free(xb); vkc_free(gb); vkc_free(yb); coli_vk_tensor_free(t);+ free(W); free(x); free(g); free(ref); free(y);+}++/* interleaved and rotate-half RoPE, in place and into another place; LayerNorm */+static void test_mla_rows(void) {+ int rows = 4, per = 3, seg = 20, rd = 12, xrow = per * seg + 5, yrow = per * (seg + 2), half = rd / 2;+ float *x = fvec((size_t)rows * xrow, 1.f), *cs = malloc((size_t)rows * rd * sizeof *cs);+ for (int r = 0; r < rows; r++) for (int j = 0; j < half; j++) {+ float ang = (float)(500 + 91 * r) * powf(10000.f, -2.f * j / rd);+ cs[r * rd + 2 * j] = cosf(ang); cs[r * rd + 2 * j + 1] = sinf(ang);+ }+ VkcBuf *cb = up(cs, (size_t)rows * rd);+ for (int style = 0; style < 2; style++) for (int inplace = 0; inplace < 2; inplace++) {+ int yr = inplace ? xrow : yrow, ys = inplace ? seg : seg + 2;+ float *ref = calloc((size_t)rows * yr, sizeof *ref);+ if (inplace) memcpy(ref, x, (size_t)rows * xrow * sizeof *ref);+ for (int r = 0; r < rows; r++) for (int j = 0; j < per; j++) {+ const float *v = x + r * xrow + j * seg; float *o = ref + r * yr + j * ys;+ for (int i = 0; i < half; i++) {+ float a = style ? v[2 * i] : v[i], b = style ? v[2 * i + 1] : v[i + half];+ float c = cs[r * rd + 2 * i], sn = cs[r * rd + 2 * i + 1];+ o[i] = a * c - b * sn; o[i + half] = b * c + a * sn;+ }+ for (int i = rd; i < seg; i++) o[i] = v[i];+ }+ VkcBuf *xb = up(x, (size_t)rows * xrow), *yb = inplace ? xb : vkc_buf((size_t)rows * yr * 4, VKC_DEV);+ VkcMlaRow p = {rows * per, per, rd, seg, style, 0, xrow, seg, 0, yr, ys, 0, rd, 0, 0, 0, 0.f};+ vkc_begin(); int ok = vkc_mla_rope(xb, cb, yb, &p); vkc_submit(1);+ float *y = down(yb, 0, (size_t)rows * yr);+ double e = relerr(y, ref, (size_t)rows * yr, 1e-3);+ CHECK(ok && e < 1e-6, "mla rope style %d in place %d: ok %d err %.2e", style, inplace, ok, e);+ if (!inplace) vkc_free(yb);+ vkc_free(xb); free(ref); free(y);+ }+ /* LayerNorm, with and without the bias, into the next segment's place */+ float *prm = fvec(2 * seg, 1.f);+ VkcBuf *pb = up(prm, 2 * seg);+ for (int hb = 0; hb < 2; hb++) {+ float *ref = calloc((size_t)rows * yrow, sizeof *ref);+ for (int r = 0; r < rows; r++) for (int j = 0; j < per; j++) {+ const float *v = x + r * xrow + j * seg; float *o = ref + r * yrow + j * (seg + 2);+ double mu = 0, var = 0; for (int i = 0; i < seg; i++) mu += v[i]; mu /= seg;+ for (int i = 0; i < seg; i++) var += (v[i] - mu) * (v[i] - mu); var /= seg;+ float rr = 1.f / sqrtf((float)var + 1e-6f);+ for (int i = 0; i < seg; i++) o[i] = (float)(v[i] - mu) * rr * prm[i] + (hb ? prm[seg + i] : 0.f);+ }+ VkcBuf *xb = up(x, (size_t)rows * xrow), *yb = vkc_buf((size_t)rows * yrow * 4, VKC_DEV);+ VkcMlaRow p = {rows * per, per, 0, seg, 0, 0, xrow, seg, 0, yrow, seg + 2, 0, 0, 0, seg, hb, 1e-6f};+ vkc_begin(); int ok = vkc_mla_lnorm(xb, pb, yb, &p); vkc_submit(1);+ float *y = down(yb, 0, (size_t)rows * yrow);+ double e = relerr(y, ref, (size_t)rows * yrow, 1e-3);+ CHECK(ok && e < 2e-6, "mla layernorm bias %d: ok %d err %.2e", hb, ok, e);+ vkc_free(xb); vkc_free(yb); free(ref); free(y);+ }+ vkc_free(pb); vkc_free(cb); free(prm); free(x); free(cs);+}++/* The MLA layer op against a double reference of colibri.c's absorbed attention:+ * geometry and formats from the caller; `split` gives the weights as [H*K x Q] and+ * [H*V x K] instead of kv_b; `list` gives every other row a selection list with a+ * skipped entry; `gate` a sigmoid gate on the values. The cache holds random rows+ * before pos_base (from kv_start); the step writes S more. Two frames: the step's+ * projections, then (after the host's selection lists) the attention. */+typedef struct { int H, Q, R, V, K, q_lora, D, S, pos_base, kv_start, style, split, list, gate, fq, fkv, fo; } MlaCase;+static void rmsref(double *y, const double *x, const float *w, int n, float eps) {+ double ss = 0; for (int i = 0; i < n; i++) ss += x[i] * x[i];+ double r = 1.0 / sqrt(ss / n + eps); for (int i = 0; i < n; i++) y[i] = x[i] * r * w[i];+}+static void test_mla(MlaCase c) {+ int H = c.H, Q = c.Q, R = c.R, V = c.V, K = c.K, D = c.D, S = c.S, pb = c.pos_base, QR = Q + R, KR = K + R;+ int cap = pb + S + 3, qin = c.q_lora > 0 ? c.q_lora : D, half = R / 2;+ float eps = 1e-5f, scale = 1.f / sqrtf((float)QR) * 1.1f;+ float *Wqa = c.q_lora ? malloc((size_t)c.q_lora * D * 4) : NULL, *Wqb = malloc((size_t)H * QR * qin * 4);+ float *Wkva = malloc((size_t)KR * D * 4), *Wo = malloc((size_t)D * H * V * 4);+ float *Wkvb = malloc((size_t)H * (Q + V) * K * 4), *Wk = malloc((size_t)H * K * Q * 4), *Wv = malloc((size_t)H * V * K * 4);+ VkcMla m = {H, Q, R, V, K, D, c.q_lora, eps, scale, c.style, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0};+ if (c.q_lora) m.q_a = mk_tensor(c.fq, c.q_lora, D, 1.f / sqrtf((float)D) * 2.f, Wqa);+ m.q_b = mk_tensor(c.fq, H * QR, qin, 1.f / sqrtf((float)qin) * 2.f, Wqb);+ m.kv_a = mk_tensor(c.fkv, KR, D, 1.f / sqrtf((float)D) * 2.f, Wkva);+ if (c.split) { m.k_abs = mk_tensor(c.fkv, H * K, Q, 1.f / sqrtf((float)Q), Wk); m.v_abs = mk_tensor(c.fkv, H * V, K, 1.f / sqrtf((float)K), Wv); }+ else {+ m.kv_b = mk_tensor(c.fkv, H * (Q + V), K, 1.f / sqrtf((float)K), Wkvb);+ for (int h = 0; h < H; h++) { /* the same weights seen as the two halves */+ for (int d = 0; d < Q; d++) for (int i = 0; i < K; i++) Wk[((size_t)h * K + i) * Q + d] = Wkvb[((size_t)h * (Q + V) + d) * K + i];+ for (int v = 0; v < V; v++) for (int i = 0; i < K; i++) Wv[((size_t)h * V + v) * K + i] = Wkvb[((size_t)h * (Q + V) + Q + v) * K + i];+ }+ }+ m.o = mk_tensor(c.fo, D, H * V, 1.f / sqrtf((float)(H * V)), Wo);+ float *prm = malloc((size_t)(qin + K + 8) * 4);+ for (int i = 0; i < qin + K + 8; i++) prm[i] = 0.5f + (rnd() % 100) / 100.f;+ m.prm = up(prm, (size_t)qin + K + 8); m.q_norm = 3; m.kv_norm = 3 + qin;+ /* the cache: rows before pos_base as the device holds them (normalized, rotated) */+ float *lat = fvec((size_t)cap * K, 1.f), *rope = R ? fvec((size_t)cap * R, 1.f) : NULL;+ float *x = fvec((size_t)S * D, 1.f), *cs = R ? malloc((size_t)S * R * 4) : NULL, *gate = fvec((size_t)S * H * V, 2.f);+ for (int s = 0; s < S; s++) for (int j = 0; j < half; j++) {+ float ang = (float)(pb + s) * powf(10000.f, -2.f * j / R);+ cs[s * R + 2 * j] = cosf(ang); cs[s * R + 2 * j + 1] = sinf(ang);+ }+ int selrow = 2 + cap;+ int *sel = calloc((size_t)S * selrow, sizeof *sel);+ for (int s = 0; s < S; s++) {+ int vis = pb + s + 1, n = 0;+ if (!c.list || s % 2) { sel[s * selrow] = -1; continue; }+ for (int t = vis - 1; t >= c.kv_start; t -= 2) sel[s * selrow + 1 + n++] = t; /* newest first, every other */+ sel[s * selrow + 1 + n++] = -1; /* a skipped entry */+ sel[s * selrow] = n;+ }+ /* reference */+ double *q = calloc((size_t)S * H * QR, 8), *kvr = calloc((size_t)S * KR, 8), *qa = calloc((size_t)S * qin, 8);+ double *latr = malloc((size_t)cap * K * 8), *roper = malloc((size_t)cap * (R ? R : 1) * 8);+ for (size_t i = 0; i < (size_t)cap * K; i++) latr[i] = lat[i];+ for (size_t i = 0; R && i < (size_t)cap * R; i++) roper[i] = rope[i];+ for (int s = 0; s < S; s++) {+ const float *xs = x + (size_t)s * D;+ if (c.q_lora) {+ double *a = qa + (size_t)s * qin;+ for (int o = 0; o < c.q_lora; o++) { double t = 0; for (int i = 0; i < D; i++) t += (double)Wqa[(size_t)o * D + i] * xs[i]; a[o] = t; }+ rmsref(a, a, prm + 3, c.q_lora, eps);+ } else for (int i = 0; i < D; i++) qa[(size_t)s * qin + i] = xs[i];+ for (int o = 0; o < H * QR; o++) { double t = 0; for (int i = 0; i < qin; i++) t += (double)Wqb[(size_t)o * qin + i] * qa[(size_t)s * qin + i]; q[(size_t)s * H * QR + o] = t; }+ for (int o = 0; o < KR; o++) { double t = 0; for (int i = 0; i < D; i++) t += (double)Wkva[(size_t)o * D + i] * xs[i]; kvr[(size_t)s * KR + o] = t; }+ rmsref(latr + (size_t)(pb + s) * K, kvr + (size_t)s * KR, prm + 3 + qin, K, eps);+ for (int h = 0; h <= H; h++) { /* the heads' rotated parts, then the shared key's */+ double *v = h < H ? q + (size_t)s * H * QR + h * QR + Q : kvr + (size_t)s * KR + K, in[256];+ double *o = h < H ? v : roper + (size_t)(pb + s) * R;+ for (int i = 0; i < R; i++) in[i] = v[i];+ for (int i = 0; i < half; i++) {+ double a = c.style ? in[2 * i] : in[i], b = c.style ? in[2 * i + 1] : in[i + half];+ double cc = cs[s * R + 2 * i], sn = cs[s * R + 2 * i + 1];+ o[i] = a * cc - b * sn; o[i + half] = b * cc + a * sn;+ }+ }+ }+ float *ref = malloc((size_t)S * D * 4);+ double *ctx = calloc((size_t)H * V, 8);+ for (int s = 0; s < S; s++) {+ for (int h = 0; h < H; h++) {+ const double *qs = q + (size_t)s * H * QR + h * QR;+ double qabs[1024], clat[1024], *sc = malloc((size_t)cap * 8);+ for (int i = 0; i < K; i++) { double t = 0; for (int d = 0; d < Q; d++) t += (double)Wk[((size_t)h * K + i) * Q + d] * qs[d]; qabs[i] = t; }+ const int *ls = sel + s * selrow;+ int n = ls[0] >= 0 ? ls[0] : pb + s + 1 - c.kv_start, used = 0;+ int *pos = malloc((size_t)(n + 1) * sizeof *pos);+ for (int j = 0; j < n; j++) { int t = ls[0] >= 0 ? ls[1 + j] : c.kv_start + j; if (t >= 0) pos[used++] = t; }+ double mx = -1e300, sum = 0;+ for (int j = 0; j < used; j++) {+ double a = 0; int t = pos[j];+ for (int i = 0; i < K; i++) a += qabs[i] * latr[(size_t)t * K + i];+ for (int i = 0; i < R; i++) a += qs[Q + i] * roper[(size_t)t * R + i];+ sc[j] = a * scale; if (sc[j] > mx) mx = sc[j];+ }+ for (int j = 0; j < used; j++) { sc[j] = exp(sc[j] - mx); sum += sc[j]; }+ for (int i = 0; i < K; i++) { double a = 0; for (int j = 0; j < used; j++) a += sc[j] / sum * latr[(size_t)pos[j] * K + i]; clat[i] = a; }+ for (int v = 0; v < V; v++) {+ double a = 0; for (int i = 0; i < K; i++) a += (double)Wv[((size_t)h * V + v) * K + i] * clat[i];+ if (c.gate) a *= 1.0 / (1.0 + exp(-(double)gate[(size_t)s * H * V + h * V + v]));+ ctx[h * V + v] = a;+ }+ free(sc); free(pos);+ }+ for (int o = 0; o < D; o++) { double t = 0; for (int i = 0; i < H * V; i++) t += (double)Wo[(size_t)o * H * V + i] * ctx[i]; ref[(size_t)s * D + o] = (float)t; }+ }+ /* the device */+ VkcMlaCache cc = {up(lat, (size_t)cap * K), R ? up(rope, (size_t)cap * R) : NULL, cap};+ VkcMlaScratch scr = {0};+ VkcBuf *xb = vkc_buf((size_t)(S * D + 16) * 4, VKC_DEV), *csb = R ? up(cs, (size_t)S * R) : NULL;+ VkcBuf *gb = up(gate, (size_t)S * H * V), *ob = vkc_buf((size_t)S * D * 4, VKC_DEV);+ VkcBuf *dn = vkc_buf((size_t)S * KR * 4, VKC_DOWN), *sb = vkc_buf((size_t)S * selrow * 4, VKC_DEV);+ int ok = vkc_mla_scratch(&scr, &m, S) && vkc_begin() && vkc_write(xb, 16, x, (size_t)S * D * 4) &&+ vkc_mla_qkv(&m, &scr, xb, 16, S, pb, csb, &cc, dn, 0) && vkc_submit(0) &&+ vkc_begin() && vkc_write(sb, 0, sel, (size_t)S * selrow * 4) &&+ vkc_mla_attn(&m, &scr, S, pb, c.kv_start, &cc, c.list ? sb : NULL, 0, selrow, c.gate ? gb : NULL, 0, ob, 0) &&+ vkc_submit(1);+ float *y = down(ob, 0, (size_t)S * D);+ double e = relerr(y, ref, (size_t)S * D, 1e-3);+ /* the new cache rows, as the host's copy receives them */+ float *nl = (float *)vkc_ptr(dn);+ double el = 0, er = 0;+ for (int s = 0; s < S; s++) {+ for (int i = 0; i < K; i++) { double d = fabs(nl[(size_t)s * K + i] - latr[(size_t)(pb + s) * K + i]); if (d > el) el = d; }+ for (int i = 0; i < R; i++) { double d = fabs(nl[(size_t)S * K + (size_t)s * R + i] - roper[(size_t)(pb + s) * R + i]); if (d > er) er = d; }+ }+ CHECK(ok && e < 2e-5 && el < 2e-5 && er < 2e-5 && !bad(y, (size_t)S * D),+ "mla H %d Q %d R %d V %d K %d q_lora %d S %d pos %d kv_start %d style %d split %d list %d gate %d fmt %d/%d/%d: "+ "ok %d err %.2e latent %.2e rope %.2e", H, Q, R, V, K, c.q_lora, S, pb, c.kv_start, c.style, c.split, c.list, c.gate,+ c.fq, c.fkv, c.fo, ok, e, el, er);+ if (getenv("VKC_TEST_VERBOSE")) printf("mla case H %d K %d S %d: err %.2e latent %.2e rope %.2e\n", H, K, S, e, el, er);+ vkc_mla_scratch_free(&scr);+ vkc_free(cc.lat); vkc_free(cc.rope); vkc_free(xb); vkc_free(csb); vkc_free(gb); vkc_free(ob); vkc_free(dn); vkc_free(sb);+ vkc_free(m.prm);+ ColiVkTensor *ts[7] = {m.q_a, m.q_b, m.kv_a, m.kv_b, m.k_abs, m.v_abs, m.o};+ for (int i = 0; i < 7; i++) if (ts[i]) coli_vk_tensor_free(ts[i]);+ free(Wqa); free(Wqb); free(Wkva); free(Wo); free(Wkvb); free(Wk); free(Wv); free(prm); free(lat); free(rope);+ free(x); free(cs); free(gate); free(sel); free(q); free(kvr); free(qa); free(latr); free(roper); free(ref); free(ctx); free(y);+}++/* The DSA selection against colibri.c's, bit for bit: quarter-step queries and keys+ * and power-of-two scales make every score exact on both sides, and the many zero+ * scores (every head negative) make ties the selection must break as the CPU does. */+/* negw: every head weight <= 0, so every score is 0 or below and the zeros tie at the+ * threshold far beyond top-k (the second band's order over long chunks) */+static void test_dsa(int S, int pos_base, int IH, int ID, int topk, int force, int negw) {+ int T = pos_base + S, krow = ID + 3, qrow = IH * ID + 1, wrow = IH + 2, selrow = 1 + topk + 2, scrow = T + 5;+ /* the buffers start at offsets 1 (queries), 2 (weights) and 3 (keys) */+ float *q = malloc((size_t)(S * qrow + 1) * 4), *k = malloc((size_t)(T * 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 < T * 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) - (negw ? 8 : 4)) * 0.5f;+ for (int t = 0; t < T; t += 5) for (int i = 0; i < ID; i++) k[3 + t * krow + i] = k[3 + (t / 5) * krow + i]; /* equal keys: ties */+ float qs = 0.25f, wsc = 0.5f;+ int *ref = calloc((size_t)S * selrow, sizeof *ref), fails0 = fails;+ for (int s = 0; s < S; s++) {+ int nk = pos_base + s + 1, *dst = ref + s * selrow;+ if (nk <= topk && !force) { dst[0] = -1; continue; }+ int keep = nk < topk ? nk : topk;+ float *isc = malloc((size_t)nk * 4), *tmp = malloc((size_t)nk * 4);+ for (int t = 0; t < nk; t++) {+ float a = 0;+ for (int h = 0; h < IH; h++) {+ float d0 = 0; for (int i = 0; i < ID; i++) d0 += q[1 + s * qrow + h * ID + i] * k[3 + t * krow + i];+ d0 *= qs; if (d0 > 0) a += w[2 + s * wrow + h] * d0;+ }+ isc[t] = a * wsc;+ }+ memcpy(tmp, isc, (size_t)nk * 4);+ for (int a = 0; a < nk; a++) for (int b = a + 1; b < nk; b++) if (tmp[b] > tmp[a]) { float x = tmp[a]; tmp[a] = tmp[b]; tmp[b] = x; }+ float thr = tmp[keep - 1];+ int nd = 0;+ for (int t = 0; t < nk && nd < keep; t++) if (isc[t] > thr) dst[1 + nd++] = t;+ for (int t = 0; t < nk && nd < keep; t++) if (isc[t] == thr) dst[1 + nd++] = t;+ dst[0] = nd;+ free(isc); free(tmp);+ }+ VkcBuf *qb = up(q, (size_t)S * qrow + 1), *kb = up(k, (size_t)T * krow + 3), *wb = up(w, (size_t)S * wrow + 2);+ VkcBuf *scb = vkc_buf((size_t)S * scrow * 4, VKC_DEV), *sb = vkc_buf((size_t)S * selrow * 4, VKC_DOWN);+ VkcDsa p = {S, pos_base, IH, ID, topk, force, 1, qrow, 2, wrow, 3, krow, scrow, selrow, qs, wsc};+ vkc_begin(); int ok = vkc_dsa_select(qb, wb, kb, scb, sb, &p); vkc_submit(1);+ const int *got = (const int *)vkc_ptr(sb);+ CHECK(ok, "dsa S %d pos %d: not recorded", S, pos_base);+ for (int s = 0; ok && s < S && fails == fails0; s++) {+ int n = ref[s * selrow] < 0 ? 0 : ref[s * selrow];+ int same = got[s * selrow] == ref[s * selrow];+ for (int j = 0; same && j < n; j++) same = got[s * selrow + 1 + j] == ref[s * selrow + 1 + j];+ CHECK(same, "dsa S %d pos %d IH %d ID %d topk %d force %d: row %d differs (count %d, expected %d)",+ S, pos_base, IH, ID, topk, force, s, got[s * selrow], ref[s * selrow]);+ if (!same && getenv("DSA_DEBUG")) { for (int j = 0; j < n; j++) printf(" %d/%d", got[s * selrow + 1 + j], ref[s * selrow + 1 + j]); printf("\n"); }+ }+ vkc_free(qb); vkc_free(kb); vkc_free(wb); vkc_free(scb); vkc_free(sb);+ free(q); free(k); free(w); free(ref);+}+/* ---- frames: many ops, frames in flight, ordering ---------------------------------------- */static void test_frames(void) {int n = 1000;@@ -521,6 +872,30 @@ int main(int argc, char **argv) {test_qsa();test_ple();test_frames();+ if (!vkc_mla_ready()) { fails++; printf("FAIL: the MLA shaders did not load\n"); }+ else {+ int hf[9] = {1, 2, 4, 5, 7, 10, 11, 12, 13};+ for (int k = 0; k < 9; k++) if (hf[k] != 7) { test_hgemv(hf[k], 0); test_hgemv(hf[k], 1); }+ test_mla_rows();+ printf("mla ops done\n");+ /* H Q R V K q_lora D S pos kv_start style split list gate fq fkv fo */+ MlaCase cases[] = {+ {4, 24, 8, 32, 32, 64, 128, 1, 12, 0, 1, 0, 0, 0, 10, 10, 10}, /* colibri's tiny, decode */+ {4, 24, 8, 32, 32, 64, 128, 5, 7, 0, 1, 0, 0, 0, 10, 10, 10}, /* prefill rows after earlier ones */+ {4, 24, 8, 32, 32, 64, 128, 1, 70, 0, 1, 0, 1, 0, 10, 10, 10}, /* a selection list */+ {3, 16, 16, 20, 48, 0, 96, 3, 9, 0, 0, 1, 0, 1, 1, 1, 1}, /* no q latent, rotate-half, split, gate, int8 */+ {2, 64, 0, 64, 128, 64, 128, 4, 66, 0, 0, 1, 1, 0, 4, 4, 4}, /* NoPE, int4-g64, lists */+ {2, 32, 64, 16, 64, 128, 128, 1, 300, 5, 1, 0, 0, 0, 2, 2, 11}, /* a long context from kv_start, int4 rows, bf16 */+ {2, 192, 64, 256, 512, 128, 256, 2, 70, 0, 1, 0, 0, 0, 4, 4, 4}, /* GLM-5.2's heads */+ {1, 16, 8, 16, 1024, 32, 64, 1, 20, 0, 1, 0, 0, 1, 10, 5, 10}, /* the largest latent, int3-g64 */+ };+ for (size_t k = 0; k < sizeof cases / sizeof *cases; k++) test_mla(cases[k]);+ printf("mla done\n");+ test_dsa(1, 30, 2, 16, 8, 0, 0); test_dsa(4, 40, 4, 32, 16, 0, 0); test_dsa(3, 5, 2, 16, 64, 0, 0);+ test_dsa(3, 5, 2, 16, 64, 1, 0); test_dsa(2, 700, 3, 64, 100, 0, 0); test_dsa(1, 9, 64, 64, 4, 0, 0);+ test_dsa(2, 900, 2, 16, 50, 0, 1);+ printf("dsa 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 f4b81f04..03adb438 100644--- a/c/vk_chain.c+++ b/c/vk_chain.c@@ -35,9 +35,14 @@ static const char *const pipe_file[P_NPIPE] = {#define VKC_PROF_Q 512/* COLI_VK_CHAIN_PROF=1: device time per kind of op (timestamps after every op; ops* that run side by side between two barriers share the time unevenly) */-enum { PK_GEMV8, PK_GEMV, PK_GEMM, PK_NORM, PK_ROPE, PK_ATTN, PK_DNCONV, PK_DNREC, PK_EW, PK_QSA, PK_PLE, PK_COPY, PK_N };+enum { PK_GEMV8, PK_GEMV, PK_GEMM, PK_NORM, PK_ROPE, PK_ATTN, PK_DNCONV, PK_DNREC, PK_EW, PK_QSA, PK_PLE, PK_COPY,+ PK_MLA, PK_MLAW, PK_DSA, PK_N };static const char *const pk_name[PK_N] = {"GEMV int8", "GEMV other", "tiled GEMM", "norm", "rope", "attention",- "dn conv", "dn recurrence", "element-wise", "qsa", "ple", "copy"};+ "dn conv", "dn recurrence", "element-wise", "qsa", "ple", "copy",+ "mla", "mla weights", "dsa"};+/* the MLA pipelines: optional (an engine without MLA layers needs none of them) */+enum { PM_MLA, PM_HGEMV, PM_DSA, PM_N };+static const char *const mla_file[PM_N] = {"chain_mla.spv", "chain_hgemv.spv", "chain_dsa.spv"};/* ---- memory: blocks per kind, buffers bound at offsets inside them -------------- */typedef struct { VkDeviceMemory mem; uint8_t *map; } VkcBlock;@@ -74,6 +79,7 @@ static struct {VkPipeline gemm[VKC_GEMM_MAX]; int gemm_bm[VKC_GEMM_MAX], gemm_bn[VKC_GEMM_MAX], ngemm;VkPipeline dnrec[VKC_DNREC_MAX]; int dnrec_kd[VKC_DNREC_MAX], ndnrec;VkShaderModule mod_gemv4; VkPipeline gemv4; int gemv4_xs; /* chain_gemv.comp: the vectorized decode GEMV */+ VkShaderModule mmod[PM_N]; VkPipeline mpipe[PM_N]; int mla_ok; /* chain_mla, chain_hgemv, chain_dsa */VkCommandPool cpool;VkcFrame fr[VKC_FRAMES];int cur; /* the open frame, -1 none */@@ -275,6 +281,21 @@ int vkc_init(void) {if ((K.gemv4 = make_pipe(K.mod_gemv4, &si))) K.gemv4_xs = xs;}}+ /* the MLA shaders, optional: without them only the MLA ops decline */+ K.mla_ok = 1;+ for (int i = 0; i < PM_N; i++) {+ char path[1200];+ const char *sl = strrchr(K.core.spv_path, '/');+ size_t pre = sl ? (size_t)(sl - K.core.spv_path) + 1 : 0;+ FILE *f = NULL;+ if (pre + strlen(mla_file[i]) + 1 < sizeof path) {+ memcpy(path, K.core.spv_path, pre); strcpy(path + pre, mla_file[i]);+ f = fopen(path, "rb");+ }+ if (f) fclose(f);+ 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 = 0;+ }/* 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++) {@@ -758,6 +779,139 @@ int vkc_ple(VkcBuf *keys, VkcBuf *hyp, VkcBuf *val, VkcBuf *prm, VkcBuf *gated,return record(K.pipe[P_PLE], bd, 8, p, sizeof *p, gx, gy, 1);}+/* ---- multi-head latent attention ------------------------------------------------- */+int vkc_mla_ready(void) { return vkc_ready() && K.mla_ok; }++int vkc_mla_core(VkcBuf *qabs, VkcBuf *qr, VkcBuf *lat, VkcBuf *rope, VkcBuf *sel, VkcBuf *clat, const VkcMlaCore *p) {+ K.kind = PK_MLA;+ if (!K.mla_ok || p->S < 1 || p->H < 1 || p->K < 1 || p->K > 1024 || p->R < 0 || p->R > 128 ||+ (p->R > 0 && !rope) || p->pos_base < 0 || p->kv_start < 0 || p->kv_start > p->pos_base) return 0;+ struct { int mode; VkcMlaCore b; } pc = {0, *p};+ if (!sel) pc.b.sel_row = 0;+ VkcBind bd[6] = {B(qabs, 0), B(qr, 0), B(lat, 0), B(p->R > 0 ? rope : NULL, 0), B(pc.b.sel_row > 0 ? sel : NULL, 0),+ B(clat, 1)};+ return record(K.mpipe[PM_MLA], bd, 6, &pc, sizeof pc, (uint32_t)p->H, (uint32_t)p->S, 1);+}+static int mla_rowop(int mode, VkcBuf *x, VkcBuf *aux, VkcBuf *y, const VkcMlaRow *p) {+ if (!K.mla_ok || !open_frame() || K.lost || p->nseg < 0) return 0;+ if (p->nseg == 0) return 1;+ if (mode == 1 && (p->rd < 2 || p->rd > 256 || (p->rd & 1) || p->rd > p->seg_len)) return 0;+ if (mode == 2 && p->seg_len < 1) return 0;+ struct { int mode; VkcMlaRow b; int copy_rest; } pc = {mode, *p, x != y};+ VkcBind bd[6] = {B(x, x == y), B(aux, 0), B(NULL, 0), B(NULL, 0), B(NULL, 0), B(y, 1)};+ uint32_t gx, gy; grid((uint64_t)p->nseg, &gx, &gy);+ return record(K.mpipe[PM_MLA], bd, 6, &pc, sizeof pc, gx, gy, 1);+}+int vkc_mla_rope(VkcBuf *x, VkcBuf *cs, VkcBuf *y, const VkcMlaRow *p) { K.kind = PK_ROPE; return mla_rowop(1, x, cs, y, p); }+int vkc_mla_lnorm(VkcBuf *x, VkcBuf *prm, VkcBuf *y, const VkcMlaRow *p) { K.kind = PK_NORM; return mla_rowop(2, x, prm, y, p); }++int vkc_mla_hgemv(ColiVkTensor *t, VkcBuf *x, VkcBuf *y, VkcBuf *gate, const VkcHgemv *p) {+ K.kind = PK_MLAW;+ ColiVkTensorInfo ti;+ if (!K.mla_ok || !open_frame() || K.lost || !coli_vk_tensor_info(t, &ti) || p->S < 1 || p->S > 65535 ||+ p->H < 1 || p->H > 65535 || p->n < 1 || (p->trans && p->n > 1024)) return 0;+ int f = ti.fmt;+ if (!(f == 1 || f == 2 || f == 4 || f == 5 || f == 7 || f == 10 || f == 11 || f == 12 || f == 13)) return 0;+ if ((f == 4 || f == 7 || f == 12 || f == 13) && ti.gs < 1) return 0;+ if ((int64_t)(p->H - 1) * p->hstride + p->hoff + p->n > (int64_t)ti.O) return 0; /* the rows exist */+ struct { int mode, fmt, I, rowWords, gs, S, H, n, hstride, hoff, x_off, x_row, x_seg, y_off, y_row, y_seg,+ g_off, g_row, has_gate; } pc = {p->trans, f, ti.I, ti.rowWords, ti.gs, p->S, p->H, p->n, p->hstride, p->hoff,+ p->x_off, p->x_row, p->x_seg, p->y_off, p->y_row, p->y_seg, p->g_off, p->g_row, gate && p->has_gate};+ VkcBind bd[5] = {B(x, 0), {(VkBuffer)ti.wbuf, 0, 0, 0}, {(VkBuffer)ti.sbuf, 0, 0, 0}, B(y, 1), B(pc.has_gate ? gate : NULL, 0)};+ if (p->trans) return record(K.mpipe[PM_HGEMV], bd, 5, &pc, sizeof pc, (uint32_t)p->H, (uint32_t)p->S, 1);+ /* rows: a subgroup each, grid-stride (at least four subgroups a workgroup) */+ int64_t rows = (int64_t)p->H * p->n, wg = (rows + 7) / 8;+ if (wg > 4096) wg = 4096;+ return record(K.mpipe[PM_HGEMV], bd, 5, &pc, sizeof pc, (uint32_t)wg, (uint32_t)p->S, 1);+}++int vkc_dsa_select(VkcBuf *iq, VkcBuf *hw, VkcBuf *keys, VkcBuf *sc, VkcBuf *sel, const VkcDsa *p) {+ K.kind = PK_DSA;+ if (!K.mla_ok || p->S < 1 || p->S > 65535 || p->IH < 1 || p->IH > 64 || p->ID < 1 || p->IH * p->ID > 4096 ||+ p->topk < 1 || p->pos_base < 0 || p->sc_row < p->pos_base + p->S ||+ p->sel_row < 1 + (p->topk < p->pos_base + p->S ? p->topk : p->pos_base + p->S)) return 0;+ struct { int mode; VkcDsa b; } pc = {0, *p};+ VkcBind bd[5] = {B(iq, 0), B(hw, 0), B(keys, 0), B(sc, 1), B(sel, 1)};+ return record(K.mpipe[PM_DSA], bd, 5, &pc, sizeof pc, (uint32_t)p->S, 1, 1);+}++int vkc_mla_scratch(VkcMlaScratch *s, const VkcMla *m, int rows) {+ if (s->rows >= rows && s->q) return 1;+ size_t r = (size_t)rows, H = (size_t)m->H;+ int ok = vkc_reserve(&s->qa, (m->q_lora > 0 ? r * m->q_lora : 1) * 4, VKC_DEV) &&+ vkc_reserve(&s->q, r * H * (m->Q + m->R) * 4, VKC_DEV) &&+ vkc_reserve(&s->kv, r * (m->K + m->R) * 4, VKC_DEV) &&+ vkc_reserve(&s->qabs, r * H * m->K * 4, VKC_DEV) &&+ vkc_reserve(&s->clat, r * H * m->K * 4, VKC_DEV) &&+ vkc_reserve(&s->ctx, r * H * m->V * 4, VKC_DEV);+ s->rows = ok ? rows : 0;+ return ok;+}+void vkc_mla_scratch_free(VkcMlaScratch *s) {+ vkc_free(s->qa); vkc_free(s->q); vkc_free(s->kv); vkc_free(s->qabs); vkc_free(s->clat); vkc_free(s->ctx);+ memset(s, 0, sizeof *s);+}+/* the tensor is there and has the shape [O x I] */+static int mla_shape(ColiVkTensor *t, int O, int I) {+ ColiVkTensorInfo ti;+ return t && coli_vk_tensor_info(t, &ti) && ti.I == I && ti.O == O;+}+int vkc_mla_qkv(const VkcMla *m, VkcMlaScratch *s, VkcBuf *x, size_t x_off, int S, int pos_base,+ VkcBuf *cs, VkcMlaCache *c, VkcBuf *down, size_t down_off) {+ int H = m->H, QR = m->Q + m->R, KR = m->K + m->R;+ if (!K.mla_ok || S < 1 || S > s->rows || pos_base < 0 || (int64_t)pos_base + S > c->cap || m->R < 0 ||+ (m->R & 1) || m->R > 128 || m->K < 1 || m->K > 1024 || (m->R > 0 && (!cs || !c->rope)) ||+ !mla_shape(m->q_b, H * QR, m->q_lora > 0 ? m->q_lora : m->D) || !mla_shape(m->kv_a, KR, m->D) ||+ (m->q_lora > 0 && !mla_shape(m->q_a, m->q_lora, m->D))) return 0;+ int ok;+ if (m->q_lora > 0) {+ VkcNorm qn = {S, m->q_lora, 1, 0, m->q_lora, m->q_lora, 0, m->q_lora, m->q_lora, (int)m->q_norm, 0, 0, m->eps, 1.f};+ ok = vkc_matmul(m->q_a, x, x_off, s->qa, 0, S) && vkc_norm(s->qa, m->prm, s->qa, &qn) &&+ vkc_matmul(m->q_b, s->qa, 0, s->q, 0, S);+ } else ok = vkc_matmul(m->q_b, x, x_off, s->q, 0, S);+ ok = ok && vkc_matmul(m->kv_a, x, x_off, s->kv, 0, S);+ VkcNorm ln = {S, m->K, 1, 0, KR, KR, pos_base * m->K, m->K, m->K, (int)m->kv_norm, 0, 0, m->eps, 1.f};+ ok = ok && vkc_norm(s->kv, m->prm, c->lat, &ln);+ if (ok && m->R > 0) {+ VkcMlaRow rq = {S * H, H, m->R, m->R, m->rope_style, m->Q, H * QR, QR, m->Q, H * QR, QR, 0, m->R, 0, 0, 0, 0.f};+ VkcMlaRow rk = {S, 1, m->R, m->R, m->rope_style, m->K, KR, 0, pos_base * m->R, m->R, 0, 0, m->R, 0, 0, 0, 0.f};+ ok = vkc_mla_rope(s->q, cs, s->q, &rq) && vkc_mla_rope(s->kv, cs, c->rope, &rk);+ }+ if (ok && down)+ ok = vkc_copy(down, down_off, c->lat, (size_t)pos_base * m->K, (size_t)S * m->K) &&+ (m->R == 0 || vkc_copy(down, down_off + (size_t)S * m->K, c->rope, (size_t)pos_base * m->R, (size_t)S * m->R));+ return ok;+}+int vkc_mla_attn(const VkcMla *m, VkcMlaScratch *s, int S, int pos_base, int kv_start, VkcMlaCache *c,+ VkcBuf *sel, size_t sel_off, int sel_row, VkcBuf *gate, size_t gate_off, VkcBuf *out, size_t out_off) {+ int H = m->H, QR = m->Q + m->R, HK = H * m->K, HV = H * m->V;+ if (!K.mla_ok || S < 1 || S > s->rows || (int64_t)pos_base + S > c->cap) return 0;+ if (m->kv_b ? !mla_shape(m->kv_b, H * (m->Q + m->V), m->K)+ : !(mla_shape(m->k_abs, HK, m->Q) && mla_shape(m->v_abs, HV, m->K))) return 0;+ if (m->o && out && !mla_shape(m->o, m->D, HV)) return 0;+ int ok;+ if (m->kv_b) { /* qa[s][h][i] = sum_d kv_b[h*(Q+V) + d][i] q[s][h][d], d < Q */+ VkcHgemv a = {1, S, H, m->Q, m->Q + m->V, 0, 0, H * QR, QR, 0, HK, m->K, 0, 0, 0};+ ok = vkc_mla_hgemv(m->kv_b, s->q, s->qabs, NULL, &a);+ } else { /* qa[s][h][i] = k_abs[h*K + i] . q[s][h][0..Q) */+ VkcHgemv a = {0, S, H, m->K, m->K, 0, 0, H * QR, QR, 0, HK, m->K, 0, 0, 0};+ ok = vkc_mla_hgemv(m->k_abs, s->q, s->qabs, NULL, &a);+ }+ VkcMlaCore cp = {S, H, m->K, m->R, pos_base, kv_start, 0, HK, m->K, m->Q, H * QR, QR, 0, m->K, 0, m->R,+ (int)sel_off, sel ? sel_row : 0, 0, HK, m->K, m->scale};+ ok = ok && vkc_mla_core(s->qabs, s->q, c->lat, c->rope, sel, s->clat, &cp);+ VkcHgemv v = {0, S, H, m->V, m->kv_b ? m->Q + m->V : m->V, m->kv_b ? m->Q : 0, 0, HK, m->K, 0, HV, m->V,+ (int)gate_off, HV, gate != NULL};+ ok = ok && vkc_mla_hgemv(m->kv_b ? m->kv_b : m->v_abs, s->clat, s->ctx, gate, &v);+ if (ok && m->o && out) ok = vkc_matmul(m->o, s->ctx, 0, out, out_off, S);+ return ok;+}+int vkc_mla(const VkcMla *m, VkcMlaScratch *s, VkcBuf *x, size_t x_off, int S, int pos_base, int kv_start,+ VkcBuf *cs, VkcMlaCache *c, VkcBuf *out, size_t out_off) {+ return vkc_mla_qkv(m, s, x, x_off, S, pos_base, cs, c, NULL, 0) &&+ vkc_mla_attn(m, s, S, pos_base, kv_start, c, NULL, 0, 0, NULL, 0, out, out_off);+}+void vkc_stats(VkcStats *st) { *st = K.st; }void vkc_prof_print(void) {if (!K.prof) return;@@ -797,6 +951,10 @@ void vkc_shutdown(void) {if (K.pipe[i]) vkDestroyPipeline(K.dev, K.pipe[i], NULL);if (K.mod[i]) vkDestroyShaderModule(K.dev, K.mod[i], NULL);}+ for (int i = 0; i < PM_N; i++) {+ if (K.mpipe[i]) vkDestroyPipeline(K.dev, K.mpipe[i], NULL);+ if (K.mmod[i]) vkDestroyShaderModule(K.dev, K.mmod[i], NULL);+ }for (int i = 0; i < K.ngemm; i++) vkDestroyPipeline(K.dev, K.gemm[i], NULL);for (int i = 0; i < K.ndnrec; i++) vkDestroyPipeline(K.dev, K.dnrec[i], NULL);if (K.gemv4) vkDestroyPipeline(K.dev, K.gemv4, NULL);diff --git a/c/vk_chain.h b/c/vk_chain.hindex 5c177295..62a04692 100644--- a/c/vk_chain.h+++ b/c/vk_chain.h@@ -25,6 +25,8 @@* fp32 tiled GEMM; and the chain's shaders (shaders/chain_*.comp), each documented* at its top: chain_norm, chain_rope, chain_attn, chain_dnconv, chain_dnrec,* chain_ew, chain_qsa, chain_ple. Offsets and strides are in floats.+ * - multi-head latent attention: the MLA ops and the layer op below (chain_mla,+ * chain_hgemv, chain_dsa), loaded beside the others but optional.** Threading: the engine thread only (the main queue is the backend's, used from the* same thread by coli_vk_matmul; the expert tier submits on its own queue).@@ -119,6 +121,116 @@ typedef struct { int mode, S, C, H, CK, NG, keys_off, hyp_off, val_off, snap_rowint vkc_ple(VkcBuf *keys, VkcBuf *hyp, VkcBuf *val, VkcBuf *prm, VkcBuf *gated, VkcBuf *normv,VkcBuf *conv, VkcBuf *ring, const VkcPle *p);+/* ---- multi-head latent attention (MLA) -------------------------------------------+ * The attention of GLM-5.2, GLM-5.3, DeepSeek V3-style and Kimi K3's MLA layers, for S+ * rows (one at decode, a prompt chunk at prefill), with the KV cache on the device. Per+ * head h the query has Q no-position floats and R rotated ones; the cache holds, per+ * position, the normalized latent (K floats, kv_lora) and the rotated shared key (R).+ * Weight absorption: the no-position query enters the latent space once per head+ * (qa = W_k^T q_nope), the scores are qa . latent + q_rot . rope_key, and the value+ * rows apply once to the softmax-weighted latent (ctx = W_v clat). Nothing assumes a+ * model's shapes: H, Q, R (0 = NoPE), V, K, q_lora (0 = no q latent), the RoPE style,+ * the softmax scale (YaRN's mscale^2 included by the caller) and the cos/sin table+ * (YaRN's frequencies and mscale included by the caller) are all the caller's.+ *+ * Two levels. The ops (shaders/chain_mla.comp, chain_hgemv.comp, chain_dsa.comp):+ * vkc_mla_core the attention core over the cache: scores, online softmax, clat;+ * the causal range or a selection list (a DSA indexer's)+ * vkc_mla_hgemv per-head block matmuls of a resident tensor (the absorbed query+ * from kv_b's key rows, transposed, or from a [H*K x Q] key matrix;+ * the value rows; an optional sigmoid gate on the values)+ * vkc_mla_rope RoPE from a host cos/sin table, rotate-half or interleaved pairs in+ * and halves out, in place or into a cache row+ * vkc_mla_lnorm LayerNorm with weight and bias (the indexer's key norm)+ * vkc_dsa_select a token-level DSA indexer's scores and top-k, in the CPU's order+ * and the layer op, vkc_mla_qkv + vkc_mla_attn (or vkc_mla for both): q_a, its norm,+ * q_b (or q straight from the hidden rows), kv_a, the latent norm, RoPE, the new rows+ * into the cache (and a copy for the host's), then the absorbed core, the values, the+ * gate and o_proj. Between the two an engine records what reads the projections (a+ * DSA indexer reads the normalized q latent, s->qa).+ * The cache is the caller's (VkcMlaCache): positions [kv_start, pos_base) must be there+ * before a step from pos_base (the engine keeps a watermark, as for the GQA caches);+ * the step writes [pos_base, pos_base + S).+ * Limits: K <= 1024, R <= 128 and even, Q <= 1024 for kv_b's transposed absorption,+ * IH <= 64 and IH*ID <= 4096 for the indexer. The ops return 0 (nothing recorded) when+ * the MLA shaders are missing or a limit is passed; vkc_mla_ready() says whether the+ * shaders are there. */+int vkc_mla_ready(void);++/* chain_mla.comp mode 0: clat[s][h] (o_off + s*o_row + h*o_seg) from the absorbed query+ * qabs (qa_off + s*qa_row + h*qa_seg, K floats) and the rotated query (qr_off + ..., R),+ * over lat (lat_off + t*lat_row) and rope (rope_off + t*rope_row) at the positions+ * kv_start..pos_base+s or sel's list (sel_row 0: none; sel[sel_off + s*sel_row] = count,+ * -1 the causal range, then the positions, a negative one skipped). rope may be NULL with R 0. */+typedef struct { int S, H, K, R, pos_base, kv_start, qa_off, qa_row, qa_seg, qr_off, qr_row, qr_seg,+ lat_off, lat_row, rope_off, rope_row, sel_off, sel_row, o_off, o_row, o_seg; float scale; } VkcMlaCore;+int vkc_mla_core(VkcBuf *qabs, VkcBuf *qr, VkcBuf *lat, VkcBuf *rope, VkcBuf *sel, VkcBuf *clat, const VkcMlaCore *p);+/* chain_mla.comp modes 1 and 2: nseg segments, segment g at row g / per_row, index+ * g % per_row: x_off + row*x_row + j*x_seg (y likewise; y may be x).+ * RoPE: the first rd floats rotate with the cos/sin pairs at cs_off + row*cs_row, the+ * rest of seg_len is copied when y is elsewhere. LayerNorm: seg_len floats, weight at+ * w_off and bias at b_off (has_b) in prm. */+#define VKC_ROPE_HALF 0 /* a = x[i], b = x[i + rd/2] */+#define VKC_ROPE_INTERLEAVED 1 /* a = x[2i], b = x[2i + 1], written to i and i + rd/2 */+typedef struct { int nseg, per_row, rd, seg_len, style, x_off, x_row, x_seg, y_off, y_row, y_seg,+ cs_off, cs_row, w_off, b_off, has_b; float eps; } VkcMlaRow;+int vkc_mla_rope(VkcBuf *x, VkcBuf *cs, VkcBuf *y, const VkcMlaRow *p);+int vkc_mla_lnorm(VkcBuf *x, VkcBuf *prm, VkcBuf *y, const VkcMlaRow *p);+/* chain_hgemv.comp: head h's block is t's rows h*hstride + hoff + [0, n).+ * trans 0: y[s][h][o] = W[row o] . x[s][h][0..I), o < n (has_gate: times+ * sigmoid(gate[g_off + s*g_row + h*n + o]));+ * trans 1: y[s][h][i] = sum_d W[row d][i] * x[s][h][d], d < n, i < I.+ * x[s][h] at x_off + s*x_row + h*x_seg, y[s][h] at y_off + s*y_row + h*y_seg. */+typedef struct { int trans, S, H, n, hstride, hoff, x_off, x_row, x_seg, y_off, y_row, y_seg, g_off, g_row, has_gate; } VkcHgemv;+int vkc_mla_hgemv(ColiVkTensor *t, VkcBuf *x, VkcBuf *y, VkcBuf *gate, const VkcHgemv *p);+/* chain_dsa.comp mode 0: row s (position pos_base + s) scores its pos_base+s+1 positions+ * as (sum_h [d_h > 0] w_h d_h) * wscale, d_h = (q_h . k_t) * qscale (q at q_off ++ * s*q_row, IH x ID; w at w_off + s*w_row; k_t at k_off + t*k_row), into sc[s*sc_row + t],+ * and writes sel[s*sel_row] = keep, then the positions: those above the keep-th largest+ * score in position order, then those equal to it in position order. With no more+ * positions than topk (and force 0), sel[s*sel_row] = -1: every position. */+typedef struct { int S, pos_base, IH, ID, topk, force, q_off, q_row, w_off, w_row, k_off, k_row, sc_row, sel_row;+ float qscale, wscale; } VkcDsa;+int vkc_dsa_select(VkcBuf *iq, VkcBuf *hw, VkcBuf *keys, VkcBuf *sc, VkcBuf *sel, const VkcDsa *p);++/* The layer op. Tensors are the resident copies the per-matrix path uploads+ * (coli_vk_tensor_ensure), in any format the backend holds. */+typedef struct {+ int H, Q, R, V, K; /* heads; per head qk_nope, qk_rope (0 = NoPE), v_head; kv_lora */+ int D, q_lora; /* hidden; q_lora 0: no q latent, q_b reads the hidden rows */+ float eps; /* the latent RMSNorms' eps */+ float scale; /* the softmax scale */+ int rope_style; /* VKC_ROPE_HALF or VKC_ROPE_INTERLEAVED */+ ColiVkTensor *q_a; /* [q_lora x D]; NULL with q_lora 0 */+ ColiVkTensor *q_b; /* [H*(Q+R) x (q_lora or D)] */+ ColiVkTensor *kv_a; /* [K+R x D]: the latent, then the shared key's rotated part */+ ColiVkTensor *kv_b; /* [H*(Q+V) x K], per head Q key rows then V value rows; or: */+ ColiVkTensor *k_abs, *v_abs; /* [H*K x Q] (W_k^T per head) and [H*V x K] */+ ColiVkTensor *o; /* [D x H*V]; NULL: the context stays in s->ctx */+ VkcBuf *prm; /* the norm weights: q latent at q_norm (unused with q_lora 0), */+ size_t q_norm, kv_norm; /* kv latent at kv_norm (floats) */+} VkcMla;+typedef struct { VkcBuf *qa, *q, *kv, *qabs, *clat, *ctx; int rows; } VkcMlaScratch;+typedef struct { VkcBuf *lat, *rope; int cap; } VkcMlaCache; /* [cap][K] and [cap][R] (rope NULL with R 0) */+/* scratch for `rows` rows (grows, never shrinks); free releases it */+int vkc_mla_scratch(VkcMlaScratch *s, const VkcMla *m, int rows);+void vkc_mla_scratch_free(VkcMlaScratch *s);+/* x: S rows of D floats at x_off (the layer's normalized input). cs: the cos/sin pairs+ * of the S positions, R floats a row (NULL with R 0). Leaves s->qa = the normalized q+ * latent [S][q_lora] and s->q = the queries [S][H*(Q+R)], rotated; writes the cache's+ * rows [pos_base, pos_base+S) and, when down is given, copies them to down at down_off+ * (S*K latent floats, then S*R rope floats) for the host's cache. */+int vkc_mla_qkv(const VkcMla *m, VkcMlaScratch *s, VkcBuf *x, size_t x_off, int S, int pos_base,+ VkcBuf *cs, VkcMlaCache *c, VkcBuf *down, size_t down_off);+/* The core over positions kv_start..pos_base+s (or sel's lists, sel_row > 0), the values+ * (times sigmoid(gate[gate_off + s*H*V + h*V + v]) when gate is given) into s->ctx, then+ * out[out_off + s*D] = o(ctx) when m->o and out are given. */+int vkc_mla_attn(const VkcMla *m, VkcMlaScratch *s, int S, int pos_base, int kv_start, VkcMlaCache *c,+ VkcBuf *sel, size_t sel_off, int sel_row, VkcBuf *gate, size_t gate_off, VkcBuf *out, size_t out_off);+/* both, the causal range */+int vkc_mla(const VkcMla *m, VkcMlaScratch *s, VkcBuf *x, size_t x_off, int S, int pos_base, int kv_start,+ VkcBuf *cs, VkcMlaCache *c, VkcBuf *out, size_t out_off);+/* 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 4977814f..a651aeae 100644--- a/docs/vulkan.md+++ b/docs/vulkan.md@@ -859,6 +859,43 @@ What each remaining architecture needs on top of today's shaders:| 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 |+### Multi-head latent attention on the chain (`vkc_mla`)++The MLA layers (GLM-5.2, GLM-5.3, the DeepSeek V3 family's attention, Kimi K3's MLA+layers) have chain ops of their own, in `vk_chain.h`, written for any geometry: H heads+of Q no-position and R rotated query floats (R = 0 for NoPE), V value floats, a latent of+K floats (`kv_lora`), q_lora from 0 (q straight from the hidden rows) up, RoPE as rotate+-half or as interleaved pairs, the softmax scale and the cos/sin table from the caller (a+YaRN model passes its scaled frequencies, its mscale on the table and mscale squared on+the scale). The cache on the device holds, per position, the normalized latent and the+rotated shared key; the engine owns it, mirrors the host's rows behind a watermark as the+GQA engines do, and copies each step's new rows back.++| Op | Shader | What it does |+|---|---|---|+| `vkc_mla_qkv` | `chain_norm`, `chain_mla` (mode 1) and `vkc_matmul` | q_a, its RMSNorm and q_b (or q_b alone), kv_a, the latent's RMSNorm into the cache row, RoPE on q's rotated part and on the shared key into the cache row, a copy of the new rows for the host |+| `vkc_mla_attn` | `chain_hgemv`, `chain_mla` (mode 0) | the absorbed query (each head's Q values times its key rows of `kv_b`, read transposed, or a `[H*K x Q]` matrix), the attention core over the cache with an online softmax (the causal range or a selection list with skipped entries), the value rows on the softmax-weighted latent, an optional sigmoid gate, o_proj |+| `vkc_mla_rope`, `vkc_mla_lnorm` | `chain_mla` (modes 1, 2) | RoPE over segments from a host table, in place or into another buffer; LayerNorm with weight and bias (an indexer's key norm) |+| `vkc_dsa_select` | `chain_dsa` | a token-level DSA indexer: each position's score `(sum_h [d_h > 0] w_h d_h) * wscale`, `d_h = (q_h . k_t) * qscale`, and the top-k in the CPU's order (above the k-th score in position order, then the ties in position order), or "every position" while the context is within top-k |++The weights stay in the format the engine already holds them in (int8 and int4 rows,+int4 and int8 and fp8 in groups, int3-g64, MXFP4, f32, bf16): the per-head blocks read+them where the backend uploaded them. Between `vkc_mla_qkv` and `vkc_mla_attn` an engine+records what reads the projections (a DSA indexer reads the normalized q latent the first+leaves in its scratch). Limits: K up to 1024, R up to 128, Q up to 1024 where kv_b's key+rows are read transposed, an indexer of up to 64 heads and 4096 query floats.++`make vk-chain-check VK=1` runs them against double-precision references of colibri.c's+absorbed attention: every weight format both ways through the per-head blocks, RoPE in+both styles in place and into a cache row, LayerNorm with and without a bias, and the+layer op over eight geometries (q latent or none, NoPE, `kv_b` or the split halves,+selection lists with skipped entries, a gate, prefill rows after earlier ones, a long+context from a nonzero start, GLM-5.2's head shape, a latent of 1024). Measured on+Lavapipe and on an Intel Iris Xe (Mesa's Dozen): the layer's output within 5e-7 of its+largest value and the new cache rows within 7e-7 (the test's bound is 2e-5). The+indexer's selection is checked bit for bit, ties included, on scores that are exact in+float on both sides.+## Adding an engine to the tierEvery MoE engine here is on the tier ([the table above](#the-routed-expert-tier-vk_tierc));