A 2.78-trillion-parameter Kimi K3 running inference on a single CPU in 8.24 GB of RAM. Portable C99: no BLAS, no framework, no GPU.
C avx2c99cpu-inferencedeep-learningfrom-scratchinference-enginekimi-k3linear-attentionllmllm-inferencemachine-learningmemory-efficientmixture-of-expertsmoemxfp4quantizationsimdsystems-programmingtransformerzero-dependencies
feat(chat): reuse the previous turn's state instead of re-prefilling
Fareed Khanfdf4505a7bcc
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0b2eac4..b9bdd1a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -175,7 +175,7 @@ jobs:run: |make CC=clang CFLAGS="-O1 -g -std=gnu99 -Wall -Wextra -fsanitize=address,undefined -fno-omit-frame-pointer" \LDFLAGS="-lm -fsanitize=address,undefined -lpsapi -lwinpthread" ARCH= \- bin/test_ops bin/test_cfg bin/test_cache bin/test_st bin/test_st_faults bin/test_sampler bin/test_json bin/k3_model+ bin/test_ops bin/test_cfg bin/test_cache bin/test_st bin/test_st_faults bin/test_sampler bin/test_json bin/k3_model bin/test_prefixcp /clang64/bin/libclang_rt.asan_dynamic-x86_64.dll /clang64/bin/libwinpthread-1.dll /clang64/bin/libc++.dll bin/- name: Run under sanitizersenv:@@ -194,6 +194,7 @@ jobs:./bin/test_json.exe./bin/test_sampler.exe./bin/k3_model.exe tests/fixtures+ ./bin/test_prefix.exe# CMakeLists.txt documents itself as staying interchangeable with the Make build, but# nothing in CI ever actually built or ran tests through CMake before this job -- that@@ -250,6 +251,8 @@ jobs:LDFLAGS="-lm -fsanitize=address,undefined" ARCH= \bin/test_ops bin/test_cfg bin/test_cache bin/test_st bin/test_st_faults bin/test_sampler bin/test_json \bin/test_model_stream bin/k3_model \+ bin/test_ops bin/test_cfg bin/test_cache bin/test_st bin/test_st_faults \+ bin/test_model_stream bin/k3_model bin/test_prefix \bin/bench_kernels \-j"$(nproc)"- name: Run under sanitizers@@ -270,6 +273,7 @@ jobs:./bin/test_sampler./bin/test_model_stream tests/fixtures/st./bin/k3_model tests/fixtures+ ./bin/test_prefix# The ms and GFLOP/s it prints are meaningless under -O1 with ASan interceptors# on every load. It is run for what ASan sees, not for what it reports../bin/bench_kernelsdiff --git a/CMakeLists.txt b/CMakeLists.txtindex 8b07183..2b95083 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -160,6 +160,9 @@ target_include_directories(test_state PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/cltarget_link_libraries(test_chat PRIVATE k3_chat)k3_add_test(test_sampler tests/unit/test_sampler.c)target_link_libraries(test_sampler PRIVATE k3_chat)+k3_add_test(test_prefix tests/unit/test_prefix.c)+# k3_prefix.h lives with the chat code; the test needs only that include directory.+target_include_directories(test_prefix PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/chat)k3_add_test(scale_test tests/unit/scale_test.c)k3_add_test(test_trunk tests/unit/test_trunk.c)k3_add_test(k3_model tests/unit/k3_model.c)@@ -200,6 +203,7 @@ add_test(NAME shard_faults COMMAND test_st_faults ${FIX}/st ${CMAKE_CURRENT_BINAadd_test(NAME json_refusals COMMAND test_json)add_test(NAME sampler COMMAND test_sampler)add_test(NAME state_file COMMAND test_state ${CMAKE_CURRENT_BINARY_DIR}/state)+add_test(NAME chat_prefix COMMAND test_prefix)add_test(NAME model_stream COMMAND test_model_stream ${FIX}/st)add_test(NAME ultra_cli_contractCOMMAND ${CMAKE_COMMAND} -DCLI=$<TARGET_FILE:k3_cli>diff --git a/Makefile b/Makefileindex 2a6a079..2543081 100644--- a/Makefile+++ b/Makefile@@ -156,7 +156,7 @@ CHAT_SRC := src/chat/k3_chat.c src/chat/k3_sampler.cCLI_BIN := $(BIN)/k3# Tests that need no checkpoint. These run in CI on every push.-UNIT_TESTS := test_ops test_cache test_st test_model_stream test_cfg test_tok test_chat test_sampler scale_test k3_model test_trunk test_st_faults test_state test_cancel test_json+UNIT_TESTS := test_ops test_cache test_st test_model_stream test_cfg test_tok test_chat test_sampler scale_test k3_model test_trunk test_st_faults test_prefix test_state test_cancel test_json# Tests that need real shards. Built and run by `make test-all` with SHARD_DIR set;# see the weights-test target below.WEIGHT_TESTS := test_expert test_real_layer@@ -227,6 +227,10 @@ $(BIN)/test_cancel: tests/unit/test_cancel.c src/cli/k3_cancel.h | $(BIN)# The state file format is plain stdio over arrays; no OpenMP, no platform calls.$(BIN)/test_state: tests/unit/test_state.c src/cli/k3_state.c | $(BIN)$(CC) -O2 -std=gnu99 $(WARN) $(INCLUDES) -Isrc/cli $^ -o $@ -lm+# The prefix record is a header of pure C99 with no engine dependency; the engine-level+# equivalence it relies on is GATE 3b of k3_model.+$(BIN)/test_prefix: tests/unit/test_prefix.c src/chat/k3_prefix.h | $(BIN)+ $(CC) -O2 -std=c99 $(WARN) -Wno-unused-function $(INCLUDES) $< -o $@# Allocates at REAL model widths (a ~1.8 GB KDA layer), so it needs the optimised build# rather than the portable C99 one the tokenizer and config tests use.@@ -316,6 +320,7 @@ test: $(CLI_BIN) $(TEST_BINS)echo " which ships with the checkpoint. Run: make test TOK_FILES=/path/to/k3model"; \fi@echo "== sampler =="; ./$(BIN)/test_sampler+ @echo "== chat prefix record =="; ./$(BIN)/test_prefix@echo "== real dimensions =="; ./$(BIN)/scale_test@echo "== trunk streaming =="; ./$(BIN)/test_trunk@echo "== full-model oracle =="; ./$(BIN)/k3_model $(FIXTURES)diff --git a/README.md b/README.mdindex 9083f4d..346beae 100644--- a/README.md+++ b/README.md@@ -457,7 +457,10 @@ canonical record, including `<think>…</think>` and `<response>…</response>`.Treat that file as sensitive: it can contain every user message and the complete assistantreasoning record, which K3 requires to continue a conversation faithfully. On restart theengine validates, re-renders, and re-prefills the transcript; it deliberately does not-serialize opaque KV, MLA, or KDA state. A supplied `--system` must exactly match an existing+serialize opaque KV, MLA, or KDA state. Within one session under `--incremental` the+state a turn built is kept, and the next turn prefills only its new tail when the+rendered transcript begins with exactly the ids that state was fed (the REPL prints how+many positions were reused); `/reset` or any other divergence starts over. A supplied `--system` must exactly match an existinginitial system record. Literal control-marker text in user messages is encoded as ordinarytext, never as an XTML control token.diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 30302a9..030ae5b 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -40,10 +40,14 @@ is a property the test suite depends on.## 6. Chat retained-state equivalence-Text chat now implements K3's official XTML formatting, JSONL restart, and safe complete-history re-prefill. The next optimization is retaining in-process KDA/MLA state across-REPL turns only after an equivalence gate proves that its token stream matches a full-re-prefill of the same transcript.+Text chat implements K3's official XTML formatting, JSONL restart, and, under+`--incremental`, retains the KDA/MLA state across REPL turns: the ids are recorded where+they are fed (`src/chat/k3_prefix.h`), and a turn whose rendered transcript begins with+exactly that record prefills only its tail. The equivalence gate that had to exist first+is GATE 3b of `tests/unit/k3_model.c`: turn 2 on top of turn 1's state must be+bit-identical -- logits, every KV row, the KDA state -- to a full prefill of the same+transcript. Any divergence (`/reset`, an edited history) starts over. Restart from a+`--history` file still re-prefills: no opaque state is serialised.## 7. Visiondiff --git a/src/chat/k3_prefix.h b/src/chat/k3_prefix.hnew file mode 100644index 0000000..dbe7f13--- /dev/null+++ b/src/chat/k3_prefix.h@@ -0,0 +1,138 @@+/* k3_prefix.h - reuse the state a previous REPL turn already built.+ *+ * WHY+ * The chat REPL re-prefilled the whole transcript every turn (k3_run.c chat_run:+ * "the first version re-prefills the full transcript for every REPL turn"). On a+ * streamed trunk every replayed position re-reads its experts from disk, so the cost+ * of turn N grew with turns 1..N-1, and the KV cache and KDA state that turn N-1 left+ * behind were zeroed and rebuilt from the same tokens.+ *+ * THE IDEA+ * After a turn the engine's state covers some number of positions. If the next+ * prompt BEGINS with exactly the token ids those positions were built from, the+ * 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 REPL's own bookkeeping+ * ("prompt + generated - 1"). Whether the last sampled token was fed back, whether a+ * turn stopped on <|end_of_msg|> or on --gen, whether a forward failed halfway: each+ * changes the answer, and getting it wrong does not crash, it 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) are exactly the token ids the current state was built from,+ * in position order. Everything else follows from it.+ *+ * ALL OR NOTHING+ * The KDA recurrent state is not positional: the matrix after N tokens cannot be+ * truncated to the matrix after N-3. So a prompt that shares only part of the record+ * reuses none of it. The one thing this must never do is answer from a state built+ * from different tokens, and the equivalence gate (tests/unit/k3_model.c GATE 3b)+ * requires the reused path to produce logits bit-identical to a full prefill.+ *+ * TAINT+ * An input that its token ids do not describe (nothing in the text REPL today; an+ * audio or image frame that reuses one placeholder id would be one) marks the state+ * tainted, and a tainted state is never reused.+ */+#ifndef K3_PREFIX_H+#define K3_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 */+} K3Prefix;++/* Size the record to the state it describes. 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 k3_prefix_alloc(K3Prefix *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, ShortConv and+ * recurrent buffers, so the two can never disagree. */+static inline void k3_prefix_clear(K3Prefix *p)+{+ if (!p) return;+ p->len = 0;+ p->tainted = 0;+}++static inline void k3_prefix_free(K3Prefix *p)+{+ if (!p) return;+ free(p->fed);+ p->fed = NULL;+ p->cap = p->len = 0;+ p->tainted = 0;+}++/* Grow the record to `cap`, keeping the first `keep` positions.+ *+ * The REPL grows its KV cache when a longer prompt arrives. If it grows by COPYING the+ * cached positions the record must survive with them, or reuse can never fire in the+ * one case it exists for: a conversation whose prompt gets longer every turn. Returns 0+ * if the record could not be preserved, and leaves it EMPTY rather than stale, so the+ * caller then treats the state as unreusable. */+static inline int k3_prefix_grow(K3Prefix *p, int cap, int keep)+{+ if (!p || cap <= 0) return 0;+ int *grown = (int *)calloc((size_t)cap, sizeof(int));+ if (!grown) { k3_prefix_free(p); return 0; }+ if (keep > p->len) keep = p->len;+ if (keep > cap) keep = cap;+ if (keep > 0 && p->fed) memcpy(grown, p->fed, (size_t)keep * sizeof(int));+ free(p->fed);+ p->fed = grown;+ p->cap = cap;+ p->len = keep > 0 ? keep : 0;+ return 1;+}++/* Record n tokens fed at absolute positions pos0..pos0+n-1. An out-of-range write drops+ * the record rather than truncating it: a partial record would claim coverage the state+ * does not have. A write that skips positions (pos0 > len) is the same lie and is+ * dropped for the same reason. */+static inline void k3_prefix_record(K3Prefix *p, const int *ids, int pos0, int n)+{+ if (!p || !p->fed || !ids || n <= 0 || pos0 < 0) return;+ if (pos0 + n > p->cap || pos0 > p->len) { 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 k3_prefix_taint(K3Prefix *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 k3_prefix_reuse(const K3Prefix *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 /* K3_PREFIX_H */diff --git a/src/cli/k3_run.c b/src/cli/k3_run.cindex 12af376..c326ace 100644--- a/src/cli/k3_run.c+++ b/src/cli/k3_run.c@@ -67,6 +67,7 @@#include "k3_trunk.h"#include "k3_tok.h" /* text in/out; the --ids path never touches it */#include "k3_chat.h"+#include "k3_prefix.h"#include "k3_sampler.h"#include "k3_cfg.h" /* read the checkpoint's own config rather than assuming it */#include "k3_cancel.h" /* first Ctrl-C stops at a safe point; see the header */@@ -263,7 +264,9 @@ static void usage(FILE *f)" --tok DIR directory with tiktoken.model and tokenizer_config.json\n""\n""chat (text-only Kimi K3 XTML):\n"-" --chat terminal REPL; uses the official XTML template\n"+" --chat terminal REPL; uses the official XTML template. With\n"+" --incremental each turn prefills only what the previous\n"+" turn did not already feed the model\n"" --system TEXT initial system message (stored in --history)\n"" --history PATH portable JSONL transcript; rebuilt on restart\n"" --temperature X turn chat sampling on, at this temperature (default: greedy)\n"@@ -549,8 +552,12 @@ static int forward(Weights *w, const K3Cfg *c, K3Cache *cache, const int *ids, i/* ----------------------------------------------------------------------- chat ----* Chat deliberately owns only transcript and decode policy. It calls the exact same* forward() and streamed K3Cache as batch mode, so --preset/--trunk-gb/--cache-gb keep- * their meanings. The first version re-prefills the full transcript for every REPL- * turn; retaining a live suffix is enabled only after its equivalence gate exists. */+ * their meanings. With --incremental a turn keeps the KV cache and recurrent state it+ * built, and the next turn prefills only its new tail when the rendered transcript+ * begins with exactly the ids that state was fed (src/chat/k3_prefix.h); any divergence,+ * including /reset, starts over. GATE 3b of tests/unit/k3_model.c holds the reused path+ * bit-identical to a full prefill. Full recompute (no --incremental) carries no state+ * and still re-runs the whole transcript every step. */static int chat_read_line(char **out){char *line = NULL; size_t cap = 0;@@ -595,9 +602,10 @@ static int chat_resize(int want, int *tmax, int nl, int maxb, size_t kper,float *ns = (float *)malloc(sc_need * sizeof(*ns));int *nq = (int *)malloc((size_t)(want + 8) * sizeof(*nq));float *nk = NULL, *nr = NULL;+ const size_t kvrow = (size_t)c->n_heads * (c->qk_nope + c->v_head);+ const size_t kvper = (size_t)want * kvrow;+ const size_t rpper = (size_t)want * c->qk_rope;if (w->kvc) {- const size_t kvper = (size_t)want * c->n_heads * (c->qk_nope + c->v_head);- const size_t rpper = (size_t)want * c->qk_rope;nk = (float *)calloc(kvper * (size_t)w->n_mla, sizeof(*nk));nr = (float *)calloc(rpper * (size_t)w->n_mla, sizeof(*nr));}@@ -607,7 +615,21 @@ static int chat_resize(int want, int *tmax, int nl, int maxb, size_t kper,}free(*h); free(*br); free(*sc); free(*seq);*h = nh; *br = nb; *sc = ns; *seq = nq;- if (w->kvc) { free(w->kvc); free(w->ropec); w->kvc = nk; w->ropec = nr; w->kv_cap = want; }+ if (w->kvc) {+ /* Grow by COPYING the positions already cached: they are what the next turn+ * reuses. Rows are [pos][H][kvd] per MLA layer, so the per-layer stride changes+ * with the capacity and the copy is one memcpy per layer, not one for the lot. */+ const size_t old_kv = (size_t)w->kv_cap * kvrow;+ const size_t old_rp = (size_t)w->kv_cap * c->qk_rope;+ const size_t keep = (size_t)(w->cached > 0 ? w->cached : 0);+ for (int mi = 0; mi < w->n_mla; mi++) {+ memcpy(nk + (size_t)mi * kvper, w->kvc + (size_t)mi * old_kv,+ keep * kvrow * sizeof(*nk));+ memcpy(nr + (size_t)mi * rpper, w->ropec + (size_t)mi * old_rp,+ keep * (size_t)c->qk_rope * sizeof(*nr));+ }+ free(w->kvc); free(w->ropec); w->kvc = nk; w->ropec = nr; w->kv_cap = want;+ }*tmax = want;(void)nl; (void)kper;return 0;@@ -618,7 +640,8 @@ static int chat_run(Tok *tok, const K3ChatTemplate *tmpl, K3ChatHistory *historyint incremental, int greedy, double temperature, double top_p,int top_k, uint64_t seed, Weights *w, const K3Cfg *c, K3Cache *cache,int nl, int *tmax, float **h, float **br, float *ks,- float **sc, float *lg, int **seq, int *outtok, int maxb, size_t kper)+ float **sc, float *lg, int **seq, int *outtok, int maxb, size_t kper,+ K3Prefix *pf){char err[512]; int turn = 0;int *prompt = *prompt_ref;@@ -639,28 +662,51 @@ static int chat_run(Tok *tok, const K3ChatTemplate *tmpl, K3ChatHistory *historyreturn 1;}}- if (chat_resize(need, tmax, nl, maxb, kper, w, c, h, br, sc, seq) != 0) return 1;+ {+ const int old_tmax = *tmax;+ if (chat_resize(need, tmax, nl, maxb, kper, w, c, h, br, sc, seq) != 0) return 1;+ /* The KV cache grew by copying its cached positions (chat_resize), so the+ * record grows with it. If the record cannot be preserved it is dropped and+ * this turn re-prefills; reuse is an optimisation, never a reason to fail. */+ if (*tmax != old_tmax && incremental) (void)k3_prefix_grow(pf, *tmax, w->cached);+ }memcpy(*seq, prompt, (size_t)np * sizeof(**seq));- memset(ks, 0, kper * (size_t)nl * sizeof(*ks));- if (incremental) {- const size_t kvper = (size_t)w->kv_cap * c->n_heads * (c->qk_nope + c->v_head);- const size_t rpper = (size_t)w->kv_cap * c->qk_rope;- memset(w->kvc, 0, kvper * (size_t)w->n_mla * sizeof(*w->kvc));- memset(w->ropec, 0, rpper * (size_t)w->n_mla * sizeof(*w->ropec));+ /* Reuse the previous turn's state only when this prompt begins with EXACTLY the+ * ids that state was built from, and the engine agrees about how many that is.+ * Anything else -- turn 1, /reset, an edited transcript, a failed forward last+ * turn -- clears every carried buffer and prefills from position 0, which is what+ * every turn did before. */+ int base = incremental ? k3_prefix_reuse(pf, prompt, np) : 0;+ if (base > 0 && base != w->cached) base = 0;+ if (base == 0) {+ memset(ks, 0, kper * (size_t)nl * sizeof(*ks));+ if (incremental) {+ const size_t kvper = (size_t)w->kv_cap * c->n_heads * (c->qk_nope + c->v_head);+ const size_t rpper = (size_t)w->kv_cap * c->qk_rope;+ memset(w->kvc, 0, kvper * (size_t)w->n_mla * sizeof(*w->kvc));+ memset(w->ropec, 0, rpper * (size_t)w->n_mla * sizeof(*w->ropec));+ k3_prefix_clear(pf);+ }+ w->cached = 0;}- w->cached = 0;+ if (incremental)+ printf("chat: %d of %d prompt positions already cached, prefilling %d\n",+ base, np, np - base);int T = np, nraw = 0, frc = 0;K3Sampler sampler; k3_sampler_init(&sampler, temperature, top_p, top_k, seed, (uint64_t)(turn + 1));const double t_turn0 = now_s();while (nraw < gen) {if (incremental) {+ /* Record ids WHERE THEY ARE FED (k3_prefix.h): the record, not the+ * REPL's arithmetic, is what the next turn's reuse decision consults. */if (!nraw) {- frc = forward(w, c, cache, *seq, T, lg, *sc, *h, *br, ks, NULL);- if (!frc) w->cached = T;+ frc = forward(w, c, cache, *seq + base, T - base, lg, *sc, *h, *br, ks, NULL);+ if (!frc) { w->cached = T; k3_prefix_record(pf, *seq + base, base, T - base); }} else {frc = forward(w, c, cache, *seq + T - 1, 1, lg, *sc, *h, *br, ks, NULL);- if (!frc) w->cached++;+ if (!frc) { w->cached++; k3_prefix_record(pf, *seq + T - 1, T - 1, 1); }}+ if (frc) k3_prefix_clear(pf); /* the state absorbed part of a failed step */} else {frc = forward(w, c, cache, *seq, T, lg, *sc, *h, *br, ks, NULL);}@@ -1551,10 +1597,16 @@ int main(int argc, char **argv)}if (chat) {+ /* The record of what the carried state was built from. Sized with the KV cache+ * and grown with it; if it cannot be allocated every turn simply re-prefills. */+ K3Prefix pf; memset(&pf, 0, sizeof pf);+ if (incremental && !k3_prefix_alloc(&pf, Tmax))+ fprintf(stderr, "chat: no memory for the prefix record; every turn will re-prefill\n");const int rc = chat_run(&tok, &chat_template, &chat_history, &chat_opts, history_path,&prompt, np, gen, incremental, greedy, temperature,top_p, top_k, seed, &w, &c, &cache, NL, &Tmax, &h, &br, ks,- &sc, lg, &seq, outtok, maxb, kper);+ &sc, lg, &seq, outtok, maxb, kper, &pf);+ k3_prefix_free(&pf);free(w.kvc); free(w.ropec); free(w.mla_slot);if (w.trunk) k3_trunk_close(w.trunk);k3_cache_free(&cache);diff --git a/tests/unit/k3_model.c b/tests/unit/k3_model.cindex 06080c9..b545f1f 100644--- a/tests/unit/k3_model.c+++ b/tests/unit/k3_model.c@@ -231,6 +231,41 @@ static void forward(Model *m, const K3Cfg *c, const int *ids, int T, float *logistatic int argmax_(const float *v, int n){ int b = 0; for (int i = 1; i < n; i++) if (v[i] > v[b]) b = i; return b; }+/* One INCREMENTAL forward: nT tokens at absolute positions base..base+nT-1 through the+ * cached decoder, carrying the KDA state in ks and the MLA KV cache in kvc/rpc, writing+ * the logits of the LAST new position to lg. This is the shape of every call the CLI's+ * --incremental and --chat paths make: the whole prompt once, then one token per step,+ * and (chat) the next turn's tail on top of the previous turn's state. */+static void inc_forward(Model *m, const K3Cfg *c, const int *ids, int base, int nT, int cap,+ float *kvc, float *rpc, size_t kvper, size_t rpper,+ float *ks, size_t kper, float *sc, float *h, float *br, float *lg)+{+ const int E = c->hidden;+ const int maxb = c->n_layers / c->attn_res_block + 2;+ for (int t = 0; t < nT; t++)+ memcpy(h + (size_t)t * E, m->embed + (size_t)ids[t] * E, (size_t)E * sizeof(float));+ memset(br, 0, (size_t)nT * (size_t)maxb * (size_t)E * sizeof(float));+ int nb = 0;+ for (int L = 0; L < c->n_layers; L++)+ k3_decoder_layer_inc(h, br, &nb, &m->lay[L], c, L, nT,+ ks + kper * (size_t)L, sc,+ kvc + kvper * (size_t)L, rpc + rpper * (size_t)L, base, cap);+ /* model-level aggregator and head, on the LAST new position */+ float *fold = sc, *src = fold + E;+ const int lastt = nT - 1;+ if (m->out_res_norm && m->out_res_proj) {+ for (int i = 0; i < E; i++) fold[i] = m->out_res_norm[i] * m->out_res_proj[i];+ for (int b = 0; b < nb; b++)+ memcpy(src + (size_t)b * E, br + ((size_t)lastt * maxb + b) * E,+ (size_t)E * sizeof(float));+ memcpy(src + (size_t)nb * E, h + (size_t)lastt * E, (size_t)E * sizeof(float));+ k3_attn_res(h + (size_t)lastt * E, src, fold, nb + 1, E, c->rms_eps);+ }+ float *nrm = sc;+ k3_rmsnorm(nrm, h + (size_t)lastt * E, m->final_norm, E, c->rms_eps);+ k3_matmul(lg, nrm, m->lm_head, E, c->vocab);+}+/* Config is read through k3_cfg.h, which never substitutes a default for a missing* field: it collects every absent key and refuses the load. Do not reintroduce a* defaulting reader here. A default turns "this program cannot understand this config"@@ -390,37 +425,8 @@ int main(int argc, char **argv)/* first call feeds the whole prompt, later calls feed one token */const int base = cached;const int nT = (step == 0) ? np : 1;- for (int t = 0; t < nT; t++)- memcpy(h_i + (size_t)t * c.hidden,- m->embed + (size_t)gi[base + t] * c.hidden,- (size_t)c.hidden * sizeof(float));- memset(br_i, 0, (size_t)nT * (size_t)maxb * (size_t)c.hidden * sizeof(float));- int nb_i = 0;- for (int L = 0; L < c.n_layers; L++)- k3_decoder_layer_inc(h_i, br_i, &nb_i, &m->lay[L], &c, L, nT,- ks_i + kper * (size_t)L, sc_i,- kvc + kvper * (size_t)L,- rpc + rpper * (size_t)L, base, T);- /* model-level aggregator and head, on the LAST new position */- float *fold = sc_i, *src = fold + c.hidden;- const int lastt = nT - 1;- if (m->out_res_norm && m->out_res_proj) {- for (int i = 0; i < c.hidden; i++)- fold[i] = m->out_res_norm[i] * m->out_res_proj[i];- for (int b = 0; b < nb_i; b++)- memcpy(src + (size_t)b * c.hidden,- br_i + ((size_t)lastt * maxb + b) * c.hidden,- (size_t)c.hidden * sizeof(float));- memcpy(src + (size_t)nb_i * c.hidden,- h_i + (size_t)lastt * c.hidden, (size_t)c.hidden * sizeof(float));- k3_attn_res(h_i + (size_t)lastt * c.hidden, src, fold,- nb_i + 1, c.hidden, c.rms_eps);- }- float *nrm = sc_i;- k3_rmsnorm(nrm, h_i + (size_t)lastt * c.hidden, m->final_norm,- c.hidden, c.rms_eps);- k3_matmul(lg_i, nrm, m->lm_head, c.hidden, c.vocab);-+ inc_forward(m, &c, gi + base, base, nT, T, kvc, rpc, kvper, rpper,+ ks_i, kper, sc_i, h_i, br_i, lg_i);cached = base + nT;if (cached >= T) break;gi[cached] = argmax_(lg_i, c.vocab);@@ -430,6 +436,56 @@ int main(int argc, char **argv)printf("GATE 3 incremental : %d/%d generated tokens match full_ids"" <- KV cache + carried KDA state\n", iok, T - np);gok = (iok == T - np) ? gok : -1; /* fail the verdict if incremental diverged */++ /* ---- GATE 3b: PREFIX REUSE across REPL turns --------------------------------+ * The chat REPL keeps the state a turn leaves behind and, when the next prompt+ * begins with exactly the ids that state was built from (src/chat/k3_prefix.h),+ * prefills only the tail instead of the whole transcript. That is sound only if+ * feeding [0..k) as a turn -- the prompt in one chunk, then one token per step,+ * exactly as chat_run feeds them -- and then [k..T) as the next turn's tail leaves+ * the engine in the SAME state as feeding [0..T) at once: every KV row, the KDA+ * matrix, the ShortConv history. Demand bit-identical logits at position T-1 and+ * bit-identical KV caches; token equality would hide a near tie or a stale row.+ * This is the equivalence gate the REPL's first version said it was waiting for+ * before retaining a live suffix. */+ int pr_ok = 0;+ {+ const int k = np + (T - np) / 2; /* turn 1 ends here; turn 2 adds T-k */+ float *kvc2 = (float *)calloc(kvper * (size_t)c.n_layers, sizeof(float));+ float *rpc2 = (float *)calloc(rpper * (size_t)c.n_layers, sizeof(float));+ float *ks2 = (float *)calloc(kper * (size_t)c.n_layers, sizeof(float));+ float *lg2 = (float *)malloc((size_t)c.vocab * sizeof(float));+ if (kvc2 && rpc2 && ks2 && lg2 && kvc && rpc && ks_i && lg_i && sc_i && h_i && br_i+ && k > np && k < T) {+ /* turn 1 as the REPL feeds it, on the state left by GATE 3, cleared */+ memset(kvc, 0, kvper * (size_t)c.n_layers * sizeof(float));+ memset(rpc, 0, rpper * (size_t)c.n_layers * sizeof(float));+ memset(ks_i, 0, kper * (size_t)c.n_layers * sizeof(float));+ inc_forward(m, &c, full, 0, np, T, kvc, rpc, kvper, rpper,+ ks_i, kper, sc_i, h_i, br_i, lg_i);+ for (int pos = np; pos < k; pos++)+ inc_forward(m, &c, full + pos, pos, 1, T, kvc, rpc, kvper, rpper,+ ks_i, kper, sc_i, h_i, br_i, lg_i);+ /* turn 2: only the tail, on top of turn 1's state */+ inc_forward(m, &c, full + k, k, T - k, T, kvc, rpc, kvper, rpper,+ ks_i, kper, sc_i, h_i, br_i, lg_i);+ /* the reference: the whole turn-2 prompt from a cleared state, which is+ * what the REPL did before */+ inc_forward(m, &c, full, 0, T, T, kvc2, rpc2, kvper, rpper,+ ks2, kper, sc_i, h_i, br_i, lg2);+ pr_ok = memcmp(lg_i, lg2, (size_t)c.vocab * sizeof(float)) == 0+ && memcmp(kvc, kvc2, kvper * (size_t)c.n_layers * sizeof(float)) == 0+ && memcmp(rpc, rpc2, rpper * (size_t)c.n_layers * sizeof(float)) == 0+ && memcmp(ks_i, ks2, kper * (size_t)c.n_layers * sizeof(float)) == 0;+ printf("GATE 3b prefix reuse : %s <- turn 2 (%d reused + %d new) "+ "bit-identical to a full %d-token prefill: logits, KV, KDA state\n",+ pr_ok ? "PASS" : "FAIL", k, T - k, T);+ } else {+ printf("GATE 3b prefix reuse : FAIL <- could not allocate or split\n");+ }+ free(kvc2); free(rpc2); free(ks2); free(lg2);+ }+ gok = pr_ok ? gok : -1;free(kvc); free(rpc); free(sc_i); free(h_i); free(br_i); free(ks_i); free(lg_i); free(gi);}diff --git a/tests/unit/test_prefix.c b/tests/unit/test_prefix.cnew file mode 100644index 0000000..1358482--- /dev/null+++ b/tests/unit/test_prefix.c@@ -0,0 +1,96 @@+/* test_prefix.c - the prefix record must say "all of it" or "none of it", never a lie.+ *+ * The record decides whether a REPL turn skips its prefill. Every wrong answer here is+ * silent at the engine level: reusing a state built from different tokens produces a+ * fluent reply to a conversation that did not happen. So each rule the header states+ * is pinned by a case that would pass a plausible wrong implementation:+ * - a longest-common-prefix implementation passes every "exact continuation" case+ * and fails "diverges at the last recorded token" (it would return 3, not 0);+ * - a counter-based implementation cannot tell a dropped record from a full one;+ * - a grow that forgets to keep the fed ids makes reuse impossible on turn 2.+ *+ * usage: test_prefix+ */+#include <stdio.h>+#include <string.h>++#include "k3_prefix.h"++static int g_fail = 0;++static void ck(int ok, const char *what)+{+ printf(" %s %s\n", ok ? "PASS" : "FAIL", what);+ if (!ok) g_fail++;+}++int main(void)+{+ K3Prefix p; memset(&p, 0, sizeof p);+ const int turn1[] = { 7, 8, 9, 10, 11 };+ const int turn2[] = { 7, 8, 9, 10, 11, 12, 13 }; /* exact continuation */+ const int other[] = { 7, 8, 9, 10, 99, 12, 13 }; /* diverges at the LAST fed id */+ const int shorter[] = { 7, 8, 9 }; /* a prefix of the record */+ const int same[] = { 7, 8, 9, 10, 11 }; /* equal to the record */++ printf("prefix record\n");++ /* ---- an empty or unallocated record never reuses ---- */+ ck(k3_prefix_reuse(&p, turn2, 7) == 0, "unallocated record reuses nothing");+ ck(k3_prefix_alloc(&p, 8) == 1, "alloc 8 positions");+ ck(k3_prefix_reuse(&p, turn2, 7) == 0, "empty record reuses nothing");++ /* ---- record as fed: the prompt in one chunk, then one token at a time ---- */+ k3_prefix_record(&p, turn1, 0, 3); /* prefill 3 */+ k3_prefix_record(&p, turn1 + 3, 3, 1); /* decode step */+ k3_prefix_record(&p, turn1 + 4, 4, 1); /* decode step */+ ck(p.len == 5, "five positions recorded across three feeds");++ /* ---- the contract: all of the record, or none of it ---- */+ ck(k3_prefix_reuse(&p, turn2, 7) == 5, "exact continuation reuses all 5");+ ck(k3_prefix_reuse(&p, other, 7) == 0, "divergence at position 4 reuses NONE (not 4)");+ ck(k3_prefix_reuse(&p, shorter, 3) == 0, "a prefix of the record cannot be rewound to");+ ck(k3_prefix_reuse(&p, same, 5) == 0, "an equal prompt needs at least one new token");++ /* ---- taint: a state the ids cannot describe is never reused ---- */+ k3_prefix_taint(&p);+ ck(k3_prefix_reuse(&p, turn2, 7) == 0, "tainted state reuses nothing");+ k3_prefix_clear(&p);+ ck(p.len == 0 && !p.tainted, "clear drops both the record and the taint");++ /* ---- grow keeps the fed ids, so a longer prompt on turn 2 can still reuse ---- */+ k3_prefix_record(&p, turn1, 0, 5);+ ck(k3_prefix_grow(&p, 64, 5) == 1 && p.cap == 64 && p.len == 5,+ "grow to 64 keeps 5 positions");+ ck(k3_prefix_reuse(&p, turn2, 7) == 5, "reuse still fires after growth");+ ck(k3_prefix_grow(&p, 64, 3) == 1 && p.len == 3,+ "grow keeping fewer positions shortens the record to what was kept");+ ck(k3_prefix_reuse(&p, turn2, 7) == 3, "a shortened record reuses only what it covers");++ /* ---- a write the record cannot hold drops it rather than truncating it ---- */+ ck(k3_prefix_alloc(&p, 4) == 1, "realloc to 4 positions");+ k3_prefix_record(&p, turn1, 0, 5);+ ck(p.len == 0, "5 tokens into a 4-slot record leave it EMPTY, not 4 long");+ k3_prefix_record(&p, turn1, 0, 2);+ k3_prefix_record(&p, turn1 + 3, 3, 1); /* skips position 2 */+ ck(p.len == 0, "a feed that skips a position drops the record");++ /* ---- re-recording an earlier position rewrites it (restart after divergence) ---- */+ ck(k3_prefix_alloc(&p, 8) == 1, "realloc to 8 positions");+ k3_prefix_record(&p, turn1, 0, 5);+ k3_prefix_clear(&p);+ k3_prefix_record(&p, other, 0, 7);+ ck(k3_prefix_reuse(&p, other, 7) == 0 && p.len == 7,+ "after a restart the record describes the new sequence");+ {+ const int other_cont[] = { 7, 8, 9, 10, 99, 12, 13, 14 };+ ck(k3_prefix_reuse(&p, other_cont, 8) == 7, "and its continuation reuses all 7");+ ck(k3_prefix_reuse(&p, turn2, 7) == 0, "while the old sequence no longer matches");+ }++ k3_prefix_free(&p);+ ck(p.fed == NULL && p.cap == 0 && p.len == 0, "free resets everything");++ printf("\n%s\n", g_fail ? "PREFIX RECORD TESTS FAILED" : "PREFIX RECORD TESTS PASSED");+ return g_fail ? 1 : 0;+}