Skip to content

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

C

vulkan chain: a diffusion step's attention, tiled (chain_attn_full)

JustVugg004765b2a174
diff --git a/c/Makefile b/c/Makefile
index 7719eaa6..4b86266f 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -743,6 +743,9 @@ VK_SPV += shaders/chain_kvs.spv
VK_SPV += shaders/chain_enc.spv
# the attention core on the matrix units for prompt chunks (optional at run time)
VK_SPV += shaders/chain_attn_flash.spv
+# a diffusion step's attention, every query row over every key row (made on first use;
+# qwenimage_chain.h)
+VK_SPV += shaders/chain_attn_full.spv
endif
# Optional AMD XDNA2 (Ryzen AI NPU) lane, Windows. Same opt-in shape as VK=1:
diff --git a/c/qwenimage_chain.h b/c/qwenimage_chain.h
index 6cb62a3c..10ca2267 100644
--- a/c/qwenimage_chain.h
+++ b/c/qwenimage_chain.h
@@ -133,13 +133,21 @@ static int qic_attn(const VkcEncAttn *at, int N, int L) {
long long b = vkc_attn_slice_budget(), per = (long long)(L + N) * at->H * at->hd;
int rr = b > 0 ? (int)(b / per / 16 * 16) : N;
if (rr < 16) rr = 16;
- int ok = 1;
+ /* chain_attn_full where it loads (head dims 32, 64 and 128), the encoders'
+ * attention over row ranges otherwise */
+ int full = (at->hd == 32 || at->hd == 64 || at->hd == 128) && vkc_attn_full_ready(), ok = 1;
for (int r0 = 0; ok && r0 < N; r0 += rr) {
- VkcEncAttn x = *at;
- x.S = N - r0 < rr ? N - r0 : rr;
- x.q_off = at->q_off + r0 * at->kv_row; x.o_off = at->o_off + r0 * at->o_row;
- ok = vkc_enc_attn(g_qic.qkv, NULL, NULL, g_qic.a, g_qic.rng, NULL, NULL, &x) &&
- (r0 + rr >= N || (vkc_submit(0) && vkc_begin()));
+ int n = N - r0 < rr ? N - r0 : rr;
+ if (full) {
+ VkcAttnFull f = {n, L + N, at->H, at->hd, at->q_off + r0 * at->kv_row, at->kv_row, at->k_off, at->v_off,
+ at->kv_row, at->o_off + r0 * at->o_row, at->o_row, at->scale};
+ ok = vkc_attn_full(g_qic.qkv, g_qic.a, &f);
+ } else {
+ VkcEncAttn x = *at;
+ x.S = n; x.q_off = at->q_off + r0 * at->kv_row; x.o_off = at->o_off + r0 * at->o_row;
+ ok = vkc_enc_attn(g_qic.qkv, NULL, NULL, g_qic.a, g_qic.rng, NULL, NULL, &x);
+ }
+ ok = ok && (r0 + rr >= N || (vkc_submit(0) && vkc_begin()));
}
return ok;
}
diff --git a/c/shaders/chain_attn_full.comp b/c/shaders/chain_attn_full.comp
new file mode 100644
index 00000000..4ef96008
--- /dev/null
+++ b/c/shaders/chain_attn_full.comp
@@ -0,0 +1,117 @@
+#version 450
+// The image rows' attention of a diffusion step (vk_chain.c, vkc_attn_full; Qwen-Image's
+// DiT): S query rows, each over all T key rows, every head. No mask but the end of the
+// keys and no cache: q, k and v are rows of one buffer, token-major,
+// q[q_off + i*q_row + h*HD + d], k[k_off + t*kv_row + h*HD + d], v[v_off + t*kv_row + h*HD + d]
+// o[o_off + i*o_row + h*HD + d] = sum_t softmax_t(scale * q_i,h . k_t,h) v_t,h[d]
+// One workgroup of 256 threads takes 64 query rows of one head through the keys in tiles
+// of 64. Thread (ty, tx) = (t / 16, t % 16) scores rows 4ty..4ty+3 against keys
+// 4tx..4tx+3, from chunks of 32 dims of Q and K staged in shared memory, and accumulates
+// the dims tx, tx+16, ... of the same rows' output from 32 keys of V at a time. The
+// softmax runs online in float: each tile's row max, the running sum and the output
+// rescaled by exp(old max - new max); the CPU normalizes the scores first and sums the
+// row in double, so the two agree to rounding. HD (a specialization constant) is 32, 64
+// or 128. Shared memory: 37.5 KB.
+layout(local_size_x = 256) in;
+layout(constant_id = 0) const int HD = 128;
+#define BR 64
+#define BC 64
+#define DC 32
+#define DPT (HD / 16)
+
+layout(std430, binding = 0) readonly buffer QKV { float x[]; };
+layout(std430, binding = 1) writeonly buffer OB { float o[]; };
+layout(push_constant) uniform P {
+ int S, T, H, hd, q_off, q_row, k_off, v_off, kv_row, o_off, o_row;
+ float scale;
+} p;
+
+shared float sb[2 * BR * (DC + 1)]; // Q and K chunks, [64][33] each; later a V chunk, [32][HD]
+shared float ps[BR * (BC + 1)]; // the tile's exp(score - max), [64][65]
+shared float red[BR * 16]; // per-row partial maxima, then sums
+
+void main() {
+ int t = int(gl_LocalInvocationID.x), ty = t / 16, tx = t % 16;
+ int h = int(gl_WorkGroupID.y), r0 = int(gl_WorkGroupID.x) * BR, hb = h * HD;
+ float acc[4][DPT], m[4], l[4];
+ for (int i = 0; i < 4; i++) {
+ m[i] = -1e30; l[i] = 0.0;
+ for (int dd = 0; dd < DPT; dd++) acc[i][dd] = 0.0;
+ }
+ for (int kb = 0; kb < p.T; kb += BC) {
+ float s[4][4];
+ for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) s[i][j] = 0.0;
+ for (int dc = 0; dc < HD; dc += DC) {
+ barrier(); // the previous chunk (or V) is read
+ for (int e = t; e < BR * DC; e += 256) {
+ int r = e / DC, c = e - r * DC, row = r0 + r, key = kb + r;
+ sb[r * (DC + 1) + c] = row < p.S ? x[p.q_off + row * p.q_row + hb + dc + c] : 0.0;
+ sb[BR * (DC + 1) + r * (DC + 1) + c] = key < p.T ? x[p.k_off + key * p.kv_row + hb + dc + c] : 0.0;
+ }
+ barrier();
+ for (int c = 0; c < DC; c++) {
+ float a[4], b[4];
+ for (int i = 0; i < 4; i++) a[i] = sb[(4 * ty + i) * (DC + 1) + c];
+ for (int j = 0; j < 4; j++) b[j] = sb[BR * (DC + 1) + (4 * tx + j) * (DC + 1) + c];
+ for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) s[i][j] += a[i] * b[j];
+ }
+ }
+ // the tile's row maxima across the 16 threads that share the rows
+ float mn[4];
+ for (int i = 0; i < 4; i++) {
+ float mt = -1e30;
+ for (int j = 0; j < 4; j++) {
+ s[i][j] = kb + 4 * tx + j < p.T ? s[i][j] * p.scale : -1e30;
+ mt = max(mt, s[i][j]);
+ }
+ red[(4 * ty + i) * 16 + tx] = mt;
+ }
+ barrier();
+ for (int i = 0; i < 4; i++) {
+ float mx = m[i];
+ for (int k = 0; k < 16; k++) mx = max(mx, red[(4 * ty + i) * 16 + k]);
+ mn[i] = mx;
+ }
+ barrier(); // red is read: the sums take it
+ for (int i = 0; i < 4; i++) {
+ float rs = 0.0;
+ for (int j = 0; j < 4; j++) {
+ float e = kb + 4 * tx + j < p.T ? exp(s[i][j] - mn[i]) : 0.0;
+ ps[(4 * ty + i) * (BC + 1) + 4 * tx + j] = e;
+ rs += e;
+ }
+ red[(4 * ty + i) * 16 + tx] = rs;
+ }
+ barrier();
+ for (int i = 0; i < 4; i++) {
+ float sum = 0.0;
+ for (int k = 0; k < 16; k++) sum += red[(4 * ty + i) * 16 + k];
+ float al = exp(m[i] - mn[i]);
+ l[i] = l[i] * al + sum; m[i] = mn[i];
+ for (int dd = 0; dd < DPT; dd++) acc[i][dd] *= al;
+ }
+ // P . V, 32 keys of V at a time in the chunks' space
+ for (int kc = 0; kc < BC; kc += 32) {
+ barrier(); // the chunks and the sums are read
+ for (int e = t; e < 32 * HD; e += 256) {
+ int kk = e / HD, d = e - kk * HD, key = kb + kc + kk;
+ sb[e] = key < p.T ? x[p.v_off + key * p.kv_row + hb + d] : 0.0;
+ }
+ barrier();
+ for (int kk = 0; kk < 32; kk++) {
+ float pv[4];
+ for (int i = 0; i < 4; i++) pv[i] = ps[(4 * ty + i) * (BC + 1) + kc + kk];
+ for (int dd = 0; dd < DPT; dd++) {
+ float vv = sb[kk * HD + tx + 16 * dd];
+ for (int i = 0; i < 4; i++) acc[i][dd] += pv[i] * vv;
+ }
+ }
+ }
+ }
+ for (int i = 0; i < 4; i++) {
+ int row = r0 + 4 * ty + i;
+ if (row >= p.S) continue;
+ float inv = 1.0 / l[i];
+ for (int dd = 0; dd < DPT; dd++) o[p.o_off + row * p.o_row + hb + tx + 16 * dd] = acc[i][dd] * inv;
+ }
+}
diff --git a/c/shaders/chain_attn_full.spv b/c/shaders/chain_attn_full.spv
new file mode 100644
index 00000000..3babcce3
Binary files /dev/null and b/c/shaders/chain_attn_full.spv differ
diff --git a/c/tests/test_vk_chain.c b/c/tests/test_vk_chain.c
index 1a1e3fbb..15b0e133 100644
--- a/c/tests/test_vk_chain.c
+++ b/c/tests/test_vk_chain.c
@@ -269,6 +269,52 @@ static void test_attn_hk(int S, int pos_base, int H, int KVH, int hd, int use_li
}
static void test_attn(int S, int pos_base, int hd, int use_list) { test_attn_hk(S, pos_base, 4, 2, hd, use_list); }
+/* GATE_ADD (Qwen-Image's gated residual): y = a + e[col] * b, a gate per column. */
+static void test_ew_gate(void) {
+ int R = 5, D = 70;
+ size_t n = (size_t)R * D;
+ float *a = fvec(n, 2.f), *b = fvec(n, 2.f), *e = fvec(D + 3, 1.f), *ref = malloc(n * sizeof *ref);
+ for (size_t i = 0; i < n; i++) ref[i] = a[i] + e[3 + i % D] * b[i];
+ VkcBuf *ab = up(a, n), *bb = up(b, n), *eb = up(e, D + 3);
+ VkcEw p = {VKC_EW_GATE_ADD, (int)n, D, 1, 0, 0, 0, 0, 0, 0, 3, 1.f};
+ vkc_begin(); int ok = vkc_ew(ab, ab, bb, NULL, eb, &p); vkc_submit(1); /* in place, as the chain runs it */
+ float *y = down(ab, 0, n);
+ double err = relerr(y, ref, n, 1e-3);
+ CHECK(ok && err < 1e-6, "ew gate-add: err %.2e", err);
+ free(y); vkc_free(ab); vkc_free(bb); vkc_free(eb); free(a); free(b); free(e); free(ref);
+}
+
+/* A diffusion step's attention (vkc_attn_full, Qwen-Image's DiT): S query rows, each over
+ * all T key rows, token-major in one buffer (q, then k and v at their offsets), heads of
+ * hd; S and T away from the shader's tiles of 64. */
+static void test_attn_full(int S, int T, int H, int hd) {
+ int D = H * hd, qrow = D + 8, kvrow = D + 24, qoff = 4, koff = qoff + S * qrow + 16, voff = koff + T * kvrow + 8;
+ size_t n = (size_t)voff + (size_t)T * kvrow + 8;
+ float *x = fvec(n, 1.f), scale = 1.f / sqrtf((float)hd);
+ float *ref = malloc((size_t)S * D * sizeof *ref);
+ double *sc = malloc((size_t)T * sizeof *sc);
+ for (int s = 0; s < S; s++) for (int h = 0; h < H; h++) {
+ double mx = -1e300, sum = 0;
+ for (int t = 0; t < T; t++) {
+ double a = 0;
+ for (int d = 0; d < hd; d++) a += (double)x[qoff + (size_t)s * qrow + h * hd + d] * x[koff + (size_t)t * kvrow + h * hd + d];
+ sc[t] = a * scale; if (sc[t] > mx) mx = sc[t];
+ }
+ for (int t = 0; t < T; t++) { sc[t] = exp(sc[t] - mx); sum += sc[t]; }
+ for (int d = 0; d < hd; d++) {
+ double a = 0;
+ for (int t = 0; t < T; t++) a += sc[t] / sum * x[voff + (size_t)t * kvrow + h * hd + d];
+ ref[(size_t)s * D + h * hd + d] = (float)a;
+ }
+ }
+ VkcBuf *xb = up(x, n), *ob = vkc_buf(((size_t)S * D + 32) * 4, VKC_DOWN);
+ VkcAttnFull p = {S, T, H, hd, qoff, qrow, koff, voff, kvrow, 32, D, scale};
+ vkc_begin(); int ok = vkc_attn_full(xb, ob, &p); ok = vkc_submit(1) && ok;
+ double e = relerr((float *)vkc_ptr(ob) + 32, ref, (size_t)S * D, 1e-3);
+ CHECK(ok && e < 2e-5, "attn full S %d T %d H %d hd %d: err %.2e", S, T, H, hd, e);
+ vkc_free(xb); vkc_free(ob); free(x); free(ref); free(sc);
+}
+
/* MiMo's attention (vkc_attn_w): row s at pos = pos_base + s sees the positions
* max(0, pos - win + 1)..pos (win 0: from 0); position t sits in row t % ring of the
* cache (ring 0: row t), rows position-major (kv_pm) or head-major; V has its own head
@@ -2681,6 +2727,12 @@ int main(int argc, char **argv) {
if (!vkc_kvs_ready()) { fails++; printf("FAIL: the split KV shader did not load\n"); }
else { test_kvs(); test_kvs_cold(); printf("kvs done\n"); }
if (getenv("COLI_VK_DEV2")) { test_dev2(spv); printf("dev2 done\n"); }
+ /* a diffusion step's attention: one tile, partial tiles of rows and keys, every head
+ * dim (last: the shared random stream the tests above draw from stays theirs) */
+ test_attn_full(5, 9, 2, 32); test_attn_full(64, 64, 1, 128); test_attn_full(130, 200, 3, 128);
+ test_attn_full(70, 129, 2, 64); test_attn_full(1, 300, 4, 128);
+ printf("attn full done\n");
+ test_ew_gate();
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.c
index a7c94037..7edd6f5a 100644
--- a/c/vk_chain.c
+++ b/c/vk_chain.c
@@ -1393,6 +1393,37 @@ int vkc_relattn(VkcBuf *q, VkcBuf *kc, VkcBuf *vc, VkcBuf *o, VkcBuf *kvs, VkcBu
/* ---- the decision engines' encoders: chain_enc.comp, made on first use ---- */
static struct { VkShaderModule mod; VkPipeline pipe; int tried; } g_ke[2];
#define KE (g_ke[g_kd])
+/* chain_attn_full.comp (a diffusion step's attention): made on first use, a pipeline per
+ * head dim (its specialization constant) */
+static struct { VkShaderModule mod; VkPipeline pipe[3]; int tried; } g_kf[2];
+#define KF (g_kf[g_kd])
+static void kf_shutdown(void) {
+ for (int i = 0; i < 3; i++) if (KF.pipe[i]) vkDestroyPipeline(KC.dev, KF.pipe[i], NULL);
+ if (KF.mod) vkDestroyShaderModule(KC.dev, KF.mod, NULL);
+ memset(&KF, 0, sizeof KF);
+}
+int vkc_attn_full(VkcBuf *qkv, VkcBuf *o, const VkcAttnFull *p) {
+ if (!vkc_ready() || p->S < 1 || p->T < 1 || p->H < 1 || (p->hd != 32 && p->hd != 64 && p->hd != 128) ||
+ (int64_t)p->S > 65535LL * 64 || p->H > 65535) return 0;
+ int k = p->hd == 32 ? 0 : p->hd == 64 ? 1 : 2;
+ if (!KF.pipe[k]) {
+ if (!KF.mod && !KF.tried) { KF.tried = 1; KF.mod = load_module(KC.core.spv_path, "chain_attn_full.spv"); }
+ if (!KF.mod) return 0;
+ int hd = p->hd;
+ VkSpecializationMapEntry me = {0, 0, sizeof(int)};
+ VkSpecializationInfo si = {1, &me, sizeof(int), &hd};
+ if (!(KF.pipe[k] = make_pipe(KF.mod, &si))) return 0;
+ }
+ KC.kind = PK_ATTN;
+ VkcBind bd[2] = {B(qkv, 0), B(o, 1)};
+ return record(KF.pipe[k], bd, 2, p, sizeof *p, (uint32_t)((p->S + 63) / 64), (uint32_t)p->H, 1);
+}
+int vkc_attn_full_ready(void) {
+ if (!vkc_ready()) return 0;
+ if (!KF.mod && !KF.tried) { KF.tried = 1; KF.mod = load_module(KC.core.spv_path, "chain_attn_full.spv"); }
+ return KF.mod != VK_NULL_HANDLE;
+}
+
static VkPipeline ke_pipe(void) {
if (KE.pipe || KE.tried || !vkc_ready()) return KE.pipe;
KE.tried = 1;
@@ -1687,6 +1718,7 @@ void vkc_shutdown(void) {
kx_shutdown();
kab_shutdown();
ke_shutdown();
+ kf_shutdown();
for (int i = 0; i < P_NPIPE; i++) {
if (KC.pipe[i]) vkDestroyPipeline(KC.dev, KC.pipe[i], NULL);
if (KC.mod[i]) vkDestroyShaderModule(KC.dev, KC.mod[i], NULL);
diff --git a/c/vk_chain.h b/c/vk_chain.h
index a5c3c263..99ab02c2 100644
--- a/c/vk_chain.h
+++ b/c/vk_chain.h
@@ -678,6 +678,15 @@ int vkc_enc_attn(VkcBuf *qkv, VkcBuf *c2p, VkcBuf *p2c, VkcBuf *o, VkcBuf *rng,
typedef struct { int mode, S, H, hd, x_off, x_row, p_off, p_row, y_off, nr, r0; } VkcEncRel;
int vkc_enc_rel(VkcBuf *x, VkcBuf *pt, VkcBuf *y, const VkcEncRel *p);
+/* chain_attn_full.comp: a diffusion step's attention (Qwen-Image's DiT). S query rows, each
+ * over all T key rows, H heads of hd (32, 64 or 128) floats, q, k and v token-major in one
+ * buffer: q[q_off + i*q_row + h*hd + d], k and v at k_off and v_off + t*kv_row + h*hd + d,
+ * the output at o_off + i*o_row + h*hd + d; the softmax's scale. 64 query rows of a head a
+ * workgroup, the keys in tiles of 64, the softmax online in float. Made on first use. */
+typedef struct { int S, T, H, hd, q_off, q_row, k_off, v_off, kv_row, o_off, o_row; float scale; } VkcAttnFull;
+int vkc_attn_full(VkcBuf *qkv, VkcBuf *o, const VkcAttnFull *p);
+int vkc_attn_full_ready(void);
+
/* counters, for the engines' [VK] lines */
typedef struct {
unsigned long long frames, waits, ops, matmuls, gemms, barriers, bytes_up, bytes_down;