Run frontier MoE models on hardware you already own β pure C, zero deps, experts streamed from disk. Tiny engine, immense model. π¦
C
perf(k3): measured adaptive expert-tier fill (K3_VK_UP=auto)
JustVuggd8ed3746d5fe
diff --git a/c/Makefile b/c/Makefileindex a142d590..c3a55fa7 100644--- a/c/Makefile+++ b/c/Makefile@@ -457,7 +457,7 @@ ifneq (,$(LINUX))TEST_BINS += tests/test_uring$(EXE)endififeq ($(COLI_V4_SUPPORTED),1)-TEST_BINS += tests/test_v4_hybrid_policy$(EXE)+TEST_BINS += tests/test_v4_hybrid_policy$(EXE) tests/test_k3_fill_budget$(EXE)TEST_BINS += tests/test_deepseek_v4$(EXE) tests/test_v4_ownership$(EXE) \tests/test_v4_serve_framing$(EXE)endif@@ -1336,7 +1336,10 @@ tests/test_corpus_draft$(EXE): tests/test_corpus_draft.c colibri.c st.h uring.htests/test_cap_precedence$(EXE): tests/test_cap_precedence.c colibri.c st.h uring.h json.h tok.h tok_unicode.h compat.h grammar.h tier.h quant.h sample.h kv_persist.h telemetry.h$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)-tests/test_v4_hybrid_policy$(EXE): tests/test_v4_hybrid_policy.c deepseek_v4_hybrid.h+tests/test_v4_hybrid_policy$(EXE): tests/test_v4_hybrid_policy.c deepseek_v4_hybrid.h hybrid_split.h+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)++tests/test_k3_fill_budget$(EXE): tests/test_k3_fill_budget.c hybrid_split.h$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)tests/test_ram_clamp$(EXE): tests/test_ram_clamp.c colibri.c st.h uring.h json.h tok.h tok_unicode.h compat.h grammar.h tier.h quant.h sample.h kv_persist.h telemetry.hdiff --git a/c/deepseek_v4_hybrid.h b/c/deepseek_v4_hybrid.hindex 3f3046bc..5e104a75 100644--- a/c/deepseek_v4_hybrid.h+++ b/c/deepseek_v4_hybrid.h@@ -1,54 +1,7 @@-/* deepseek_v4_hybrid.h β the q* fill/execute split for GPU expert misses.- *- * On a decode step some routed experts are resident in VRAM and some are not.- * Today the engine is all-or-nothing: one missing expert sends the WHOLE- * token's routed MoE to the CPU, and every miss is uploaded over PCIe- * unconditionally. The hybrid split partitions the m missing experts into a- * fill set (upload to VRAM, compute on GPU) and a host set (compute on CPU),- * sized so the two branches take the same time:- *- * T_fill(q) ~= q * S / B_P (PCIe transfer of q experts)- * T_host(m-q)~= (m-q) * S / (B_H-B_P) (host compute of the rest)- *- * Balancing the two gives the closed form- *- * q* = m * B_P / B_H- *- * with B_P the measured fill bandwidth and B_H the measured host execution- * bandwidth. As B_H approaches B_P, q* approaches m and the split degenerates- * into plain upload-everything β which is also the answer while the- * bandwidths are still unmeasured. Both bandwidths are live EMAs of the- * engine's own uploads and expert forwards, never assumptions.- *- * Everything in this header is pure arithmetic so the CI can test the policy- * on machines with no GPU at all; the CUDA wiring lives in deepseek_v4.c- * behind DSV4_HYBRID=1. */+/* deepseek_v4_hybrid.h β kept as a shim: the policies moved to the shared+ * hybrid_split.h when Kimi K3 grew its adaptive tier fill. Same functions,+ * same contracts; nothing V4-specific ever lived here. */#ifndef DEEPSEEK_V4_HYBRID_H#define DEEPSEEK_V4_HYBRID_H--/* How many of `missing` experts to upload-and-run-on-GPU; the caller computes- * the rest on the CPU. Bandwidths are in experts/second (only their RATIO- * matters, so any consistent unit works). Unmeasured or nonsensical- * bandwidths fall back to `missing` β the engine's historical- * upload-everything behaviour, never something new. */-static inline int coli_v4_hybrid_fill_count(int missing, double fill_bw,- double host_bw) {- if (missing <= 0) return 0;- if (fill_bw <= 0.0 || host_bw <= 0.0) return missing;- double ideal = (double)missing * fill_bw / host_bw; /* q* = m*B_P/B_H */- int fill = (int)(ideal + 0.5);- if (fill < 0) fill = 0;- if (fill > missing) fill = missing;- return fill;-}--/* One-pole EMA for the live bandwidth estimates. A non-positive sample is- * ignored (a failed or zero-length measurement must not poison the state);- * the first valid sample seeds the average directly. */-static inline double coli_v4_hybrid_ema(double previous, double sample) {- if (sample <= 0.0) return previous;- if (previous <= 0.0) return sample;- return previous * 0.8 + sample * 0.2;-}--#endif /* DEEPSEEK_V4_HYBRID_H */+#include "hybrid_split.h"+#endifdiff --git a/c/hybrid_split.h b/c/hybrid_split.hnew file mode 100644index 00000000..a3038b79--- /dev/null+++ b/c/hybrid_split.h@@ -0,0 +1,65 @@+/* hybrid_split.h β pure split/budget policies for GPU-tier work, shared by+ * the engines. Everything here is arithmetic on measured rates so the CI can+ * test the decisions on machines with no GPU at all; each engine's wiring+ * stays in its own file behind its own opt-in switch.+ *+ * DSV4 hybrid decode split (DSV4_HYBRID=1): of m experts missing from the+ * VRAM mirrors, upload-and-run q* = m * B_P / B_H on the GPU and compute the+ * rest on the host, so the transfer branch and the host branch finish+ * together (derivation in the function comment below).+ *+ * K3 adaptive tier fill (K3_VK_UP=auto): the fill-once routed-expert tier+ * uploads from freshly-read RAM slots inline on the decode thread, so every+ * upload is decode latency. The budget bounds that investment to a fraction+ * of the measured step time instead of a hardcoded count. */+#ifndef HYBRID_SPLIT_H+#define HYBRID_SPLIT_H++/* How many of `missing` experts to upload-and-run-on-GPU; the caller computes+ * the rest on the host. Balancing the two concurrent branches,+ * T_fill(q) ~= q*S/B_P against T_host(m-q) ~= (m-q)*S/(B_H-B_P),+ * gives the closed form q* = m * B_P / B_H, clamped to [0, m]. Bandwidths+ * are in experts/second (only their ratio matters). Unmeasured or+ * nonsensical bandwidths fall back to `missing` β the historical+ * upload-everything behaviour, never something new. */+static inline int coli_v4_hybrid_fill_count(int missing, double fill_bw,+ double host_bw) {+ if (missing <= 0) return 0;+ if (fill_bw <= 0.0 || host_bw <= 0.0) return missing;+ double ideal = (double)missing * fill_bw / host_bw;+ int fill = (int)(ideal + 0.5);+ if (fill < 0) fill = 0;+ if (fill > missing) fill = missing;+ return fill;+}++/* One-pole EMA for the live rate estimates. A non-positive sample is ignored+ * (a failed or zero-length measurement must not poison the state); the first+ * valid sample seeds the average directly. */+static inline double coli_v4_hybrid_ema(double previous, double sample) {+ if (sample <= 0.0) return previous;+ if (previous <= 0.0) return sample;+ return previous * 0.8 + sample * 0.2;+}++/* Per-step upload budget for a fill-once tier whose uploads run INLINE on+ * the decode thread: spend at most `fraction` of the measured step time on+ * uploads, i.e. budget = fraction * step_seconds / upload_seconds. While+ * either rate is unmeasured the caller's legacy fixed cap applies, so+ * enabling the adaptive mode can never behave worse than the default before+ * the first measurements exist. Clamped to [1, 64]: at least one upload per+ * step keeps the tier filling even on a slow bus, and 64 bounds the latency+ * spike a mismeasured step could buy. */+static inline int coli_k3_fill_budget(double step_seconds,+ double upload_seconds,+ double fraction, int legacy_cap) {+ if (step_seconds <= 0.0 || upload_seconds <= 0.0) return legacy_cap;+ if (fraction <= 0.0) return 1;+ double ideal = fraction * step_seconds / upload_seconds;+ int budget = (int)(ideal + 0.5);+ if (budget < 1) budget = 1;+ if (budget > 64) budget = 64;+ return budget;+}++#endif /* HYBRID_SPLIT_H */diff --git a/c/kimi_k3.c b/c/kimi_k3.cindex e5d1343c..d327c335 100644--- a/c/kimi_k3.c+++ b/c/kimi_k3.c@@ -48,7 +48,11 @@* experts skip disk AND CPU at decode. CPU fallback* everywhere; output identical.* K3_VK_GB=N VRAM cap for the tier (default: driver budget)- * K3_VK_UP=N routed-expert uploads per step (default 8)+ * K3_VK_UP=N|auto routed-expert uploads per step (default 8). `auto`+ * bounds the inline upload time to a fraction of the+ * measured decode step (K3_VK_FILL_FRAC, default 0.25)+ * instead of a fixed count β a slow bus stops stalling+ * decode, a fast one fills the tier sooner.* K3_METAL=0|1 Metal tier (build with `make METAL=1 kimi_k3`; Phase 4:* scaffolding only β dispatch hooks present, forward NOT* IMPLEMENTED; all ops fall through to CPU).@@ -108,7 +112,8 @@#endif#include "omp_tune.h"#include "route_trace.h"-#include "kv_prefix.h" /* KV prefix reuse (shared) */+#include "kv_prefix.h"+#include "hybrid_split.h" /* KV prefix reuse (shared) */#include "serve_codec.h"/* ---------- config ---------- */@@ -353,6 +358,10 @@ static int g_k3_vk=0; /* backend live (K3_VK=0 disables) */typedef struct { void *w1, *w2, *w3; } VkExp; /* ColiVkTensor* triple */static VkExp *g_vkexp; static int64_t g_vkexp_n;static int g_vk_upcap=8, g_vk_up_left=0, g_vk_full=0;+static int g_vk_up_auto=0; /* K3_VK_UP=auto: measured budget */+static double g_vk_fill_frac=0.25; /* K3_VK_FILL_FRAC of step time */+static double g_vk_step_ema, g_vk_upload_ema; /* seconds, decode steps only */+static int g_vk_cap_now=8; /* last budget chosen (reporting) */static long g_vk_hit=0, g_vk_res=0;static double g_vk_gb=0; /* K3_VK_GB cap (0 = driver budget) */static const char *k3_vk_spv(char *buf, size_t n){@@ -931,7 +940,13 @@ static void model_init(Model *m, const char *snap, int n_layers_env){}if(g_k3_vk){g_vk_gb=getenv("K3_VK_GB")?atof(getenv("K3_VK_GB")):0;- g_vk_upcap=getenv("K3_VK_UP")?atoi(getenv("K3_VK_UP")):8;+ { const char *up=getenv("K3_VK_UP");+ if(up&&!strcmp(up,"auto")){+ g_vk_up_auto=1; /* opt-in: measured budget below */+ const char *fr=getenv("K3_VK_FILL_FRAC");+ if(fr){ double f=atof(fr); if(f>0.0&&f<=1.0) g_vk_fill_frac=f; }+ } else g_vk_upcap=up?atoi(up):8; }+ g_vk_cap_now=g_vk_upcap;g_vkexp_n=(int64_t)c->n_layers*c->n_experts;g_vkexp=calloc((size_t)g_vkexp_n,sizeof(VkExp));if(!g_vkexp) g_k3_vk=0;@@ -946,8 +961,9 @@ static void model_init(Model *m, const char *snap, int n_layers_env){nsh+=w_vk_upload(&sm2->sh_gate)+w_vk_upload(&sm2->sh_up)+w_vk_upload(&sm2->sh_down);}double used=0,budget=0; coli_vk_mem_budget(&used,&budget);- fprintf(stderr,"[K3-VK] resident: %d shared-expert mats (%.1f/%.1f GB); routed MXFP4 tier fills at decode (K3_VK_UP=%d/step, cap %s)\n",- nsh,used,budget,g_vk_upcap,g_vk_gb>0?"K3_VK_GB":"driver budget");+ char vk_cap_str[16]; snprintf(vk_cap_str,sizeof vk_cap_str,"%d",g_vk_upcap);+ fprintf(stderr,"[K3-VK] resident: %d shared-expert mats (%.1f/%.1f GB); routed MXFP4 tier fills at decode (K3_VK_UP=%s/step, cap %s)\n",+ nsh,used,budget,g_vk_up_auto?"auto":vk_cap_str,g_vk_gb>0?"K3_VK_GB":"driver budget");}}#endif@@ -1592,6 +1608,7 @@ static void vk_expert_try_upload(Model *m, int li, int eid, Slot *s){return; }uint8_t *w1p=s->buf, *w1s=w1p+m->e_w1p, *w2p=w1s+m->e_w1s, *w2s=w2p+m->e_w2p,*w3p=w2s+m->e_w2s, *w3s=w3p+m->e_w1p;+ double up_t0=now_s(); /* whole upload incl. scale expand */int LT=m->c.latent, MI=m->c.moe_inter;int64_t n1=m->e_w1s, n2=m->e_w2s; /* scale counts = scale bytes (u8) */float *sc=falloc(n1>n2?n1:n2);@@ -1612,6 +1629,7 @@ static void vk_expert_try_upload(Model *m, int li, int eid, Slot *s){return;}g_vk_res++; g_vk_up_left--;+ g_vk_upload_ema=coli_v4_hybrid_ema(g_vk_upload_ema,now_s()-up_t0);}#endif@@ -1999,7 +2017,15 @@ static float *step_chunk_ex(Model *m, const int *ids, int pos0, int C,Cfg *c=&m->c; int D=c->hidden;if(cancelled) *cancelled=0;#ifdef COLI_VULKAN- g_vk_up_left=g_vk_upcap; /* routed-tier upload budget per step */+ /* Routed-tier upload budget for this step. Fixed cap by default;+ * K3_VK_UP=auto bounds the inline upload time to a fraction of the+ * measured decode step instead (hybrid_split.h) β legacy cap until both+ * rates have samples, so enabling auto never starts worse. */+ if(g_vk_up_auto&&!g_vk_full)+ g_vk_cap_now=coli_k3_fill_budget(g_vk_step_ema,g_vk_upload_ema,+ g_vk_fill_frac,g_vk_upcap);+ g_vk_up_left=g_vk_up_auto?g_vk_cap_now:g_vk_upcap;+ double vk_step_t0=(g_vk_up_auto&&C==1)?now_s():0.0;#endifint nbmax=(c->n_layers+c->res_bs-1)/c->res_bs;float *hidden=falloc((int64_t)C*D), *bres=falloc((int64_t)C*nbmax*D);@@ -2093,6 +2119,10 @@ static float *step_chunk_ex(Model *m, const int *ids, int pos0, int C,}/* record what was just fed, at the positions it went to (kv_prefix.h) */if(!cancelled||!*cancelled) kv_prefix_record(&m->kvp,ids,pos0,C);+#ifdef COLI_VULKAN+ if(g_vk_up_auto&&C==1&&vk_step_t0>0.0)+ g_vk_step_ema=coli_v4_hybrid_ema(g_vk_step_ema,now_s()-vk_step_t0);+#endiffree(hidden);free(bres);free(prefix);free(nrm);free(att);free(mix);free(mlp);return logits;}@@ -2889,8 +2919,16 @@ static int serve_one(Model *m, Tok *T, ServeReq *q){dt,np,gen,disk,0.0,moe>disk?moe-disk:moe,m->t_attn-a0,m->t_head-h0,gen+1);fflush(stdout);#ifdef COLI_VULKAN- if(g_k3_vk) fprintf(stderr,"[K3-VK] routed tier: %ld resident, %ld GPU hits so far\n",- g_vk_res,g_vk_hit);+ if(g_k3_vk){+ if(g_vk_up_auto)+ fprintf(stderr,"[K3-VK] routed tier: %ld resident, %ld GPU hits | "+ "fill auto cap=%d (step %.2fms, upload %.2fms, frac %.2f)\n",+ g_vk_res,g_vk_hit,g_vk_cap_now,+ g_vk_step_ema*1e3,g_vk_upload_ema*1e3,g_vk_fill_frac);+ else+ fprintf(stderr,"[K3-VK] routed tier: %ld resident, %ld GPU hits so far\n",+ g_vk_res,g_vk_hit);+ }#endifreturn 0;}@@ -3109,6 +3147,11 @@ int main(int argc, char **argv){(unsigned long long)m.hits,(unsigned long long)(m.hits+m.miss),m.ebytes/1e9);fprintf(stderr,"[K3] time: attn %.1fs moe %.1fs (eload %.1fs) head %.1fs | RSS %.1f GB\n",m.t_attn,m.t_moe,m.t_eload,m.t_head,rss_gb());+#ifdef COLI_VULKAN+ if(g_k3_vk&&g_vk_up_auto)+ fprintf(stderr,"[K3-VK] fill auto: cap=%d (step %.2fms, upload %.2fms, frac %.2f) | %ld resident\n",+ g_vk_cap_now,g_vk_step_ema*1e3,g_vk_upload_ema*1e3,g_vk_fill_frac,g_vk_res);+#endif/* One line, every engine, one format: `coli tune` sweeps scheduling knobs and* needs tokens-and-elapsed to compare candidates. Before this only colibri* emitted a parseable throughput line (REPLAY decode), so the tuner wasdiff --git a/c/tests/test_k3_fill_budget.c b/c/tests/test_k3_fill_budget.cnew file mode 100644index 00000000..5d2eeb00--- /dev/null+++ b/c/tests/test_k3_fill_budget.c@@ -0,0 +1,42 @@+/* test_k3_fill_budget.c β the adaptive tier-fill budget contract.+ *+ * coli_k3_fill_budget() bounds the INLINE upload investment of K3's+ * fill-once Vulkan expert tier to a fraction of the measured decode step:+ * budget = fraction * step_s / upload_s, clamped to [1, 64], with the legacy+ * fixed cap while either rate is unmeasured β enabling K3_VK_UP=auto can+ * never start worse than the default. Pure arithmetic, GPU-less testable. */+#include <stdio.h>+#include "../hybrid_split.h"++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)++int main(void) {+ /* unmeasured rates: the legacy cap applies verbatim */+ CHECK(coli_k3_fill_budget(0.0, 0.001, 0.25, 8) == 8, "no step -> legacy");+ CHECK(coli_k3_fill_budget(0.010, 0.0, 0.25, 8) == 8, "no upload -> legacy");+ CHECK(coli_k3_fill_budget(-1.0, -1.0, 0.25, 3) == 3, "bad rates -> legacy");++ /* the budget: fraction * step / upload */+ CHECK(coli_k3_fill_budget(0.100, 0.005, 0.25, 8) == 5, "25%% of 100ms at 5ms -> 5");+ CHECK(coli_k3_fill_budget(0.100, 0.001, 0.25, 8) == 25, "fast bus -> more");+ CHECK(coli_k3_fill_budget(0.010, 0.010, 0.25, 8) == 1, "slow bus -> floor 1");++ /* clamps */+ CHECK(coli_k3_fill_budget(10.0, 0.0001, 0.25, 8) == 64, "ceiling 64");+ CHECK(coli_k3_fill_budget(0.100, 0.005, 0.0, 8) == 1, "zero fraction -> floor");++ /* monotone in step time: a slower step affords more uploads */+ int previous = 0;+ for (int step = 1; step <= 20; step++) {+ int budget = coli_k3_fill_budget(0.005 * step, 0.004, 0.25, 8);+ CHECK(budget >= previous, "monotone in step time (step %d)", step);+ previous = budget;+ }++ if (failures) { fprintf(stderr, "%d failure(s)\n", failures); return 1; }+ printf("test_k3_fill_budget: ok\n");+ return 0;+}