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

deepseek_v4: reuse the KV prefix instead of re-prefilling every turn

JustVuggc08dd23be29a
diff --git a/c/Makefile b/c/Makefile
index fc3e95dc..c2113155 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -409,6 +409,9 @@ deepseek-v4-tiny-check: deepseek-v4-tiny-generate
$(PYTHON) tests/test_deepseek_v4_tiny.py \
--binary ./$(if $(IS_WIN),deepseek_v4.exe,deepseek_v4) \
--fixture ./deepseek_v4_tiny
+ $(PYTHON) tests/test_deepseek_v4_prefix.py \
+ --binary $(CURDIR)/$(if $(IS_WIN),deepseek_v4.exe,deepseek_v4) \
+ --fixture $(CURDIR)/deepseek_v4_tiny
deepseek-v4-oracle: deepseek-v4
@test -n "$(MODEL)" || { echo "usage: make deepseek-v4-oracle MODEL=/path/to/checkpoint" >&2; exit 2; }
diff --git a/c/deepseek_v4.c b/c/deepseek_v4.c
index 0c17ff50..31cb57ec 100644
--- a/c/deepseek_v4.c
+++ b/c/deepseek_v4.c
@@ -6733,6 +6733,7 @@ static void session_free_attention(ColiV4Session *session) {
void coli_v4_session_destroy(ColiV4Session *session) {
if (!session) return;
+ kv_prefix_free(&session->fed);
session_free_attention(session);
session_free_buffers(session);
if (session->tokenizer_ready) {
@@ -6819,6 +6820,14 @@ int coli_v4_session_create(ColiV4Session **output, ColiV4Engine *engine,
snprintf(error, error_size, "out of memory allocating session buffers");
return -1;
}
+ /* Holds prompt and generated ids together: the next request's prompt
+ * contains both, so both have to match for the state to be reusable.
+ * A failure here is not an error — kv_prefix_alloc leaves the record empty,
+ * kv_prefix_reuse then returns 0, and every request prefills in full, which
+ * is exactly the behaviour before this change. */
+ (void)kv_prefix_alloc(&session->fed,
+ session->max_prompt_tokens +
+ session->max_new_tokens_cap + 64);
*output = session;
return 0;
}
@@ -6871,8 +6880,7 @@ int coli_v4_session_generate(ColiV4Session *session,
session->text_length = 0;
session->prompt_count = 0;
session->generated_count = 0;
- for (int layer = 0; layer < session->config.num_hidden_layers; layer++)
- coli_v4_window_attention_reset(session->attention[layer]);
+ session->prefix_reused = 0;
int max_new = options->max_new_tokens;
if (max_new > session->max_new_tokens_cap)
@@ -6900,9 +6908,38 @@ int coli_v4_session_generate(ColiV4Session *session,
int *generated = session->generated;
size_t hd = (size_t)config->hc_mult * config->hidden_size;
- for (int item = 0; item < prompt_count; item++)
+ /* ---------------------------------------------------------------------
+ * KV PREFIX REUSE.
+ *
+ * The window attention state is not truncatable to an arbitrary position:
+ * the sliding window is a ring and the compressor carries recurrent
+ * kv_state/score_state rather than per-position rows. What it *can* do is
+ * keep going. So the reusable case is the exact one a conversation
+ * produces: turn N+1's prompt begins with every id turn N fed, prompt and
+ * reply alike, and only the tail is new.
+ *
+ * kv_prefix_reuse returns 0 unless the recorded ids are a strict prefix of
+ * this prompt, so a divergent or shorter prompt falls back to a full reset
+ * and prefill, and the reuse path always has at least one token left to
+ * feed. Nothing about the math changes: positions stay absolute and the
+ * tail is prefilled at start=reuse, so the logits are the ones a cold run
+ * would have produced.
+ * ------------------------------------------------------------------- */
+ int reuse = kv_prefix_reuse(&session->fed, session->prompt_ids, prompt_count);
+ if (!reuse)
+ for (int layer = 0; layer < config->num_hidden_layers; layer++)
+ coli_v4_window_attention_reset(session->attention[layer]);
+ session->prefix_reused = reuse;
+ if (reuse && getenv("V4_PREFIX_LOG"))
+ fprintf(stderr, "[PREFIX] reusing %d of %d prompt tokens\n",
+ reuse, prompt_count);
+
+ int fresh = prompt_count - reuse;
+ for (int item = 0; item < fresh; item++)
if (load_embedding(state + (size_t)item * hd, index, config,
- session->prompt_ids[item])) {
+ session->prompt_ids[reuse + item])) {
+ /* The state now matches neither the old ids nor the new ones. */
+ kv_prefix_taint(&session->fed);
if (error && error_size)
snprintf(error, error_size, "cannot load embedding");
return -1;
@@ -6910,16 +6947,28 @@ int coli_v4_session_generate(ColiV4Session *session,
double setup_done = spec_now();
if (target_batch(engine, &state, &next, attention, index, config, experts,
- session->prompt_ids, 0, prompt_count, error, error_size))
+ session->prompt_ids + reuse, reuse, fresh,
+ error, error_size)) {
+ kv_prefix_taint(&session->fed);
return -1;
+ }
session->state = state;
session->next = next;
- const float *last = state + (size_t)(prompt_count - 1) * hd;
+ /* The batch holds only the fresh tail, so the final row is at fresh-1
+ * even though its absolute position is prompt_count-1. */
+ const float *last = state + (size_t)(fresh - 1) * hd;
int current = 0;
float current_logit = 0.0f;
if (final_hidden(hidden, last, index, config, error, error_size) ||
- head_argmax(engine, hidden, index, config, &current, &current_logit))
+ head_argmax(engine, hidden, index, config, &current, &current_logit)) {
+ kv_prefix_taint(&session->fed);
return -1;
+ }
+ /* The prompt is in the attention state from here on; record it before the
+ * decode loop so a failure mid-generation still leaves fed describing what
+ * was actually fed. */
+ kv_prefix_record(&session->fed, session->prompt_ids + reuse, reuse, fresh);
+ session->fed.len = prompt_count;
int generated_count = 0;
int last_processed = prompt_count - 1;
generated[generated_count++] = current;
@@ -6931,13 +6980,21 @@ int coli_v4_session_generate(ColiV4Session *session,
while (!done && generated_count < max_new) {
int position = last_processed + 1;
if (target_token(engine, &state, &next, attention, index, config, experts,
- current, position, error, error_size))
+ current, position, error, error_size)) {
+ kv_prefix_taint(&session->fed);
return -1;
+ }
+ /* `current` is now in the attention state at `position`. Record it here,
+ * before head_argmax overwrites it: the token generated last is never
+ * fed, so recording after the loop would claim one token too many. */
+ kv_prefix_record(&session->fed, &current, position, 1);
session->state = state;
session->next = next;
if (final_hidden(hidden, state, index, config, error, error_size) ||
- head_argmax(engine, hidden, index, config, &current, &current_logit))
+ head_argmax(engine, hidden, index, config, &current, &current_logit)) {
+ kv_prefix_taint(&session->fed);
return -1;
+ }
last_processed = position;
generated[generated_count++] = current;
done = session_emit_token(session, on_token, user_data, current,
@@ -7304,10 +7361,15 @@ static void v4_serve_one(ColiV4Engine *engine, ColiV4Session *session,
int length_limited = !stream.cancelled && !stats.eos_stopped &&
stats.generated_tokens >= request->max_tokens;
double decode = stats.decode_sec > 0.0 ? stats.decode_sec : elapsed;
- printf("DONE %s STAT %d %.3f %.1f %.2f %d %d\n",
+ /* Trailing field: prompt tokens served from the previous turn's attention
+ * state instead of being prefilled again. Appended rather than inserted --
+ * openai_server.py accepts `len(fields) >= 7`, so an older reader ignores
+ * it and a newer one can report it. */
+ printf("DONE %s STAT %d %.3f %.1f %.2f %d %d %d\n",
request->id, completion,
decode > 0.0 ? completion / decode : 0.0,
- hit_rate, v4_serve_rss_gb(), stats.prompt_tokens, length_limited);
+ hit_rate, v4_serve_rss_gb(), stats.prompt_tokens, length_limited,
+ session->prefix_reused);
fflush(stdout);
}
diff --git a/c/deepseek_v4_internal.h b/c/deepseek_v4_internal.h
index 7158dbcd..b62e24da 100644
--- a/c/deepseek_v4_internal.h
+++ b/c/deepseek_v4_internal.h
@@ -639,6 +639,7 @@ void coli_v4_engine_attach_session(ColiV4Engine *engine);
void coli_v4_engine_detach_session(ColiV4Engine *engine);
#include "tok.h"
+#include "kv_prefix.h"
struct ColiV4Session {
ColiV4Engine *engine;
@@ -657,6 +658,12 @@ struct ColiV4Session {
int tokenizer_ready;
char *text;
int text_length;
+ /* Token ids this session's attention state already holds, prompt and
+ * generated alike, in the shared format colibri.c/inkling.c/kimi_k3.c use.
+ * A follow-up request whose prompt starts with exactly these ids continues
+ * from that position instead of re-prefilling it. */
+ kv_prefix fed;
+ int prefix_reused; /* reuse length of the request in flight, for stats */
};
/* RAM-tiered expert open used by coli_v4_engine_open (replaces ld --wrap). */
diff --git a/c/tests/test_deepseek_v4_prefix.py b/c/tests/test_deepseek_v4_prefix.py
new file mode 100644
index 00000000..65d328fb
--- /dev/null
+++ b/c/tests/test_deepseek_v4_prefix.py
@@ -0,0 +1,225 @@
+#!/usr/bin/env python3
+"""KV prefix reuse on the DeepSeek V4 serve path.
+
+The property under test is not "it is faster" -- it is that reusing the
+attention state produces the bytes a cold prefill would have produced. So each
+case runs the same second turn twice: once as the continuation of a warm
+session, once against a freshly started engine, and requires the two to agree
+token for token.
+
+Speaking the SUBMIT/DATA/DONE protocol directly rather than through
+openai_server.Engine keeps the test on the engine's own contract, including the
+trailing reuse field of the DONE frame.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+
+def token_prompt(ids: list[int]) -> str:
+ return "".join(f"<t{token:03d}>" for token in ids)
+
+
+def parse_tokens(text: str) -> list[int]:
+ """The tiny fixture's vocabulary is <tNNN>, so a reply decodes back to ids."""
+ return [int(match) for match in re.findall(r"<t(\d+)>", text)]
+
+
+class Serve:
+ """One persistent `SERVE=1` engine process."""
+
+ def __init__(self, binary: Path, model: Path, ctx: str = "128") -> None:
+ env = dict(os.environ, SERVE="1", SNAP=str(model), CTX=ctx,
+ V4_PREFIX_LOG="1")
+ self.process = subprocess.Popen(
+ [str(binary)], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, env=env,
+ )
+ self.counter = 0
+
+ def submit(self, prompt: str, max_tokens: int) -> tuple[str, int]:
+ """Returns the generated text and the DONE frame's reuse count."""
+ self.counter += 1
+ request_id = f"r{self.counter}"
+ payload = prompt.encode("utf-8")
+ header = (f"SUBMIT {request_id} 0 {len(payload)} {max_tokens} "
+ f"0.0 1.0 0\n").encode("ascii")
+ assert self.process.stdin is not None
+ self.process.stdin.write(header + payload + b"\n")
+ self.process.stdin.flush()
+
+ pieces: list[bytes] = []
+ reuse = -1
+ stream = self.process.stdout
+ assert stream is not None
+ while True:
+ line = stream.readline()
+ if not line:
+ raise AssertionError(
+ f"engine closed stdout during {request_id}; "
+ f"stderr:\n{self._drain_stderr()}"
+ )
+ fields = line.decode("utf-8", "replace").split()
+ if not fields:
+ continue
+ if fields[0] == "ERROR":
+ raise AssertionError(f"engine ERROR: {line!r}")
+ if fields[0] == "DATA" and len(fields) == 3:
+ size = int(fields[2])
+ pieces.append(stream.read(size))
+ stream.read(1) # trailing newline
+ elif fields[0] == "DONE":
+ # DONE <id> STAT <completion> <tok/s> <hit%> <rss> <prompt> <cap> [<reuse>]
+ if len(fields) >= 10:
+ reuse = int(fields[9])
+ break
+ return b"".join(pieces).decode("utf-8", "replace"), reuse
+
+ def _drain_stderr(self) -> str:
+ assert self.process.stderr is not None
+ try:
+ return self.process.stderr.read(8192).decode("utf-8", "replace")
+ except Exception: # pragma: no cover
+ return "<unavailable>"
+
+ def close(self) -> None:
+ try:
+ if self.process.stdin:
+ self.process.stdin.close()
+ self.process.wait(timeout=30)
+ except Exception: # pragma: no cover
+ self.process.kill()
+
+
+def check_growing_conversation(binary: Path, model: Path,
+ case: dict[str, object]) -> None:
+ """Turn 2 extends turn 1: the state is reused, the output does not change."""
+ first_ids = list(case["prompt_ids"]) # type: ignore[arg-type]
+ max_new = 4
+
+ warm = Serve(binary, model)
+ try:
+ first_text, first_reuse = warm.submit(token_prompt(first_ids), max_new)
+ if first_reuse != 0:
+ raise AssertionError(
+ f"first turn of a fresh session reused {first_reuse} tokens; "
+ "there was nothing to reuse"
+ )
+ # What the engine feeds is the prompt plus every generated token except
+ # the last, which is emitted but never fed back. Turn 2 has to be a
+ # STRICT extension of that, which is what a chat produces: the previous
+ # prompt, the reply, then the new user text.
+ reply = parse_tokens(first_text)
+ if len(reply) < 2:
+ raise AssertionError(f"first turn produced too little: {first_text!r}")
+ fed = first_ids + reply[:-1]
+ second_ids = fed + [first_ids[0]]
+ second_text, second_reuse = warm.submit(token_prompt(second_ids), max_new)
+ finally:
+ warm.close()
+
+ cold = Serve(binary, model)
+ try:
+ cold_text, cold_reuse = cold.submit(token_prompt(second_ids), max_new)
+ finally:
+ cold.close()
+
+ if cold_reuse != 0:
+ raise AssertionError(f"cold engine reported reuse={cold_reuse}")
+ if second_text != cold_text:
+ raise AssertionError(
+ "warm continuation diverged from a cold prefill of the same prompt:\n"
+ f" warm: {second_text!r}\n cold: {cold_text!r}"
+ )
+ if second_reuse <= 0:
+ raise AssertionError(
+ "prefix reuse never fired on a prompt that extends the previous "
+ f"turn (reuse={second_reuse}); the optimisation is inert"
+ )
+ if second_reuse < len(first_ids):
+ raise AssertionError(
+ f"reused only {second_reuse} tokens, expected at least the "
+ f"{len(first_ids)} prompt tokens of the previous turn"
+ )
+ print(f"PASS prefix reuse: {second_reuse} tokens reused, "
+ f"output identical to a cold prefill")
+
+
+def check_divergent_prompt_resets(binary: Path, model: Path,
+ case: dict[str, object]) -> None:
+ """A prompt that is not an extension must fall back to a full prefill."""
+ first_ids = list(case["prompt_ids"]) # type: ignore[arg-type]
+ other_ids = [token + 1 for token in first_ids]
+ max_new = 4
+
+ warm = Serve(binary, model)
+ try:
+ warm.submit(token_prompt(first_ids), max_new)
+ divergent_text, reuse = warm.submit(token_prompt(other_ids), max_new)
+ finally:
+ warm.close()
+
+ cold = Serve(binary, model)
+ try:
+ cold_text, _ = cold.submit(token_prompt(other_ids), max_new)
+ finally:
+ cold.close()
+
+ if reuse != 0:
+ raise AssertionError(
+ f"reused {reuse} tokens from a prompt that shares no full prefix"
+ )
+ if divergent_text != cold_text:
+ raise AssertionError(
+ "divergent prompt did not reset the state:\n"
+ f" warm: {divergent_text!r}\n cold: {cold_text!r}"
+ )
+ print("PASS prefix reset: divergent prompt re-prefills and matches cold")
+
+
+def check_repeated_prompt(binary: Path, model: Path,
+ case: dict[str, object]) -> None:
+ """An identical prompt is not a strict extension: it must re-prefill."""
+ ids = list(case["prompt_ids"]) # type: ignore[arg-type]
+ max_new = 4
+
+ warm = Serve(binary, model)
+ try:
+ first_text, _ = warm.submit(token_prompt(ids), max_new)
+ second_text, reuse = warm.submit(token_prompt(ids), max_new)
+ finally:
+ warm.close()
+
+ if reuse != 0:
+ raise AssertionError(f"identical prompt reported reuse={reuse}")
+ if first_text != second_text:
+ raise AssertionError(
+ f"repeated prompt changed answer: {first_text!r} vs {second_text!r}"
+ )
+ print("PASS prefix repeat: identical prompt re-prefills, answer unchanged")
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--binary", required=True, type=Path)
+ parser.add_argument("--fixture", required=True, type=Path)
+ arguments = parser.parse_args()
+
+ reference = json.loads((arguments.fixture / "ref.json").read_text("utf-8"))
+ case = reference["cases"]["short"]
+
+ check_growing_conversation(arguments.binary, arguments.fixture, case)
+ check_repeated_prompt(arguments.binary, arguments.fixture, case)
+ check_divergent_prompt_resets(arguments.binary, arguments.fixture, case)
+ print("PASS DeepSeek V4 KV prefix reuse: all checks completed")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())