Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
perf(cache): index Inkling and Kimi expert slots
JustVugg60b9c3e01890
diff --git a/c/Makefile b/c/Makefileindex d221d37c..d09e5153 100644--- a/c/Makefile+++ b/c/Makefile@@ -1113,9 +1113,15 @@ tests/test_serve_codec$(EXE): tests/test_serve_codec.c serve_codec.h compat.htests/test_inkling_serve_framing$(EXE): tests/test_inkling_serve_framing.c inkling.c st.h json.h tok.h tok_unicode.h tok_unicode_o200k.h compat.h omp_tune.h route_trace.h kv_prefix.h serve_codec.h $(INK_CUDA_OBJ) $(METAL_OBJ)$(CC) $(CFLAGS) $< $(INK_CUDA_OBJ) $(METAL_OBJ) -o $@ $(LDFLAGS)+tests/test_inkling_cache_index$(EXE): tests/test_inkling_cache_index.c inkling.c st.h json.h tok.h tok_unicode.h tok_unicode_o200k.h compat.h omp_tune.h route_trace.h kv_prefix.h serve_codec.h $(INK_CUDA_OBJ) $(METAL_OBJ)+ $(CC) $(CFLAGS) $< $(INK_CUDA_OBJ) $(METAL_OBJ) -o $@ $(LDFLAGS)+tests/test_kimi_serve_framing$(EXE): tests/test_kimi_serve_framing.c kimi_k3.c kv_prefix.h serve_codec.h st.h json.h tok.h tok_unicode.h tok_unicode_o200k.h compat.h quant.h omp_tune.h route_trace.h$(CC) $(NOCUDA_CFLAGS) $< $(VK_OBJ) -o $@ $(NOCUDA_LDFLAGS)+tests/test_kimi_cache_index$(EXE): tests/test_kimi_cache_index.c kimi_k3.c kv_prefix.h serve_codec.h st.h json.h tok.h tok_unicode.h tok_unicode_o200k.h compat.h quant.h omp_tune.h route_trace.h+ $(CC) $(NOCUDA_CFLAGS) $< $(VK_OBJ) -o $@ $(NOCUDA_LDFLAGS)+tests/test_k3_chat_tools$(EXE): tests/test_k3_chat_tools.c kimi_k3.c kv_prefix.h serve_codec.h st.h json.h tok.h tok_unicode.h tok_unicode_o200k.h compat.h quant.h omp_tune.h route_trace.h$(CC) $(NOCUDA_CFLAGS) $< $(VK_OBJ) -o $@ $(NOCUDA_LDFLAGS)diff --git a/c/inkling.c b/c/inkling.cindex e6fdc390..0956de50 100644--- a/c/inkling.c+++ b/c/inkling.c@@ -124,7 +124,11 @@ typedef struct {int8_t *q13, *q2; /* bits>0: runtime-quantized int8 */float *f13, *f2; /* bits==0: raw f32 (oracle) */} Slot;-typedef struct { Slot *slots; int n, cap; } LCache;+typedef struct {+ Slot *slots;+ int *slot_by_expert; /* expert id -> local slot, -1 if absent */+ int n, cap;+} LCache;typedef struct {Cfg c;@@ -919,7 +923,16 @@ static void model_init(Model *m, const char *snap, int cap, int bits) {cap, (double)cap*slotb*nsp/1e9);}m->cache = calloc(c->n_layers, sizeof(LCache));- for (int i = 0; i < c->n_layers; i++) { m->cache[i].cap = cap; m->cache[i].slots = calloc(cap, sizeof(Slot)); }+ for (int i = 0; i < c->n_layers; i++) {+ LCache *lc = &m->cache[i];+ lc->cap = cap;+ lc->slots = calloc(cap, sizeof(Slot));+ if (c->sparse[i]) {+ lc->slot_by_expert = malloc((size_t)E * sizeof(int));+ if (!lc->slot_by_expert) { fprintf(stderr,"OOM expert cache index\n"); exit(1); }+ for (int e = 0; e < E; e++) lc->slot_by_expert[e] = -1;+ }+ }/* container mode: slot storage is one page-aligned slab per sparse layer* (weights) plus one for the row scales, with every slot's pointers carved* out up front. Slots then recycle their region on eviction — no per-slot@@ -977,18 +990,35 @@ static double mem_avail_bytes(void) {}/* ---------- routed-expert slots: serial bookkeeping, parallel fills ---------- */-static Slot *slot_find(Model *m, int layer, int eid) {+#ifdef COLI_CACHE_INDEX_TEST+static uint64_t g_slot_index_probes;+#define SLOT_INDEX_PROBE() (g_slot_index_probes++)+#else+#define SLOT_INDEX_PROBE() ((void)0)+#endif+/* Cache identity is mutated only by slot_acquire(), which keeps this index in+ * lockstep with the slot. Fills change bytes/filled but never identity. The+ * validation makes a stale/corrupt entry a miss instead of serving another+ * expert's weights; production slot_find then touches the LRU clock. */+static Slot *slot_indexed(Model *m, int layer, int eid) {LCache *lc = &m->cache[layer];- for (int i = 0; i < lc->n; i++) if (lc->slots[i].eid == eid) {- lc->slots[i].used = ++m->clock;- return &lc->slots[i];- }- return NULL;+ if (eid < 0 || eid >= m->c.n_experts || !lc->slot_by_expert) return NULL;+ SLOT_INDEX_PROBE();+ int i = lc->slot_by_expert[eid];+ if (i < 0 || i >= lc->n || lc->slots[i].eid != eid) return NULL;+ return &lc->slots[i];+}+static Slot *slot_find(Model *m, int layer, int eid) {+ Slot *s = slot_indexed(m, layer, eid);+ if (s) s->used = ++m->clock;+ return s;}/* allocate a slot (or evict the LRU non-pinned one); serial callers only */static Slot *slot_acquire(Model *m, int layer, int eid) {LCache *lc = &m->cache[layer]; Cfg *c = &m->c;+ if (eid < 0 || eid >= c->n_experts || !lc->slot_by_expert) {+ fprintf(stderr,"layer %d: invalid expert id %d for cache index\n",layer,eid); exit(1); }int64_t D = c->hidden, I = c->moe_inter, n13 = 2*I*D, n2 = D*I;Slot *s;if (lc->n < lc->cap) {@@ -1005,7 +1035,12 @@ static Slot *slot_acquire(Model *m, int layer, int eid) {if (lru < 0) { fprintf(stderr, "layer %d: cache cap %d entirely pinned\n", layer, lc->cap); exit(1); }s = &lc->slots[lru];}+ int si = (int)(s - lc->slots);+ if (s->eid >= 0 && s->eid < c->n_experts &&+ lc->slot_by_expert[s->eid] == si)+ lc->slot_by_expert[s->eid] = -1;s->eid = eid; s->used = ++m->clock; s->filled = 0; s->pinned = 0;+ lc->slot_by_expert[eid] = si;return s;}@@ -1078,8 +1113,7 @@ static void pins_load(Model *m, const char *snap) {for (int r = 0; r < m->npin; r++) { /* top-N selection */int best = -1; uint32_t bv = 0;for (int e = 0; e < E; e++) {- int taken = 0;- for (int z = 0; z < r; z++) if (ps[np-r+z]->eid == e) { taken = 1; break; }+ int taken = slot_indexed(m, i, e) != NULL;if (!taken && tmp[e] >= bv && tmp[e] > 0) { bv = tmp[e]; best = e; }}if (best < 0) break;@@ -2078,10 +2112,9 @@ static void serve_tiers_emap(Model *m) {char *hex = malloc((size_t)nsp*E*2 + 1); int w = 0;for (int i = 0; i < c->n_layers; i++) {if (!c->sparse[i]) continue;- LCache *lc = &m->cache[i];for (int e = 0; e < E; e++) {- int tier = 0;- for (int z = 0; z < lc->n; z++) if (lc->slots[z].eid == e && lc->slots[z].filled) { tier = 1; break; }+ Slot *resident = slot_indexed(m, i, e);+ int tier = resident && resident->filled;uint32_t u = m->eusage[i] ? m->eusage[i][e] : 0;int heat = 0; while (u) { heat++; u >>= 1; } if (heat > 63) heat = 63;int b = (tier << 6) | heat;diff --git a/c/kimi_k3.c b/c/kimi_k3.cindex e11cca9c..e1b5936a 100644--- a/c/kimi_k3.c+++ b/c/kimi_k3.c@@ -167,7 +167,11 @@ typedef struct { int eid; uint8_t *buf, *base; uint64_t used; int pinned; } Slot* tok/s when the pins came from a single prompt). *//* base = 4K-aligned allocation (O_DIRECT target);* buf = expert data view inside it (= base + off%4K) */-typedef struct { Slot *s; int n, cap; } LCache;+typedef struct {+ Slot *s;+ int *slot_by_expert; /* expert id -> local slot, -1 if absent */+ int n, cap;+} LCache;typedef struct {Cfg c;@@ -1026,7 +1030,11 @@ static void model_init(Model *m, const char *snap, int n_layers_env){m->ecache=calloc((size_t)ncl,sizeof(LCache)); }for(int i=0;i<c->n_layers;i++) if(m->L[i].sparse){m->ecache[i].cap=cap; m->ecache[i].s=calloc(cap,sizeof(Slot));+ m->ecache[i].slot_by_expert=malloc((size_t)c->n_experts*sizeof(int));+ if(!m->ecache[i].s||!m->ecache[i].slot_by_expert){+ fprintf(stderr,"OOM expert cache/index\n"); exit(1); }for(int j2=0;j2<cap;j2++) m->ecache[i].s[j2].eid=-1;+ for(int e=0;e<c->n_experts;e++) m->ecache[i].slot_by_expert[e]=-1;}fprintf(stderr,"[K3] init done in %.1fs | %d layers | expert cache %d/layer (%.1f MB/slot) | RSS %.1f GB\n",now_s()-t0,c->n_layers,cap,m->e_slot/1e6,rss_gb());@@ -1367,10 +1375,45 @@ static void kda_forward(Model *m, Layer *l, int li, const float *x, int C, float* slots) and, when K3_DIRECT=1 (default) and st.h has an O_DIRECT twin fd,* bypass the page cache: measured on the box 7.1 GB/s direct vs 2.9 buffered* (and ~1.8 effective once the resident weights leave no cache headroom). */-static Slot *slot_find(Model *m, int li, int eid){+/* Cache slots are serially published by cache_promote() or pin_seed(). Expert+ * reads land in ws[] first and never enter this index until their bytes are+ * complete. Validate both the local range and identity before returning: a+ * broken invariant must become a miss, never another expert's weights. */+#ifdef COLI_CACHE_INDEX_TEST+static uint64_t g_slot_index_probes;+#define SLOT_INDEX_PROBE() (g_slot_index_probes++)+#else+#define SLOT_INDEX_PROBE() ((void)0)+#endif+static Slot *slot_indexed(Model *m, int li, int eid){LCache *lc=&m->ecache[li];- for(int i=0;i<lc->n;i++) if(lc->s[i].eid==eid){ m->hits++; lc->s[i].used=++m->clock; return &lc->s[i]; }- return NULL;+ if(eid<0||eid>=m->c.n_experts||!lc->slot_by_expert) return NULL;+ SLOT_INDEX_PROBE();+ int i=lc->slot_by_expert[eid];+ if(i<0||i>=lc->n||lc->s[i].eid!=eid) return NULL;+ return &lc->s[i];+}+static Slot *slot_find(Model *m, int li, int eid){+ Slot *s=slot_indexed(m,li,eid);+ if(s){ m->hits++; s->used=++m->clock; }+ return s;+}+static void cache_unindex(Model *m,int li,Slot *s){+ LCache *lc=&m->ecache[li]; int i=(int)(s-lc->s);+ if(s->eid>=0&&s->eid<m->c.n_experts&&lc->slot_by_expert[s->eid]==i)+ lc->slot_by_expert[s->eid]=-1;+}+static void cache_index(Model *m,int li,Slot *s){+ LCache *lc=&m->ecache[li]; int i=(int)(s-lc->s);+ if(s->eid<0||s->eid>=m->c.n_experts||i<0||i>=lc->n){+ fprintf(stderr,"layer %d: invalid expert cache publication\n",li); exit(1); }+ lc->slot_by_expert[s->eid]=i;+}+static void cache_promote(Model *m,int li,Slot *dst,Slot *loaded){+ cache_unindex(m,li,dst);+ Slot tmp=*dst; *dst=*loaded; *loaded=tmp;+ dst->used=++m->clock;+ cache_index(m,li,dst);}static void expert_read(Model *m, int li, int eid, Slot *s){if(!s->base){@@ -1683,8 +1726,7 @@ static void experts_apply_union(Model *m, int li, int nu, const int *uids,if(lru<0) break; /* every slot pinned: keep the read */dst=&lc->s[lru];}- Slot tmp=*dst; *dst=m->ws[q]; m->ws[q]=tmp;- dst->used=++m->clock;+ cache_promote(m,li,dst,&m->ws[q]);}}free(zq_all); free(zsc_all);@@ -1748,15 +1790,14 @@ static void pin_seed(Model *m, int64_t hist){int best=-1; uint32_t bestc=0;for(int e=0;e<c->n_experts;e++){if(u[e]<=bestc) continue;- int taken=0;- for(int i=0;i<lc->n;i++) if(lc->s[i].eid==e){ taken=1; break; }+ int taken=slot_indexed(m,li,e)!=NULL;if(!taken){ best=e; bestc=u[e]; }}if(best<0) break; /* history is exhausted */Slot *d=&lc->s[lc->n];expert_read(m,li,best,d);d->eid=best; d->used=++m->clock; d->pinned=1;- lc->n++; pinned_total++;+ lc->n++; cache_index(m,li,d); pinned_total++;}}if(pinned_total)diff --git a/c/tests/test_inkling_cache_index.c b/c/tests/test_inkling_cache_index.cnew file mode 100644index 00000000..797f6af4--- /dev/null+++ b/c/tests/test_inkling_cache_index.c@@ -0,0 +1,88 @@+/* Model-free regression for Inkling's expert -> slot index. The fixture uses+ * two tiny slots: no checkpoint, tokenizer, GPU or meaningful RAM required. */+#define COLI_CACHE_INDEX_TEST 1+#define main inkling_main_unused+#include "../inkling.c"+#undef main++static int failures;+#define CHECK(cond, ...) do { if (!(cond)) { \+ fprintf(stderr,"FAIL %s:%d: ",__FILE__,__LINE__); \+ fprintf(stderr,__VA_ARGS__); fputc('\n',stderr); failures++; } } while (0)++static void init_cache(Model *m){+ memset(m,0,sizeof(*m));+ m->c.n_layers=1; m->c.n_experts=6; m->c.hidden=2; m->c.moe_inter=2;+ m->cache=calloc(1,sizeof(LCache));+ m->cache[0].cap=2;+ m->cache[0].slots=calloc(2,sizeof(Slot));+ m->cache[0].slot_by_expert=malloc(6*sizeof(int));+ for(int e=0;e<6;e++) m->cache[0].slot_by_expert[e]=-1;+}++static void free_cache(Model *m){+ for(int i=0;i<m->cache[0].cap;i++){+ free(m->cache[0].slots[i].f13);+ free(m->cache[0].slots[i].f2);+ }+ free(m->cache[0].slot_by_expert);+ free(m->cache[0].slots);+ free(m->cache);+}++static void check_lookup_scaling(int cap){+ Model m; memset(&m,0,sizeof(m));+ m.c.n_layers=1; m.c.n_experts=cap;+ m.cache=calloc(1,sizeof(LCache));+ LCache *lc=&m.cache[0]; lc->cap=lc->n=cap;+ lc->slots=calloc((size_t)cap,sizeof(Slot));+ lc->slot_by_expert=malloc((size_t)cap*sizeof(int));+ for(int i=0;i<cap;i++){ lc->slots[i].eid=i; lc->slot_by_expert[i]=i; }+ g_slot_index_probes=0;+ CHECK(slot_indexed(&m,0,cap-1)==&lc->slots[cap-1],+ "last-slot lookup failed at cap %d",cap);+ CHECK(g_slot_index_probes==1,+ "indexed lookup used %llu probes at cap %d, expected 1",+ (unsigned long long)g_slot_index_probes,cap);+ printf("inkling lookup probes: cap=%d indexed=%llu legacy-worst=%d\n",+ cap,(unsigned long long)g_slot_index_probes,cap);+ free(lc->slot_by_expert); free(lc->slots); free(m.cache);+}++int main(void){+ Model m; init_cache(&m); LCache *lc=&m.cache[0];++ Slot *one=slot_acquire(&m,0,1); one->filled=1;+ Slot *two=slot_acquire(&m,0,2); two->filled=1;+ CHECK(lc->slot_by_expert[1]==0&&lc->slot_by_expert[2]==1,+ "initial publications are not indexed");+ CHECK(slot_find(&m,0,1)==one,"indexed hit did not return expert 1");++ /* Expert 1 was just touched, so expert 2 is the deterministic LRU victim. */+ Slot *three=slot_acquire(&m,0,3); three->filled=1;+ CHECK(three==two,"wrong LRU slot was reused");+ CHECK(lc->slot_by_expert[2]==-1&&slot_indexed(&m,0,2)==NULL,+ "evicted expert 2 kept a mapping");+ CHECK(slot_indexed(&m,0,1)==one&&slot_indexed(&m,0,3)==three,+ "slot reuse damaged a live or new mapping");++ /* Pinning does not change identity: the other slot must be reused. */+ one->pinned=1;+ Slot *four=slot_acquire(&m,0,4); four->filled=1;+ CHECK(four==three,"pinned slot was selected as victim");+ CHECK(slot_indexed(&m,0,1)==one&&slot_indexed(&m,0,3)==NULL&&+ slot_indexed(&m,0,4)==four,"pin/eviction index mismatch");++ /* Defense in depth: a corrupt entry must never serve another expert. */+ lc->slot_by_expert[5]=0;+ CHECK(slot_indexed(&m,0,5)==NULL,"stale entry served the wrong weights");+ CHECK(slot_indexed(&m,0,-1)==NULL&&slot_indexed(&m,0,6)==NULL,+ "out-of-range lookup was accepted");++ free_cache(&m);+ check_lookup_scaling(44);+ check_lookup_scaling(219);+ if(failures){ fprintf(stderr,"inkling cache index: %d failure(s)\n",failures); return 1; }+ puts("inkling cache index: ok");+ return 0;+}diff --git a/c/tests/test_kimi_cache_index.c b/c/tests/test_kimi_cache_index.cnew file mode 100644index 00000000..f5c6a17e--- /dev/null+++ b/c/tests/test_kimi_cache_index.c@@ -0,0 +1,79 @@+/* Model-free regression for Kimi K3's expert -> slot index and ws[] promotion.+ * Synthetic pointers prove that swapping a loaded working slot still recycles+ * the victim allocation; no checkpoint or substantial memory is involved. */+#define COLI_CACHE_INDEX_TEST 1+#define main kimi_k3_main_unused+#include "../kimi_k3.c"+#undef main++static int failures;+#define CHECK(cond, ...) do { if (!(cond)) { \+ fprintf(stderr,"FAIL %s:%d: ",__FILE__,__LINE__); \+ fprintf(stderr,__VA_ARGS__); fputc('\n',stderr); failures++; } } while (0)++static void init_cache(Model *m){+ memset(m,0,sizeof(*m));+ m->c.n_layers=1; m->c.n_experts=6;+ m->ecache=calloc(1,sizeof(LCache));+ m->ecache[0].cap=2;+ m->ecache[0].s=calloc(2,sizeof(Slot));+ m->ecache[0].slot_by_expert=malloc(6*sizeof(int));+ for(int i=0;i<2;i++) m->ecache[0].s[i].eid=-1;+ for(int e=0;e<6;e++) m->ecache[0].slot_by_expert[e]=-1;+}++static void check_lookup_scaling(int cap){+ Model m; memset(&m,0,sizeof(m));+ m.c.n_layers=1; m.c.n_experts=cap;+ m.ecache=calloc(1,sizeof(LCache));+ LCache *lc=&m.ecache[0]; lc->cap=lc->n=cap;+ lc->s=calloc((size_t)cap,sizeof(Slot));+ lc->slot_by_expert=malloc((size_t)cap*sizeof(int));+ for(int i=0;i<cap;i++){ lc->s[i].eid=i; lc->slot_by_expert[i]=i; }+ g_slot_index_probes=0;+ CHECK(slot_indexed(&m,0,cap-1)==&lc->s[cap-1],+ "last-slot lookup failed at cap %d",cap);+ CHECK(g_slot_index_probes==1,+ "indexed lookup used %llu probes at cap %d, expected 1",+ (unsigned long long)g_slot_index_probes,cap);+ printf("kimi lookup probes: cap=%d indexed=%llu legacy-worst=%d\n",+ cap,(unsigned long long)g_slot_index_probes,cap);+ free(lc->slot_by_expert); free(lc->s); free(m.ecache);+}++int main(void){+ Model m; init_cache(&m); LCache *lc=&m.ecache[0];+ unsigned char a=1,b=2,c=3;++ m.ws[0]=(Slot){.eid=1,.base=&a,.buf=&a};+ Slot *dst=&lc->s[lc->n++]; cache_promote(&m,0,dst,&m.ws[0]);+ m.ws[0]=(Slot){.eid=2,.base=&b,.buf=&b};+ dst=&lc->s[lc->n++]; cache_promote(&m,0,dst,&m.ws[0]);+ CHECK(lc->slot_by_expert[1]==0&&lc->slot_by_expert[2]==1,+ "initial promotions are not indexed");+ uint64_t hits=m.hits;+ CHECK(slot_find(&m,0,1)==&lc->s[0]&&m.hits==hits+1,+ "indexed hit did not preserve Kimi hit accounting");++ /* Replace expert 2. Its allocation must move back to ws[] for reuse. */+ m.ws[0]=(Slot){.eid=3,.base=&c,.buf=&c};+ cache_promote(&m,0,&lc->s[1],&m.ws[0]);+ CHECK(lc->slot_by_expert[2]==-1&&slot_indexed(&m,0,2)==NULL,+ "evicted expert 2 kept a mapping");+ CHECK(slot_indexed(&m,0,1)==&lc->s[0]&&slot_indexed(&m,0,3)==&lc->s[1],+ "promotion damaged a live or new mapping");+ CHECK(m.ws[0].eid==2&&m.ws[0].base==&b&&m.ws[0].buf==&b,+ "promotion failed to recycle the victim working buffer");++ lc->slot_by_expert[4]=0;+ CHECK(slot_indexed(&m,0,4)==NULL,"stale entry served the wrong weights");+ CHECK(slot_indexed(&m,0,-1)==NULL&&slot_indexed(&m,0,6)==NULL,+ "out-of-range lookup was accepted");++ free(lc->slot_by_expert); free(lc->s); free(m.ecache);+ check_lookup_scaling(44);+ check_lookup_scaling(219);+ if(failures){ fprintf(stderr,"kimi cache index: %d failure(s)\n",failures); return 1; }+ puts("kimi cache index: ok");+ return 0;+}