Skip to content

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.

feat(cli): checksum the state file and publish it with an atomic rename

Fareed Khan16843c5b4a73
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8ddf12b..8b07183 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -116,7 +116,7 @@ if(K3_OPENMP_TARGET)
endif()
# ------------------------------------------------------------------------------ cli --
-add_executable(k3_cli src/cli/k3_run.c)
+add_executable(k3_cli src/cli/k3_run.c src/cli/k3_state.c)
set_target_properties(k3_cli PROPERTIES OUTPUT_NAME k3)
# Chat is deliberately separate from the inference library: it is CLI policy and
@@ -154,6 +154,9 @@ k3_add_test(test_st_faults tests/unit/test_st_faults.c)
k3_add_test(test_json tests/unit/test_json.c)
k3_add_test(test_cancel tests/unit/test_cancel.c)
target_include_directories(test_cancel PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/cli)
+k3_add_test(test_state tests/unit/test_state.c)
+target_sources(test_state PRIVATE src/cli/k3_state.c)
+target_include_directories(test_state PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/cli)
target_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)
@@ -196,6 +199,7 @@ add_test(NAME safetensors COMMAND test_st ${FIX}/st ${CMAKE_CURRENT_BINARY_DIR
add_test(NAME shard_faults COMMAND test_st_faults ${FIX}/st ${CMAKE_CURRENT_BINARY_DIR}/stfault)
add_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 model_stream COMMAND test_model_stream ${FIX}/st)
add_test(NAME ultra_cli_contract
COMMAND ${CMAKE_COMMAND} -DCLI=$<TARGET_FILE:k3_cli>
diff --git a/Makefile b/Makefile
index 19048d2..2a6a079 100644
--- a/Makefile
+++ b/Makefile
@@ -151,12 +151,12 @@ ENGINE_SRC := src/core/k3_ops.c \
src/model/k3_bind.c
ENGINE_OBJ := $(patsubst %.c,$(BUILD)/%.o,$(ENGINE_SRC))
-CLI_SRC := src/cli/k3_run.c
+CLI_SRC := src/cli/k3_run.c src/cli/k3_state.c
CHAT_SRC := src/chat/k3_chat.c src/chat/k3_sampler.c
CLI_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_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_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
@@ -224,6 +224,9 @@ $(BIN)/test_cfg: tests/unit/test_cfg.c src/core/k3_ops.c | $(BIN)
# Signal handling only; no OpenMP, no platform calls beyond signal() and write().
$(BIN)/test_cancel: tests/unit/test_cancel.c src/cli/k3_cancel.h | $(BIN)
$(CC) -O2 -std=gnu99 $(WARN) $(INCLUDES) -Isrc/cli $< -o $@
+# 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
# 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.
@@ -279,6 +282,7 @@ test: $(CLI_BIN) $(TEST_BINS)
@echo "== model streaming =="; ./$(BIN)/test_model_stream $(FIXTURES)/st
@echo "== shard faults =="; ./$(BIN)/test_st_faults $(FIXTURES)/st $(BUILD)/stfault
@echo "== json refusals =="; ./$(BIN)/test_json
+ @echo "== state file =="; ./$(BIN)/test_state $(BUILD)/state
@echo "== config reader =="; ./$(BIN)/test_cfg fixture $(FIXTURES)/ref_k3.json
@echo "== interrupt contract =="; ./$(BIN)/test_cancel
@echo "== config refusals =="; \
diff --git a/src/cli/k3_run.c b/src/cli/k3_run.c
index 58ea8ed..12af376 100644
--- a/src/cli/k3_run.c
+++ b/src/cli/k3_run.c
@@ -70,6 +70,7 @@
#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 */
+#include "k3_state.h" /* --save-state / --load-state file format */
static double now_s(void)
{
@@ -157,42 +158,6 @@ static void json_string(FILE *f, const char *s)
fputc('"', f);
}
-/* ------------------------------------------------------- conversation state ----
- * Everything the engine carries between tokens, on disk. The point is turn two of a
- * conversation: without this, resuming re-reads the whole prompt through all 93 layers,
- * which on a streamed trunk costs minutes; with it, a resumed session pays only for the
- * tokens actually new.
- *
- * Three things are carried, and only three: the KDA recurrent matrices plus ShortConv
- * history (fixed size, independent of context), the MLA KV cache, and the shared rope
- * rows. The AttnRes block buffer is NOT carried because forward() clears it on entry and
- * rebuilds it from the layer outputs every pass; saving it would be saving scratch.
- *
- * The KV cache is stored position-major inside each MLA layer's slice, so only the
- * OCCUPIED positions are written and a resumed run may size its cache differently. The
- * header carries a config fingerprint: restoring state built by a different architecture
- * would produce fluent, wrong output with nothing to indicate it, which is the one
- * failure mode this engine refuses to have. */
-#define K3_STATE_MAGIC "K3ST"
-#define K3_STATE_VER 1
-
-typedef struct {
- char magic[4];
- int32_t version;
- int32_t fp[12]; /* config fingerprint */
- int32_t n_bound, n_mla, cached, nseq;
- int64_t kper; /* KDA+conv floats per layer */
- int64_t kvpp, ropepp; /* KV / rope floats per position, per MLA layer */
-} K3StateHdr;
-
-static void k3_state_fp(const K3Cfg *c, int32_t *fp)
-{
- fp[0] = c->hidden; fp[1] = c->n_layers; fp[2] = c->vocab;
- fp[3] = c->kda_heads; fp[4] = c->kda_head_dim; fp[5] = c->conv_k;
- fp[6] = c->n_heads; fp[7] = c->qk_nope; fp[8] = c->qk_rope;
- fp[9] = c->v_head; fp[10] = c->n_experts; fp[11] = c->topk;
-}
-
#define K3_SPEC_MAX 8
/* Longest-suffix n-gram drafting for --spec: if the last n ids (n=3, then 2) already
* appeared earlier in the sequence, propose the ids that followed them there. Costs
@@ -200,106 +165,6 @@ static void k3_state_fp(const K3Cfg *c, int32_t *fp)
* drafts are PROPOSALS only; batched greedy verification accepts precisely the prefix
* the model itself would have emitted, so the output stream is identical to serial
* decode by construction, and the A/B gate checks it. */
-/* Reads only the header, so the caller can size buffers before committing to a load. */
-static int k3_state_peek(const char *path, K3StateHdr *hd)
-{
- FILE *f = fopen(path, "rb");
- if (!f) { perror(path); return -1; }
- const size_t got = fread(hd, 1, sizeof *hd, f);
- fclose(f);
- if (got != sizeof *hd || memcmp(hd->magic, K3_STATE_MAGIC, 4) != 0) {
- fprintf(stderr, "%s is not a k3 state file\n", path);
- return -1;
- }
- if (hd->version != K3_STATE_VER) {
- fprintf(stderr, "%s is state version %d, this build writes %d\n",
- path, hd->version, K3_STATE_VER);
- return -1;
- }
- return 0;
-}
-
-static int k3_state_load(const char *path, const K3Cfg *c, const K3StateHdr *hd,
- int *seq, float *ks, float *kvc, float *ropec,
- int n_bound, int n_mla, int kv_cap)
-{
- int32_t fp[12];
- k3_state_fp(c, fp);
- if (memcmp(fp, hd->fp, sizeof fp) != 0) {
- fprintf(stderr, "REFUSING: %s was written by a different model architecture.\n"
- " Restoring it would produce fluent, wrong output.\n", path);
- return -1;
- }
- if (hd->n_bound != n_bound || hd->n_mla != n_mla) {
- fprintf(stderr, "REFUSING: %s holds %d bound layers and %d MLA layers, "
- "this run has %d and %d\n",
- path, hd->n_bound, hd->n_mla, n_bound, n_mla);
- return -1;
- }
- if (hd->cached > kv_cap) {
- fprintf(stderr, "REFUSING: %s holds %d positions, this run's KV cache is %d.\n"
- " Raise --gen or shorten the prompt.\n", path, hd->cached, kv_cap);
- return -1;
- }
- FILE *f = fopen(path, "rb");
- if (!f) { perror(path); return -1; }
- if (fseek(f, (long)sizeof *hd, SEEK_SET) != 0) { fclose(f); return -1; }
-
- int rc = 0;
- if (fread(seq, sizeof(int), (size_t)hd->nseq, f) != (size_t)hd->nseq) rc = -1;
- if (!rc && fread(ks, sizeof(float), (size_t)hd->kper * n_bound, f)
- != (size_t)hd->kper * (size_t)n_bound) rc = -1;
- /* Position-major inside each layer slice, so a differently-sized destination cache
- * is written slice by slice rather than as one block. */
- for (int mi = 0; !rc && mi < n_mla; mi++) {
- float *dst = kvc + (size_t)mi * kv_cap * hd->kvpp;
- const size_t n = (size_t)hd->cached * hd->kvpp;
- if (fread(dst, sizeof(float), n, f) != n) rc = -1;
- }
- for (int mi = 0; !rc && mi < n_mla; mi++) {
- float *dst = ropec + (size_t)mi * kv_cap * hd->ropepp;
- const size_t n = (size_t)hd->cached * hd->ropepp;
- if (fread(dst, sizeof(float), n, f) != n) rc = -1;
- }
- fclose(f);
- if (rc) fprintf(stderr, "%s is truncated\n", path);
- return rc;
-}
-
-static int k3_state_save(const char *path, const K3Cfg *c, const int *seq, int nseq,
- const float *ks, const float *kvc, const float *ropec,
- int n_bound, int n_mla, int kv_cap, int cached,
- int64_t kper, int64_t kvpp, int64_t ropepp)
-{
- FILE *f = fopen(path, "wb");
- if (!f) { perror(path); return -1; }
- K3StateHdr hd;
- memset(&hd, 0, sizeof hd);
- memcpy(hd.magic, K3_STATE_MAGIC, 4);
- hd.version = K3_STATE_VER;
- k3_state_fp(c, hd.fp);
- hd.n_bound = n_bound; hd.n_mla = n_mla; hd.cached = cached; hd.nseq = nseq;
- hd.kper = kper; hd.kvpp = kvpp; hd.ropepp = ropepp;
-
- int rc = 0;
- if (fwrite(&hd, sizeof hd, 1, f) != 1) rc = -1;
- if (!rc && fwrite(seq, sizeof(int), (size_t)nseq, f) != (size_t)nseq) rc = -1;
- if (!rc && fwrite(ks, sizeof(float), (size_t)kper * n_bound, f)
- != (size_t)kper * (size_t)n_bound) rc = -1;
- for (int mi = 0; !rc && mi < n_mla; mi++) {
- const float *src = kvc + (size_t)mi * kv_cap * kvpp;
- const size_t n = (size_t)cached * kvpp;
- if (fwrite(src, sizeof(float), n, f) != n) rc = -1;
- }
- for (int mi = 0; !rc && mi < n_mla; mi++) {
- const float *src = ropec + (size_t)mi * kv_cap * ropepp;
- const size_t n = (size_t)cached * ropepp;
- if (fwrite(src, sizeof(float), n, f) != n) rc = -1;
- }
- if (fclose(f) != 0) rc = -1;
- if (rc) fprintf(stderr, "failed writing %s\n", path);
- return rc;
-}
static int spec_draft(const int *seq, int T, int cap, int *out)
{
diff --git a/src/cli/k3_state.c b/src/cli/k3_state.c
new file mode 100644
index 0000000..655b38f
--- /dev/null
+++ b/src/cli/k3_state.c
@@ -0,0 +1,216 @@
+/* k3_state.c - see k3_state.h. */
+#define _POSIX_C_SOURCE 200809L
+#include "k3_portable_io.h" /* fsync() and rename() shims for MinGW; see the header */
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include "k3_state.h"
+
+void k3_state_fp(const K3Cfg *c, int32_t *fp)
+{
+ fp[0] = c->hidden; fp[1] = c->n_layers; fp[2] = c->vocab;
+ fp[3] = c->kda_heads; fp[4] = c->kda_head_dim; fp[5] = c->conv_k;
+ fp[6] = c->n_heads; fp[7] = c->qk_nope; fp[8] = c->qk_rope;
+ fp[9] = c->v_head; fp[10] = c->n_experts; fp[11] = c->topk;
+}
+
+/* FNV-1a folded eight bytes at a time. Each step is xor with the next word then a
+ * multiply by an odd constant, and multiplying by an odd number is a bijection mod
+ * 2^64, so a change to any single word always changes the running value, and every
+ * later step maps distinct values to distinct values. One damaged byte anywhere in the
+ * payload is therefore always caught; this is corruption detection, not an integrity
+ * proof against an adversary, and it does not claim to be. Eight bytes per step rather
+ * than one because the payload is 0.63 GB of recurrent state plus the KV cache at full
+ * scale, hashed once on save and once on load. */
+uint64_t k3_state_hash(uint64_t h, const void *p, size_t n)
+{
+ const unsigned char *b = (const unsigned char *)p;
+ size_t i = 0;
+ for (; i + 8 <= n; i += 8) {
+ uint64_t w;
+ memcpy(&w, b + i, 8);
+ h ^= w;
+ h *= 0x100000001b3ULL;
+ }
+ for (; i < n; i++) {
+ h ^= b[i];
+ h *= 0x100000001b3ULL;
+ }
+ return h;
+}
+
+int k3_state_peek(const char *path, K3StateHdr *hd)
+{
+ FILE *f = fopen(path, "rb");
+ if (!f) { perror(path); return -1; }
+ const size_t got = fread(hd, 1, sizeof *hd, f);
+ fclose(f);
+ if (got != sizeof *hd || memcmp(hd->magic, K3_STATE_MAGIC, 4) != 0) {
+ fprintf(stderr, "%s is not a k3 state file\n", path);
+ return -1;
+ }
+ if (hd->version != K3_STATE_VER) {
+ fprintf(stderr, "%s is state version %d, this build writes %d\n",
+ path, hd->version, K3_STATE_VER);
+ return -1;
+ }
+ return 0;
+}
+
+/* fread that folds what it read into the running hash. */
+static size_t hread(void *dst, size_t sz, size_t n, FILE *f, uint64_t *h)
+{
+ const size_t got = fread(dst, sz, n, f);
+ *h = k3_state_hash(*h, dst, got * sz);
+ return got;
+}
+
+int k3_state_load(const char *path, const K3Cfg *c, const K3StateHdr *hd,
+ int *seq, float *ks, float *kvc, float *ropec,
+ int n_bound, int n_mla, int kv_cap)
+{
+ int32_t fp[12];
+ k3_state_fp(c, fp);
+ if (memcmp(fp, hd->fp, sizeof fp) != 0) {
+ fprintf(stderr, "REFUSING: %s was written by a different model architecture.\n"
+ " Restoring it would produce fluent, wrong output.\n", path);
+ return -1;
+ }
+ if (hd->n_bound != n_bound || hd->n_mla != n_mla) {
+ fprintf(stderr, "REFUSING: %s holds %d bound layers and %d MLA layers, "
+ "this run has %d and %d\n",
+ path, hd->n_bound, hd->n_mla, n_bound, n_mla);
+ return -1;
+ }
+ if (hd->cached > kv_cap) {
+ fprintf(stderr, "REFUSING: %s holds %d positions, this run's KV cache is %d.\n"
+ " Raise --gen or shorten the prompt.\n", path, hd->cached, kv_cap);
+ return -1;
+ }
+ FILE *f = fopen(path, "rb");
+ if (!f) { perror(path); return -1; }
+ if (fseek(f, (long)sizeof *hd, SEEK_SET) != 0) { fclose(f); return -1; }
+
+ int rc = 0;
+ uint64_t h = K3_STATE_HASH_INIT;
+ if (hread(seq, sizeof(int), (size_t)hd->nseq, f, &h) != (size_t)hd->nseq) rc = -1;
+ if (!rc && hread(ks, sizeof(float), (size_t)hd->kper * n_bound, f, &h)
+ != (size_t)hd->kper * (size_t)n_bound) rc = -1;
+ /* Position-major inside each layer slice, so a differently-sized destination cache
+ * is written slice by slice rather than as one block. */
+ for (int mi = 0; !rc && mi < n_mla; mi++) {
+ float *dst = kvc + (size_t)mi * kv_cap * hd->kvpp;
+ const size_t n = (size_t)hd->cached * hd->kvpp;
+ if (hread(dst, sizeof(float), n, f, &h) != n) rc = -1;
+ }
+ for (int mi = 0; !rc && mi < n_mla; mi++) {
+ float *dst = ropec + (size_t)mi * kv_cap * hd->ropepp;
+ const size_t n = (size_t)hd->cached * hd->ropepp;
+ if (hread(dst, sizeof(float), n, f, &h) != n) rc = -1;
+ }
+ fclose(f);
+ if (rc) { fprintf(stderr, "%s is truncated\n", path); return rc; }
+ /* Every read came back full, so the file has the right SHAPE. This is the check
+ * that sees a wrong BYTE: a flipped bit in a recurrent matrix restores cleanly and
+ * decodes fluently, and nothing after this point can tell. */
+ if (h != hd->payload_hash) {
+ fprintf(stderr, "REFUSING: %s does not hash to what its header says\n"
+ " (header %016llx, contents %016llx). The payload is damaged;\n"
+ " restoring it would produce fluent, wrong output.\n",
+ path, (unsigned long long)hd->payload_hash, (unsigned long long)h);
+ return -1;
+ }
+ return 0;
+}
+
+/* fwrite that folds what it wrote into the running hash. */
+static size_t hwrite(const void *src, size_t sz, size_t n, FILE *f, uint64_t *h)
+{
+ const size_t put = fwrite(src, sz, n, f);
+ *h = k3_state_hash(*h, src, put * sz);
+ return put;
+}
+
+int k3_state_save(const char *path, const K3Cfg *c, const int *seq, int nseq,
+ const float *ks, const float *kvc, const float *ropec,
+ int n_bound, int n_mla, int kv_cap, int cached,
+ int64_t kper, int64_t kvpp, int64_t ropepp)
+{
+ /* Staged next to the destination and published by rename, the same way the chat
+ * history writer does it (k3_chat_history_save). Opening the destination directly
+ * truncated it first, so a crash or a full disk mid-save left a file that was too
+ * short to load, and the previous good state was already gone. Now the destination
+ * changes exactly once, from the old complete file to the new complete file. */
+ char tmp[4096];
+ if (snprintf(tmp, sizeof tmp, "%s.tmp.XXXXXX", path) >= (int)sizeof tmp) {
+ fprintf(stderr, "%s: path too long\n", path);
+ return -1;
+ }
+ const int fd = mkstemp(tmp);
+ if (fd < 0) {
+ fprintf(stderr, "cannot stage %s next to %s: %s\n", tmp, path, strerror(errno));
+ return -1;
+ }
+#ifndef _WIN32
+ /* mkstemp creates 0600. The file used to be created by fopen, i.e. 0666 less the
+ * umask, and a saved state should stay as readable as before: give the temp file
+ * that mode now, so the rename publishes it. Windows has no group/other bits. */
+ {
+ const mode_t um = umask(0);
+ umask(um);
+ if (fchmod(fd, 0666 & ~um) != 0) {
+ fprintf(stderr, "cannot set the mode of %s: %s\n", tmp, strerror(errno));
+ close(fd); unlink(tmp);
+ return -1;
+ }
+ }
+#endif
+ FILE *f = fdopen(fd, "wb");
+ if (!f) { close(fd); unlink(tmp); perror(path); return -1; }
+
+ K3StateHdr hd;
+ memset(&hd, 0, sizeof hd);
+ memcpy(hd.magic, K3_STATE_MAGIC, 4);
+ hd.version = K3_STATE_VER;
+ k3_state_fp(c, hd.fp);
+ hd.n_bound = n_bound; hd.n_mla = n_mla; hd.cached = cached; hd.nseq = nseq;
+ hd.kper = kper; hd.kvpp = kvpp; hd.ropepp = ropepp;
+
+ /* The hash is known only after the payload has been walked, and walking it twice
+ * would double the memory traffic of a save, so the header goes out first with the
+ * hash still zero and is rewritten in place at the end. The file is still the temp
+ * file at that point; nothing observes the intermediate header. */
+ int rc = 0;
+ uint64_t h = K3_STATE_HASH_INIT;
+ if (fwrite(&hd, sizeof hd, 1, f) != 1) rc = -1;
+ if (!rc && hwrite(seq, sizeof(int), (size_t)nseq, f, &h) != (size_t)nseq) rc = -1;
+ if (!rc && hwrite(ks, sizeof(float), (size_t)kper * n_bound, f, &h)
+ != (size_t)kper * (size_t)n_bound) rc = -1;
+ for (int mi = 0; !rc && mi < n_mla; mi++) {
+ const float *src = kvc + (size_t)mi * kv_cap * kvpp;
+ const size_t n = (size_t)cached * kvpp;
+ if (hwrite(src, sizeof(float), n, f, &h) != n) rc = -1;
+ }
+ for (int mi = 0; !rc && mi < n_mla; mi++) {
+ const float *src = ropec + (size_t)mi * kv_cap * ropepp;
+ const size_t n = (size_t)cached * ropepp;
+ if (hwrite(src, sizeof(float), n, f, &h) != n) rc = -1;
+ }
+ hd.payload_hash = h;
+ if (!rc && fseek(f, 0, SEEK_SET) != 0) rc = -1;
+ if (!rc && fwrite(&hd, sizeof hd, 1, f) != 1) rc = -1;
+ if (!rc && fflush(f) != 0) rc = -1;
+ if (!rc && fsync(fd) != 0) rc = -1;
+ if (fclose(f) != 0) rc = -1;
+ if (!rc && rename(tmp, path) != 0) rc = -1;
+ if (rc) {
+ fprintf(stderr, "failed writing %s: %s\n", path, strerror(errno));
+ unlink(tmp);
+ }
+ return rc;
+}
diff --git a/src/cli/k3_state.h b/src/cli/k3_state.h
new file mode 100644
index 0000000..a5f2ec9
--- /dev/null
+++ b/src/cli/k3_state.h
@@ -0,0 +1,71 @@
+/* k3_state.h - the conversation state file behind --save-state / --load-state.
+ *
+ * Everything the engine carries between tokens, on disk. The point is turn two of a
+ * conversation: without this, resuming re-reads the whole prompt through all 93 layers,
+ * which on a streamed trunk costs minutes; with it, a resumed session pays only for the
+ * tokens actually new.
+ *
+ * Three things are carried, and only three: the KDA recurrent matrices plus ShortConv
+ * history (fixed size, independent of context), the MLA KV cache, and the shared rope
+ * rows. The AttnRes block buffer is NOT carried because forward() clears it on entry and
+ * rebuilds it from the layer outputs every pass; saving it would be saving scratch.
+ *
+ * The KV cache is stored position-major inside each MLA layer's slice, so only the
+ * OCCUPIED positions are written and a resumed run may size its cache differently. The
+ * header carries a config fingerprint: restoring state built by a different architecture
+ * would produce fluent, wrong output with nothing to indicate it, which is the one
+ * failure mode this engine refuses to have.
+ *
+ * This lives outside k3_run.c so the format has a test that needs no checkpoint
+ * (tests/unit/test_state.c): the arrays are just floats and ints of the sizes the header
+ * declares, and every refusal below is reachable with synthetic ones. */
+#ifndef K3_STATE_H
+#define K3_STATE_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include "k3.h"
+
+#define K3_STATE_MAGIC "K3ST"
+/* Version 2 adds payload_hash. A version 1 file is refused rather than read with a
+ * guessed layout; state files are session artifacts, written and read by the same
+ * binary within one conversation, not a long-lived format. */
+#define K3_STATE_VER 2
+
+typedef struct {
+ char magic[4];
+ int32_t version;
+ int32_t fp[12]; /* config fingerprint */
+ int32_t n_bound, n_mla, cached, nseq;
+ int64_t kper; /* KDA+conv floats per layer */
+ int64_t kvpp, ropepp; /* KV / rope floats per position, per MLA layer */
+ /* k3_state_hash over the payload bytes in file order: seq, ks, then the KV and
+ * rope slices. Checked on load; a file whose every fread comes back full can still
+ * hold a damaged matrix, and this is the only check that sees it. */
+ uint64_t payload_hash;
+} K3StateHdr;
+
+#define K3_STATE_HASH_INIT 0xcbf29ce484222325ULL /* FNV-1a offset basis */
+uint64_t k3_state_hash(uint64_t h, const void *p, size_t n);
+
+void k3_state_fp(const K3Cfg *c, int32_t *fp);
+
+/* Reads only the header, so the caller can size buffers before committing to a load.
+ * Returns 0, or -1 after printing why the file was refused. */
+int k3_state_peek(const char *path, K3StateHdr *hd);
+
+/* Restores the payload described by a header k3_state_peek accepted. seq must hold
+ * hd->nseq ints, ks hd->kper * n_bound floats, kvc and ropec n_mla slices of kv_cap
+ * positions each. Returns 0, or -1 after printing why; on -1 the arrays are not to be
+ * trusted. */
+int k3_state_load(const char *path, const K3Cfg *c, const K3StateHdr *hd,
+ int *seq, float *ks, float *kvc, float *ropec,
+ int n_bound, int n_mla, int kv_cap);
+
+int k3_state_save(const char *path, const K3Cfg *c, const int *seq, int nseq,
+ const float *ks, const float *kvc, const float *ropec,
+ int n_bound, int n_mla, int kv_cap, int cached,
+ int64_t kper, int64_t kvpp, int64_t ropepp);
+
+#endif /* K3_STATE_H */
diff --git a/tests/unit/test_state.c b/tests/unit/test_state.c
new file mode 100644
index 0000000..0e4fd1d
--- /dev/null
+++ b/tests/unit/test_state.c
@@ -0,0 +1,337 @@
+/* test_state.c - the --save-state / --load-state file must round-trip exactly and
+ * refuse anything else loudly.
+ *
+ * WHY THIS FILE EXISTS
+ * A state file is restored straight into the KDA recurrent matrices and the MLA KV
+ * cache, and decode continues from whatever it holds. Nothing downstream can tell a
+ * good restore from a bad one: the tokens come out fluent either way. So the reader
+ * is the only place a damaged file can be caught, and until now it had no test that
+ * needed no checkpoint. The arrays here are synthetic; the header logic, the
+ * position-major KV slices, and every refusal are the real code (src/cli/k3_state.c).
+ *
+ * usage: test_state <work_dir>
+ */
+#define _POSIX_C_SOURCE 200809L
+
+#include "k3_portable_io.h" /* mkdir() shim for MinGW; see the header for why */
+
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <dirent.h>
+#include <time.h>
+#ifndef _WIN32
+#include <unistd.h>
+#endif
+
+#include "k3_state.h"
+
+static int g_fail = 0;
+
+static void ck(int ok, const char *what, const char *detail)
+{
+ printf(" %s %-40s %s\n", ok ? "PASS" : "FAIL", what, detail ? detail : "");
+ if (!ok) g_fail++;
+}
+
+static unsigned char *slurp(const char *path, size_t *n)
+{
+ FILE *f = fopen(path, "rb");
+ if (!f) return NULL;
+ fseek(f, 0, SEEK_END);
+ long sz = ftell(f);
+ fseek(f, 0, SEEK_SET);
+ if (sz < 0) { fclose(f); return NULL; }
+ unsigned char *b = (unsigned char *)malloc((size_t)sz + 1);
+ if (!b || fread(b, 1, (size_t)sz, f) != (size_t)sz) { free(b); fclose(f); return NULL; }
+ fclose(f);
+ *n = (size_t)sz;
+ return b;
+}
+
+static int spit(const char *path, const unsigned char *b, size_t n)
+{
+ FILE *f = fopen(path, "wb");
+ if (!f) return -1;
+ const int ok = fwrite(b, 1, n, f) == n;
+ return (fclose(f) == 0 && ok) ? 0 : -1;
+}
+
+/* Small but not degenerate: two MLA layers, four bound layers, a KV cache with more
+ * capacity than positions in use, so the position-major slicing is exercised. */
+enum { N_BOUND = 4, N_MLA = 2, KV_CAP = 16, CACHED = 5, NSEQ = 6, KPER = 100 };
+
+static void cfg_fill(K3Cfg *c)
+{
+ memset(c, 0, sizeof *c);
+ c->hidden = 64; c->n_layers = 4; c->vocab = 256;
+ c->kda_heads = 2; c->kda_head_dim = 8; c->conv_k = 4;
+ c->n_heads = 2; c->qk_nope = 8; c->qk_rope = 4; c->v_head = 8;
+ c->n_experts = 4; c->topk = 2;
+}
+
+typedef struct {
+ int seq[NSEQ];
+ float ks[KPER * N_BOUND];
+ float *kvc, *ropec; /* N_MLA slices of kv_cap positions */
+ int kv_cap;
+ int64_t kvpp, ropepp;
+} Arrays;
+
+static void arrays_alloc(Arrays *a, int kv_cap, const K3Cfg *c)
+{
+ memset(a, 0, sizeof *a);
+ a->kv_cap = kv_cap;
+ a->kvpp = (int64_t)c->n_heads * (c->qk_nope + c->v_head);
+ a->ropepp = c->qk_rope;
+ a->kvc = (float *)calloc((size_t)N_MLA * kv_cap * a->kvpp, sizeof(float));
+ a->ropec = (float *)calloc((size_t)N_MLA * kv_cap * a->ropepp, sizeof(float));
+}
+
+static void arrays_free(Arrays *a) { free(a->kvc); free(a->ropec); }
+
+/* Every value distinct, so a slice landing one row off is caught. */
+static void arrays_pattern(Arrays *a)
+{
+ for (int i = 0; i < NSEQ; i++) a->seq[i] = 7 * i + 3;
+ for (int i = 0; i < KPER * N_BOUND; i++) a->ks[i] = 0.25f * (float)i - 3.0f;
+ for (int mi = 0; mi < N_MLA; mi++)
+ for (int p = 0; p < a->kv_cap; p++) {
+ for (int j = 0; j < a->kvpp; j++)
+ a->kvc[((size_t)mi * a->kv_cap + p) * a->kvpp + j] =
+ 1000.0f * mi + 10.0f * p + 0.01f * j;
+ for (int j = 0; j < a->ropepp; j++)
+ a->ropec[((size_t)mi * a->kv_cap + p) * a->ropepp + j] =
+ -1000.0f * mi - 10.0f * p - 0.01f * j;
+ }
+}
+
+/* The OCCUPIED positions of every slice must match; capacity beyond them is scratch. */
+static int arrays_same_occupied(const Arrays *x, const Arrays *y)
+{
+ if (memcmp(x->seq, y->seq, sizeof x->seq) != 0) return 0;
+ if (memcmp(x->ks, y->ks, sizeof x->ks) != 0) return 0;
+ for (int mi = 0; mi < N_MLA; mi++) {
+ const float *xk = x->kvc + (size_t)mi * x->kv_cap * x->kvpp;
+ const float *yk = y->kvc + (size_t)mi * y->kv_cap * y->kvpp;
+ if (memcmp(xk, yk, (size_t)CACHED * x->kvpp * sizeof(float)) != 0) return 0;
+ const float *xr = x->ropec + (size_t)mi * x->kv_cap * x->ropepp;
+ const float *yr = y->ropec + (size_t)mi * y->kv_cap * y->ropepp;
+ if (memcmp(xr, yr, (size_t)CACHED * x->ropepp * sizeof(float)) != 0) return 0;
+ }
+ return 1;
+}
+
+static int save(const char *path, const K3Cfg *c, const Arrays *a)
+{
+ return k3_state_save(path, c, a->seq, NSEQ, a->ks, a->kvc, a->ropec,
+ N_BOUND, N_MLA, a->kv_cap, CACHED, KPER, a->kvpp, a->ropepp);
+}
+
+static int load(const char *path, const K3Cfg *c, Arrays *a)
+{
+ K3StateHdr hd;
+ if (k3_state_peek(path, &hd) != 0) return -1;
+ return k3_state_load(path, c, &hd, a->seq, a->ks, a->kvc, a->ropec,
+ N_BOUND, N_MLA, a->kv_cap);
+}
+
+int main(int argc, char **argv)
+{
+ if (argc < 2) { fprintf(stderr, "usage: test_state <work_dir>\n"); return 2; }
+ const char *work = argv[1];
+ mkdir(work, 0755);
+ char good[4096], mut[4096];
+ snprintf(good, sizeof good, "%s/good.k3st", work);
+ snprintf(mut, sizeof mut, "%s/mut.k3st", work);
+
+ K3Cfg c; cfg_fill(&c);
+ Arrays src; arrays_alloc(&src, KV_CAP, &c); arrays_pattern(&src);
+
+ printf("state file: round trip\n");
+ ck(save(good, &c, &src) == 0, "save writes", good);
+ {
+ K3StateHdr hd; memset(&hd, 0, sizeof hd);
+ ck(k3_state_peek(good, &hd) == 0, "peek accepts what save wrote", NULL);
+ ck(hd.nseq == NSEQ && hd.cached == CACHED && hd.n_bound == N_BOUND &&
+ hd.n_mla == N_MLA && hd.kper == KPER && hd.kvpp == src.kvpp &&
+ hd.ropepp == src.ropepp, "header carries the geometry", NULL);
+ }
+ {
+ /* A resumed run may size its KV cache differently; the slices must still land. */
+ Arrays dst; arrays_alloc(&dst, KV_CAP + 9, &c);
+ ck(load(good, &c, &dst) == 0, "load into a larger cache", NULL);
+ ck(arrays_same_occupied(&src, &dst), "every occupied value identical", NULL);
+ arrays_free(&dst);
+ }
+ {
+ Arrays dst; arrays_alloc(&dst, CACHED, &c); /* exactly full */
+ ck(load(good, &c, &dst) == 0, "load into an exactly-full cache", NULL);
+ ck(arrays_same_occupied(&src, &dst), "every occupied value identical", NULL);
+ arrays_free(&dst);
+ }
+
+ printf("state file: refusals\n");
+ size_t n = 0;
+ unsigned char *img = slurp(good, &n);
+ if (!img) { fprintf(stderr, "cannot read back %s\n", good); return 1; }
+ ck(n > sizeof(K3StateHdr), "file is header plus payload", NULL);
+ {
+ Arrays dst; arrays_alloc(&dst, KV_CAP, &c);
+ spit(mut, img, n - 7);
+ ck(load(mut, &c, &dst) != 0, "truncated payload refused", NULL);
+ spit(mut, img, sizeof(K3StateHdr) - 1);
+ ck(load(mut, &c, &dst) != 0, "truncated header refused", NULL);
+ arrays_free(&dst);
+ }
+ {
+ unsigned char *m = (unsigned char *)malloc(n); memcpy(m, img, n);
+ K3StateHdr *h = (K3StateHdr *)m;
+ h->version = K3_STATE_VER + 1;
+ spit(mut, m, n);
+ K3StateHdr hd;
+ ck(k3_state_peek(mut, &hd) != 0, "other version refused at peek", NULL);
+ memcpy(m, img, n); m[1] ^= 0xFF;
+ spit(mut, m, n);
+ ck(k3_state_peek(mut, &hd) != 0, "wrong magic refused at peek", NULL);
+ free(m);
+ }
+ {
+ /* Same file, different architecture: the fingerprint is the guard. */
+ K3Cfg other = c; other.topk = 3;
+ Arrays dst; arrays_alloc(&dst, KV_CAP, &c);
+ ck(load(good, &other, &dst) != 0, "other architecture refused", NULL);
+ K3StateHdr hd; k3_state_peek(good, &hd);
+ ck(k3_state_load(good, &c, &hd, dst.seq, dst.ks, dst.kvc, dst.ropec,
+ N_BOUND + 1, N_MLA, KV_CAP) != 0, "other layer count refused", NULL);
+ ck(k3_state_load(good, &c, &hd, dst.seq, dst.ks, dst.kvc, dst.ropec,
+ N_BOUND, N_MLA, CACHED - 1) != 0, "cache too small refused", NULL);
+ arrays_free(&dst);
+ }
+ printf("state file: payload integrity\n");
+ {
+ /* One flipped byte in each region. Structure intact, every fread full: this is
+ * exactly the damage a length check cannot see, and a restore from it decodes
+ * fluent, wrong tokens. */
+ const size_t H = sizeof(K3StateHdr);
+ const size_t off_seq = H;
+ const size_t off_ks = off_seq + (size_t)NSEQ * sizeof(int);
+ const size_t off_kvc = off_ks + (size_t)KPER * N_BOUND * sizeof(float);
+ const size_t off_ropec = off_kvc + (size_t)N_MLA * CACHED * src.kvpp * sizeof(float);
+ const struct { const char *name; size_t at; } flips[] = {
+ { "flipped byte in the token ids refused", off_seq + 5 },
+ { "flipped byte in the recurrent state refused", off_ks + 333 },
+ { "flipped byte in the KV cache refused", off_kvc + 77 },
+ { "flipped byte in the rope rows refused", off_ropec + 1 },
+ { "flipped byte in the last payload byte refused", n - 1 },
+ };
+ unsigned char *m = (unsigned char *)malloc(n);
+ Arrays dst; arrays_alloc(&dst, KV_CAP, &c);
+ for (size_t i = 0; i < sizeof flips / sizeof flips[0]; i++) {
+ memcpy(m, img, n);
+ m[flips[i].at] ^= 0x01;
+ spit(mut, m, n);
+ char d[64]; snprintf(d, sizeof d, "byte %zu of %zu", flips[i].at, n);
+ ck(load(mut, &c, &dst) != 0, flips[i].name, d);
+ }
+ /* The other direction: a good payload under a header whose hash was damaged. */
+ memcpy(m, img, n);
+ m[H - 1] ^= 0x01;
+ spit(mut, m, n);
+ ck(load(mut, &c, &dst) != 0, "damaged header hash refused", NULL);
+ /* And the untouched file still loads, so the refusals above are the flips. */
+ ck(load(good, &c, &dst) == 0, "untouched file still loads", NULL);
+ free(m);
+ arrays_free(&dst);
+ }
+ {
+ /* Not a gate, a number: the hash runs once per save and once per load over a
+ * payload that is 0.63 GB of recurrent state plus the KV cache at full scale. */
+ const size_t nb = (size_t)64 << 20;
+ unsigned char *buf = (unsigned char *)malloc(nb);
+ for (size_t i = 0; i < nb; i++) buf[i] = (unsigned char)(i * 2654435761u >> 24);
+ const clock_t t0 = clock();
+ const uint64_t h = k3_state_hash(K3_STATE_HASH_INIT, buf, nb);
+ const double s = (double)(clock() - t0) / CLOCKS_PER_SEC;
+ printf(" INFO hash of %zu MB: %016llx in %.3f s (%.0f MB/s)\n",
+ nb >> 20, (unsigned long long)h, s, s > 0 ? (double)(nb >> 20) / s : 0.0);
+ ck(k3_state_hash(K3_STATE_HASH_INIT, buf, nb) == h, "hash is deterministic", NULL);
+ buf[nb / 2] ^= 0x80;
+ ck(k3_state_hash(K3_STATE_HASH_INIT, buf, nb) != h, "hash sees one flipped bit", NULL);
+ free(buf);
+ }
+
+ printf("state file: publication\n");
+ {
+ /* Publish by rename, so the destination never holds a half-written state: a
+ * crash mid-save leaves the previous file, not a truncated one. The observable
+ * on POSIX is the inode: a rename installs a new file, an in-place rewrite keeps
+ * the old one. */
+#ifndef _WIN32
+ struct stat before, after;
+ ck(stat(good, &before) == 0, "stat before re-save", NULL);
+ ck(save(good, &c, &src) == 0, "re-save over an existing file", NULL);
+ ck(stat(good, &after) == 0, "stat after re-save", NULL);
+ ck(before.st_ino != after.st_ino, "destination is a new inode (rename)", NULL);
+ /* mkstemp creates 0600; the writer must hand the file back at the mode a plain
+ * fopen would have given it, or a state saved by one user stops being readable
+ * by the group that could read it before. */
+ {
+ const mode_t um = umask(0); umask(um);
+ const mode_t want = 0666 & ~um, got = after.st_mode & 0777;
+ char d[48]; snprintf(d, sizeof d, "mode %04o, want %04o (umask %04o)", (unsigned)got, (unsigned)want, (unsigned)um);
+ ck(got == want, "published mode is fopen's, not mkstemp's", d);
+ }
+#else
+ ck(save(good, &c, &src) == 0, "re-save over an existing file", NULL);
+ printf(" SKIP %-40s %s\n", "destination is a new inode (rename)", "no inode on Windows");
+#endif
+ /* Nothing staged is left behind. */
+ int residue = 0;
+ DIR *d = opendir(work);
+ if (d) {
+ struct dirent *e;
+ while ((e = readdir(d)) != NULL)
+ if (strstr(e->d_name, ".tmp")) { residue++; printf(" leftover: %s\n", e->d_name); }
+ closedir(d);
+ }
+ ck(d != NULL && residue == 0, "no temp file left after a save", NULL);
+ }
+#ifndef _WIN32
+ {
+ /* A save that cannot stage its temp file must fail without touching the old
+ * file. Directory write permission is what mkstemp needs and what an in-place
+ * fopen(path, "wb") does not, so this is the difference between the two. */
+ char rodir[4096], ro[4096];
+ snprintf(rodir, sizeof rodir, "%s/ro", work);
+ snprintf(ro, sizeof ro, "%s/ro/state.k3st", work);
+ mkdir(rodir, 0755);
+ chmod(rodir, 0755);
+ ck(save(ro, &c, &src) == 0, "save into a writable directory", NULL);
+ size_t n0 = 0; unsigned char *img0 = slurp(ro, &n0);
+ Arrays other; arrays_alloc(&other, KV_CAP, &c); arrays_pattern(&other);
+ other.seq[0] ^= 0x7F; /* a different payload, so an in-place rewrite would show */
+ if (chmod(rodir, 0555) == 0 && access(rodir, W_OK) != 0) {
+ const int rc = save(ro, &c, &other);
+ size_t n1 = 0; unsigned char *img1 = slurp(ro, &n1);
+ ck(rc != 0, "save with no room to stage fails", NULL);
+ ck(img0 && img1 && n0 == n1 && memcmp(img0, img1, n0) == 0,
+ "and the old file is byte-identical", NULL);
+ free(img1);
+ } else {
+ printf(" SKIP %-40s %s\n", "save with no room to stage fails",
+ "directory stayed writable (running as root?)");
+ }
+ chmod(rodir, 0755);
+ free(img0);
+ arrays_free(&other);
+ }
+#endif
+ free(img);
+ arrays_free(&src);
+
+ printf("\n%s\n", g_fail ? "STATE FILE TESTS FAILED" : "STATE FILE TESTS PASSED");
+ return g_fail ? 1 : 0;
+}