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

feat(glm53): KDA and k-pool sparse attention, validated against transformers

JustVugg998701e0bba6
diff --git a/c/delta_attention.h b/c/delta_attention.h
new file mode 100644
index 00000000..8a942893
--- /dev/null
+++ b/c/delta_attention.h
@@ -0,0 +1,128 @@
+#ifndef COLIBRI_DELTA_ATTENTION_H
+#define COLIBRI_DELTA_ATTENTION_H
+
+/*
+ * Kimi Delta Attention (KDA): the gated delta rule that the linear-attention
+ * layers of Kimi K3, Qwen3.6 and GLM-5.3-Flash all run, differing only in the
+ * dimensions and in how the caller produces the gate.
+ *
+ * Per token and per head, with S the [k_dim x v_dim] recurrent state:
+ *
+ * q,k,v = SiLU(ShortConv(W{q,k,v} x)) short causal convolution first
+ * q,k = q/sqrt(|q|^2 + eps) L2 norm with eps INSIDE the sqrt
+ * q *= k_dim^-0.5
+ * S = Diag(alpha) S alpha = exp(gate), per k channel
+ * delta = (v - S^T k) * beta what the memory got wrong
+ * S = S + k delta^T write the correction back
+ * out = S^T q
+ *
+ * The two details worth stating, because both are silently wrong-looking-right
+ * if you get them backwards: the eps sits inside the square root (FLA's
+ * convention, which the reference notes is deliberately unlike F.normalize),
+ * and `delta` is computed against the state AFTER the decay but BEFORE the
+ * write, so the decay cannot be folded into the second pass.
+ *
+ * `gate` and `beta` arrive already resolved. Every model builds them
+ * differently - GLM-5.3 uses gate_lower_bound * sigmoid(exp(A_log) * (W_fb W_fa
+ * x + dt_bias)) - and that belongs to the engine, not here.
+ *
+ * No allocation: the caller owns the scratch. A per-token malloc costs more
+ * than the arithmetic at these sizes, which is the lesson #1179 paid for on the
+ * DeepSeek V4 indexer.
+ */
+
+#include <math.h>
+#include <string.h>
+
+/* Scratch needed by coli_kda_step, in floats. */
+static inline int coli_kda_scratch_floats(int heads, int k_dim, int v_dim) {
+ int mixed = 3 * heads * (k_dim > v_dim ? k_dim : v_dim);
+ return mixed + v_dim;
+}
+
+static inline float coli_kda_silu(float value) {
+ return value / (1.0f + expf(-value));
+}
+
+/* One token through one KDA layer.
+ *
+ * out [heads * v_dim] written
+ * state [heads * k_dim * v_dim] read and updated in place
+ * window [3 * heads * k_dim * kernel] convolution history, updated in place
+ * qkv [3 * heads * k_dim] this token's q, k and v projections
+ * conv_w [3 * heads * k_dim * kernel] depthwise taps, oldest first
+ * gate [heads * k_dim] log-decay, already gated by the engine
+ * beta [heads] already through its sigmoid
+ * scratch [coli_kda_scratch_floats()]
+ *
+ * k_dim and v_dim are equal in every model shipping today; they are separate
+ * arguments because the recurrence does not require them to be. */
+static inline int coli_kda_step(float *out, float *state, float *window,
+ const float *qkv, const float *conv_w,
+ const float *gate, const float *beta,
+ int heads, int k_dim, int v_dim, int kernel,
+ float norm_eps, float *scratch) {
+ if (!out || !state || !window || !qkv || !conv_w || !gate || !beta ||
+ !scratch || heads < 1 || k_dim < 1 || v_dim < 1 || kernel < 1)
+ return -1;
+
+ const int width = heads * k_dim;
+ float *mixed = scratch; /* 3 * width */
+ float *memory = scratch + 3 * width; /* v_dim */
+
+ /* Short causal convolution over each channel's own history, then SiLU. */
+ for (int channel = 0; channel < 3 * width; channel++) {
+ float *history = window + (size_t)channel * kernel;
+ memmove(history, history + 1, (size_t)(kernel - 1) * sizeof(*history));
+ history[kernel - 1] = qkv[channel];
+ const float *taps = conv_w + (size_t)channel * kernel;
+ float sum = 0.0f;
+ for (int tap = 0; tap < kernel; tap++) sum += taps[tap] * history[tap];
+ mixed[channel] = coli_kda_silu(sum);
+ }
+
+ const float query_scale = 1.0f / sqrtf((float)k_dim);
+ for (int head = 0; head < heads; head++) {
+ float *matrix = state + (size_t)head * k_dim * v_dim;
+ const float *query = mixed + (size_t)head * k_dim;
+ const float *key = mixed + width + (size_t)head * k_dim;
+ const float *value = mixed + 2 * width + (size_t)head * v_dim;
+ const float *decay = gate + (size_t)head * k_dim;
+ float *result = out + (size_t)head * v_dim;
+
+ float query_square = norm_eps, key_square = norm_eps;
+ for (int i = 0; i < k_dim; i++) {
+ query_square += query[i] * query[i];
+ key_square += key[i] * key[i];
+ }
+ const float query_norm = query_scale / sqrtf(query_square);
+ const float key_norm = 1.0f / sqrtf(key_square);
+
+ /* Pass one: decay the state and read what it currently predicts for
+ * this key. Both must happen before anything is written back. */
+ memset(memory, 0, (size_t)v_dim * sizeof(*memory));
+ for (int k = 0; k < k_dim; k++) {
+ float *row = matrix + (size_t)k * v_dim;
+ const float alpha = expf(decay[k]);
+ const float scaled_key = key[k] * key_norm;
+ for (int v = 0; v < v_dim; v++) {
+ row[v] *= alpha;
+ memory[v] += scaled_key * row[v];
+ }
+ }
+ /* Pass two: write the correction and read the answer out. */
+ memset(result, 0, (size_t)v_dim * sizeof(*result));
+ for (int k = 0; k < k_dim; k++) {
+ float *row = matrix + (size_t)k * v_dim;
+ const float scaled_key = key[k] * key_norm;
+ const float scaled_query = query[k] * query_norm;
+ for (int v = 0; v < v_dim; v++) {
+ row[v] += scaled_key * (value[v] - memory[v]) * beta[head];
+ result[v] += scaled_query * row[v];
+ }
+ }
+ }
+ return 0;
+}
+
+#endif /* COLIBRI_DELTA_ATTENTION_H */
diff --git a/c/sparse_index.h b/c/sparse_index.h
new file mode 100644
index 00000000..66da4e98
--- /dev/null
+++ b/c/sparse_index.h
@@ -0,0 +1,210 @@
+#ifndef COLIBRI_SPARSE_INDEX_H
+#define COLIBRI_SPARSE_INDEX_H
+
+/*
+ * DeepSeek-style sparse attention with k-pooling, as GLM-5.3-Flash runs it.
+ *
+ * The plain lightning indexer scores every key and keeps the top ones. With
+ * k-pooling the keys are first grouped into pools of `pool` tokens; the pools
+ * are scored and selected, and the winners expand back into their token
+ * indices. Selecting 512 pools of 4 instead of 2048 tokens is the same budget
+ * with a quarter of the scoring, and the pooled key is a per-channel softmax
+ * mixture of the pool's keys rather than an average, so a pool is not forced to
+ * describe itself by its mean.
+ *
+ * Three rules decide which pools may be chosen, and all three matter:
+ *
+ * - a pool is selectable only if it is COMPLETE (every member present) and
+ * its last token is causally visible to the query;
+ * - the incomplete tail - the tokens after the last complete pool - is
+ * appended unconditionally when the model asks for it, which is why the
+ * output is `topk + pool - 1` wide rather than `topk`;
+ * - ties go to the lower pool index, so selection is deterministic.
+ *
+ * The scores carry a ReLU. It is written here as `if (dot > 0)` before scaling,
+ * which is the same function as the reference's relu(dot * scale): ReLU
+ * commutes with a positive scale.
+ *
+ * Unselected slots are -1, and the attention below skips them. Callers must not
+ * treat the width as a count.
+ */
+
+#include <float.h>
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* Width of one query's index row: topk expanded tokens plus the tail. */
+static inline int coli_sparse_index_width(int topk, int pool, int with_tail) {
+ return with_tail ? topk + pool - 1 : topk;
+}
+
+/* Select the key blocks each query may attend.
+ *
+ * out [sequence * width] token indices, -1 where unused
+ * queries [sequence * heads * dim]
+ * keys [sequence * dim] one indexer key per token (shared by heads)
+ * gates [sequence * dim] pooling logits, per channel
+ * head_w [sequence * heads] already scaled by heads^-0.5 by the caller
+ * ape [pool * dim] per-position bias inside a pool
+ * valid [sequence] 0 marks padding
+ *
+ * Returns 0, or -1 on bad arguments or allocation failure. */
+static inline int coli_sparse_index_select(int *out, const float *queries,
+ const float *keys, const float *gates,
+ const float *head_w, const float *ape,
+ const unsigned char *valid,
+ int sequence, int heads, int dim,
+ int pool, int topk, int with_tail) {
+ if (!out || !queries || !keys || !gates || !head_w || !ape || !valid ||
+ sequence < 1 || heads < 1 || dim < 1 || pool < 1 || topk < pool || topk % pool)
+ return -1;
+
+ const int width = coli_sparse_index_width(topk, pool, with_tail);
+ const int pools = (sequence + pool - 1) / pool;
+ const int wanted = topk / pool;
+
+ float *pooled = calloc((size_t)pools * dim, sizeof(*pooled));
+ float *scores = malloc((size_t)pools * sizeof(*scores));
+ unsigned char *complete = calloc((size_t)pools, 1);
+ unsigned char *taken = calloc((size_t)pools, 1);
+ if (!pooled || !scores || !complete || !taken) {
+ free(taken); free(complete); free(scores); free(pooled);
+ return -1;
+ }
+
+ int first = 0;
+ while (first < sequence && !valid[first]) first++;
+
+ /* Pool the keys: per channel, a softmax over the pool's members using the
+ * gate logits plus the positional bias. */
+ for (int p = 0; p < pools; p++) {
+ const int start = first + p * pool;
+ complete[p] = start + pool <= sequence;
+ for (int j = 0; complete[p] && j < pool; j++)
+ if (!valid[start + j]) complete[p] = 0;
+ if (!complete[p]) continue;
+ for (int d = 0; d < dim; d++) {
+ float maximum = -FLT_MAX;
+ for (int j = 0; j < pool; j++) {
+ const float logit = gates[(size_t)(start + j) * dim + d] +
+ ape[(size_t)j * dim + d];
+ if (logit > maximum) maximum = logit;
+ }
+ float total = 0.0f;
+ for (int j = 0; j < pool; j++)
+ total += expf(gates[(size_t)(start + j) * dim + d] +
+ ape[(size_t)j * dim + d] - maximum);
+ float mixed = 0.0f;
+ for (int j = 0; j < pool; j++) {
+ const float weight = expf(gates[(size_t)(start + j) * dim + d] +
+ ape[(size_t)j * dim + d] - maximum) / total;
+ mixed += weight * keys[(size_t)(start + j) * dim + d];
+ }
+ pooled[(size_t)p * dim + d] = mixed;
+ }
+ }
+
+ const float scale = 1.0f / sqrtf((float)dim);
+ for (int q = 0; q < sequence; q++) {
+ int *row = out + (size_t)q * width;
+ for (int i = 0; i < width; i++) row[i] = -1;
+ if (!valid[q]) continue;
+
+ for (int p = 0; p < pools; p++) {
+ const int last = first + (p + 1) * pool - 1;
+ if (!complete[p] || last > q) { scores[p] = -FLT_MAX; continue; }
+ float score = 0.0f;
+ for (int h = 0; h < heads; h++) {
+ const float *query = queries + ((size_t)q * heads + h) * dim;
+ float dot = 0.0f;
+ for (int d = 0; d < dim; d++) dot += query[d] * pooled[(size_t)p * dim + d];
+ if (dot > 0.0f) /* ReLU */
+ score += head_w[(size_t)q * heads + h] * dot * scale;
+ }
+ scores[p] = score;
+ }
+
+ for (int rank = 0; rank < wanted; rank++) {
+ int best = -1;
+ for (int p = 0; p < pools; p++)
+ if (!taken[p] && scores[p] > -FLT_MAX &&
+ (best < 0 || scores[p] > scores[best])) best = p;
+ if (best < 0) break;
+ taken[best] = 1;
+ for (int j = 0; j < pool; j++) row[rank * pool + j] = first + best * pool + j;
+ }
+ memset(taken, 0, (size_t)pools);
+
+ if (with_tail) {
+ int visible = 0;
+ for (int i = first; i <= q; i++) if (valid[i]) visible++;
+ const int tail = visible % pool;
+ const int tail_start = first + visible - tail;
+ for (int j = 0; j < tail && j < pool - 1; j++)
+ if (tail_start + j <= q && valid[tail_start + j])
+ row[topk + j] = tail_start + j;
+ }
+ }
+
+ free(taken);
+ free(complete);
+ free(scores);
+ free(pooled);
+ return 0;
+}
+
+/* Softmax attention restricted to the selected indices.
+ *
+ * out [sequence * heads * value_dim]
+ * indices [sequence * width], -1 entries skipped
+ *
+ * Queries, keys and values are laid out [position][head][dim]. */
+static inline int coli_sparse_attention(float *out, const float *queries,
+ const float *keys, const float *values,
+ const int *indices, int sequence, int width,
+ int heads, int key_dim, int value_dim) {
+ if (!out || !queries || !keys || !values || !indices || sequence < 1 ||
+ width < 1 || heads < 1 || key_dim < 1 || value_dim < 1) return -1;
+ float *scores = malloc((size_t)width * sizeof(*scores));
+ if (!scores) return -1;
+ const float scale = 1.0f / sqrtf((float)key_dim);
+ for (int q = 0; q < sequence; q++) {
+ const int *selected = indices + (size_t)q * width;
+ for (int h = 0; h < heads; h++) {
+ const float *query = queries + ((size_t)q * heads + h) * key_dim;
+ float maximum = -FLT_MAX;
+ int used = 0;
+ for (int slot = 0; slot < width; slot++) {
+ const int key_position = selected[slot];
+ if (key_position < 0 || key_position >= sequence) continue;
+ const float *key = keys + ((size_t)key_position * heads + h) * key_dim;
+ float dot = 0.0f;
+ for (int d = 0; d < key_dim; d++) dot += query[d] * key[d];
+ scores[used] = dot * scale;
+ if (scores[used] > maximum) maximum = scores[used];
+ used++;
+ }
+ float *result = out + ((size_t)q * heads + h) * value_dim;
+ memset(result, 0, (size_t)value_dim * sizeof(*result));
+ if (!used) continue;
+ float total = 0.0f;
+ for (int i = 0; i < used; i++) {
+ scores[i] = expf(scores[i] - maximum);
+ total += scores[i];
+ }
+ int index = 0;
+ for (int slot = 0; slot < width; slot++) {
+ const int key_position = selected[slot];
+ if (key_position < 0 || key_position >= sequence) continue;
+ const float weight = scores[index++] / total;
+ const float *value = values + ((size_t)key_position * heads + h) * value_dim;
+ for (int d = 0; d < value_dim; d++) result[d] += weight * value[d];
+ }
+ }
+ }
+ free(scores);
+ return 0;
+}
+
+#endif /* COLIBRI_SPARSE_INDEX_H */
diff --git a/c/tests/test_delta_attention.c b/c/tests/test_delta_attention.c
new file mode 100644
index 00000000..935982db
--- /dev/null
+++ b/c/tests/test_delta_attention.c
@@ -0,0 +1,33 @@
+/* Il nostro KDA contro i vettori generati da transformers 5.16.1. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include "../delta_attention.h"
+#include "glm53_kda_case.h" /* generato da tools/make_glm53_tiny.py */
+
+int main(void) {
+ const int H = GLM53_KDA_HEADS, D = GLM53_KDA_DIM, K = GLM53_KDA_KERNEL, S = GLM53_KDA_STEPS;
+ const int width = H * D;
+ float *state = calloc((size_t)H * D * D, sizeof(float));
+ float *window = calloc((size_t)3 * width * K, sizeof(float));
+ float *scratch = malloc((size_t)coli_kda_scratch_floats(H, D, D) * sizeof(float));
+ float *out = malloc((size_t)S * width * sizeof(float));
+ for (int s = 0; s < S; s++)
+ if (coli_kda_step(out + (size_t)s * width, state, window,
+ glm53_kda_qkv + (size_t)s * 3 * width, glm53_kda_conv,
+ glm53_kda_decay + (size_t)s * width,
+ glm53_kda_beta + (size_t)s * H,
+ H, D, D, K, 1e-6f, scratch)) {
+ printf("coli_kda_step ha fallito\n"); return 1;
+ }
+ float worst = 0.f; int at = 0;
+ for (int i = 0; i < S * width; i++) {
+ float d = fabsf(out[i] - glm53_kda_output[i]);
+ if (d > worst) { worst = d; at = i; }
+ }
+ printf("KDA: %d passi x %d teste x %d, max|delta| = %.3e (indice %d: %.9g vs %.9g)\n",
+ S, H, D, worst, at, out[at], glm53_kda_output[at]);
+ if (worst > 2e-5f) { printf("FALLITO\n"); return 1; }
+ printf("PASS KDA: combacia con l'oracolo transformers\n");
+ return 0;
+}
diff --git a/c/tests/test_sparse_index.c b/c/tests/test_sparse_index.c
new file mode 100644
index 00000000..1ed74341
--- /dev/null
+++ b/c/tests/test_sparse_index.c
@@ -0,0 +1,44 @@
+/* Indexer k-pool e attenzione sparsa contro i vettori transformers. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include "../sparse_index.h"
+#include "glm53_indexer_case.h"
+#include "glm53_sparse_attention_case.h"
+
+int main(void) {
+ int ok = 1;
+ /* --- selezione dei blocchi --- */
+ const int SQ=GLM53_INDEX_SEQUENCE, H=GLM53_INDEX_HEADS, D=GLM53_INDEX_DIM;
+ const int P=GLM53_INDEX_POOL, TK=GLM53_INDEX_TOPK, W=GLM53_INDEX_WIDTH;
+ int *sel = malloc((size_t)SQ*W*sizeof(int));
+ if (coli_sparse_index_select(sel, glm53_index_queries, glm53_index_keys,
+ glm53_index_gates, glm53_index_weights, glm53_index_ape,
+ glm53_index_valid, SQ, H, D, P, TK, 1)) {
+ printf("select ha fallito\n"); return 1; }
+ int wrong = -1;
+ for (int i = 0; i < SQ*W; i++)
+ if (sel[i] != glm53_index_expected[i]) { wrong = i; break; }
+ if (wrong < 0) printf("indexer k-pool: %d query x %d slot, indici IDENTICI\n", SQ, W);
+ else { printf("indexer: differenza allo slot %d (%d vs %d atteso)\n",
+ wrong, sel[wrong], glm53_index_expected[wrong]); ok = 0;
+ for (int q=0;q<SQ;q++){ printf(" q%d nostro:",q);
+ for(int j=0;j<W;j++) printf(" %3d",sel[q*W+j]);
+ printf(" atteso:"); for(int j=0;j<W;j++) printf(" %3d",glm53_index_expected[q*W+j]);
+ printf("\n"); } }
+
+ /* --- attenzione sui blocchi selezionati --- */
+ const int S2=GLM53_SA_SEQUENCE, H2=GLM53_SA_HEADS, KD=GLM53_SA_KEY_DIM, VD=GLM53_SA_VALUE_DIM;
+ float *out = malloc((size_t)S2*H2*VD*sizeof(float));
+ if (coli_sparse_attention(out, glm53_sa_queries, glm53_sa_keys, glm53_sa_values,
+ glm53_sa_indices, S2, GLM53_SA_WIDTH, H2, KD, VD)) {
+ printf("attention ha fallito\n"); return 1; }
+ float worst=0.f; int at=0;
+ for (int i=0;i<S2*H2*VD;i++){ float d=fabsf(out[i]-glm53_sa_expected[i]);
+ if(d>worst){worst=d;at=i;} }
+ printf("attenzione sparsa: max|delta| = %.3e (indice %d: %.9g vs %.9g)\n",
+ worst, at, out[at], glm53_sa_expected[at]);
+ if (worst > 2e-5f) ok = 0;
+ printf("\n%s\n", ok ? "PASS: entrambi combaciano con l'oracolo" : "FALLITO");
+ return ok ? 0 : 1;
+}