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
fix(io): refuse safetensors headers whose spans overlap or leave gaps
Fareed Khan003c6b155639
diff --git a/src/io/k3_st.c b/src/io/k3_st.cindex acbb562..bb9f800 100644--- a/src/io/k3_st.c+++ b/src/io/k3_st.c@@ -209,6 +209,59 @@ static int push(Build *b, K3St *s, const char *name, size_t nlen, const K3Tensorreturn 0;}+/* ------------------------------------------------------------------ span sweep */++typedef struct { int64_t o0, o1; size_t idx; } Span;++static int cmp_span(const void *a, const void *b)+{+ const Span *x = (const Span *)a, *y = (const Span *)b;+ if (x->o0 != y->o0) return x->o0 < y->o0 ? -1 : 1;+ if (x->o1 != y->o1) return x->o1 < y->o1 ? -1 : 1;+ return 0;+}++/* Walk one shard's spans in offset order with a cursor from 0. Every span must start+ * exactly where the previous one ended: a start below the cursor is an overlap, a+ * start above it is a gap. A zero-length span (shape with a 0 in it) is legal wherever+ * its start meets the cursor. O(n log n) for the ~5,404 tensors a real shard holds. */+static int sweep_spans(const K3St *s, const Build *b, size_t first_idx, int64_t base,+ const char *path)+{+ const size_t n = b->n - first_idx;+ if (n == 0) return 0;+ Span *sp = (Span *)malloc(n * sizeof *sp);+ if (!sp) { fprintf(stderr, "k3_st: out of memory\n"); return -1; }+ for (size_t i = 0; i < n; i++) {+ const K3Tensor *t = &b->t[first_idx + i];+ sp[i].o0 = t->off - base;+ sp[i].o1 = sp[i].o0 + t->nbytes;+ sp[i].idx = first_idx + i;+ }+ qsort(sp, n, sizeof *sp, cmp_span);+ int64_t cursor = 0;+ size_t prev = 0; /* index into sp of the span that set cursor */+ for (size_t i = 0; i < n; i++) {+ const char *nm = s->strpool + b->noff[sp[i].idx];+ if (sp[i].o0 < cursor) {+ const char *pm = s->strpool + b->noff[sp[prev].idx];+ fprintf(stderr, "k3_st: %s: %s [%lld,%lld) overlaps %s [%lld,%lld)\n",+ path, nm, (long long)sp[i].o0, (long long)sp[i].o1,+ pm, (long long)sp[prev].o0, (long long)sp[prev].o1);+ free(sp); return -1;+ }+ if (sp[i].o0 > cursor) {+ fprintf(stderr, "k3_st: %s: %lld bytes at offset %lld belong to no tensor "+ "(gap before %s)\n",+ path, (long long)(sp[i].o0 - cursor), (long long)cursor, nm);+ free(sp); return -1;+ }+ if (sp[i].o1 > cursor) { cursor = sp[i].o1; prev = i; }+ }+ free(sp);+ return 0;+}+/* ------------------------------------------------------------------ one shard */static int scan_shard(K3St *s, Build *b, int shard, const char *path)@@ -260,6 +313,7 @@ static int scan_shard(K3St *s, Build *b, int shard, const char *path)static char name[512];int first = 1, ntensor = 0;int64_t maxend = 0;+ const size_t first_idx = b->n; /* this shard's entries are b->t[first_idx..) */for (;;) {ws(&sc);if (sc.p < sc.end && *sc.p == '}') { sc.p++; break; }@@ -370,6 +424,15 @@ static int scan_shard(K3St *s, Build *b, int shard, const char *path)ntensor++;}+ /* The spans must tile the data region exactly. Each entry above was checked on its+ * own (in range, size matches shape), but nothing so far relates them to each+ * other: two tensors claiming one span both pass, and one of them then reads the+ * other's bytes as plausible numbers; a span no tensor claims means the header and+ * the file disagree about where the data is. The reference implementation sorts+ * by data_offsets and requires each start to equal the previous end, from 0, so+ * both are refusals there. Trailing bytes stay a note, as before. */+ if (sweep_spans(s, b, first_idx, base, path) != 0) goto bad;+if (base + maxend != fsize)fprintf(stderr, "k3_st: note: %s has %lld trailing bytes after the last tensor\n",path, (long long)(fsize - base - maxend));diff --git a/tests/unit/test_st_faults.c b/tests/unit/test_st_faults.cindex 25167b7..05b1c37 100644--- a/tests/unit/test_st_faults.c+++ b/tests/unit/test_st_faults.c@@ -118,6 +118,46 @@ static uint64_t rdle64(const unsigned char *b)return v;}+/* A shard built from scratch: [8-byte LE header length][json][data]. The cases+ * below need headers whose data_offsets the fixture generator would never+ * write (it lays tensors out back to back), so they are spelled out by hand. */+static int write_synthetic_shard(const char *path, const char *header_json,+ const unsigned char *data, size_t n)+{+ FILE *f = fopen(path, "wb");+ if (!f) return -1;+ const uint64_t hlen = (uint64_t)strlen(header_json);+ unsigned char le[8];+ for (int i = 0; i < 8; i++) le[i] = (unsigned char)(hlen >> (8 * i));+ int ok = fwrite(le, 1, 8, f) == 8+ && fwrite(header_json, 1, (size_t)hlen, f) == (size_t)hlen+ && (n == 0 || fwrite(data, 1, n, f) == n);+ fclose(f);+ return ok ? 0 : -1;+}++/* One synthetic shard alone in its own directory; returns k3_st_open's rc and+ * the tensor count through *nt (only meaningful when rc == 0). */+static int open_synthetic(const char *work, const char *sub, const char *header_json,+ size_t data_bytes, int *nt)+{+ char d[1024], p[2048];+ unsigned char *data = (unsigned char *)calloc(data_bytes ? data_bytes : 1, 1);+ if (!data) return -99;+ for (size_t i = 0; i < data_bytes; i++) data[i] = (unsigned char)i;+ snprintf(d, sizeof d, "%s/%s", work, sub);+ mkdir(d, 0755);+ snprintf(p, sizeof p, "%s/model-00001-of-00001.safetensors", d);+ const int wrc = write_synthetic_shard(p, header_json, data, data_bytes);+ free(data);+ if (wrc != 0) return -99;+ K3St s;+ memset(&s, 0, sizeof s);+ const int rc = k3_st_open(&s, d);+ if (rc == 0) { *nt = s.nt; k3_st_close(&s); }+ return rc;+}+int main(int argc, char **argv){if (argc < 3) {@@ -251,6 +291,38 @@ int main(int argc, char **argv)ck(ok && (rc != 0 || shortread), "tail-truncated data surfaces loudly", "");}+ /* T5-T8: the data region must be tiled exactly. The reference implementation+ * sorts entries by data_offsets and requires each start to equal the previous+ * end, from 0. Two tensors claiming one span (T5) means one of them reads the+ * other's bytes and the shape/size check on each passes on its own; a span no+ * tensor claims (T6, T7) means the header and the file disagree about where the+ * data is. Both read back full and silent without this sweep. T8 is the+ * control: a contiguous layout with a zero-length tensor in the middle, which+ * the fixture set (empty.f32) says is legal. */+ {+ int nt = 0, rc;+ rc = open_synthetic(work, "t5",+ "{\"a\":{\"dtype\":\"F32\",\"shape\":[4],\"data_offsets\":[0,16]},"+ "\"b\":{\"dtype\":\"F32\",\"shape\":[4],\"data_offsets\":[8,24]}}", 24, &nt);+ ck(rc != 0 && rc != -99, "overlapping spans refused", rc == -99 ? "harness" : "");++ rc = open_synthetic(work, "t6",+ "{\"a\":{\"dtype\":\"F32\",\"shape\":[4],\"data_offsets\":[0,16]},"+ "\"b\":{\"dtype\":\"F32\",\"shape\":[4],\"data_offsets\":[24,40]}}", 40, &nt);+ ck(rc != 0 && rc != -99, "gap between spans refused", rc == -99 ? "harness" : "");++ rc = open_synthetic(work, "t7",+ "{\"a\":{\"dtype\":\"F32\",\"shape\":[4],\"data_offsets\":[8,24]}}", 24, &nt);+ ck(rc != 0 && rc != -99, "first span not at offset 0 refused", rc == -99 ? "harness" : "");++ rc = open_synthetic(work, "t8",+ "{\"a\":{\"dtype\":\"F32\",\"shape\":[4],\"data_offsets\":[0,16]},"+ "\"z\":{\"dtype\":\"F32\",\"shape\":[0,8],\"data_offsets\":[16,16]},"+ "\"b\":{\"dtype\":\"F32\",\"shape\":[4],\"data_offsets\":[16,32]}}", 32, &nt);+ ck(rc == 0 && nt == 3, "contiguous + zero-length tensor opens",+ rc == -99 ? "harness" : (rc != 0 ? "refused" : (nt != 3 ? "wrong tensor count" : "")));+ }+printf("\n%s\n", g_fail ? "ST-FAULT TESTS FAILED" : "ST-FAULT TESTS PASSED");return g_fail ? 1 : 0;}