Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
vulkan chain: colibri's multiplexed decode on the device
JustVugg471e8e926ab4
diff --git a/c/colibri.c b/c/colibri.cindex 72a4d1ec..1ec8130a 100644--- a/c/colibri.c+++ b/c/colibri.c@@ -7551,13 +7551,16 @@ static void layers_forward_rows_range(Model *m, float *x, int S, int pos_base,#ifdef COLI_VULKAN/* the whole forward on the device (glm_chain.h); 0: the CPU path below, as before.* A decode batch of one row of the bound KV state (a single-slot serve) is a step- * like any other; rows of several states stay on the CPU. A partial chain (the- * device holds the first N layers) hands x back after layer N - 1: the CPU runs the- * rest from there. */+ * like any other; rows of several states (KV_SLOTS' batched decode) attend each over+ * its own state's mirror (glmc_forward_rows). A partial chain (the device holds the+ * first N layers) hands x back after layer N - 1: the CPU runs the rest from there. */if(g_vk_chain && layer_begin==0 && layer_end==c->n_layers){int done=0;if(!kvs && !positions) done=glmc_forward(m,x,S,pos_base);- else if(kvs && S==1 && kvs[0]==m->kv) done=glmc_forward(m,x,1,positions?positions[0]:pos_base);+ else {+ if(kvs && positions) done=glmc_forward_rows(m,x,S,kvs,positions);+ if(!done && kvs && S==1 && kvs[0]==m->kv) done=glmc_forward(m,x,1,positions?positions[0]:pos_base);+ }if(done>=c->n_layers) return;layer_begin=done;}diff --git a/c/glm_chain.h b/c/glm_chain.hindex bbb8e1af..fd9466ec 100644--- a/c/glm_chain.h+++ b/c/glm_chain.h@@ -47,8 +47,15 @@* The layers already done in the lost forward count their experts' routing twice in* the usage statistics.*- * The chain declines (the CPU path runs, the watermark follows) for a ragged- * multi-slot decode batch, a layer range (segments), a quantized KV cache (KV8, KV_TQ),+ * KV_SLOTS' batched decode (several conversations, a row each at its own position) runs+ * on the chain too (glmc_forward_rows): the batch's matrices as one, each row's attention+ * over its own conversation's mirror (the chain's own, or one of up to COLI_VK_CHAIN_MUX+ * beside it, whole, each with its watermarks; the one read longest ago gives way) and its+ * own DSA list. Such a step stays on the CPU with the split on, past the mirrors' count+ * or the device's room, and with COLI_VK_CHAIN_MUX=0.+ *+ * The chain declines (the CPU path runs, the watermark follows) for a layer range+ * (segments), a quantized KV cache (KV8, KV_TQ),* PILOT or LOOKA (they read the residual on the host between layers), the exact verify* of COLI_EXACT_VERIFY, the CUDA backend, and a model whose matrices or geometry its* shaders do not take (int2, E8/IQ3, fp8 dense matrices; kv_lora above 1024, qk_rope@@ -70,6 +77,16 @@#include "vk_chain.h"#include "vk_kvsplit.h"+/* A KV mirror of one conversation beside the chain's own, for the rows of a multiplexed+ * decode step (glmc_forward_rows): the same arrays, its own watermarks. */+#define GLMC_MUX_MAX 16+typedef struct {+ KVState *owner; /* the conversation (NULL: free) */+ int cap; /* positions a layer holds */+ VkcMlaCache *kv; VkcBuf **ik; int *kv_valid; /* per layer, indexed as the model's */+ unsigned long long used; /* the step that last read it: the eviction's order */+} GlmcMirror;+typedef struct {int ok, failed;int lo, d; /* its layers start at lo, on device d (vkc_device) */@@ -92,6 +109,12 @@ typedef struct {float *host_routed;unsigned long long forwards;double host_ms;+ /* multiplexed decode steps: the other conversations' mirrors, the step's new rows+ * before their mirrors (latent and rope, index keys), one row's DSA selection */+ GlmcMirror mux[GLMC_MUX_MAX];+ VkcMlaCache mtmp; VkcBuf *mik, *msel;+ unsigned long long mux_steps, mux_fw, mux_rows, mux_up, mux_evict;+ int mux_noted;} GlmChain;static int g_vk_chain = 0; /* COLI_VK_CHAIN decided on, and the chain's pipelines are up */@@ -160,7 +183,14 @@ static int glmc_layer_qts(Model *m, int i, QT **q) {/* ---- the host's writes to its KV cache: the mirror's watermark follows ------------ *//* The CPU's attention writes rows [pos..] of each row's KV state for this layer. */-/* (each covers both chains; a chain's split indexes its own layers from 0) */+/* (each covers both chains and their conversations' mirrors; a chain's split indexes its+ * own layers from 0) */+static void glmc_mux_lower(GlmChain *ch, KVState *k, int from, int to, int pos) {+ if (pos < 0) pos = 0;+ for (int j = 0; j < GLMC_MUX_MAX; j++)+ if (ch->mux[j].owner == k)+ for (int i = from; i < to; i++) if (ch->mux[j].kv_valid[i] > pos) ch->mux[j].kv_valid[i] = pos;+}static void glmc_cpu_rows(Model *m, int layer, KVState *const *kvs, const int *positions, int pos_base, int S) {for (int d = 0; d < 2; d++) {GlmChain *ch = glmc_of(m, d);@@ -170,6 +200,7 @@ static void glmc_cpu_rows(Model *m, int layer, KVState *const *kvs, const int *pint pos = positions ? positions[s] : pos_base + s;if (ks == ch->owner && ch->kv_valid[layer] > pos) ch->kv_valid[layer] = pos;if (ks == ch->owner) vkc_kv_lower(&ch->ks, layer - ch->lo, pos);+ glmc_mux_lower(ch, ks, layer, layer + 1, pos);}}}@@ -177,7 +208,9 @@ static void glmc_cpu_rows(Model *m, int layer, KVState *const *kvs, const int *pstatic void glmc_host_rows(Model *m, KVState *k, int from) {for (int d = 0; d < 2; d++) {GlmChain *ch = glmc_of(m, d);- if (!ch || !ch->kv_valid || k != ch->owner) continue;+ if (!ch || !ch->kv_valid) continue;+ glmc_mux_lower(ch, k, ch->lo, ch->lo + ch->n, from);+ if (k != ch->owner) continue;for (int i = ch->lo; i < ch->lo + ch->n; i++) {if (ch->kv_valid[i] > from) ch->kv_valid[i] = from < 0 ? 0 : from;vkc_kv_lower(&ch->ks, i - ch->lo, from < 0 ? 0 : from);@@ -192,6 +225,7 @@ static void glmc_kv_reset(Model *m) {for (int i = ch->lo; i < ch->lo + ch->n; i++) ch->kv_valid[i] = 0;vkc_kv_reset(&ch->ks);ch->owner = NULL;+ glmc_mux_lower(ch, m->kv, ch->lo, ch->lo + ch->n, 0);}}@@ -692,6 +726,9 @@ static int glmc_forward(Model *m, float *xh, int S, int pos_base) {Cfg *c = &m->c; int D = c->hidden, L = c->n_layers, TK = c->index_topk;if (!m->Lc || !m->Rc || (m->has_dsa && !m->Ic)) return 0;for (int i = 0; i < L; i++) if (m->kv_start[i] != 0 || !m->Lc[i]) return 0;+ /* the rows this step writes: a mirror of the bound state beside a chain's own (a+ * multiplexed step's) holds them no longer */+ for (int d = 0; d < 2; d++) { GlmChain *x = glmc_of(m, d); if (x) glmc_mux_lower(x, m->kv, x->lo, x->lo + x->n, pos_base); }/* the chunk: the smaller of the two chains' (the selection crosses chunk by chunk) */int mirror_ok = glmc_mirror(ch, m, pos_base + S, 1);int CH = mirror_ok ? glmc_chunk_rows(ch, m) : 1;@@ -743,6 +780,297 @@ static int glmc_forward(Model *m, float *xh, int S, int pos_base) {return n + n2;}+/* ---- a multiplexed decode step: one row from each of several conversations -------- */+/* KV_SLOTS' batched decode (step_decode_batch): row s is the next token of conversation+ * kvs[s] at its own position pos[s]. Everything but the attention core is the batch's,+ * as in glmc_forward_seg; the new KV rows go to each conversation's mirror and the core+ * runs one row at a time over it (vkc_mla_attn_rows). A conversation's mirror is the+ * chain's own when the chain holds it, else one of up to COLI_VK_CHAIN_MUX (default 16,+ * 0: these steps on the CPU) beside it, whole (never split), each with its watermarks;+ * past that count, or the device's room, the one read longest ago gives way. The DSA+ * selection is per row too (each over its own conversation's index keys). */+static int g_glmc_mux = -1;+static int glmc_mux_n(void) {+ if (g_glmc_mux < 0) {+ const char *e = getenv("COLI_VK_CHAIN_MUX");+ int v = e && *e ? atoi(e) : GLMC_MUX_MAX;+ g_glmc_mux = v < 0 ? 0 : v > GLMC_MUX_MAX ? GLMC_MUX_MAX : v;+ }+ return g_glmc_mux;+}+static size_t glmc_mux_bytes(GlmChain *ch, Model *m, int cap) {+ Cfg *c = &m->c; size_t b = 0;+ for (int i = ch->lo; i < ch->lo + ch->n && cap > 0; i++)+ b += vkc_fit_buf((size_t)cap * c->kv_lora * sizeof(float)) + (c->qk_rope ? vkc_fit_buf((size_t)cap * c->qk_rope * sizeof(float)) : 0) ++ (glmc_full(m, i) ? vkc_fit_buf((size_t)cap * c->index_hd * sizeof(float)) : 0);+ return b;+}+static void glmc_mux_free(GlmChain *ch, GlmcMirror *v) {+ for (int i = ch->lo; i < ch->lo + ch->n && v->kv; i++) {+ vkc_free(v->kv[i].lat); vkc_free(v->kv[i].rope); vkc_free(v->ik[i]);+ v->kv[i] = (VkcMlaCache){NULL, NULL, 0}; v->ik[i] = NULL; v->kv_valid[i] = 0;+ }+ v->owner = NULL; v->cap = 0;+}+/* Conversation k's mirror beside the chain's own, with room for `need` positions: the+ * one that holds it, else a free one, else the one read longest ago (not by this step).+ * NULL: none to take, or no room on the device. */+static GlmcMirror *glmc_mux_get(GlmChain *ch, Model *m, KVState *k, int need) {+ Cfg *c = &m->c; int L = c->n_layers, n = glmc_mux_n();+ GlmcMirror *v = NULL, *fr = NULL, *old = NULL;+ for (int j = 0; j < n && !v; j++) {+ GlmcMirror *x = &ch->mux[j];+ if (x->owner == k) v = x;+ else if (!x->owner) { if (!fr) fr = x; }+ else if (x->used != ch->mux_steps && (!old || x->used < old->used)) old = x;+ }+ if (!v) {+ if (!(v = fr ? fr : old)) return NULL;+ if (v->owner) ch->mux_evict++; /* its buffers stay, for the conversation that takes it */+ if (!v->kv) {+ v->kv = calloc(L, sizeof *v->kv); v->ik = calloc(L, sizeof *v->ik); v->kv_valid = calloc(L, sizeof *v->kv_valid);+ if (!v->kv || !v->ik || !v->kv_valid) {+ free(v->kv); free(v->ik); free(v->kv_valid); v->kv = NULL; v->ik = NULL; v->kv_valid = NULL;+ return NULL;+ }+ }+ v->owner = k;+ for (int i = ch->lo; i < ch->lo + ch->n; i++) v->kv_valid[i] = 0;+ }+ v->used = ch->mux_steps;+ if (v->cap >= need) return v;+ int cap = 256; while (cap < need) cap *= 2;+ if (cap > k->max_t) cap = k->max_t;+ size_t room = (vkc_dev_avail() + glmc_mux_bytes(ch, m, v->cap)) / 10 * 8; /* a fifth for the rest, as the split */+ glmc_mux_free(ch, v);+ if (cap < need || glmc_mux_bytes(ch, m, cap) > room) return NULL;+ for (int i = ch->lo; i < ch->lo + ch->n; i++) {+ v->kv[i].lat = vkc_buf((size_t)cap * c->kv_lora * sizeof(float), VKC_DEV);+ v->kv[i].rope = c->qk_rope > 0 ? vkc_buf((size_t)cap * c->qk_rope * sizeof(float), VKC_DEV) : NULL;+ v->kv[i].cap = cap;+ if (glmc_full(m, i)) v->ik[i] = vkc_buf((size_t)cap * c->index_hd * sizeof(float), VKC_DEV);+ if (!v->kv[i].lat || (c->qk_rope > 0 && !v->kv[i].rope) || (glmc_full(m, i) && !v->ik[i])) { glmc_mux_free(ch, v); return NULL; }+ }+ v->owner = k; v->cap = cap;+ return v;+}+/* Record the uploads that make mirror v conversation k's below position p. */+static int glmc_mux_push(GlmChain *ch, Model *m, GlmcMirror *v, KVState *k, int p) {+ Cfg *c = &m->c; int ok = 1, K = c->kv_lora, R = c->qk_rope, ID = c->index_hd;+ for (int i = ch->lo; i < ch->lo + ch->n && ok; i++) {+ int t0 = v->kv_valid[i], n = p - t0;+ if (n > 0) {+ ok = vkc_write(v->kv[i].lat, (size_t)t0 * K, coli_kv_row(k->Lc[i], t0, K), (size_t)n * K * sizeof(float)) &&+ (R == 0 || vkc_write(v->kv[i].rope, (size_t)t0 * R, coli_kv_row(k->Rc[i], t0, R), (size_t)n * R * sizeof(float))) &&+ (!glmc_full(m, i) || vkc_write(v->ik[i], (size_t)t0 * ID, coli_kv_row(k->Ic[i], t0, ID), (size_t)n * ID * sizeof(float)));+ ch->mux_up += (unsigned long long)n;+ }+ v->kv_valid[i] = p;+ }+ return ok;+}+/* The new rows of layers [from, to) into each row's conversation (after their frame's wait). */+static void glmc_mux_pull(GlmChain *ch, Model *m, int from, int to, int S, KVState *const *kvs, const int *pos) {+ Cfg *c = &m->c; int K = c->kv_lora, R = c->qk_rope, ID = c->index_hd;+ for (int i = from; i < to; i++) {+ const float *kv = (const float *)vkc_ptr(ch->kvd) + (size_t)(i - ch->lo) * ch->kvd_layer;+ for (int s = 0; s < S; s++) {+ memcpy(coli_kv_row(kvs[s]->Lc[i], pos[s], K), kv + (size_t)s * K, K * sizeof(float));+ if (R) memcpy(coli_kv_row(kvs[s]->Rc[i], pos[s], R), kv + (size_t)S * K + (size_t)s * R, R * sizeof(float));+ if (glmc_full(m, i))+ memcpy(coli_kv_row(kvs[s]->Ic[i], pos[s], ID), kv + (size_t)S * (K + R) + (size_t)s * ID, ID * sizeof(float));+ }+ }+}+/* glmc_dsa for the rows of a multiplexed step: each row's index key into its mirror (and+ * the host's copy), each row's selection over its own conversation's keys into sel's row+ * (the select writes -1, every position, while a row's context is within index_topk) */+static int glmc_mux_dsa(GlmChain *ch, Model *m, int i, int S, const int *pos, GlmcMirror *const *mir, int ctx) {+ Cfg *c = &m->c; int IH = c->index_nh, ID = c->index_hd, R = c->qk_rope, SR = 1 + c->index_topk;+ size_t kof = (size_t)(i - ch->lo) * ch->kvd_layer + (size_t)S * (c->kv_lora + R);+ VkcMlaRow ln = {S, 1, 0, ID, 0, 0, ID, 0, 0, ID, 0, 0, 0, (int)ch->o_ixw[i], (int)ch->o_ixb[i], 1, 1e-6f};+ VkcMlaRow rk = {S, 1, R, ID, VKC_ROPE_INTERLEAVED, 0, ID, 0, 0, ID, 0, 0, R, 0, 0, 0, 0.f};+ VkcMlaRow rq = {S * IH, IH, R, ID, VKC_ROPE_INTERLEAVED, 0, IH * ID, ID, 0, IH * ID, ID, 0, R, 0, 0, 0, 0.f};+ int ok = vkc_matmul(glmc_tensor(&m->ix_wk[i]), ch->nrm, 0, ch->ikd, 0, S) &&+ vkc_mla_lnorm(ch->ikd, ch->prm, ch->mik, &ln) &&+ (R == 0 || vkc_mla_rope(ch->mik, ch->cs, ch->mik, &rk)) &&+ vkc_copy(ch->kvd, kof, ch->mik, 0, (size_t)S * ID);+ for (int s = 0; ok && s < S; s++) ok = vkc_copy(mir[s]->ik[i], (size_t)pos[s] * ID, ch->mik, (size_t)s * ID, ID);+ ok = ok && vkc_matmul(glmc_tensor(&m->ix_wq[i]), ch->sc.qa, 0, ch->iq, 0, S) &&+ (R == 0 || vkc_mla_rope(ch->iq, ch->cs, ch->iq, &rq)) &&+ vkc_matmul(glmc_tensor(&m->ix_wp[i]), ch->nrm, 0, ch->ihw, 0, S);+ for (int s = 0; ok && s < S; s++) {+ VkcDsa ds = {1, pos[s], IH, ID, c->index_topk, g_dsa_force, s * IH * ID, IH * ID, s * IH, IH, 0, ID, ctx, SR,+ 1.f / sqrtf((float)ID), 1.f / sqrtf((float)IH)};+ ok = vkc_dsa_select(ch->iq, ch->ihw, mir[s]->ik[i], ch->isc, ch->msel, &ds) &&+ vkc_copy(ch->sel, (size_t)s * SR, ch->msel, 0, SR);+ }+ return ok;+}+/* One chain's layers for the S rows of a multiplexed step (one chunk), the rows after the+ * last of them back into xh. sel_in/on_in, sel_out/on_out: glmc_forward_seg's crossing+ * selection. 0 = not taken (*lost = 1: a frame failed, the chains off). */+static int glmc_mux_seg(Model *m, GlmChain *ch, float *xh, int S, KVState *const *kvs, const int *pos,+ const int *sel_in, int on_in, int *sel_out, int *on_out, int *lost) {+ *lost = 0;+ Cfg *c = &m->c; int D = c->hidden, L = c->n_layers, K = c->kv_lora, R = c->qk_rope, ID = c->index_hd;+ int TK = c->index_topk, SR = 1 + TK, N = ch->n, lo = ch->lo, hi = lo + N, ctx = 0;+ for (int s = 0; s < S; s++) if (pos[s] + 1 > ctx) ctx = pos[s] + 1;+ int hand_sel = hi < L && m->has_dsa && !glmc_full(m, hi);+ if (hand_sel && (int64_t)S * TK > m->dsa_scap) {+ int *sl = malloc((size_t)S * TK * sizeof(int)), *ns = malloc((size_t)S * sizeof(int));+ if (!sl || !ns) { free(sl); free(ns); return 0; }+ free(m->dsa_sel); free(m->dsa_nsel);+ m->dsa_sel = sl; m->dsa_nsel = ns; m->dsa_scap = (int)((int64_t)S * TK);+ }+ /* each row's mirror: the chain's own when it holds that conversation, else one beside it */+ GlmcMirror own = {ch->owner, ch->cap, ch->kv, ch->ik, ch->kv_valid, 0};+ GlmcMirror **mir = malloc((size_t)S * sizeof *mir);+ VkcMlaCache **cl = malloc((size_t)S * sizeof *cl);+ float *inv = R ? malloc((size_t)(R / 2) * sizeof(float)) : NULL;+ if (!mir || !cl || (R && !inv)) { free(mir); free(cl); free(inv); return 0; }+ ch->mux_steps++;+ int ok = 1;+ for (int s = 0; s < S && ok; s++)+ ok = (mir[s] = kvs[s] == ch->owner && ch->cap >= pos[s] + 1 ? &own : glmc_mux_get(ch, m, kvs[s], pos[s] + 1)) != NULL;+ ok = ok && glmc_scratch(ch, m, S, ctx) && glmc_res(&ch->mtmp.lat, (size_t)S * K, VKC_DEV) &&+ (R == 0 || glmc_res(&ch->mtmp.rope, (size_t)S * R, VKC_DEV)) &&+ (!m->has_dsa || (glmc_res(&ch->mik, (size_t)S * ID, VKC_DEV) && glmc_res(&ch->msel, SR, VKC_DEV)));+ if (!ok) {+ if (!ch->mux_noted++)+ fprintf(stderr, "[VK] %s chain: no device room for the KV of %d conversations at once; such steps run on the CPU\n",+ glmc_name(ch), S);+ free(mir); free(cl); free(inv);+ return 0;+ }+ ch->mtmp.cap = S;+ vkc_gemm_rows(-1);+ for (int j = 0; j < R / 2; j++) inv[j] = powf(c->theta, -2.0f * j / R); /* rope_interleave's frequencies */+ for (int s = 0; s < S && R; s++) /* the CPU's own angles, cosines and sines, at each row's position */+ for (int j = 0; j < R / 2; j++) {+ float ang = pos[s] * inv[j];+ float *cs = (float *)vkc_ptr(ch->cs) + (size_t)s * R + 2 * j;+ cs[0] = cosf(ang); cs[1] = sinf(ang);+ }+ /* a turn that went back: every mirror of these conversations below the rows' positions */+ for (int i = lo; i < hi; i++) glmc_cpu_rows(m, i, kvs, pos, 0, S);+ if (!vkc_begin() || !vkc_write(ch->x, 0, xh, (size_t)S * D * sizeof(float))) goto lost;+ for (int s = 0; s < S; s++) if (!glmc_mux_push(ch, m, mir[s], kvs[s], pos[s])) goto lost;+ int pending = 0, pulled = lo, sel_on = 0;+ if (sel_in && on_in) { /* the primary's selection, for the layers here that reuse it */+ ok = vkc_write(ch->sel, 0, sel_in, (size_t)S * SR * sizeof(int));+ sel_on = 1;+ }+ for (int i = lo; i < hi && ok; i++) {+ Layer *l = &m->L[i];+ if (g_spec && g_prefetch && l->sparse && m->enr[i] > 0) /* the CPU path's I/O hint */+ for (int z = 0; z < m->enr[i]; z++) if (!(S <= 4 && vk_reg_served(i, m->eroute[i][z]))) expert_prefetch(m, i, m->eroute[i][z]);+ if (pending) { ok = glmc_combine(ch, m, S); pending = 0; }+ size_t ko = (size_t)(i - lo) * ch->kvd_layer;+ ok = ok && glmc_norm(ch->x, ch->prm, ch->o_in[i], ch->nrm, S, D, c->eps) &&+ vkc_mla_qkv(&ch->mla[i], &ch->sc, ch->nrm, 0, S, 0, ch->cs, &ch->mtmp, ch->kvd, ko);+ for (int s = 0; ok && s < S; s++) { /* the new rows into their conversations' mirrors */+ cl[s] = &mir[s]->kv[i];+ ok = vkc_copy(cl[s]->lat, (size_t)pos[s] * K, ch->mtmp.lat, (size_t)s * K, K) &&+ (R == 0 || vkc_copy(cl[s]->rope, (size_t)pos[s] * R, ch->mtmp.rope, (size_t)s * R, R));+ }+ if (ok && glmc_full(m, i)) { ok = glmc_mux_dsa(ch, m, i, S, pos, mir, ctx); sel_on = 1; }+ ok = ok && vkc_mla_attn_rows(&ch->mla[i], &ch->sc, S, pos, cl, sel_on ? ch->sel : NULL, 0, SR, ch->tmp, 0);+ VkcEw add = {VKC_EW_ADD, S * D, D, 1, 0, 1, 0, 0, 0, 0, 0, 1.f};+ ok = ok && vkc_ew(ch->x, ch->x, ch->tmp, NULL, NULL, &add) &&+ glmc_norm(ch->x, ch->prm, ch->o_post[i], ch->h2, S, D, c->eps);+ if (!ok) break;+ if (!l->sparse) { /* a dense layer: its MLP here, no host step */+ ok = glmc_mlp(ch, &l->gate_proj, &l->up_proj, &l->down_proj, ch->h2, ch->tmp, S) &&+ vkc_ew(ch->x, ch->x, ch->tmp, NULL, NULL, &add);+ continue;+ }+ ok = vkc_copy(ch->h2d, 0, ch->h2, 0, (size_t)S * D) && vkc_submit(0) && vkc_finish(); /* A1 */+ if (!ok) break;+ glmc_mux_pull(ch, m, pulled, i + 1, S, kvs, pos); pulled = i + 1;+ /* A2: the shared expert, while the host computes the routed experts */+ ok = vkc_begin() && glmc_mlp(ch, &l->sh_gate, &l->sh_up, &l->sh_down, ch->h2, ch->ds, S) && vkc_submit(0);+ double t1 = now_s();+ moe(m, l, i, (float *)vkc_ptr(ch->h2d), S, ch->host_routed, 0);+ memcpy(vkc_ptr(ch->routed), ch->host_routed, (size_t)S * D * sizeof(float));+ ch->host_ms += (now_s() - t1) * 1e3;+ ok = ok && vkc_begin();+ pending = 1;+ }+ int keep_sel = hand_sel || sel_out;+ if (ok && pending) ok = glmc_combine(ch, m, S);+ ok = ok && vkc_copy(ch->xd, 0, ch->x, 0, (size_t)S * D) &&+ (!keep_sel || !sel_on || vkc_copy(ch->seld, 0, ch->sel, 0, (size_t)S * SR)) && vkc_submit(1);+ if (!ok) goto lost;+ glmc_mux_pull(ch, m, pulled, hi, S, kvs, pos);+ memcpy(xh, vkc_ptr(ch->xd), (size_t)S * D * sizeof(float));+ if (sel_out) { /* the raw rows, for the second device's chain */+ *on_out = sel_on;+ if (sel_on) memcpy(sel_out, vkc_ptr(ch->seld), (size_t)S * SR * sizeof(int));+ }+ for (int s = 0; hand_sel && s < S; s++) { /* in the CPU's form: a count (0 = every position), the positions */+ const int *sr = (const int *)vkc_ptr(ch->seld) + (size_t)s * SR;+ int k = sel_on && sr[0] > 0 ? (sr[0] < TK ? sr[0] : TK) : 0;+ if (k) memcpy(m->dsa_sel + (size_t)s * TK, sr + 1, (size_t)k * sizeof(int));+ m->dsa_nsel[s] = k;+ }+ for (int s = 0; s < S; s++) for (int i = lo; i < hi; i++) mir[s]->kv_valid[i] = pos[s] + 1;+ free(mir); free(cl); free(inv);+ ch->forwards++; ch->mux_fw++; ch->mux_rows += (unsigned long long)S;+ return N;+lost: /* a frame failed: the device is gone (or would not take a command); the CPU takes over */+ free(mir); free(cl); free(inv);+ if (!vkc_lost()) { vkc_finish(); coli_vk_mark_lost_dev(ch->d); }+ g_vk_chain = 0; ch->failed = 1;+ { GlmChain *o = glmc_of(m, !ch->d); if (o) o->failed = 1; }+ fprintf(stderr, "[VK] %s chain: the device was lost in a multiplexed step; the CPU runs it again and from here on "+ "(the KV caches are the host's: there is no state to rebuild)\n", glmc_name(ch));+ *lost = 1;+ return 0;+}+/* The devices' layers for a multiplexed decode step (glmc_forward's contract: how many+ * layers ran, 0 = not taken). A single row of the bound state is the chain's own step+ * (glmc_forward), unless a mirror beside the chain's holds that conversation and the+ * chain's own does not. */+static int glmc_forward_rows(Model *m, float *xh, int S, KVState *const *kvs, const int *pos) {+ if (!g_vk_chain || g_vk_chain == COLI_VK_CHAIN_PREFILL || !glmc_mux_n() || S < 1) return 0;+ if (g_pilot || g_pilot_real || g_looka || g_kv8 || g_tq || (exact_verify_on() && g_spec_live)) return 0;+ GlmChain *ch = (GlmChain *)m->vkchain, *ch2 = (GlmChain *)m->vkchain2;+ if (!ch || !ch->ok || ch->failed || vkc_lost() || ch->ks.on) return 0;+ if (ch2 && (!ch2->ok || ch2->failed || ch2->lo != ch->lo + ch->n || ch2->ks.on)) ch2 = NULL;+ if (S == 1 && kvs[0] == m->kv) {+ int held = 0;+ for (int j = 0; j < GLMC_MUX_MAX; j++) held |= ch->mux[j].owner == kvs[0];+ if (!held || ch->owner == kvs[0]) return 0;+ }+ Cfg *c = &m->c; int D = c->hidden, L = c->n_layers, TK = c->index_topk, ctx = 0;+ for (int s = 0; s < S; s++) {+ KVState *k = kvs[s];+ if (!k || !k->Lc || !k->Rc || (m->has_dsa && !k->Ic) || pos[s] < 0 || pos[s] >= k->max_t) return 0;+ for (int i = 0; i < L; i++)+ if (k->kv_start[i] != 0 || !k->Lc[i] || (c->qk_rope && !k->Rc[i]) || (glmc_full(m, i) && !k->Ic[i])) return 0;+ if (pos[s] + 1 > ctx) ctx = pos[s] + 1;+ }+ /* one chunk: the chains' rows, and the DSA scores' scratch (rows x context) */+ int CH = glmc_chunk_rows(ch, m);+ if (ch2) { vkc_device(1); int CH2 = glmc_chunk_rows(ch2, m); vkc_device(0); if (CH2 < CH) CH = CH2; }+ if (S > CH || (m->has_dsa && (int64_t)S * ctx > ((int64_t)32 << 20))) return 0;+ int cross = ch2 && m->has_dsa && !glmc_full(m, ch2->lo), on = 0, lost = 0;+ int *sel = cross ? malloc((size_t)S * (1 + TK) * sizeof(int)) : NULL;+ float *keep = ch2 ? malloc((size_t)S * D * sizeof(float)) : NULL; /* the rows as they came in */+ if ((cross && !sel) || (ch2 && !keep)) { free(sel); free(keep); ch2 = NULL; sel = NULL; keep = NULL; }+ if (keep) memcpy(keep, xh, (size_t)S * D * sizeof(float));+ int n = glmc_mux_seg(m, ch, xh, S, kvs, pos, NULL, 0, sel, &on, &lost);+ if (!n || !ch2) { free(sel); free(keep); return n; }+ vkc_device(1);+ int n2 = glmc_mux_seg(m, ch2, xh, S, kvs, pos, sel, on, NULL, NULL, &lost);+ vkc_device(0);+ free(sel);+ if (lost) { memcpy(xh, keep, (size_t)S * D * sizeof(float)); free(keep); return 0; }+ free(keep);+ return n + n2; /* n2 0, declined: the CPU runs those layers (their mirrors follow, glmc_cpu_rows) */+}+static void glmc_report(Model *m) {for (int d = 0; d < 2 && m; d++) {GlmChain *ch = glmc_of(m, d);@@ -753,6 +1081,13 @@ static void glmc_report(Model *m) {"%.1f ms waiting for the device, %.1f ms of routed experts on the host, %.1f MiB on the device\n",glmc_name(ch), ch->forwards, st.frames, st.ops, st.matmuls, st.gemms, st.wait_ms, ch->host_ms,st.dev_bytes / 1048576.0);+ if (ch->mux_fw) {+ int held = 0;+ for (int j = 0; j < GLMC_MUX_MAX; j++) held += ch->mux[j].owner != NULL;+ fprintf(stderr, "[VK] %s chain: %llu multiplexed steps (%llu rows), %d conversation mirrors beside its own, "+ "%llu rows uploaded to them, %llu evicted\n",+ glmc_name(ch), ch->mux_fw, ch->mux_rows, held, ch->mux_up, ch->mux_evict);+ }vkc_kv_report(&ch->ks);vkc_prof_print();vkc_device(was);diff --git a/c/tests/vulkan_chain_mux.py b/c/tests/vulkan_chain_mux.pynew file mode 100644index 00000000..fbf9dc25--- /dev/null+++ b/c/tests/vulkan_chain_mux.py@@ -0,0 +1,152 @@+#!/usr/bin/env python3+"""The dense chain's multiplexed decode (KV_SLOTS, glm_chain.h's glmc_forward_rows):+several conversations at once on the CPU and with the chain, every DATA and ECHO frame+compared.++Every request of a wave goes in one write, each on its own KV slot: the engine admits+one a loop and decodes the active ones as one batch, so the batches mix rows of+different conversations at different positions, grow as requests come in and shrink as+they finish. The second wave goes back to each slot: one turn extends its conversation,+one goes back in it, one starts over. Token ids and texts must be the CPU's exactly,+the logprobs printed with them within CHAIN_SERVE_TOL (default 1e-4), and the chain's+report must show multiplexed steps of more than one row (CHAIN_MUX_STEPS=0: none, the+chain declining them; the chain's other forwards still there). CHAIN_MUX_EXPECT, a+regular expression the chain session's stderr must match; CHAIN_MUX_LOG, a file to keep+that stderr in.++usage: vulkan_chain_mux.py <engine> <snapshot> <slots> [KEY=VALUE ...] (extra environment)+"""+import os+import re+import subprocess+import sys+import threading++READY = b"\x01\x01READY\x01\x01"+++def waves(n):+ base = bytes(range(65, 65 + 23))+ one = [(base[:9 + 4 * i] + bytes([97 + i]) * (i + 1), 5 + 2 * i, "logprobs=2" if i % 2 else "") for i in range(n)]+ two = []+ for i, (prompt, _, _) in enumerate(one):+ if i % 3 == 0:+ two.append((prompt + b"xyz", 6, "")) # after the reply: the prompt and a new tail+ elif i % 3 == 1:+ two.append((prompt[:6] + b"QRS", 5, "logprobs=1")) # back inside the prompt+ else:+ two.append((b"zz" + prompt, 4, "")) # a new conversation on the slot+ return [one, two]+++def session(engine, snap, slots, extra, chain):+ env = dict(os.environ, SNAP=snap, SERVE="1", KV_SLOTS=str(slots), **extra)+ if chain:+ env.update(COLI_VULKAN="1", COLI_VK_CHAIN=os.environ.get("COLI_VK_CHAIN", "1"), COLI_VK_TIER_SYNC="1",+ COLI_USAGE=os.path.abspath("chain-mux.usage"))+ try:+ os.remove(env["COLI_USAGE"])+ except FileNotFoundError:+ pass+ p = subprocess.Popen([engine, "8", "8"], env=env, stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ err = []+ threading.Thread(target=lambda: [err.append(l) for l in iter(p.stderr.readline, b"")], daemon=True).start()+ while True:+ line = p.stdout.readline()+ if not line:+ sys.exit("engine exited before READY:\n" + b"".join(err).decode(errors="replace")[-3000:])+ if READY in line:+ break+ frames = {}+ rid = 0+ for wave in waves(slots):+ batch, ids = b"", []+ for slot, (prompt, max_tok, ext) in enumerate(wave):+ rid += 1+ ids.append(rid)+ frames[rid] = []+ batch += (f"SUBMIT {rid} {slot} {len(prompt)} {max_tok} 0 1 0" + (f" {ext}" if ext else "") ++ "\n").encode() + prompt + b"\n"+ p.stdin.write(batch)+ p.stdin.flush()+ left = set(ids)+ while left:+ line = p.stdout.readline()+ if not line:+ sys.exit("engine died:\n" + b"".join(err).decode(errors="replace")[-3000:])+ f = line.split()+ kind = f[0] if f else b""+ if kind in (b"DATA", b"ECHO"):+ body = p.stdout.read(int(f[2]))+ p.stdout.readline()+ frames[int(f[1])].append(line.rstrip() + b" " + body)+ elif kind == b"DONE":+ frames[int(f[1])].append(b"DONE")+ left.discard(int(f[1]))+ elif kind == b"ERROR":+ sys.exit(f"engine error: {line!r}")+ p.stdin.close()+ p.wait(timeout=120)+ return frames, b"".join(err).decode(errors="replace")+++TOL = float(os.environ.get("CHAIN_SERVE_TOL", "1e-4"))+WORST = [0.0]+++def close(a, b):+ if a == b:+ return True+ fa, fb = a.split(b" "), b.split(b" ")+ if len(fa) != len(fb):+ return False+ for x, y in zip(fa, fb):+ if x == y:+ continue+ try:+ if b"." not in x or abs(float(x) - float(y)) > TOL:+ return False+ WORST[0] = max(WORST[0], abs(float(x) - float(y)))+ except ValueError:+ return False+ return True+++def main():+ engine, snap, slots = sys.argv[1], sys.argv[2], int(sys.argv[3])+ extra = dict(a.split("=", 1) for a in sys.argv[4:])+ cpu, err_cpu = session(engine, snap, slots, extra, False)+ dev, err = session(engine, snap, slots, extra, True)+ for text in (err_cpu, err): # a sanitized build reports into the engine's stderr+ if "ERROR: AddressSanitizer" in text or "runtime error:" in text:+ sys.exit("FAIL: sanitizer diagnostic\n" + text[-4000:])+ if os.environ.get("CHAIN_MUX_LOG"):+ with open(os.environ["CHAIN_MUX_LOG"], "w") as f:+ f.write(err)+ mux = re.findall(r"chain: (\d+) multiplexed steps \((\d+) rows\)", err)+ none = os.environ.get("CHAIN_MUX_STEPS") == "0"+ if none and (mux or not re.search(r"chain: [1-9]\d* forwards", err)):+ sys.exit("FAIL: the chain ran multiplexed steps, or nothing at all\n" + err[-3000:])+ if not none and (not mux or not any(int(r) > int(s) for s, r in mux)):+ sys.exit("FAIL: the chain ran no multiplexed step of several rows\n" + err[-3000:])+ expect = os.environ.get("CHAIN_MUX_EXPECT")+ if expect and not re.search(expect, err):+ sys.exit(f"FAIL: the chain session's stderr has no {expect!r}\n" + err[-3000:])+ n = 0+ for rid in sorted(cpu):+ a, b = cpu[rid], dev.get(rid, [])+ if len(a) != len(b) or not all(close(x, y) for x, y in zip(a, b)):+ for x, y in zip(a, b):+ if not close(x, y):+ print(f" request {rid} cpu: {x[:200]!r}\n request {rid} vk : {y[:200]!r}")+ break+ sys.exit(f"FAIL: request {rid}'s frames differ from the CPU's ({len(a)} vs {len(b)})")+ n += len(a)+ line = [l for l in err.splitlines() if "multiplexed steps" in l or (none and " forwards" in l)][-1]+ print(f"OK mux {os.path.basename(snap)} slots={slots} {' '.join(sys.argv[4:])}: {len(cpu)} requests, "+ f"{n} frames = CPU (numbers within {WORST[0]:.1e}); {line.split('] ', 1)[1]}")+++if __name__ == "__main__":+ main()diff --git a/c/tests/vulkan_dense_only_glm.sh b/c/tests/vulkan_dense_only_glm.shindex b97c7554..b3c0498d 100644--- a/c/tests/vulkan_dense_only_glm.sh+++ b/c/tests/vulkan_dense_only_glm.sh@@ -134,13 +134,17 @@ dho_family_glm() {dho_mla_lost colibri "dense-only colibri device lost in the prompt" 3 SNAP=glm_tiny REF=ref_glm.json TF=1 -- 64 16 16dho_mla_lost colibri "dense-only colibri device lost with MTP" 12 SNAP=glm_tiny_mtp REF=glm_tiny_mtp/ref_glm.json -- 64 16 16COLI_VK_STAGED=1 dho_mla_lost colibri "dense-only colibri device lost, staged" 12 SNAP=glm_tiny REF=ref_glm.json -- 64 16 16- # serve sessions: pins, the prompt cache, the prefill read-out, drafts, two KV slots (the- # ragged batch declines the chain: per matrix on the device, kv_b on the host)+ # serve sessions: pins, the prompt cache, the prefill read-out, drafts, two KV slots,+ # several conversations at onceexport COLI_VK_DENSE_HOST=0 CHAIN_SERVE_EXPECT='dense matrices on the device only'CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 DSA_TOPK=4 DRAFT=3CHAIN_SERVE_SLOTS=2 CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 KV_SLOTS=2COLI_VK_CHAIN=2 CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 DSA_TOPK=4+ CHAIN_MUX_EXPECT="$CHAIN_SERVE_EXPECT" $PY tests/vulkan_chain_mux.py ./colibri glm_tiny_serve 3 SERVE_BATCH=1 IDOT=0 DSA_TOPK=4+ # the steps the chain does not take (MUX=0): per matrix on the device, kv_b on the host+ CHAIN_MUX_EXPECT="$CHAIN_SERVE_EXPECT" CHAIN_MUX_STEPS=0 $PY tests/vulkan_chain_mux.py ./colibri glm_tiny_serve 3 SERVE_BATCH=1 IDOT=0 COLI_VK_CHAIN_MUX=0+ rm -f chain-mux.usageunset COLI_VK_DENSE_HOST CHAIN_SERVE_EXPECT# the RAM the experts' cache gets back: RAM_GB just above the fixture's fixed reserve, the# cap cap_for_ram leaves with the host copies against the one it leaves without themdiff --git a/c/tests/vulkan_engines.sh b/c/tests/vulkan_engines.shindex b755a35b..5492374b 100755--- a/c/tests/vulkan_engines.sh+++ b/c/tests/vulkan_engines.sh@@ -2188,6 +2188,17 @@ family_glm_chain() {CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 DSA_TOPK=4 DRAFT=3CHAIN_SERVE_SLOTS=2 CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 KV_SLOTS=2COLI_VK_CHAIN=2 CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 DSA_TOPK=4+ # several conversations at once (KV_SLOTS' batched decode): each row over its own+ # conversation's mirror and DSA list; one mirror beside the chain's (evictions, and the+ # steps it cannot hold on the CPU); the device lost in a multiplexed step; MUX=0+ $PY tests/vulkan_chain_mux.py ./colibri glm_tiny_serve 3 SERVE_BATCH=1 IDOT=0+ CHAIN_MUX_LOG=mux.log $PY tests/vulkan_chain_mux.py ./colibri glm_tiny_serve 3 SERVE_BATCH=1 IDOT=0 DSA_TOPK=4+ CHAIN_MUX_EXPECT='[1-9][0-9]* evicted' $PY tests/vulkan_chain_mux.py ./colibri glm_tiny_serve 4 SERVE_BATCH=1 IDOT=0 COLI_VK_CHAIN_MUX=1+ local fr; fr=$(grep -o '[0-9]* frames' mux.log | head -1 | cut -d' ' -f1)+ CHAIN_MUX_EXPECT='lost in a multiplexed step' $PY tests/vulkan_chain_mux.py ./colibri glm_tiny_serve 3 SERVE_BATCH=1 IDOT=0 DSA_TOPK=4 \+ COLI_VK_CHAIN_FAULT=$((fr / 2))+ CHAIN_MUX_STEPS=0 $PY tests/vulkan_chain_mux.py ./colibri glm_tiny_serve 3 SERVE_BATCH=1 IDOT=0 COLI_VK_CHAIN_MUX=0+ rm -f mux.log chain-mux.usage# glm53local ids bits@@ -2257,6 +2268,11 @@ family_glm_chain_sanitize() {if grep -qE "ERROR: AddressSanitizer|runtime error:" san.log; then cat san.log; fail "asan chain serve $args: sanitizer diagnostic"; fiecho "OK asan chain serve ${args%% *}: $(tail -1 san.log)"done+ for args in "3 SERVE_BATCH=1 IDOT=0 DSA_TOPK=4" "4 SERVE_BATCH=1 IDOT=0 COLI_VK_CHAIN_MUX=1"; do+ # shellcheck disable=SC2086+ $PY tests/vulkan_chain_mux.py ./colibri glm_tiny_serve $args > san.log 2>&1 || { cat san.log; fail "asan chain mux $args"; }+ echo "OK asan chain mux: $(tail -1 san.log)"+ doneunset OMP_NUM_THREADS CAP_RAISEmake clean >/dev/null 2>&1 || true}@@ -3796,6 +3812,8 @@ kv_split_colibri() {CHAIN_SERVE_EXPECT="$E" CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 $KCHAIN_SERVE_EXPECT="$E" CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 DSA_TOPK=4 DRAFT=3 $KCHAIN_SERVE_EXPECT="$E" CHAIN_SERVE_SLOTS=2 CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 KV_SLOTS=2 $K+ # several conversations at once with the split on: those steps on the CPU+ CHAIN_MUX_EXPECT="$E" CHAIN_MUX_STEPS=0 $PY tests/vulkan_chain_mux.py ./colibri glm_tiny_serve 3 SERVE_BATCH=1 IDOT=0 DSA_TOPK=4 $K}unset CAP_RAISE}diff --git a/c/tests/vulkan_layers_dev2.sh b/c/tests/vulkan_layers_dev2.shindex 75a6035f..ba053516 100644--- a/c/tests/vulkan_layers_dev2.sh+++ b/c/tests/vulkan_layers_dev2.sh@@ -272,6 +272,16 @@ ld2_colibri() {$PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 DSA_TOPK=4 DRAFT=3 COLI_VK_DEV2=0 COLI_VK_CHAIN_LAYERS=1 COLI_VK_CHAIN_LAYERS2=2CHAIN_SERVE_EXPECT='colibri dev2 chain: [1-9][0-9]* forwards' CHAIN_SERVE_SLOTS=2 CHAIN_SERVE_DIALECT=colibri \$PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 KV_SLOTS=2 COLI_VK_DEV2=0 COLI_VK_CHAIN_LAYERS=2 COLI_VK_CHAIN_LAYERS2=2+ # several conversations at once on both devices; a shared indexer first on the second+ # (the primary's rows' DSA lists cross), and the CPU's after it+ CHAIN_MUX_EXPECT='colibri dev2 chain: [1-9][0-9]* multiplexed' \+ $PY tests/vulkan_chain_mux.py ./colibri glm_tiny_serve 3 SERVE_BATCH=1 IDOT=0 DSA_TOPK=4 COLI_VK_DEV2=0 COLI_VK_CHAIN_LAYERS=2 COLI_VK_CHAIN_LAYERS2=3+ ptl_glm_shx glm_tiny_serve glm_tiny_shx_serve+ for s in "1 2" "3 2"; do+ CHAIN_MUX_EXPECT='colibri dev2 chain: [1-9][0-9]* multiplexed' $PY tests/vulkan_chain_mux.py ./colibri glm_tiny_shx_serve 3 \+ SERVE_BATCH=1 IDOT=0 DSA_TOPK=4 COLI_VK_DEV2=0 COLI_VK_CHAIN_LAYERS=${s% *} COLI_VK_CHAIN_LAYERS2=${s#* }+ done+ rm -rf glm_tiny_shx_serve chain-mux.usage}# glm53 (GLM-5.3 Flash): the six-layer fixture, KDA and MLA alternating (the KDA state on@@ -616,6 +626,11 @@ family_layers_dev2_mla_sanitize() {SNAP=glm_tiny_shx REF=ref_glm.json USAGE_SAVE=0 DSA_TOPK=4 TF=1 COLI_VK_CHAIN_ROWS=5 ./colibri 64 16 16LD2_SAN_LOST=1 ld2_san colibri "asan ld2 colibri second device lost mid-decode" COLI_VK_CHAIN_LAYERS=2 COLI_VK_CHAIN_LAYERS2=2 \COLI_VK_CHAIN_FAULT2=10 "${G[@]}" ./colibri 64 16 16+ ptl_glm_shx glm_tiny_serve glm_tiny_shx_serve # several conversations at once, the DSA lists crossing+ $PY tests/vulkan_chain_mux.py ./colibri glm_tiny_shx_serve 3 SERVE_BATCH=1 IDOT=0 DSA_TOPK=4 COLI_VK_DEV2=0 COLI_VK_CHAIN_LAYERS=1 \+ COLI_VK_CHAIN_LAYERS2=2 > san.log 2>&1 || { cat san.log; fail "asan ld2 colibri several conversations at once"; }+ echo "OK asan ld2 colibri several conversations at once: $(tail -1 san.log)"+ rm -rf glm_tiny_shx_serve chain-mux.usageld2_san glm53 "asan ld2 glm53 KV split on both" COLI_VK_CHAIN_LAYERS=2 COLI_VK_CHAIN_LAYERS2=2 COLI_VK_KV_DEVICE_ROWS=16 COLI_VK_KV_BLOCK=4 \GLM53_BITS=32 USAGE_SAVE=0 ./glm53 --model glm53_l6s-i4 --ids $ids --greedy 8LD2_SAN_LOST=1 ld2_san glm53 "asan ld2 glm53 second device lost, the KDA state rebuilt" COLI_VK_CHAIN_LAYERS=3 COLI_VK_CHAIN_LAYERS2=3 \diff --git a/c/tests/vulkan_partial_glm.sh b/c/tests/vulkan_partial_glm.shindex 41509c2b..0c45f8f6 100644--- a/c/tests/vulkan_partial_glm.sh+++ b/c/tests/vulkan_partial_glm.sh@@ -306,12 +306,20 @@ ptl_family_glm() {{ grep -a 'resident dense\|dense matrices' ptl-ram*.log; fail "partial colibri device only: resident dense $r0 / $r2 / $r5 MB with 0 / 2 / 5 layers"; }echo "OK partial colibri device only: resident dense $r0 MB with 0 layers on the device, $r2 MB with 2, $r5 MB with 5"# serve sessions frame for frame with 2 of 5 layers: pins, the prompt cache, the prefill- # read-out, drafts, two KV slots (the ragged batch declines the chain), prompts only+ # read-out, drafts, two KV slots, prompts only; several conversations at once, the+ # shared indexer after the device's layers taking their rows' DSA listsexport CHAIN_SERVE_EXPECT='colibri chain: 2 of 5 layers on the device'CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 COLI_VK_CHAIN_LAYERS=2CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 DSA_TOPK=4 DRAFT=3 COLI_VK_CHAIN_LAYERS=2CHAIN_SERVE_SLOTS=2 CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 KV_SLOTS=2 COLI_VK_CHAIN_LAYERS=2COLI_VK_CHAIN=2 CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 DSA_TOPK=4 COLI_VK_CHAIN_LAYERS=2+ CHAIN_MUX_EXPECT="$CHAIN_SERVE_EXPECT" $PY tests/vulkan_chain_mux.py ./colibri glm_tiny_serve 3 SERVE_BATCH=1 IDOT=0 DSA_TOPK=4 COLI_VK_CHAIN_LAYERS=2+ ptl_glm_shx glm_tiny_serve glm_tiny_shx_serve+ for k in 1 3; do+ CHAIN_MUX_EXPECT="colibri chain: $k of 5 layers on the device" \+ $PY tests/vulkan_chain_mux.py ./colibri glm_tiny_shx_serve 3 SERVE_BATCH=1 IDOT=0 DSA_TOPK=4 COLI_VK_CHAIN_LAYERS=$k+ done+ rm -rf glm_tiny_shx_serve chain-mux.usageCHAIN_SERVE_EXPECT='colibri: [0-9]+ dense matrices on the device only.*the 2 of 5 layers on the device' COLI_VK_DENSE_HOST=0 \CHAIN_SERVE_DIALECT=colibri $PY tests/vulkan_chain_serve.py ./colibri glm_tiny_serve SERVE_BATCH=1 IDOT=0 COLI_VK_CHAIN_LAYERS=2unset CHAIN_SERVE_EXPECTdiff --git a/c/vk_chain.c b/c/vk_chain.cindex 0a3d3444..d0e151ea 100644--- a/c/vk_chain.c+++ b/c/vk_chain.c@@ -1303,6 +1303,35 @@ int vkc_mla_attn(const VkcMla *m, VkcMlaScratch *s, int S, int pos_base, int kv_if (ok && m->o && out) ok = vkc_matmul(m->o, s->ctx, 0, out, out_off, S);return ok;}+/* vkc_mla_attn for rows of different sequences: row s attends its own cache c[s] over+ * positions 0..pos[s] (or sel's list at sel_off + s*sel_row); the absorption, the values+ * and o_proj take every row at once, the core one row at a time. */+int vkc_mla_attn_rows(const VkcMla *m, VkcMlaScratch *s, int S, const int *pos, VkcMlaCache *const *c,+ VkcBuf *sel, size_t sel_off, int sel_row, VkcBuf *out, size_t out_off) {+ int H = m->H, QR = m->Q + m->R, HK = H * m->K, HV = H * m->V;+ if (!KC.mla_ok || S < 1 || S > s->rows) return 0;+ for (int r = 0; r < S; r++) if (!c[r] || pos[r] < 0 || (int64_t)pos[r] + 1 > c[r]->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) {+ 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 {+ 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);+ }+ for (int r = 0; ok && r < S; r++) {+ VkcMlaCore cp = {1, H, m->K, m->R, pos[r], 0, r * HK, HK, m->K, m->Q + r * H * QR, H * QR, QR, 0, m->K, 0, m->R,+ (int)sel_off + (sel ? r * sel_row : 0), sel ? sel_row : 0, r * HK, HK, m->K, m->scale};+ ok = vkc_mla_core(s->qabs, s->q, c[r]->lat, c[r]->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, 0, HV, 0};+ ok = ok && vkc_mla_hgemv(m->kv_b ? m->kv_b : m->v_abs, s->clat, s->ctx, NULL, &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) &&diff --git a/c/vk_chain.h b/c/vk_chain.hindex 95c58069..4d4bcee5 100644--- a/c/vk_chain.h+++ b/c/vk_chain.h@@ -294,6 +294,12 @@ int vkc_mla_qkv(const VkcMla *m, VkcMlaScratch *s, VkcBuf *x, size_t x_off, int* 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);+/* The same for rows of different sequences (a multiplexed decode step): row s attends its+ * own cache c[s] over positions 0..pos[s] (or sel's list at sel_off + s*sel_row; sel's+ * row count -1 is that causal range); the projections take every row at once, the core+ * one row at a time. */+int vkc_mla_attn_rows(const VkcMla *m, VkcMlaScratch *s, int S, const int *pos, VkcMlaCache *const *c,+ VkcBuf *sel, size_t sel_off, int sel_row, 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);diff --git a/c/vk_kvsplit.h b/c/vk_kvsplit.hindex 97fc28ac..d906da30 100644--- a/c/vk_kvsplit.h+++ b/c/vk_kvsplit.h@@ -157,6 +157,16 @@ static long vkc_kv_env(const char *name, long def) {* engine holds now (freed before the new ones). Returns 1 for whole mirrors (ks->on = 0:* the chain as before), 2 for the split (ks->on = 1, tables ready, every block in the* host's RAM until a step places it), 0 when not even the split can run. */+/* The current device's free bytes: the driver's budget less what is in use, else the+ * local heap less the weights and the chain's buffers. */+static size_t vkc_dev_avail(void) {+ double used = 0, bud = 0;+ if (coli_vk_mem_budget_dev(vkc_device_now(), &used, &bud)) return bud > used ? (size_t)((bud - used) * 1e9) : 0;+ size_t dev = coli_vk_device_local_bytes_dev(vkc_device_now()), w = 0, n = 0;+ VkcStats st; vkc_stats(&st);+ coli_vk_mem_info_dev(vkc_device_now(), &w, &n);+ return dev > w + st.dev_bytes ? dev - w - st.dev_bytes : 0;+}/* vkc_kv_plan_need: the same with the whole mirrors' bytes given (need_bytes; 0: nl * cap* * row_bytes), for layers whose caches differ (DeepSeek's compressed rows, one ratio a* layer): the decision compares those bytes with the budget, the tables cover cap@@ -176,16 +186,7 @@ static int vkc_kv_plan_need(VkcKvSplit *ks, const char *engine, int nl, size_t rif (forced >= cap) return 1;rows = forced;} else {- double used = 0, bud = 0;- size_t avail;- if (coli_vk_mem_budget_dev(vkc_device_now(), &used, &bud)) avail = bud > used ? (size_t)((bud - used) * 1e9) : 0;- else {- size_t dev = coli_vk_device_local_bytes_dev(vkc_device_now()), w = 0, n = 0;- VkcStats st; vkc_stats(&st);- coli_vk_mem_info_dev(vkc_device_now(), &w, &n);- avail = dev > w + st.dev_bytes ? dev - w - st.dev_bytes : 0;- }- avail += held;+ size_t avail = vkc_dev_avail() + held;size_t room = avail / 10 * 8; /* a fifth for scratch, frames and the rest */if (need <= room) return 1;rows = (long)(room / ((size_t)nl * row_bytes));diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.mdindex 723fcdc6..94e1a2ff 100644--- a/docs/ENVIRONMENT.md+++ b/docs/ENVIRONMENT.md@@ -271,6 +271,7 @@ With `COLI_VULKAN=1` every MoE engine (qwen36, qwen38, inkling, olmoe, kimi_k3,| `COLI_VK_CHAIN_LAYERS2` | from the second device's free memory | With `COLI_VK_DEV2` and a partial chain: how many of the layers after the primary's the second device's chain places ([vulkan.md](vulkan.md#layers-on-two-devices)). Unset or `auto`: the most that fit that device's free memory less `COLI_VK_TIER_RESERVE_GB` and the chain's fixed buffers; `n`: n layers. The head stays on the host. The `[VK] <engine> dev2 chain: n of m layers on the device ...` line says what was decided. DeepSeek V4.1 starts the second device only at a layer that reads nothing the layers before it make (the primary's fit comes down to one). || `COLI_VK_CHAIN_DEV2` | `1` | `0` keeps the dense chain's layers off the second device (`COLI_VK_DEV2` then holds experts only). || `COLI_VK_CHAIN_FAULT2` | unset | Tests: the n-th frame on the second device's chain fails as a lost device's would (frame 1 is its setup: its layers stay on the CPU). Both chains go off; the CPU runs from there, the recurrent state rebuilt where a device held it. |+| `COLI_VK_CHAIN_MUX` | `16` | colibri: how many conversations' KV mirrors the chain keeps on the device beside its own for `KV_SLOTS`' batched decode ([vulkan.md](vulkan.md#glm-52-and-glm-53-flash-on-the-chain)), up to 16; past that the one read longest ago gives way. `0`: those steps run on the CPU, as before. || `COLI_VK_DEVICE_CAP_MB` | unset | Tests: the device holds at most this many MiB of device-local memory (a fraction is taken). An allocation past it fails as out of device memory, and every budget the engines read (`VK_EXT_memory_budget`'s, the expert tier's, the chunk's, the partial chain's fit) reports the cap and this process's bytes, so Lavapipe behaves like a small card. The second device (`COLI_VK_DEV2`) gets the same cap. A `[VK] COLI_VK_DEVICE_CAP_MB=...` line says it is on. || `COLI_VK_ATTN_BLOCK` | `16` | Rows from which the chain's attention takes the blocked shader (`chain_attnb.comp`: K and V read once per block of rows); `0` never. Below it, and at decode, `chain_attn.comp` as before. || `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. |diff --git a/docs/vulkan.md b/docs/vulkan.mdindex d5fbca7c..4fa7762a 100644--- a/docs/vulkan.md+++ b/docs/vulkan.md@@ -1506,7 +1506,31 @@ rebuilds the KDA state on the CPU from the input rows the chain records since thcopy was last current (embedding rows, or the vision tower's), a prefill's worth of CPUwork.-**Declined** (the CPU path runs, the state synced first): a ragged multi-slot decode+**Several conversations at once (colibri).** `KV_SLOTS`' batched decode (one row from+each active conversation, each at its own position) runs on the chain: the norms, the+projections and the MoE take the batch's rows as one; each row's new KV rows go to its+own conversation's mirror, and its attention core runs over that mirror+(`vkc_mla_attn_rows`) with its own DSA list over its own index keys. A conversation's+mirror is the chain's own when the chain holds it (the last one a prompt or a one-row+step ran for), else one of up to `COLI_VK_CHAIN_MUX` (default 16) beside it: whole,+with its own watermarks, which a turn that goes back in its conversation lowers as on+the host. Past that count the mirror read longest ago gives way, and its conversation's+rows go up again from the host when it comes back. A mirror holds `positions x+(kv_lora + qk_rope)` floats a layer (and `positions x index_hd` on a full DSA layer),+positions in powers of two up to the context, and is placed only within four fifths of+the device's free memory. A step whose conversations the mirrors cannot all hold, a+step with the KV split on, and `COLI_VK_CHAIN_MUX=0` run on the CPU as before. With a+second device each chain runs its layers for the whole batch, the DSA lists crossing as+in one conversation's step; a partial chain hands the rows (and their lists) to the CPU+after its layers. The `[VK] colibri chain: n multiplexed steps (r rows), ...` line at+exit says what ran. `tests/vulkan_chain_mux.py` compares every frame with the CPU's:+waves of requests on 3 and 4 slots sent at once (the batches grow and shrink; the+second wave extends, rewinds and replaces each conversation), DSA top-4, one mirror+beside the chain's, the device lost in a multiplexed step, the partial chain and two+devices with a shared indexer at their edges. Not yet measured with a real checkpoint.+glm53 still runs such steps on the CPU.++**Declined** (the CPU path runs, the state synced first): glm53's multi-slot decodebatch (a single-slot serve's one-row batch takes the chain), a layer range (a segment),a quantized KV cache (KV8, KV_TQ), PILOT, LOOKA, the exact verify of`COLI_EXACT_VERIFY`, the CUDA backend, matrices with no device form (int2, E8/IQ3, fp8@@ -3009,7 +3033,7 @@ hit-rate line is the tier-effectiveness number.GEMM shaders would save both copies; it is not written.- Without the dense chain, DSA top-k selection, ragged multi-slot serving, andquantized-KV caches fall back to the CPU attention path; with it, the DSA selection- runs on the device.+ and colibri's multi-slot serving run on the device.- Not yet done: a fully resident-layer pipeline for the engines other than qwen36,qwen38, colibri and glm53 ([the dense chain](#the-dense-chain-vk_chainc) is theirs), Polaris/gfx803 validation on realhardware (the shaders use dynamic subgroup sizes and are wave64-safe by