Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
deepseek_v41: opt-in KV prefix reuse, and a resumed prefill that is exact
JustVuggfcf0aae2e364
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d511d5d2..d4b5285e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -684,6 +684,16 @@ jobs:SNAP=dsv41_tiny COLI_MODEL_MIRROR=dsv41_divergent ./deepseek_v41 8 dsv41_tiny/ref.json > divergent.txt 2>divergent.errcmp primary.txt divergent.txtgrep -q "header differs from the primary copy" divergent.err+ - name: KV prefix reuse (opt-in here) and the resumed-prefill exactness+ run: |+ cd c+ # Two gates in one file. The first is exactness and is ours: a prefill+ # that resumes mid-sequence must compute what a cold prefill computes,+ # which is what the index-key schedule fix is for. The second is the+ # shared contract, minus the one scenario this engine cannot satisfy --+ # a prefix holding generated positions, which attend differently from+ # prefilled ones by the vendor's own design. The override says so.+ DSV41_TINY=dsv41_tiny python3 -m unittest -v tests.test_dsv41_prefix_serve- name: "A prompt longer than one block, so the block boundary is crossed"run: |cd c@@ -1155,7 +1165,7 @@ jobs:# rieseguiva un binario non strumentato. Uno di quei test era rosso da# settimane senza che nessuno potesse vederlo.- name: Build the engines those tests exercise- run: make -C c kimi_k3 inkling colibri olmoe qwen38 qwen36+ run: make -C c kimi_k3 inkling colibri olmoe qwen38 qwen36 deepseek_v41- name: Python test suiterun: cd c && python3 -m unittest discover -s tests -p 'test_*.py'diff --git a/c/Makefile b/c/Makefileindex 0bf732f0..2bacd221 100644--- a/c/Makefile+++ b/c/Makefile@@ -1078,7 +1078,7 @@ qwen36$(EXE): qwen36.c serve_poll.h cli_args.h qwen36_tier.h expert_ffn.h st.h j# DeepSeek V4.1 Flash: one file, like every other portable engine. The fp4 experts# stream from the official checkpoint and quant.h's mxfp4 kernel reads them as they# are, so there is no conversion target here to go with it.-deepseek_v41$(EXE): deepseek_v41.c cli_args.h st.h json.h tok.h tok_unicode.h compat.h omp_tune.h quant.h \+deepseek_v41$(EXE): deepseek_v41.c cli_args.h st.h json.h tok.h tok_unicode.h compat.h omp_tune.h kv_prefix.h quant.h \sparse_attn.h hyper_connections.h serve_codec.h serve_poll.h .build-config$(CC) $(CFLAGS) deepseek_v41.c -o deepseek_v41$(EXE) $(LDFLAGS)diff --git a/c/deepseek_v41.c b/c/deepseek_v41.cindex e84b4c05..f7da5616 100644--- a/c/deepseek_v41.c+++ b/c/deepseek_v41.c@@ -63,6 +63,7 @@#include "quant.h"#include "sparse_attn.h"#include "omp_tune.h"+#include "kv_prefix.h" /* riuso del prefisso tra turni (shared) */#include <pthread.h> /* ehit_mark publishes the lazy HITS table under a lock */#if defined(__AVX2__)#include <immintrin.h>@@ -846,6 +847,24 @@ typedef struct {* speculative step keeps only the prefix that verified, and the next draft has to* seed the stages with exactly the positions that were committed */int last_start, last_rows;+ /* Whether THIS forward's rows may be rolled back, i.e. whether it is the+ * speculative verify batch. The per-layer undo buffers (ring_save,+ * cstate_save_*) are sized for one draft block and nothing else, because+ * until prefix reuse existed a forward with many rows always started at+ * position 0 and took the batched paths that write no undo at all. A+ * prefill that resumes mid-sequence is many rows AND past position 0, so+ * the guard cannot be `n > 1` any more: it has to be the reason the buffers+ * exist. A prefill is never rolled back. */+ int rollback_save;+ /* What the state describes, so a turn that resends the transcript feeds only+ * the new tail. Everything a turn builds here is position-indexed and+ * append-only -- the window rings and their position map, the compressor's+ * group slots and its partial group, the index keys, the engram history --+ * so a state that stopped at position P IS the state at P. The one thing+ * that is not described by a token id is an image: its placeholders carry+ * the same id whatever the picture was, so consuming one taints the record+ * (see kv_prefix.h). */+ kv_prefix kvp;} Model;/* ------------------------------------------------------------ rope --------- */@@ -1189,6 +1208,28 @@ static int expert_read_depth(void) {* once out of it -- to leave the cache exactly as cold as it was. V41_DIRECT=0* restores the buffered path, which is the arm of the A/B and the escape hatch* on a device where the direct path turns out to be slower. */+/* COLI_KV_PREFIX: on this engine reuse is OPT-IN, which it is on no other.+ *+ * Everywhere else a reused prefix is the same computation as a cold prefill, so+ * reuse changes the time and nothing else and can be on by default. Here it is+ * not, and the reason is the vendor's, not ours: a query reads one set of index+ * keys when its position is prefilled (its layer's own index owner, masked to+ * the query's reach) and another when the position is decoded (whatever was+ * published last). Both are load-bearing -- giving the prefill the decode+ * schedule drops the tiny oracle to 7/8, giving the decode the prefill owner+ * drops it to 1/8 -- so a position that was generated in an earlier turn does+ * not attend the way the same text attends when prefilled cold.+ *+ * What that costs: a conversation resumed from its own state and the same+ * conversation re-read from scratch can answer differently. The resumed state is+ * the sequential one, so it is not the wrong answer; it is a different one, and+ * on a 510 GB model it arrives in seconds instead of minutes. That is a trade+ * the person running the engine should make, so it is asked for rather than+ * assumed. A resumed PREFILL is exact (docs/deepseek-v41.md records the split+ * measurements), so a prompt that only ever grows without generated text in+ * between -- an agent resending a document, a tool loop -- reuses losslessly. */+static int kv_prefix_on(void){ const char *e = getenv("COLI_KV_PREFIX"); return e && *e != '0'; }+static int expert_direct(void) {static int on = -1;if (on < 0) on = getenv("V41_DIRECT") ? atoi(getenv("V41_DIRECT")) : 1;@@ -1410,6 +1451,10 @@ static void model_load(Model *m, const char *snap, int ecap, int engram_cache_roCfg *c = &m->c;cfg_load(c, snap);attn_project_check(c);+ /* Sized with the state it describes. CTX caps max_positions (#1526), so this+ * is one int per position the engine can actually hold, not per position the+ * checkpoint allows. A failure here disables reuse and nothing else. */+ kv_prefix_alloc(&m->kvp, c->max_positions);/* COLI_MODEL_DIRS: the container split across drives as DISTINCT shards, so* the 510 GB this engine streams can live on two drives of ~256 GB instead* of one of 512 -- which is the configuration most people can actually@@ -1655,7 +1700,7 @@ static int compressor_run(Model *m, int layer, const float *x, int n, int start_for (int t = 0; t < n; t++) {int pos = start_pos + t;int slot = pos % ratio;- if (n > 1) {+ if (n > 1 && m->rollback_save) {memcpy(l->cstate_save_kv + (size_t)t * hd, l->cstate_kv + (size_t)slot * hd,(size_t)hd * sizeof(float));memcpy(l->cstate_save_score + (size_t)t * hd, l->cstate_score + (size_t)slot * hd,@@ -1763,7 +1808,13 @@ static void indexer_run(Model *m, int layer, const float *x, const float *qr, inint published = published_owner(m, layer, start_pos, t);if (published >= 0) ikey = m->L[published].ikey;else if (m->pub_rows > 0) { if (m->pub_before) ikey = m->pub_before; }- else if (m->published_index_k) ikey = m->published_index_k;+ /* One position reads whatever was published last; a prefill reads its+ * own index owner, whose keys already cover the whole chunk and are+ * masked to each query's reach by `lens` above. A resumed prefill+ * inherits a published pointer from the previous turn, and honouring+ * it here would make the same position read different keys than it+ * read when prefilled cold. */+ else if (n == 1 && m->published_index_k) ikey = m->published_index_k;}mv8(q, &l->idx_wq_b, qr + (size_t)t * c->q_lora);for (int h = 0; h < nh; h++)@@ -2025,7 +2076,7 @@ static void attention_run(Model *m, int layer, const float *x, int n, int start_for (int t = 0; t < n; t++) {if (start_pos > 0) {int pos = start_pos + t, slot = pos % c->window;- if (n > 1) {+ if (n > 1 && m->rollback_save) {memcpy(l->ring_save + (size_t)t * hd, l->window + (size_t)slot * hd,(size_t)hd * sizeof(float));l->ring_save_pos[t] = l->window_pos[slot];@@ -2791,12 +2842,25 @@ static int spec_step(Model *m, int token, int start_pos, int main_rows,mv8(scratch, &sp->main_proj, m->main_hidden + (size_t)t * targets * dim);rms_into(main_x + (size_t)t * dim, scratch, sp->main_norm.w, dim, c->norm_eps);}- if (start_pos == 0) {+ /* Seed only, no drafting: that is what a NULL draft buffer asks for. Until+ * prefix reuse existed this was spelled `start_pos == 0`, because the only+ * forward that ever started at position 0 was the prompt's. A prefill that+ * resumes mid-sequence is the same call at a different position, and it has+ * to seed the stages at THAT position -- writing the tail's keys into slots+ * 0..rows-1 would leave the stages describing a sequence nobody fed. */+ if (!draft) {for (int stage = 0; stage < c->n_mtp; stage++)- spec_attention(m, stage, NULL, 0, 0, main_x, main_rows, NULL);+ spec_attention(m, stage, NULL, 0, start_pos, main_x, main_rows, NULL);free(main_x); free(scratch);return 0;}+ /* A cold run still declines to draft on the first decode step, where+ * start_pos is still the prefill's 0 and the stages were seeded a moment+ * ago. Kept separate from the guard above so this change does not move when+ * a cold conversation starts drafting; a resumed one starts immediately,+ * which costs a draft round's reads and can only change the acceptance+ * rate, never a token -- every draft is verified before it is emitted. */+ if (start_pos == 0) { free(main_x); free(scratch); return 0; }float *h = xmalloc((size_t)block * hc * dim * sizeof(float), "spec streams");for (int i = 0; i < block; i++) {@@ -2943,7 +3007,20 @@ static void forward_full(Model *m, const int *ids, int n, float *logits, int allm->pub_before = m->published_index_k;m->pub_before_layer = m->published_index_layer;m->pub_rows = 0;- if (n > 1 && start_pos > 0) {+ /* Only the speculative verify batch is ever rolled back (spec_verify is its+ * only caller), and only it may write the per-layer undo buffers. */+ m->rollback_save = all_logits;+ /* Several positions at once is either the speculative verify batch, which+ * needs this per-row schedule because its rows are consecutive decode steps,+ * or a prefill, which reads its index owner's keys for the whole chunk. The+ * condition used to be `start_pos > 0`, which picked out the speculative+ * case only because a prefill always started at position 0. A prefill that+ * resumes mid-sequence is many rows past position 0 and is still a prefill:+ * given the decode schedule it reads a different layer's keys than the same+ * positions read when they were prefilled cold, and picks a different+ * index top-k. `all_logits` is what actually distinguishes the two --+ * spec_verify is its only caller. */+ if (n > 1 && all_logits) {m->pub_layer = realloc(m->pub_layer, (size_t)n * sizeof(int));if (!m->pub_layer) { fprintf(stderr, "OOM sizing the publish schedule\n"); exit(1); }m->pub_rows = n;@@ -3106,6 +3183,11 @@ static void forward_full(Model *m, const int *ids, int n, float *logits, int alltrace("logits", -1, logits + (size_t)(all_logits ? n - 1 : 0) * c->vocab, c->vocab);m->pos += n;+ /* Recorded where the tokens entered the state, and only for the MAIN stream:+ * the draft stages read this window and never write it, so a speculative+ * round adds nothing here until spec_verify commits through forward_batch. */+ if (image_rows || image_mask) kv_prefix_taint(&m->kvp);+ kv_prefix_record(&m->kvp, ids, start_pos, n);m->last_start = start_pos;m->last_rows = n;m->forwards++;@@ -3146,6 +3228,10 @@ static void model_reset(Model *m) {m->published_index_k = NULL;m->shared_topk_rows = m->shared_topk_width = 0;m->pos = 0;+ /* Paired with the reset on purpose: whoever drops the state must also forget+ * what it was built from, or the two disagree in favour of the one nobody+ * can check. */+ kv_prefix_clear(&m->kvp);}static const ColiServeWireProfile v41_wire = {@@ -3242,6 +3328,11 @@ static void spec_rollback(Model *m, int start_pos, int committed, int rows) {m->pos = start_pos + committed;m->last_rows = committed;if (m->engram.active && m->engram.history_len > m->pos) m->engram.history_len = m->pos;+ /* The record follows the rollback for the same reason the engram history+ * does: the rejected rows are no longer in the state, and a record that+ * still claimed them would hand the next turn positions nothing holds. The+ * ids below m->pos are the committed ones, so truncating is enough. */+ if (m->kvp.len > m->pos) m->kvp.len = m->pos;if (m->pub_rows > 0) {const float *published = m->pub_before;int layer = m->pub_before_layer;@@ -3464,9 +3555,32 @@ static void serve_loop(Model *m, Tok *tokenizer, const char *snap) {mir_bytes0[r] = g_mir_bytes[r];mir_reads0[r] = g_mir_nread[r];}- model_reset(m);int n_prompt = tok_encode(tokenizer, (const char *)command.payload,(int)command.payload_bytes, ids, c->max_positions);+ /* Decided BEFORE the reset, because the reset is what it decides about.+ * A chat client resends the whole transcript every turn; if this prompt+ * begins with the ids the state was built from, that state already IS+ * the state at those positions, so only the tail is fed. Reuse is all or+ * nothing -- nothing here can rewind four caches and a ring. An image+ * refuses it outright: the placeholder ids describe the span but not the+ * picture, and the span's offsets are computed against the whole prompt.+ * COLI_KV_PREFIX=0 disables it, COLI_PREFIX_LOG=1 reports the decision. */+ int reuse = 0;+ if (n_prompt >= 1 && kv_prefix_on() && !pending_image)+ reuse = kv_prefix_reuse(&m->kvp, ids, n_prompt);+ if (getenv("COLI_PREFIX_LOG")) {+ if (reuse)+ fprintf(stderr, "[PREFIX] reusing %d of %d prompt tokens (%.0f%%)\n",+ reuse, n_prompt, 100.0 * reuse / n_prompt);+ else+ fprintf(stderr, "[PREFIX] no reuse: held=%d cap=%d prompt=%d%s%s%s\n",+ m->kvp.len, m->kvp.cap, n_prompt,+ m->kvp.tainted ? " tainted" : "",+ pending_image ? " (image)" : "",+ kv_prefix_on() ? "" : " (off: set COLI_KV_PREFIX=1)");+ fflush(stderr);+ }+ if (!reuse) model_reset(m);if (n_prompt < 1) {coli_serve_write_error(stdout, command.id, "EMPTY_PROMPT");coli_serve_command_dispose(&command); continue;@@ -3510,7 +3624,10 @@ static void serve_loop(Model *m, Tok *tokenizer, const char *snap) {}}free(pending_image); pending_image = NULL;- forward_with_image(m, ids, n_prompt, logits, aligned, image_at, image_h, image_w, image_mask);+ /* `reuse` is the ABSOLUTE position of the first fresh token: every cache+ * here is position-indexed, so this has to be the real offset. */+ forward_with_image(m, ids + reuse, n_prompt - reuse, logits, aligned,+ image_at, image_h, image_w, image_mask);free(aligned); free(image_mask);uint64_t prefill_bytes = m->expert_bytes - ebytes0;double prefill_disk = m->t_disk - disk0;diff --git a/c/tests/prefix_serve_harness.py b/c/tests/prefix_serve_harness.pyindex fd988228..09dd9580 100644--- a/c/tests/prefix_serve_harness.py+++ b/c/tests/prefix_serve_harness.py@@ -146,6 +146,13 @@ class PrefixReuseContract:scenarios once more with no engine behind them."""+ # An engine whose fixture round-trips every token id through text can demand+ # the stronger property in the replay scenario below: that reuse actually+ # FIRES when the client appends the reply. A fixture with more ids than the+ # byte range cannot, because the reply comes back as different text and the+ # prompt legitimately diverges.+ REPLAY_REUSES = False+def spawn(self, log_prefix=True, reuse=True): # pragma: no cover - overriddenraise NotImplementedError@@ -256,17 +263,25 @@ class PrefixReuseContract:def test_a_turn_that_replays_the_reply_is_never_wrong(self):"""The real chat shape: the client appends the assistant's reply and anew question. Whether the reply survives this fixture's decode-encode- round trip decides whether reuse FIRES, and that is allowed to vary --- what may never vary is the answer."""+ round trip decides whether reuse FIRES, and on a fixture with more token+ ids than bytes that is allowed to vary -- what may never vary is the+ answer. Where it does round-trip (REPLAY_REUSES), firing is required:+ this is the one scenario whose prefix contains GENERATED positions, so+ it is what holds an engine to keeping its record honest about them."""warm = self.spawn()opening = b"The capital of France is"- reply = warm.ask("1", opening, max_tok=4)+ reply = warm.ask("1", opening, max_tok=8)second = opening + reply + b" and the capital of Spain is"got = warm.ask("2", second, max_tok=8)- warm.close()+ log = warm.close()cold = self.spawn(log_prefix=False)fresh = cold.ask("1", second, max_tok=8)cold.close()self.assertEqual(got, fresh, "replaying the reply changed the answer")+ if self.REPLAY_REUSES:+ self.assertIn("[PREFIX] reusing", log,+ "the turn that replays the reply did not reuse: the "+ "record does not describe the generated positions.\n"+ "engine said:\n" + (log or "(nothing on stderr)"))diff --git a/c/tests/test_dsv41_prefix_serve.py b/c/tests/test_dsv41_prefix_serve.pynew file mode 100644index 00000000..949b0f5e--- /dev/null+++ b/c/tests/test_dsv41_prefix_serve.py@@ -0,0 +1,129 @@+"""KV prefix reuse on DeepSeek V4.1: the shared contract, against the tiny fixture.++V4.1 is the hardest case in the tree and the reason the contract is worth having.+A turn here does not build one tensor: it builds a window ring per layer with its+own position map, a compressed KV and index-key cache whose slot is position over+the compression ratio, the compressor's partial group, and the engram history.+All of them are position-indexed and append-only, which is exactly why reuse is+sound -- a state that stopped at position P is the state at P -- and also why a+wrong reuse length would corrupt five things at once, silently.++Speculative decoding (DSpark) is on by default here and rolls the caches back to+the last draft that verified. The record follows that rollback, so what it claims+is what the caches hold. Its acceptance rate may differ between a warm and a cold+engine; the emitted tokens may not, because every draft is verified by the main+model before a single one is written.++Runs against the tiny random-init fixture the oracle job already builds+(tools/make_dsv41_tiny.py): no checkpoint, no fast disk.+"""+import os+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from prefix_serve_harness import PrefixReuseContract, ServeEngine # noqa: E402++HERE = Path(__file__).resolve().parent.parent+ENGINE = HERE / ("deepseek_v41.exe" if sys.platform == "win32" else "deepseek_v41")+FIXTURE = Path(os.environ.get("DSV41_TINY", HERE / "dsv41_tiny"))++[email protected](ENGINE.exists(), "deepseek_v41 is not built")[email protected]((FIXTURE / "model.safetensors").exists(),+ "tiny dsv41 fixture is absent (tools/make_dsv41_tiny.py)")+class Dsv41PrefixServeTest(PrefixReuseContract, unittest.TestCase):+ # This fixture's vocabulary is the byte range, so a reply survives the round+ # trip and the replay scenario can require reuse to fire. It is also the+ # scenario that covers the speculative rollback: DSpark drafts through that+ # turn, the main model rejects some of them, and the record has to give those+ # positions back or the next turn finds a prefix the caches no longer hold.+ REPLAY_REUSES = True++ def spawn(self, log_prefix=True, reuse=True):+ # Reuse is opt-in on this engine (see the comment on kv_prefix_on), so+ # the arm that wants it has to ask. `reuse=False` still wins: the harness+ # sets COLI_KV_PREFIX=0 after this env is merged.+ return ServeEngine(ENGINE, ["8"],+ {"SNAP": str(FIXTURE), "SERVE": "1", "COLI_KV_PREFIX": "1"},+ log_prefix=log_prefix, reuse=reuse)++ def test_a_turn_that_replays_the_reply_is_never_wrong(self):+ """Overridden, because on this engine it is not true, and the reason is+ the architecture rather than the wiring.++ A query reads one set of index keys when its position is PREFILLED (its+ layer's own index owner, masked to the query's reach) and another when+ the position is DECODED (whatever was published last). Both are the+ vendor's: give the prefill the decode schedule and the tiny oracle drops+ to 7/8, give the decode the prefill owner and it drops to 1/8. So a+ position generated in an earlier turn does not attend the way the same+ text attends when prefilled cold, and a prefix that contains the reply+ cannot reproduce a cold engine's answer.++ What this asserts instead is what does hold, and what a user is entitled+ to: the reuse fires, the engine is deterministic about it, and turning+ reuse off returns the cold answer exactly. The exactness of a resumed+ PREFILL -- the part that is ours to get right -- is gated by+ test_a_resumed_prefill_matches_a_cold_one below.+ """+ opening = b"The capital of France is"++ warm = self.spawn()+ reply = warm.ask("1", opening, max_tok=8)+ second = opening + reply + b" and the capital of Spain is"+ got = warm.ask("2", second, max_tok=8)+ log = warm.close()++ again = self.spawn(log_prefix=False)+ again.ask("1", opening, max_tok=8)+ twice = again.ask("2", second, max_tok=8)+ again.close()++ off = self.spawn(log_prefix=False, reuse=False)+ off.ask("1", opening, max_tok=8)+ without = off.ask("2", second, max_tok=8)+ off.close()++ cold = self.spawn(log_prefix=False, reuse=False)+ fresh = cold.ask("1", second, max_tok=8)+ cold.close()++ self.assertIn("[PREFIX] reusing", log,+ "the turn that replays the reply did not reuse: the record "+ "does not describe the generated positions.\n"+ "engine said:\n" + (log or "(nothing on stderr)"))+ self.assertEqual(got, twice, "the reused answer is not deterministic")+ self.assertEqual(without, fresh,+ "with reuse off, the second turn must still be a cold prefill")++ def test_a_resumed_prefill_matches_a_cold_one(self):+ """The exactness that IS ours: a prefill that resumes mid-sequence has to+ compute what a cold prefill computes for the same positions.++ This is what the index-key schedule fix is for. It used to select the+ speculative batch by `start_pos > 0`, which a resumed prefill also+ matches, so its rows read another layer's published keys and picked a+ different index top-k. Every turn here asks for one token, so nothing+ generated enters the record and the whole prefix is prefilled text.+ """+ full = b"The capital of France is a question about geography and the capital of Spain is another one"+ cold = self.spawn(log_prefix=False)+ expected = cold.ask("1", full, max_tok=8)+ cold.close()++ for tail in (4, 12, 24, 48):+ with self.subTest(tail=tail):+ warm = self.spawn()+ warm.ask("1", full[:-tail])+ got = warm.ask("2", full, max_tok=8)+ log = warm.close()+ self.assertIn("[PREFIX] reusing", log, "no reuse, so nothing is proven")+ self.assertEqual(got, expected,+ f"a prefill resumed {tail} bytes from the end does not "+ f"reproduce the cold one")+++if __name__ == "__main__":+ unittest.main()diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.mdindex 50fb8ee3..b3d36252 100644--- a/docs/ENVIRONMENT.md+++ b/docs/ENVIRONMENT.md@@ -375,7 +375,7 @@ Read **only** by `c/inkling.c`.| `INK_METAL_MIN_S` | `1` | Minimum batch S to send the MoE block to Metal. `=2` restores the prefill-only gate (which mattered when the residency set was absent and per-block `useResource` churn cost ~135 ms). || `INK_PREFIX_LOG` | unset | Log the KV-prefix reuse decision and its reason, as `K3_PREFIX_LOG` does for K3. || `COLI_PREFIX_LOG` | unset | Same line for the engines that take the shared record (Qwen3.6, OLMoE): reports how many prompt tokens were reused, or why none were. |-| `COLI_KV_PREFIX` | on | `0` disables KV-prefix reuse on those engines. The escape hatch, and the B arm of the A/B that shows reuse changes nothing but the time. |+| `COLI_KV_PREFIX` | on, except DeepSeek V4.1 | `0` disables KV-prefix reuse; on `deepseek_v41` reuse is OFF until you set `1`. That engine reads one set of index keys for a prefilled position and another for a decoded one, both the vendor's, so a prefix holding an earlier turn's generated tokens answers differently than the same text read cold. A resumed prefill is exact. || `GPU_DEV` | `0` | CUDA device index for the inkling CUDA backend. || `NOGPU` | unset | If set, skip GPU init entirely (both CUDA and Metal), regardless of the other GPU variables. |diff --git a/docs/deepseek-v41.md b/docs/deepseek-v41.mdindex 235e7640..a4cee5b3 100644--- a/docs/deepseek-v41.md+++ b/docs/deepseek-v41.md@@ -332,6 +332,7 @@ and costs the contention. Anything that tries again has to start from that.| variable | default | what it does ||---|---|---|+| `COLI_KV_PREFIX` | **off on this engine** | `1` reuses the previous turn's state when the new prompt begins with what that state was built from, instead of re-reading the transcript. Off by default here and on nowhere else: see "Reusing a turn" below for what it costs. || `V41_STATS` | off | per-turn accounting on stderr: the n-gram cache, the expert bytes and their rate, and how many drafts were accepted. Off by default because `coli chat` shows the engine's stderr next to the answer. || `V41_READ_DEPTH` | 8 | expert tensors read at once when a step misses the cache (see above). `1` restores the serial read the engine used to do, for an A/B. || `COLI_MODEL_MIRROR` | unset | `;`/`,`-separated read-only copies of the checkpoint on other drives; expert reads split across the primary and every replica (see above). `SNAP_MIRROR` is the legacy alias. |@@ -347,6 +348,50 @@ and costs the contention. Anything that tries again has to start from that.| `V41_DSPARK_MINACC` | 60 | percent of drafts that must be accepted over a window of ten for drafting to continue; below it, drafts pause for 64 tokens. 60 is the measured break-even, not a guess. || `V41_SPEC_FORCE` | unset | oracle mode only: draft the reference's tokens (`1`), corrupt the last one (`2`), or use the head's own (`3`), to exercise the verification path on a fixture whose draft head is random. |+## Reusing a turn, and why it is asked for rather than assumed++A chat client resends the whole conversation every turn. Every other engine in+the tree skips the part it already holds, because for them a reused prefix is+the same computation as a cold prefill: the reuse changes the time and nothing+else. Here it is not, and the reason belongs to the model rather than to us.++A query reads one set of index keys when its position is **prefilled** -- its+layer's own index owner, masked to what the query can reach -- and another when+the position is **decoded**, namely whatever was published last. Both are the+vendor's, and neither can be moved to match the other:++| | tiny oracle |+|---|---|+| as shipped | 8/8 |+| the prefill given the decode schedule | 7/8 |+| the decode given the prefill owner | 1/8 |++So a position generated in an earlier turn does not attend the way the same text+attends when it is prefilled cold. A resumed conversation and the same+conversation re-read from scratch can answer differently. The resumed state is+the sequential one, so it is not the wrong answer -- it is a different one, and+that is a trade the person running the engine makes, not one the engine makes+for them. `COLI_KV_PREFIX=1` asks for it.++What is exact, and gated in CI, is a resumed **prefill**: a prompt that grows+without generated text in between -- an agent resending a document, a tool loop+-- reuses losslessly. Measured on the tiny fixture, a prefill that resumes 4,+12, 24 or 48 tokens from the end reproduces the cold prefill's tokens exactly.+That was not free: the index-key schedule used to be selected by `start_pos > 0`,+which meant "the speculative verify batch" only because a prefill always started+at position 0. A resumed prefill matched it too and took the decode schedule,+reading another layer's keys and choosing a different index top-k. It is now+selected by the flag that actually distinguishes the two.++Three more things the attempt turned up, all of them unreachable before reuse+existed and all fixed here: the per-layer undo buffers (`ring_save`,+`cstate_save_*`) are sized for one draft block and were written on any multi-row+forward past position 0, which a resumed prefill overflows; `spec_step` decided+"seed the stages, do not draft" by `start_pos == 0` and seeded them at position+0, so a resumed prefill fell into the drafting path with no draft buffer; and the+record follows the speculative rollback, so it never claims rows the caches gave+back.+## How it is tested`tools/dsv41_ref.py` is a torch reimplementation of the vendor's kernels on the CPU: