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: causal attention of a prompt chunk on the matrix units

huppifluppd9821e5131ec
diff --git a/c/Makefile b/c/Makefile
index d883728c..103c9629 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -736,6 +736,8 @@ VK_SPV += shaders/chain_kvs.spv
# the decision engines' encoders (laya, gliner_decide): bidirectional attention over row
# ranges with DeBERTa's relative terms, LayerNorm, GeGLU, RoPE (made on first use)
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
endif
# Optional AMD XDNA2 (Ryzen AI NPU) lane, Windows. Same opt-in shape as VK=1:
@@ -876,6 +878,12 @@ vk_chain.o: vk_chain.c .build-config
shaders/%.spv: shaders/%.comp
@command -v $(GLSLC) >/dev/null 2>&1 || { echo "glslc not found: install shaderc (for VK=1)" >&2; exit 1; }
$(GLSLC) --target-env=vulkan1.2 $< -o $@
+# chain_attn_flash.comp needs the same glslc as qmatmul_coop.comp below, with the same
+# fallback; without its .spv the chain keeps chain_attn.comp.
+shaders/chain_attn_flash.spv: shaders/chain_attn_flash.comp
+ @command -v $(GLSLC) >/dev/null 2>&1 || { echo "glslc not found: install shaderc (for VK=1)" >&2; exit 1; }
+ $(GLSLC) --target-env=vulkan1.2 $< -o $@ || { [ -f $@ ] && touch $@ && \
+ echo "warning: $(GLSLC) cannot compile $<, keeping the committed $@" >&2; }
# The cooperative-matrix GEMM needs a glslc that knows GL_KHR_cooperative_matrix
# (shaderc 2023.6+). An older one keeps the committed .spv instead of failing the build;
# at run time the shader is optional anyway (the fp32 GEMM takes over without it).
diff --git a/c/backend_vulkan.c b/c/backend_vulkan.c
index dcd52a5d..b85ebb20 100644
--- a/c/backend_vulkan.c
+++ b/c/backend_vulkan.c
@@ -4463,6 +4463,7 @@ int coli_vk_core(ColiVkCore *o) {
}
o->gemm_min_s = G.gemm_min_s; o->gemm_min_so = G.gemm_min_so;
o->integrated = coli_vk_device_integrated(); o->shares_ram = coli_vk_device_shares_ram();
+ o->coop_sg = G.has_coop ? G.coop_sg : 0;
return 1;
}
int coli_vk_tensor_info(const ColiVkTensor *t, ColiVkTensorInfo *o) {
diff --git a/c/backend_vulkan.h b/c/backend_vulkan.h
index 882fb7d1..9fa97d2f 100644
--- a/c/backend_vulkan.h
+++ b/c/backend_vulkan.h
@@ -395,6 +395,7 @@ typedef struct {
int gemm_tiles, gemm_tile[4][6]; /* bm, bn, bk, tm, tn, pf */
int gemm_min_s, gemm_min_so;
int has_prio, integrated, shares_ram;
+ int coop_sg; /* subgroup size the cooperative-matrix shaders run at; 0 = none */
} ColiVkCore;
int coli_vk_core(ColiVkCore *out);
/* A resident tensor's buffers (VkBuffer as void *) and layout; 0 for a COLI_VK_DEV2 one. */
diff --git a/c/shaders/chain_attn_flash.comp b/c/shaders/chain_attn_flash.comp
new file mode 100644
index 00000000..2358f0a9
--- /dev/null
+++ b/c/shaders/chain_attn_flash.comp
@@ -0,0 +1,183 @@
+#version 450
+// The dense chain's attention core on the matrix units (vk_chain.c, VKC_P_ATTN_FLASH):
+// chain_attn.comp's causal case (no selection list, window, ring, sink or second V
+// width, head-major cache) for a prompt chunk, KHR cooperative matrix f16 x f16 -> f32.
+// Same bindings and push constants as chain_attn.comp, so vkc_attn_w picks either.
+// After llama.cpp's flash_attn_cm1.comp (MIT): 16 query rows, 64 keys a step, 4
+// subgroups of 64, the softmax on a shared copy of the scores. For Qwen3.6 on RADV:
+// * GQA folded: the 16 rows are 16/GQ tokens x the GQ query heads of ONE kv head, so
+// every K/V block is staged once for all of them;
+// * two passes instead of an online softmax: pass 1 finds each row's max m and sum l,
+// pass 2 recomputes the scores and adds exp(s - m) * V straight into the
+// accumulators (no rescaling, O never leaves the registers), / l at the end;
+// * K/V arrive f32 and are converted to f16 while staged, in 16x16 tiles stored
+// contiguously (strided cooperative-matrix loads measured slow on RADV);
+// * causality inline: key t is valid for row r iff t <= pos_base + token(r).
+// Q is scaled before its f16 rounding; P = exp(s - m) is in (0, 1]. Not bit-identical
+// to chain_attn.comp (f16 operands); the CPU's order differs from both anyway.
+// Grid: x = ceil(S / (16/GQ)) token groups, y = kv heads. HD and GQ are specialization
+// constants (HD a multiple of 64 up to 256, GQ dividing 16).
+#extension GL_KHR_cooperative_matrix : require
+#extension GL_KHR_memory_scope_semantics : require
+#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require
+#extension GL_EXT_control_flow_attributes : enable
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_clustered : require
+layout(local_size_x = 256) in;
+layout(constant_id = 0) const uint HD = 256; // head dim, multiple of 64
+layout(constant_id = 1) const uint GQ = 8; // query heads per kv head, divides 16
+#define TPW (16u / GQ) // tokens per workgroup
+#define BC 64u // keys per block
+#define NDT (HD / 16u) // 16-wide head-dim tiles
+#define NDS (NDT / 4u) // head-dim tiles of O per subgroup
+
+layout(std430, binding = 0) readonly buffer QB { float q[]; };
+layout(std430, binding = 1) readonly buffer KB { float kc[]; }; // K[k_off + (kvh*cap + t)*hd + d]
+layout(std430, binding = 2) readonly buffer VB { float vc[]; }; // V likewise from v_off
+layout(std430, binding = 3) buffer OB { float o[]; };
+layout(std430, binding = 4) readonly buffer GB { float gt[]; };
+layout(push_constant) uniform P { // chain_attn.comp's; the fields after v_off are zero here
+ int S, H, KVH, hd, pos_base, cap;
+ int q_off, q_row, q_seg;
+ int g_off, g_row, g_seg, has_gate;
+ int o_off, o_row;
+ int sel_off, sel_row;
+ float scale;
+ int k_off, v_off;
+ int win, ring, vd, kv_pm, sink, sink_off;
+} p;
+
+// K or V block (or Q before the loop), f16, 16x16 tiles of 256 values each:
+// tile (a, b) at (a * NDT + b) * 256, element (row, col) at row * 16 + col.
+// K: a = key tile, b = dim tile, row = key, col = dim -> loaded ColumnMajor as B(dim, key)
+// V: same layout -> loaded RowMajor as B(key, dim)
+shared uvec4 skv[BC * HD / 8u];
+shared float ss[4u * 256u]; // scores, tile per subgroup (row, key); output staging at the end
+shared float16_t sp[4u * 256u]; // P as 4 A tiles (row, key)
+shared float sinvl[16]; // 1 / l per row
+
+uint pk(float a, float b) { return packFloat2x16(f16vec2(float16_t(a), float16_t(b))); }
+
+// stage keys k0 .. k0+63 of kv head g from f32 memory into skv (zero past nt)
+void stage(uint g, uint k0, uint nt, uint tid, bool isv) {
+ for (uint e = tid; e < BC * HD / 8u; e += 256u) {
+ uint kl = e / (HD / 8u), d8 = e % (HD / 8u); // consecutive threads: consecutive dims of one key
+ uint key = k0 + kl, d = d8 * 8u;
+ vec4 a = vec4(0.0), b = vec4(0.0);
+ if (key < nt) {
+ uint base = (g * uint(p.cap) + key) * HD + d;
+ if (isv) { base += uint(p.v_off); a = vec4(vc[base], vc[base+1u], vc[base+2u], vc[base+3u]); b = vec4(vc[base+4u], vc[base+5u], vc[base+6u], vc[base+7u]); }
+ else { base += uint(p.k_off); a = vec4(kc[base], kc[base+1u], kc[base+2u], kc[base+3u]); b = vec4(kc[base+4u], kc[base+5u], kc[base+6u], kc[base+7u]); }
+ }
+ skv[((kl >> 4u) * NDT + (d8 >> 1u)) * 32u + (kl & 15u) * 2u + (d8 & 1u)] = uvec4(pk(a.x, a.y), pk(a.z, a.w), pk(b.x, b.y), pk(b.z, b.w));
+ }
+}
+
+void main() {
+ uint tid = gl_LocalInvocationID.x, sgi = gl_SubgroupID, lane = gl_SubgroupInvocationID;
+ uint S = uint(p.S), H = uint(p.H), g = gl_WorkGroupID.y;
+ uint t0 = gl_WorkGroupID.x * TPW;
+ uint nt = uint(p.pos_base) + S;
+ uint tlast = min(t0 + TPW, S) - 1u;
+ uint nkb = (uint(p.pos_base) + tlast) / BC + 1u; // key blocks this workgroup needs
+
+ // softmax thread layout: row = tid / 16, 16 lanes per row, keys cl + 16 i
+ uint row = tid >> 4u, cl = tid & 15u;
+ uint rtok = t0 + row / GQ;
+ uint qpos = uint(p.pos_base) + min(rtok, S - 1u);
+
+ // Q (scaled) -> f16 A tiles in registers
+ coopmat<float16_t, gl_ScopeSubgroup, 16, 16, gl_MatrixUseA> A[NDT];
+ for (uint e = tid; e < 16u * HD / 8u; e += 256u) {
+ uint r = e / (HD / 8u), d8 = e % (HD / 8u), tk = t0 + r / GQ, h = g * GQ + r % GQ;
+ vec4 a = vec4(0.0), b = vec4(0.0);
+ if (tk < S) {
+ uint base = uint(p.q_off) + tk * uint(p.q_row) + h * uint(p.q_seg) + d8 * 8u;
+ a = vec4(q[base], q[base+1u], q[base+2u], q[base+3u]) * p.scale;
+ b = vec4(q[base+4u], q[base+5u], q[base+6u], q[base+7u]) * p.scale;
+ }
+ skv[(d8 >> 1u) * 32u + r * 2u + (d8 & 1u)] = uvec4(pk(a.x, a.y), pk(a.z, a.w), pk(b.x, b.y), pk(b.z, b.w));
+ }
+ barrier();
+ [[unroll]] for (uint j = 0u; j < NDT; j++) coopMatLoad(A[j], skv, j * 32u, 2u, gl_CooperativeMatrixLayoutRowMajor);
+ barrier();
+
+ coopmat<float16_t, gl_ScopeSubgroup, 16, 16, gl_MatrixUseB> B;
+ coopmat<float, gl_ScopeSubgroup, 16, 16, gl_MatrixUseAccumulator> Sc;
+ float m = -1e30, l = 0.0;
+
+ // pass 1: row max and sum
+ for (uint kb = 0u; kb < nkb; kb++) {
+ stage(g, kb * BC, nt, tid, false);
+ barrier();
+ Sc = coopmat<float, gl_ScopeSubgroup, 16, 16, gl_MatrixUseAccumulator>(0.0);
+ [[unroll]] for (uint j = 0u; j < NDT; j++) {
+ coopMatLoad(B, skv, (sgi * NDT + j) * 32u, 2u, gl_CooperativeMatrixLayoutColumnMajor);
+ Sc = coopMatMulAdd(A[j], B, Sc);
+ }
+ coopMatStore(Sc, ss, sgi * 256u, 16u, gl_CooperativeMatrixLayoutRowMajor);
+ barrier();
+ float sv[4], bm = -1e30;
+ [[unroll]] for (uint i = 0u; i < 4u; i++) {
+ uint key = kb * BC + i * 16u + cl;
+ sv[i] = key <= qpos ? ss[i * 256u + row * 16u + cl] : -1e30;
+ bm = max(bm, sv[i]);
+ }
+ bm = subgroupClusteredMax(bm, 16u);
+ float mn = max(m, bm), part = 0.0;
+ [[unroll]] for (uint i = 0u; i < 4u; i++) part += sv[i] > -1e29 ? exp(sv[i] - mn) : 0.0;
+ l = l * exp(m - mn) + subgroupClusteredAdd(part, 16u);
+ m = mn;
+ barrier(); // skv and ss are rewritten next block
+ }
+ // P stays exp(s - m) in (0, 1] and O is divided by l at the end: normalised
+ // probabilities of a long row fall below f16's normal range (6e-5)
+ if (cl == 0u) sinvl[row] = 1.0 / l;
+
+ // pass 2: O = sum_t exp(s - m) * V (/ l at the end)
+ coopmat<float, gl_ScopeSubgroup, 16, 16, gl_MatrixUseAccumulator> Oa[NDS];
+ [[unroll]] for (uint u = 0u; u < NDS; u++) Oa[u] = coopmat<float, gl_ScopeSubgroup, 16, 16, gl_MatrixUseAccumulator>(0.0);
+ coopmat<float16_t, gl_ScopeSubgroup, 16, 16, gl_MatrixUseA> PA;
+ for (uint kb = 0u; kb < nkb; kb++) {
+ stage(g, kb * BC, nt, tid, false);
+ barrier();
+ Sc = coopmat<float, gl_ScopeSubgroup, 16, 16, gl_MatrixUseAccumulator>(0.0);
+ [[unroll]] for (uint j = 0u; j < NDT; j++) {
+ coopMatLoad(B, skv, (sgi * NDT + j) * 32u, 2u, gl_CooperativeMatrixLayoutColumnMajor);
+ Sc = coopMatMulAdd(A[j], B, Sc);
+ }
+ coopMatStore(Sc, ss, sgi * 256u, 16u, gl_CooperativeMatrixLayoutRowMajor);
+ barrier(); // scores complete, K block consumed
+ [[unroll]] for (uint i = 0u; i < 4u; i++) {
+ uint key = kb * BC + i * 16u + cl;
+ float s = ss[i * 256u + row * 16u + cl];
+ sp[i * 256u + row * 16u + cl] = float16_t(key <= qpos ? exp(s - m) : 0.0);
+ }
+ stage(g, kb * BC, nt, tid, true);
+ barrier();
+ [[unroll]] for (uint kt = 0u; kt < 4u; kt++) {
+ coopMatLoad(PA, sp, kt * 256u, 16u, gl_CooperativeMatrixLayoutRowMajor);
+ [[unroll]] for (uint u = 0u; u < NDS; u++) {
+ coopMatLoad(B, skv, (kt * NDT + sgi * NDS + u) * 32u, 2u, gl_CooperativeMatrixLayoutRowMajor);
+ Oa[u] = coopMatMulAdd(PA, B, Oa[u]);
+ }
+ }
+ barrier();
+ }
+
+ // out: rows map to (token, head), not a uniform stride -> via this subgroup's ss tile
+ [[unroll]] for (uint u = 0u; u < NDS; u++) {
+ coopMatStore(Oa[u], ss, sgi * 256u, 16u, gl_CooperativeMatrixLayoutRowMajor);
+ subgroupMemoryBarrierShared(); subgroupBarrier();
+ for (uint e = lane; e < 256u; e += gl_SubgroupSize) {
+ uint r = e >> 4u, c = e & 15u, tk = t0 + r / GQ, h = g * GQ + r % GQ;
+ if (tk < S) {
+ uint d = (sgi * NDS + u) * 16u + c;
+ float v = ss[sgi * 256u + e] * sinvl[r];
+ if (p.has_gate != 0) v *= 1.0 / (1.0 + exp(-gt[uint(p.g_off) + tk * uint(p.g_row) + h * uint(p.g_seg) + d]));
+ o[uint(p.o_off) + tk * uint(p.o_row) + h * HD + d] = v;
+ }
+ }
+ subgroupMemoryBarrierShared(); subgroupBarrier();
+ }
+}
diff --git a/c/shaders/chain_attn_flash.spv b/c/shaders/chain_attn_flash.spv
new file mode 100644
index 00000000..650e0891
Binary files /dev/null and b/c/shaders/chain_attn_flash.spv differ
diff --git a/c/tests/test_vk_chain.c b/c/tests/test_vk_chain.c
index 6b6e4f0b..64d89ea4 100644
--- a/c/tests/test_vk_chain.c
+++ b/c/tests/test_vk_chain.c
@@ -253,9 +253,12 @@ static void test_attn_hk(int S, int pos_base, int H, int KVH, int hd, int use_li
VkcAttn p = {S, H, KVH, hd, pos_base, cap, 0, H * qseg, qseg, hd, H * qseg, qseg, 1, 0, H * hd, 0, use_list ? selrow : 0, scale, koff, koff};
vkc_begin(); int ok = vkc_attn(qb, kb, vb, ob, qb, lb, &p); vkc_submit(1);
float *o = vkc_ptr(ob);
+ /* chain_attn_flash's operands are f16: its bound where it may have run */
+ int fl = vkc_attn_flash_rows();
double e = relerr(o, ref, (size_t)S * H * hd, 1e-3);
- CHECK(ok && e < 2e-5, "attn S %d pos %d H %d/%d hd %d list %d (block from %d): err %.2e", S, pos_base, H, KVH, hd,
- use_list, vkc_attn_block_rows(), e);
+ double tol = fl > 0 && S >= fl && !use_list && hd % 64 == 0 && 16 % (H / KVH) == 0 ? 2e-3 : 2e-5;
+ CHECK(ok && e < tol, "attn S %d pos %d H %d/%d hd %d list %d (block from %d, flash from %d): err %.2e", S, pos_base, H, KVH, hd,
+ use_list, vkc_attn_block_rows(), fl, e);
vkc_free(qb); vkc_free(kb); vkc_free(vb); vkc_free(ob); vkc_free(lb);
free(q); free(kc); free(vc); free(sel); free(ref);
}
@@ -2356,6 +2359,21 @@ int main(int argc, char **argv) {
test_rope();
test_chunk_rows();
test_attn(1, 0, 16, 0); test_attn(1, 140, 32, 0); test_attn(5, 200, 64, 0); test_attn(6, 9, 256, 1); test_attn(130, 3, 24, 0);
+ /* prompt chunks on the matrix units where the device has them (chain_attn_flash, from
+ * 16 rows): Qwen3.6's heads (hd 256, 8 query heads per kv head) from position 0 and
+ * after earlier rows, a chunk over several 64-key blocks with a partial last token
+ * group, hd 64 with GQA 2, hd 128 with GQA 16; then cut in slices */
+ {
+ VkcStats s0; vkc_stats(&s0);
+ test_attn_hk(16, 0, 16, 2, 256, 0); test_attn_hk(37, 200, 16, 2, 256, 0); test_attn_hk(130, 3, 4, 2, 64, 0);
+ test_attn_hk(21, 70, 16, 1, 128, 0);
+ setenv("COLI_VK_ATTN_SLICE", "60000", 1);
+ test_attn_hk(40, 7, 16, 2, 256, 0); test_attn_hk(130, 3, 4, 2, 64, 0);
+ unsetenv("COLI_VK_ATTN_SLICE");
+ VkcStats s1; vkc_stats(&s1);
+ printf(" attention on the matrix units: %llu calls\n", s1.attn_flash - s0.attn_flash);
+ }
+ setenv("COLI_VK_CHAIN_FLASH", "0", 1); /* the blocked and plain cases below: their own shaders */
/* MiMo: a prompt's rows through a window (from position 0, and past it), a decode row
* over a ring as large as the window, prefill rows over a larger ring, full attention
* with V's own head dim, a window wider than a tile, the head-major layout with a
@@ -2394,6 +2412,7 @@ int main(int argc, char **argv) {
printf(" attention in slices: %llu extra submissions\n", s1.attn_slices - s0.attn_slices);
unsetenv("COLI_VK_ATTN_SLICE");
}
+ unsetenv("COLI_VK_CHAIN_FLASH");
printf("attn done\n");
test_dnconv(0); test_dnconv(1);
test_dnrec(8, 8, 8, 4, 0); test_dnrec(4, 4, 4, 2, 1); test_dnrec(128, 128, 4, 2, 0); test_dnrec(32, 100, 6, 3, 1);
diff --git a/c/vk_chain.c b/c/vk_chain.c
index c45c0f00..c69c3550 100644
--- a/c/vk_chain.c
+++ b/c/vk_chain.c
@@ -98,6 +98,9 @@ static struct {
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 */
+ /* chain_attn_flash.comp: the attention core on the matrix units for prompt chunks,
+ * one pipeline per (head dim, query heads per kv head) */
+ VkShaderModule mod_fa; VkPipeline fa[4]; int fa_hd[4], fa_gq[4], nfa;
VkPipeline kdarec[VKC_KDA_MAX]; int kdarec_kd[VKC_KDA_MAX], nkdarec; /* chain_kda's recurrence per key dim */
VkCommandPool cpool;
VkcFrame fr[VKC_FRAMES];
@@ -317,6 +320,9 @@ 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];
+ /* the attention core on the matrix units (vkc_attn_flash_rows): subgroups of 64 with
+ * cooperative matrices, the shader's tiling assumes four of them */
+ if (K.core.coop_sg == 64) K.mod_fa = load_module(K.core.spv_path, "chain_attn_flash.spv");
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;
@@ -799,6 +805,38 @@ static int attn_slice_next(void) { /* the open frame out, a new one in */
K.st.attn_slices++;
return vkc_submit(0) && vkc_begin();
}
+/* chain_attn_flash.comp's pipeline for this head dim and grouping, made on first use;
+ * NULL when the shader is missing or the pipeline fails */
+static VkPipeline fa_pipe(int hd, int gq) {
+ for (int i = 0; i < K.nfa; i++) if (K.fa_hd[i] == hd && K.fa_gq[i] == gq) return K.fa[i];
+ if (!K.mod_fa || K.nfa == 4) return VK_NULL_HANDLE;
+ int32_t sv[2] = {hd, gq};
+ VkSpecializationMapEntry me[2] = {{0, 0, 4}, {1, 4, 4}};
+ VkSpecializationInfo si = {2, me, sizeof sv, sv};
+ VkPipelineShaderStageRequiredSubgroupSizeCreateInfoEXT rss = {
+ .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO_EXT,
+ .requiredSubgroupSize = 64};
+ VkComputePipelineCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
+ .stage = {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .pNext = &rss,
+ .flags = VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT_EXT,
+ .stage = VK_SHADER_STAGE_COMPUTE_BIT, .module = K.mod_fa, .pName = "main",
+ .pSpecializationInfo = &si}, .layout = K.pl};
+ VkPipeline p = VK_NULL_HANDLE;
+ if (vkCreateComputePipelines(K.dev, VK_NULL_HANDLE, 1, &ci, NULL, &p) != VK_SUCCESS) {
+ vkDestroyShaderModule(K.dev, K.mod_fa, NULL); K.mod_fa = VK_NULL_HANDLE; /* not again */
+ return VK_NULL_HANDLE;
+ }
+ K.fa[K.nfa] = p; K.fa_hd[K.nfa] = hd; K.fa_gq[K.nfa++] = gq;
+ return p;
+}
+/* From COLI_VK_CHAIN_FLASH rows (16; 0 = never) a plain causal attention (no list,
+ * window, ring, sink or second V width, head dim a multiple of 64) takes
+ * chain_attn_flash where the device has it, ahead of the blocked shader. */
+int vkc_attn_flash_rows(void) {
+ const char *e = getenv("COLI_VK_CHAIN_FLASH");
+ int v = e && *e ? atoi(e) : 16;
+ return v < 0 ? 0 : v;
+}
int vkc_attn_block_rows(void) {
const char *e = getenv("COLI_VK_ATTN_BLOCK");
int v = e && *e ? atoi(e) : 16;
@@ -811,9 +849,14 @@ int vkc_attn_w(VkcBuf *q, VkcBuf *kc, VkcBuf *vc, VkcBuf *o, VkcBuf *gate, VkcBu
if (w.vd <= 0) w.vd = w.a.hd;
if (w.a.hd > 256 || w.vd > 256 || w.a.H % w.a.KVH || w.win < 0 || w.ring < 0 || (w.sink && !snk)) return 0;
VkcBind bd[7] = {B(q, 0), B(kc, 0), B(vc, 0), B(o, 1), B(gate, 0), B(sel, 0), B(snk, 0)};
- int G = w.a.H / w.a.KVH, blk = vkc_attn_block_rows();
- int blocked = blk > 0 && w.a.S >= blk && G <= 32 && kab_pipe(), br = w.a.sel_row > 0 ? 1 : 32 / G;
- int S = w.a.S, rr = attn_slice_rows(S, w.a.pos_base, (double)w.a.H * (w.a.hd > w.vd ? w.a.hd : w.vd), blocked ? br : 1);
+ int G = w.a.H / w.a.KVH, blk = vkc_attn_block_rows(), fl = vkc_attn_flash_rows();
+ /* a prompt chunk's plain causal attention on the matrix units (chain_attn_flash),
+ * 16 / G rows a workgroup; else the blocked shader, else chain_attn */
+ VkPipeline fp = K.mod_fa && fl > 0 && w.a.S >= fl && !(sel && w.a.sel_row > 0) && !w.win && !w.ring && !w.kv_pm &&
+ !w.sink && w.vd == w.a.hd && w.a.hd % 64 == 0 && 16 % G == 0 ? fa_pipe(w.a.hd, G) : VK_NULL_HANDLE;
+ int blocked = !fp && blk > 0 && w.a.S >= blk && G <= 32 && kab_pipe(), br = w.a.sel_row > 0 ? 1 : 32 / G;
+ int S = w.a.S, rr = attn_slice_rows(S, w.a.pos_base, (double)w.a.H * (w.a.hd > w.vd ? w.a.hd : w.vd),
+ fp ? 16 / G : blocked ? br : 1);
int ok = 1;
for (int r0 = 0; ok && r0 < S; r0 += rr) {
VkcAttnW x = w;
@@ -822,7 +865,10 @@ int vkc_attn_w(VkcBuf *q, VkcBuf *kc, VkcBuf *vc, VkcBuf *o, VkcBuf *gate, VkcBu
x.a.q_off += r0 * w.a.q_row; x.a.g_off += r0 * w.a.g_row; x.a.o_off += r0 * w.a.o_row;
if (w.a.sel_row > 0) x.a.sel_off += r0 * w.a.sel_row;
if (r0 && !attn_slice_next()) return 0;
- if (blocked) {
+ if (fp) {
+ ok = record(fp, bd, 7, &x, sizeof x, (uint32_t)((x.a.S + 16 / G - 1) / (16 / G)), (uint32_t)x.a.KVH, 1);
+ K.st.attn_flash += ok;
+ } else if (blocked) {
struct { VkcAttnW w; int br; } pc = {x, br};
ok = record(KAB.pipe, bd, 7, &pc, sizeof pc, (uint32_t)x.a.KVH, (uint32_t)((x.a.S + br - 1) / br), 1);
K.st.attn_blocked += ok;
@@ -1488,6 +1534,8 @@ void vkc_shutdown(void) {
if (K.mod_gemv4) vkDestroyShaderModule(K.dev, K.mod_gemv4, NULL);
if (K.mod_gemm) vkDestroyShaderModule(K.dev, K.mod_gemm, NULL);
if (K.mod_dnrec) vkDestroyShaderModule(K.dev, K.mod_dnrec, NULL);
+ for (int i = 0; i < K.nfa; i++) vkDestroyPipeline(K.dev, K.fa[i], NULL);
+ if (K.mod_fa) vkDestroyShaderModule(K.dev, K.mod_fa, NULL);
if (K.pl) vkDestroyPipelineLayout(K.dev, K.pl, NULL);
if (K.dsl) vkDestroyDescriptorSetLayout(K.dev, K.dsl, NULL);
dsv4_shutdown();
diff --git a/c/vk_chain.h b/c/vk_chain.h
index f67041ae..39f4e42e 100644
--- a/c/vk_chain.h
+++ b/c/vk_chain.h
@@ -112,6 +112,7 @@ int vkc_attn_w(VkcBuf *q, VkcBuf *kc, VkcBuf *vc, VkcBuf *o, VkcBuf *gate, VkcB
* chain_attnb.comp: a workgroup per KV head and block of rows, each K and V row read once
* per block instead of once per (head, row); below it chain_attn as before. */
int vkc_attn_block_rows(void);
+int vkc_attn_flash_rows(void); /* COLI_VK_CHAIN_FLASH: rows from which chain_attn_flash runs (0 = never) */
/* The attention ops (vkc_attn, vkc_attn_w, vkc_mla_core, vkc_relattn) whose rows x positions
* x heads x head dim pass COLI_VK_ATTN_SLICE (2^32; 0 = never) record their rows in slices,
* each ending its frame (submitted, not waited for) and the next in a new one: no single
@@ -645,6 +646,7 @@ typedef struct {
double wait_ms; /* host time blocked in fence waits */
size_t dev_bytes; /* live chain buffers */
unsigned long long attn_blocked; /* attention calls through chain_attnb (blocks of rows) */
+ unsigned long long attn_flash; /* attention calls through chain_attn_flash (matrix units) */
unsigned long long attn_slices; /* extra submissions that cut a long attention (COLI_VK_ATTN_SLICE) */
} VkcStats;
void vkc_stats(VkcStats *st);
diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md
index 6d2d8025..deafdec3 100644
--- a/docs/ENVIRONMENT.md
+++ b/docs/ENVIRONMENT.md
@@ -266,6 +266,7 @@ With `COLI_VULKAN=1` every MoE engine (qwen36, qwen38, inkling, olmoe, kimi_k3,
| `COLI_VK_ATTN_SLICE` | `4294967296` | Rows x positions x heads x head dim past which the chain's attention ops are recorded in slices of rows, a submission each, so no submission of a big prompt chunk runs past a driver's job timeout; `0` never. |
| `COLI_VK_CHAIN` (laya, gliner_decide) | on for a GPU, discrete or integrated; off on a CPU device | The decision engines' encoder forward (and Laya's head layers) recorded as one submission on the device, the activations staying there (`decide_vk.h`, [vulkan.md](vulkan.md#the-decision-engines)). `0`: matrix by matrix through the device (`COLI_VK_DENSE` decides, as above), the rest on the CPU; `1`: on. The `[VK] <engine>: forward on the device ...` line says which and why. Clef's is qwen36's chain, as above. |
| `COLI_VK_IMPORT` | on for a model without routed experts on a device sharing the CPU's RAM; off otherwise | qwen36: the device reads the int8 and f16 dense rows where the host keeps them (`VK_EXT_external_memory_host`, `coli_vk_tensor_import`) instead of holding a copy of each. `1` requests import, `0` copies. On an integrated GPU, imported rows remain shared even with `COLI_VK_DENSE_HOST=0`: they already have one physical copy, and their pages stay alive while Vulkan reads them. `COLI_VK_IMPORT=0` forces an independent device copy whose host pages can be released; only those released pages count as RAM given back. On other devices, `COLI_VK_DENSE_HOST=0` disables import. Unset, on for the dense 27B family (Qwen3.8-27B, Clef) on an integrated GPU or Lavapipe, whose trunk is the whole model and would be held twice (Clef's f16 trunk, 54 GB, twice past a 61 GB box); a copy elsewhere. Where the device cannot import (no extension, staged uploads) the rows are copied. See [vulkan.md](vulkan.md#the-decision-engines). |
+| `COLI_VK_CHAIN_FLASH` | `16` | Rows of a forward from which the chain's causal attention (no selection list, window, ring or sink, head dim a multiple of 64) runs on the matrix units (`chain_attn_flash.comp`, f16 operands) on a device with cooperative matrices at subgroup size 64. Ahead of `COLI_VK_ATTN_BLOCK`'s blocked shader. `0` never. |
| `COLI_VK_CHAIN_GEMV` | on | `0`: the chain's decode matrices take `qmatmul.comp`'s GEMV instead of `chain_gemv.comp`'s. |
| `COLI_VK_CHAIN_SPIN_US` | `2000` | How long a wait on a chain frame polls before blocking. |
| `COLI_VK_CHAIN_PROF` | off | `1`: device time per kind of chain op, one line per run. |
diff --git a/docs/vulkan.md b/docs/vulkan.md
index 3e1245e7..3427b382 100644
--- a/docs/vulkan.md
+++ b/docs/vulkan.md
@@ -1026,6 +1026,7 @@ f32 throughout, as the CPU's f32 path.
| `COLI_VK_CHAIN` | on for a discrete GPU; on an integrated GPU with the expert tier, what the engine measured (qwen36 and olmoe on, qwen38 off; mimo, inkling, colibri, glm53, kimi_k3, deepseek_v41 and deepseek_v4 off: not measured); off on a CPU device | `1`: every layer's dense chain on the device; `2`: prompts only (forwards of more than two rows that are not a speculative verify; decode and verifies on the per-matrix path, the state moving between the two); `0`: the per-matrix path. The `[VK] <engine>: dense chain ...` line says which and why. |
| `COLI_VK_CHAIN_ROWS` | from the budget, up to 8192 | Prompt rows per chunk: a longer prompt runs every layer chunk by chunk (the device's scratch is sized for one chunk). Unset or `auto`: the most rows whose buffers fit half the free device memory, up to `COLI_VK_CHAIN_ROWS_MAX` (8192); see [big prompt chunks](#big-prompt-chunks-and-expert-streaming). It was 512 before. |
| `COLI_VK_CHAIN_LAYERS` | what fits | The engines on [the partial chain](#a-partial-chain): the first N layers on the device, the CPU the rest and the head. Unset or `auto`: the most layers the device's free memory holds (every layer when they fit, the chain as before); `n`: n layers; `0`: the chain off. |
+| `COLI_VK_CHAIN_FLASH` | `16` | Rows from which a forward's plain causal attention runs on the matrix units (`chain_attn_flash.comp`: query heads of one kv head folded into 16-row tiles, K/V staged once per block as f16, two passes); `0` never. Needs cooperative matrices at subgroup size 64; otherwise, and for a selection list, a window, a ring or a sink, the blocked shader or `chain_attn.comp`. On a Radeon 8060S (Qwen3.6, 1011-token prompt) the attention went from 186 ms (`chain_attnb`) to 22 ms, the first token from 2.08 to 1.85 s, perplexity unchanged (7.65). |
| `COLI_VK_CHAIN_GEMV` | on | `0`: the decode matrices take `qmatmul.comp`'s GEMV instead of `chain_gemv.comp`'s. |
| `COLI_VK_CHAIN_SPIN_US` | `2000` | How long a wait on a chain frame polls the fence before blocking. |
| `COLI_VK_CHAIN_PROF` | off | `1`: one `[VK] chain profile` line of device time per kind of op (timestamps). |