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

fix(qwen36): heap per-thread attention score rows — 8k context smashed the stack

kreuzzelgc30c5457bbe8
diff --git a/c/Makefile b/c/Makefile
index f131359f..21f9e8e7 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -882,6 +882,11 @@ olmoe$(EXE): olmoe.c st.h json.h compat.h sample.h tok.h tok_unicode.h tok_unico
qwen36$(EXE): qwen36.c st.h json.h compat.h
$(CC) $(CFLAGS) qwen36.c -o qwen36$(EXE) $(LDFLAGS)
+# Context-size gates: KV layout, growth across requests, and the attention
+# capacity. Includes qwen36.c directly, so no model file is needed.
+tests/test_qwen36_ctx$(EXE): tests/test_qwen36_ctx.c qwen36.c st.h json.h compat.h
+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+
inkling$(EXE): inkling.c st.h json.h compat.h $(INK_CUDA_OBJ) $(METAL_OBJ)
$(CC) $(CFLAGS) inkling.c $(INK_CUDA_OBJ) $(METAL_OBJ) -o inkling$(EXE) $(LDFLAGS)
diff --git a/c/qwen36.c b/c/qwen36.c
index 9fd721e5..13856894 100644
--- a/c/qwen36.c
+++ b/c/qwen36.c
@@ -26,9 +26,33 @@
#include <stdint.h>
#include <time.h>
#include <pthread.h>
+#ifdef _OPENMP
+#include <omp.h>
+#endif
#if defined(__AVX2__)
#include <immintrin.h>
#endif
+
+/* Hard context ceiling: the model's max_position_embeddings. Every buffer that
+ * scales with position (KV cache, attention score row) is allocated from max_t,
+ * so this is a policy limit, not a buffer limit -- but it is ONE limit, named
+ * once. It used to be the literal 8192 in two unrelated places: the size of a
+ * stack array in attention() and the default of Q36_MAXT in serve_one(). They
+ * agreed by luck, and raising Q36_MAXT moved the guard without moving the
+ * buffer, so a longer prompt overran the stack instead of being refused.
+ * Context costs 40 KB/token in KV (10 attention layers, f32) -- 128k is 5.0 GiB
+ * -- which is why Q36_MAXT still defaults far below this. */
+#define QWEN36_ATTN_MAX_CTX 262144
+#define QWEN36_DEFAULT_MAX_CTX 8192
+
+/* Effective ceiling: Q36_MAXT if set and sane, the conservative default
+ * otherwise; never above the hard limit. */
+static int qwen36_max_ctx(void) {
+ const char *e = getenv("Q36_MAXT");
+ int v = (e && *e) ? atoi(e) : QWEN36_DEFAULT_MAX_CTX;
+ if (v < 1) v = QWEN36_DEFAULT_MAX_CTX;
+ return v > QWEN36_ATTN_MAX_CTX ? QWEN36_ATTN_MAX_CTX : v;
+}
#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)
#include <sys/resource.h>
#include <unistd.h>
@@ -574,6 +598,8 @@ typedef struct {
float **DN_conv; /* [n_layers] conv ring [conv_dim, convk-1] for DeltaNet layers (NULL for attn) */
uint64_t clock, hits, miss;
float **K, **V; int kv_len, max_t, kv_cap;
+ float *attn_sc; /* [attn_sc_thr * kv_cap] score rows, one per thread */
+ int attn_sc_thr;
double dense_load_s;
uint32_t *freq;
int freq_token_count, hot_pinned, hot_n, warmup_tokens, token_count;
@@ -1353,7 +1379,11 @@ static void attention(Model *m, Layer *l, int layer, float *x, int S, int pos_ba
int kvh = hh / q_per_kv;
int qpos = pos_base + s;
const float *qv = query + ((int64_t)s*H + hh)*hd;
- float sc[8192];
+ int tid = 0;
+#ifdef _OPENMP
+ tid = omp_get_thread_num();
+#endif
+ float *sc = m->attn_sc + (int64_t)tid * m->kv_cap;
for (int t = 0; t <= qpos; t++) {
const float *kv = m->K[layer] + ((int64_t)kvh*m->max_t + t)*kvd;
float acc = 0; for (int dd = 0; dd < kvd; dd++) acc += qv[dd]*kv[dd];
@@ -1834,11 +1864,30 @@ static void ensure_kv(Model *m){
m->V[i] = falloc((int64_t)c->kv_heads * m->max_t * c->k_head_dim);
} else { m->K[i] = NULL; m->V[i] = NULL; }
}
+ /* Attention scores: one row per thread, indexed by absolute position, so
+ * each row must hold max_t entries. Sized here rather than in attention()
+ * because it grows with the context exactly like the KV cache does, and
+ * because a per-call allocation would run 10x per token. */
+ free(m->attn_sc);
+ m->attn_sc_thr = 1;
+#ifdef _OPENMP
+ m->attn_sc_thr = omp_get_max_threads();
+ if (m->attn_sc_thr < 1) m->attn_sc_thr = 1;
+#endif
+ m->attn_sc = falloc((int64_t)m->attn_sc_thr * m->max_t);
m->kv_cap = m->max_t;
}
static void generate(Model *m, const int *prompt, int np, int n_new, int *out) {
Cfg *c = &m->c;
+ /* Same ceiling serve_one() enforces. Past max_position_embeddings the RoPE
+ * positions leave the range the model was trained on, so this is a
+ * correctness limit, not just a memory one. */
+ if (np + n_new > QWEN36_ATTN_MAX_CTX) {
+ fprintf(stderr, "[ctx] prompt %d + %d new exceeds the %d-token ceiling\n",
+ np, n_new, QWEN36_ATTN_MAX_CTX);
+ exit(1);
+ }
m->max_t = np + n_new;
reset_recurrent(m);
ensure_kv(m);
@@ -1868,6 +1917,11 @@ static void generate(Model *m, const int *prompt, int np, int n_new, int *out) {
static int tf_nll(Model *m, const int *full, int nfull, int np, double *nll_out) {
Cfg *c = &m->c;
+ if (nfull > QWEN36_ATTN_MAX_CTX) {
+ fprintf(stderr, "[ctx] %d tokens exceed the %d-token ceiling\n",
+ nfull, QWEN36_ATTN_MAX_CTX);
+ exit(1);
+ }
m->max_t = nfull;
reset_recurrent(m);
ensure_kv(m);
@@ -1984,7 +2038,7 @@ static int serve_eos_ids(int *ids, int cap){
static void serve_one(Model *m, ServeReq *q){
int *ids=NULL, np=0;
encode_text(q->payload, &ids, &np); /* payload is raw prompt text; qwen36 adds no BOS */
- int max_ctx = getenv("Q36_MAXT")?atoi(getenv("Q36_MAXT")):8192;
+ int max_ctx = qwen36_max_ctx();
if(np<1 || np+q->max_tok>max_ctx){
printf("ERROR %s CONTEXT_EXCEEDED prompt_tokens=%d requested=%d capacity=%d\n",q->id,np,q->max_tok,max_ctx);
fflush(stdout); free(ids); return;
diff --git a/c/tests/test_qwen36_ctx.c b/c/tests/test_qwen36_ctx.c
new file mode 100644
index 00000000..f6e03670
--- /dev/null
+++ b/c/tests/test_qwen36_ctx.c
@@ -0,0 +1,154 @@
+/* Context-size gates for the qwen36 hybrid engine.
+ *
+ * Regression test for the fixed-size score buffer: attention() used to keep one
+ * score per attended key in a stack `float sc[8192]`, filled with
+ * `for (t = 0; t <= qpos; t++)`. serve_one() carried the same literal as the
+ * Q36_MAXT default, and generate()/tf_nll() checked nothing at all. The two
+ * literals agreed only by luck: raising Q36_MAXT moved the guard without moving
+ * the buffer, so a longer prompt smashed the stack instead of being refused.
+ * Same class of bug as #122/#110 in the MLA path, and fixed the same way -- a
+ * per-thread heap buffer sized from max_t, plus one named capacity.
+ *
+ * The 40-layer hybrid also keeps two kinds of state, and only one of them
+ * grows: the 10 Gated Attention layers hold a KV cache, while the 30 Gated
+ * DeltaNet layers hold a recurrent state of fixed size and get no KV cache at
+ * all (ensure_kv leaves K[i]/V[i] NULL). Mixing those up silently allocates 4x
+ * the memory or indexes a NULL layer, so the layout is worth pinning too.
+ *
+ * No model file: ensure_kv only reads n_layers/is_attn/kv_heads/k_head_dim.
+ */
+#define main qwen36_main_unused
+#include "../qwen36.c"
+#undef main
+
+static int fails = 0;
+
+/* Same pattern as test_omp_tune.c / test_stops.c, and for the same reason:
+ * compat.h maps setenv() to SetEnvironmentVariableA, which updates the Win32
+ * environment block -- but getenv() reads the CRT's own copy and never sees
+ * it, so the value under test would silently not arrive. _putenv_s updates
+ * the copy getenv() reads. */
+static void env_set(const char *name, const char *value) {
+#ifdef _WIN32
+ _putenv_s(name, value);
+#else
+ setenv(name, value, 1);
+#endif
+}
+
+static void env_unset(const char *name) {
+#ifdef _WIN32
+ _putenv_s(name, "");
+#else
+ unsetenv(name);
+#endif
+}
+
+static void ck(int cond, const char *what) {
+ if (cond) { printf(" ok %s\n", what); return; }
+ printf(" FAIL %s\n", what);
+ fails++;
+}
+
+/* the shipping Qwen3.6-35B-A3B geometry, from qwen36_meta.json */
+#define REAL_LAYERS 40
+#define REAL_KVHEADS 2
+#define REAL_KHEADDIM 256
+#define REAL_ATTN_LAYERS 10 /* i % 4 == 3 */
+
+static void shape_model(Model *m, int n_layers, int kv_heads, int k_head_dim) {
+ memset(m, 0, sizeof(*m));
+ m->c.n_layers = n_layers;
+ m->c.kv_heads = kv_heads;
+ m->c.k_head_dim = k_head_dim;
+ m->c.is_attn = calloc(n_layers, 1);
+ for (int i = 0; i < n_layers; i++) m->c.is_attn[i] = (i % 4 == 3);
+}
+
+/* --- the layout every run depends on ------------------------------------- */
+static void case_layout(void) {
+ Model m; shape_model(&m, REAL_LAYERS, REAL_KVHEADS, REAL_KHEADDIM);
+ printf("KV layout at a short context\n");
+
+ m.max_t = 4096;
+ ensure_kv(&m);
+ ck(m.kv_cap == 4096, "kv_cap follows max_t");
+
+ int with_cache = 0, without = 0;
+ for (int i = 0; i < m.c.n_layers; i++) {
+ if (m.c.is_attn[i]) { if (m.K[i] && m.V[i]) with_cache++; }
+ else if (!m.K[i] && !m.V[i]) without++;
+ }
+ ck(with_cache == REAL_ATTN_LAYERS, "every attention layer has K and V");
+ ck(without == REAL_LAYERS - REAL_ATTN_LAYERS,
+ "no DeltaNet layer has a KV cache (recurrent state instead of history)");
+
+ /* 2 kv heads * 256 dims * 4 B * 2 (K and V) * 10 layers */
+ ck(2 * (int64_t)REAL_KVHEADS * REAL_KHEADDIM * (int64_t)sizeof(float)
+ * REAL_ATTN_LAYERS == 40960, "context costs 40 KB per token");
+
+ /* under ASan this is the actual out-of-bounds gate, not a formality */
+ for (int i = 0; i < m.c.n_layers; i++) {
+ if (!m.c.is_attn[i]) continue;
+ int64_t last = (int64_t)m.c.kv_heads * m.max_t * m.c.k_head_dim - 1;
+ m.K[i][last] = 1.f; m.V[i][last] = 2.f;
+ }
+ ck(1, "last element of every cache is writable");
+}
+
+/* --- serve reuses one cache across requests of different lengths ---------- */
+static void case_growth(void) {
+ Model m; shape_model(&m, REAL_LAYERS, REAL_KVHEADS, REAL_KHEADDIM);
+ printf("growth across requests\n");
+
+ m.max_t = 512; ensure_kv(&m);
+ float *first = m.K[3];
+ m.max_t = 256; ensure_kv(&m);
+ ck(m.K[3] == first && m.kv_cap == 512,
+ "a shorter request leaves the cache alone (never shrinks)");
+
+ m.max_t = 2048; ensure_kv(&m);
+ ck(m.kv_cap == 2048, "a longer request grows the cache");
+ int64_t last = (int64_t)m.c.kv_heads * m.max_t * m.c.k_head_dim - 1;
+ m.K[3][last] = 1.f; /* the re-allocation must be sized to the NEW max_t */
+ ck(1, "the grown cache is writable to its last element");
+}
+
+/* --- the ceiling itself --------------------------------------------------- */
+static void case_ceiling(void) {
+ printf("attention capacity\n");
+ /* One capacity, named once, enforced on every path that sets max_t --
+ * instead of a stack array in attention() and a second literal in
+ * serve_one() that happened to agree. */
+ ck(QWEN36_ATTN_MAX_CTX >= 131072,
+ "declared capacity covers the model's context length");
+
+ /* The score rows must be sized from max_t and carry one row per thread,
+ * so a context past the old 8192 has somewhere to go. */
+ Model m; shape_model(&m, 8, REAL_KVHEADS, 16);
+ m.max_t = 16384; /* twice the old fixed buffer */
+ ensure_kv(&m);
+ ck(m.attn_sc != NULL && m.attn_sc_thr >= 1, "per-thread score rows allocated");
+ for (int t = 0; t < m.attn_sc_thr; t++)
+ m.attn_sc[(int64_t)t * m.kv_cap + m.kv_cap - 1] = 1.f;
+ ck(1, "every thread's score row holds max_t entries");
+
+ /* Q36_MAXT may lower the ceiling but never raise it past the capacity. */
+ env_set("Q36_MAXT", "999999999");
+ ck(qwen36_max_ctx() == QWEN36_ATTN_MAX_CTX,
+ "Q36_MAXT cannot be raised past the capacity");
+ env_set("Q36_MAXT", "4096");
+ ck(qwen36_max_ctx() == 4096, "Q36_MAXT can lower the ceiling");
+ env_unset("Q36_MAXT");
+ ck(qwen36_max_ctx() == QWEN36_DEFAULT_MAX_CTX,
+ "unset Q36_MAXT falls back to the conservative default");
+}
+
+int main(void) {
+ case_layout();
+ case_growth();
+ case_ceiling();
+ if (fails) { printf("FAILED %d\n", fails); return 1; }
+ printf("OK test_qwen36_ctx\n");
+ return 0;
+}