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(inkling): reuse the attention state a previous turn already built

JustVugg639e3c32c0c4
diff --git a/c/Makefile b/c/Makefile
index 06f4e8df..e5639dc6 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -743,3 +743,6 @@ clean:
bench: iobench$(EXE)
@if [ -n "$(ARGS)" ]; then ./iobench$(EXE) $(ARGS); else echo "built iobench$(EXE) β€” run: ./iobench$(EXE) <file> <MB> <iters> <threads> <direct 0|1>"; fi
.PHONY: all colibri glm iq3 rans fuzz-rans cuda-test hip-test gpu-compile cuda-bench cuda-dll portable test-c test-python test check clean install uninstall bench
+
+tests/test_kv_prefix$(EXE): tests/test_kv_prefix.c kv_prefix.h
+ $(CC) $(CFLAGS) tests/test_kv_prefix.c -o tests/test_kv_prefix$(EXE) $(LDFLAGS)
diff --git a/c/inkling.c b/c/inkling.c
index c698d587..3625087a 100644
--- a/c/inkling.c
+++ b/c/inkling.c
@@ -33,7 +33,8 @@
#endif
#include "st.h"
#include "tok.h"
-#include "route_trace.h" /* shared routing telemetry (#700) */
+#include "route_trace.h"
+#include "kv_prefix.h" /* KV prefix reuse (shared) */ /* shared routing telemetry (#700) */
#ifdef COLI_CUDA
#include "backend_cuda_ink.h"
static int g_cuda = 0;
@@ -143,6 +144,9 @@ typedef struct {
float **K, **V; int kv_len, max_t; /* per-layer [kv][max_t][hd] */
float **cs[4]; /* conv states, [n_layers][C*(K-1)] */
double dense_load_s;
+ /* KV prefix reuse: what the current K/V and conv states were built from.
+ * See kv_prefix.h β€” recorded where the tokens are fed, never derived. */
+ kv_prefix kvp;
} Model;
/* ---------- utility ---------- */
@@ -1406,6 +1410,11 @@ static float *step_mm(Model *m, const int *ids, int S, int pos0, int *tf_out,
for (int64_t j = 0; j < (int64_t)S*D; j++) x[j] += tmp[j];
}
m->kv_len = pos0 + S;
+ /* record what was just fed, at the positions it went to (kv_prefix.h).
+ * Audio taints the record: every frame carries the same token id while the
+ * mel payload differs, so ids alone cannot tell two clips apart. */
+ kv_prefix_record(&m->kvp, ids, pos0, S);
+ if (dmel && naud > 0) kv_prefix_taint(&m->kvp);
float *last = falloc(D);
float *logit = falloc(c->unpad_vocab);
if (tf_out) {
@@ -1431,6 +1440,7 @@ static float *step(Model *m, const int *ids, int S, int pos0, int *tf_out) {
static void state_reset(Model *m) {
Cfg *c = &m->c;
m->kv_len = 0;
+ kv_prefix_clear(&m->kvp);
for (int i = 0; i < c->n_layers; i++) {
int kvdim = L_KV(c,i) * L_HD(c,i);
for (int j = 0; j < 4; j++)
@@ -1443,6 +1453,11 @@ static void kv_alloc(Model *m, int max_t) {
if (m->K && max_t <= m->max_t) return; /* reuse across prompts when big enough */
if (m->K) for (int i = 0; i < c->n_layers; i++) { free(m->K[i]); free(m->V[i]); }
free(m->K); free(m->V);
+ /* The record is sized with the KV it describes: growing these buffers
+ * discards the positions it refers to, so it is dropped at the same
+ * moment. A failed allocation just disables reuse. */
+ kv_prefix_alloc(&m->kvp, max_t);
+ m->kv_len = 0;
m->max_t = max_t;
m->K = calloc(c->n_layers, sizeof(float*)); m->V = calloc(c->n_layers, sizeof(float*));
for (int i = 0; i < c->n_layers; i++) {
@@ -1646,13 +1661,38 @@ static void serve_one(Model *m, Tok *T, SReq *q) {
m->audio_norm ? "" : " β€” snapshot has no audio tensors");
fflush(stdout); free(ids); return;
}
- state_reset(m);
+ /* KV PREFIX REUSE (#639 for GLM; this engine re-prefilled every turn).
+ * A chat client resends the whole transcript each turn, so turn N used to
+ * re-process turns 1..N-1 from scratch β€” the cost of a message grew with
+ * the conversation, and every replayed position pulled its experts off
+ * disk again. When this prompt begins with the sequence the state already
+ * holds, that state IS the state at that position: keep it and prefill
+ * only the tail.
+ *
+ * Requirements, all necessary:
+ * - kv_alloc must not have grown (it frees the K/V fed[] describes), so
+ * the reuse decision is taken AFTER it
+ * - at least one new token, since the state cannot be rewound
+ * - no audio on either side: every audio frame carries the same token id,
+ * so ids alone cannot tell two different clips apart
+ * Either the reused positions are token-identical or nothing is reused;
+ * the emitted tokens are unchanged in both cases. */
kv_alloc(m, np + q->max_tok + 8);
+ /* naud>0 taints this turn before the comparison, not after: a request that
+ * brings its own audio must not match a text-only state either. */
+ if (naud > 0) kv_prefix_taint(&m->kvp);
+ int reuse = kv_prefix_reuse(&m->kvp, ids, np);
+ if (!reuse) state_reset(m);
+ else if (getenv("INK_PREFIX_LOG"))
+ fprintf(stderr, "[PREFIX] reusing %d of %d prompt tokens (%.0f%%)\n",
+ reuse, np, 100.0 * reuse / np);
double t0 = now_s();
uint64_t h0 = m->hits, m0 = m->miss;
/* per-turn phase snapshot for the PROF line (timers accumulate globally) */
double f0 = m->t_fill, e0 = m->t_expert, s0 = m->t_shared, a0 = m->t_attn;
- float *logit = step_mm(m, ids, np, 0, NULL, q->audio, naud);
+ /* `reuse` is the ABSOLUTE position of the first fresh token: attention and
+ * the KV slots are position-indexed, so this has to be the real offset. */
+ float *logit = step_mm(m, ids + reuse, np - reuse, reuse, NULL, q->audio, naud);
int len = np, gen = 0, limited = 1, cancelled = 0;
char buf[512];
/* repetition-penalty history: prompt tail + emitted tokens, ring of 128 */
diff --git a/c/kv_prefix.h b/c/kv_prefix.h
new file mode 100644
index 00000000..e4d3f7ed
--- /dev/null
+++ b/c/kv_prefix.h
@@ -0,0 +1,108 @@
+/* kv_prefix.h β€” reuse the attention state a previous turn already built.
+ *
+ * A chat client resends the whole transcript every turn. colibri.c has pinned
+ * each conversation to a KV slot since #639, so its turn N prefills only the
+ * new text; inkling.c, kimi_k3.c and deepseek were written without it and
+ * re-processed turns 1..N-1 from scratch. The cost of a message therefore grew
+ * with the length of the conversation, and every replayed position pulled its
+ * experts off disk again β€” on a streaming engine that is the dominant cost, not
+ * a rounding error. Measured on DeepSeek V4, a second turn that reused 82% of
+ * its prompt took 61s instead of 320s.
+ *
+ * THE IDEA. After a turn, the engine's state covers some number of positions.
+ * If the next prompt BEGINS with the token sequence that produced them, that
+ * state already IS the state at that position: skip the reset and prefill only
+ * the tail. No snapshot, no rewind β€” a prompt that diverges anywhere starts
+ * over.
+ *
+ * WHY A RECORD AND NOT A COUNTER. It is tempting to derive the reusable length
+ * from the caller's own bookkeeping ("prompt_count + generated - 1"). That
+ * invariant differs per engine β€” whether the last sampled token was fed back,
+ * whether a chunked prefill ran to completion, whether generation stopped early
+ * β€” and getting it wrong does not crash: it silently answers from a state that
+ * belongs to a different conversation. So the ids are recorded WHERE THEY ARE
+ * FED, and the record is the only description of the state anyone consults.
+ *
+ * INVARIANT: fed[0..len-1] are exactly the token ids the current state was
+ * built from, in position order. Everything else follows from it.
+ *
+ * TAINT. Some inputs are not described by their token ids. Inkling's audio
+ * frames all carry the same id (c->audio_tok) while the mel payload differs, so
+ * an id-only comparison would cheerfully "match" two different clips. A state
+ * that consumed such an input is marked tainted and is never reused.
+ */
+#ifndef KV_PREFIX_H
+#define KV_PREFIX_H
+
+#include <stdlib.h>
+#include <string.h>
+
+typedef struct {
+ int *fed; /* token ids at positions 0..len-1 */
+ int len; /* positions the state currently covers */
+ int cap; /* allocated positions */
+ int tainted; /* state consumed something token ids cannot describe */
+} kv_prefix;
+
+/* Size the record to the KV it describes. Call it wherever the KV buffers are
+ * (re)allocated: growing them discards the positions fed[] refers to, so the
+ * record has to be dropped at the same moment. Returns 0 on allocation
+ * failure, in which case reuse is simply disabled β€” this is an optimisation
+ * and must never be the reason a turn fails. */
+static inline int kv_prefix_alloc(kv_prefix *p, int cap) {
+ if (!p) return 0;
+ free(p->fed);
+ p->fed = (cap > 0) ? (int *)calloc((size_t)cap, sizeof(int)) : NULL;
+ p->cap = p->fed ? cap : 0;
+ p->len = 0;
+ p->tainted = 0;
+ return p->fed != NULL;
+}
+
+/* Forget the state. Pair this with whatever zeroes the engine's own KV/conv/
+ * recurrent buffers, so the two can never disagree. */
+static inline void kv_prefix_clear(kv_prefix *p) {
+ if (!p) return;
+ p->len = 0;
+ p->tainted = 0;
+}
+
+static inline void kv_prefix_free(kv_prefix *p) {
+ if (!p) return;
+ free(p->fed);
+ p->fed = NULL;
+ p->cap = p->len = 0;
+ p->tainted = 0;
+}
+
+/* Record n tokens fed at absolute positions pos0..pos0+n-1. Out-of-range
+ * writes drop the record rather than truncating it: a partial record would
+ * claim coverage the state does not have. */
+static inline void kv_prefix_record(kv_prefix *p, const int *ids,
+ int pos0, int n) {
+ if (!p || !p->fed || !ids || n <= 0 || pos0 < 0) return;
+ if (pos0 + n > p->cap) { p->len = 0; return; }
+ memcpy(p->fed + pos0, ids, (size_t)n * sizeof(int));
+ if (pos0 + n > p->len) p->len = pos0 + n;
+}
+
+/* Mark the state as holding something the ids do not describe (see TAINT). */
+static inline void kv_prefix_taint(kv_prefix *p) {
+ if (p) p->tainted = 1;
+}
+
+/* How many leading tokens of this prompt the state already holds: either all
+ * `len` of them, or none.
+ *
+ * Requires at least one NEW token (len < n). A prompt that is a prefix of, or
+ * equal to, the recorded sequence would need the state REWOUND, which nothing
+ * here can do β€” and prefilling zero tokens leaves the caller with no final
+ * hidden state to sample from. */
+static inline int kv_prefix_reuse(const kv_prefix *p, const int *ids, int n) {
+ if (!p || !p->fed || !ids) return 0;
+ if (p->tainted || p->len <= 0 || p->len >= n) return 0;
+ if (memcmp(p->fed, ids, (size_t)p->len * sizeof(int)) != 0) return 0;
+ return p->len;
+}
+
+#endif /* KV_PREFIX_H */
diff --git a/c/tests/test_kv_prefix.c b/c/tests/test_kv_prefix.c
new file mode 100644
index 00000000..23d5f827
--- /dev/null
+++ b/c/tests/test_kv_prefix.c
@@ -0,0 +1,93 @@
+/* test_kv_prefix β€” the reuse decision, exhaustively.
+ *
+ * This is the piece that must not be wrong. A bad reuse length does not crash:
+ * it answers the user from an attention state built out of a different
+ * conversation, and the output looks like a plausible reply. So every rejection
+ * rule gets its own case here, including the ones that look paranoid.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "../kv_prefix.h"
+
+static int failures;
+#define CHECK(cond, ...) do { if (!(cond)) { \
+ fprintf(stderr, "FAIL %s:%d: ", __FILE__, __LINE__); \
+ fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); failures++; } } while (0)
+
+int main(void) {
+ kv_prefix p = {0};
+ CHECK(kv_prefix_alloc(&p, 16), "alloc failed");
+
+ const int turn1[] = {5, 6, 7};
+ const int turn2[] = {5, 6, 7, 8, 9}; /* extends turn1 */
+ const int other[] = {5, 6, 99, 8, 9}; /* diverges at index 2 */
+
+ /* nothing recorded yet */
+ CHECK(kv_prefix_reuse(&p, turn2, 5) == 0, "empty record must not be reused");
+
+ kv_prefix_record(&p, turn1, 0, 3);
+ CHECK(p.len == 3, "len=%d, want 3", p.len);
+ CHECK(kv_prefix_reuse(&p, turn2, 5) == 3, "an extending prompt reuses all 3");
+ CHECK(kv_prefix_reuse(&p, other, 5) == 0, "a diverging prompt reuses nothing");
+
+ /* Equal length: reusing everything would leave no token to prefill, so the
+ * caller would have no final hidden state to sample from. */
+ CHECK(kv_prefix_reuse(&p, turn1, 3) == 0, "equal-length prompt must not reuse");
+
+ /* Shorter prompt: the state holds MORE than asked for and cannot be
+ * rewound. Reusing 3 positions for a 2-token prompt would answer with a
+ * token the user deleted still in context. */
+ const int shorter[] = {5, 6};
+ CHECK(kv_prefix_reuse(&p, shorter, 2) == 0, "shorter prompt must not reuse");
+
+ /* Divergence at the very first token. */
+ const int first[] = {1, 6, 7, 8};
+ CHECK(kv_prefix_reuse(&p, first, 4) == 0, "divergence at 0 reuses nothing");
+
+ /* Divergence at the LAST recorded token β€” the boundary a memcmp length
+ * that is off by one would let through. */
+ const int last[] = {5, 6, 70, 8};
+ CHECK(kv_prefix_reuse(&p, last, 4) == 0, "divergence at len-1 reuses nothing");
+
+ /* Appending: the record must describe the whole state, not the last write. */
+ const int gen[] = {8, 9};
+ kv_prefix_record(&p, gen, 3, 2);
+ CHECK(p.len == 5, "len=%d after append, want 5", p.len);
+ const int turn3[] = {5, 6, 7, 8, 9, 10};
+ CHECK(kv_prefix_reuse(&p, turn3, 6) == 5, "reuse must cover prompt+generated");
+
+ /* Taint: same ids, different payload (Inkling audio). */
+ kv_prefix_taint(&p);
+ CHECK(kv_prefix_reuse(&p, turn3, 6) == 0, "a tainted state is never reused");
+ kv_prefix_clear(&p);
+ CHECK(p.tainted == 0 && p.len == 0, "clear must drop both len and taint");
+
+ /* A write past the end drops the record instead of truncating it: claiming
+ * coverage the state does not have is the one failure that answers wrongly. */
+ CHECK(kv_prefix_alloc(&p, 4), "realloc failed");
+ kv_prefix_record(&p, turn1, 0, 3);
+ const int spill[] = {1, 2, 3};
+ kv_prefix_record(&p, spill, 3, 3); /* 3+3 > cap 4 */
+ CHECK(p.len == 0, "overflowing write must drop the record, len=%d", p.len);
+ CHECK(kv_prefix_reuse(&p, turn2, 5) == 0, "dropped record must not be reused");
+
+ /* Growing the buffers invalidates everything: the KV they describe is gone. */
+ CHECK(kv_prefix_alloc(&p, 32), "grow failed");
+ CHECK(p.len == 0 && p.tainted == 0, "alloc must reset the record");
+
+ /* Defensive: a NULL record is inert, not a crash. Engines disable reuse by
+ * leaving fed==NULL when the allocation fails. */
+ kv_prefix nul = {0};
+ CHECK(kv_prefix_reuse(&nul, turn2, 5) == 0, "NULL record reuses nothing");
+ kv_prefix_record(&nul, turn1, 0, 3); /* must not crash */
+ kv_prefix_clear(&nul);
+ kv_prefix_free(&nul);
+
+ kv_prefix_free(&p);
+ CHECK(p.fed == NULL && p.cap == 0, "free must clear the record");
+
+ if (failures) { fprintf(stderr, "%d check(s) failed\n", failures); return 1; }
+ puts("kv_prefix: ok");
+ return 0;
+}