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
test: add the weightless gate suite
FareedKhan-dev5b0944c6d6d0
diff --git a/tests/unit/k3_model.c b/tests/unit/k3_model.cnew file mode 100644index 0000000..64f7caa--- /dev/null+++ b/tests/unit/k3_model.c@@ -0,0 +1,443 @@+/* k3_model.c - the full Kimi K3 forward pass, and the oracle gate.+ *+ * This is the point at which "every component passes" becomes "the engine is+ * correct". It loads the tiny checkpoint exported by tools/export_weights.py, runs+ * the complete 13-layer forward, and compares against fixtures/ref_k3.json, which+ * was produced by the pure-torch reference.+ *+ * Two things must match, and they test different code paths:+ * tf_pred argmax at every position of ONE teacher-forced forward. Exercises+ * prefill: the chunked-equivalent path, AttnRes across the whole stack,+ * and the KDA recurrence run over the full sequence in one call.+ * full_ids greedy decode. Exercises the same machinery re-entered per token.+ *+ * The bar is exact: 32/32 teacher-forced positions and 20/20 greedily decoded tokens+ * must match ref_k3.json. Not "close", the same integers. A single mismatch fails+ * the gate, because on a discrete argmax there is no such thing as a small error:+ * either the token is right or the sentence has diverged.+ *+ * Positions inside the PROMPT are expected to disagree: the model is randomly+ * initialised and the prompt is random, so it has no reason to predict its own+ * input. Only the GENERATED span is a real test, and it must be exact.+ */+#include <math.h>+#include <stdarg.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "json.h"+#include "k3.h"+#include "k3_cfg.h" /* one config reader for both shapes; never defaults a field */++/* ------------------------------------------------------------ weight store ---- */+typedef struct {+ float *blob;+ jval *man; /* the "tensors" object: name -> {offset, shape} */+ char *arena;+ char *raw;+} Store;++static char *slurp_(const char *p, long *len)+{+ FILE *f = fopen(p, "rb");+ if (!f) { fprintf(stderr, "cannot open %s\n", p); return NULL; }+ fseek(f, 0, SEEK_END); long n = ftell(f); fseek(f, 0, SEEK_SET);+ char *b = (char *)malloc((size_t)n + 1);+ if (!b || fread(b, 1, (size_t)n, f) != (size_t)n) { free(b); fclose(f); return NULL; }+ b[n] = 0; fclose(f); if (len) *len = n;+ return b;+}++static int store_open(Store *s, const char *dir)+{+ char p[512];+ snprintf(p, sizeof p, "%s/tiny_k3.json", dir);+ s->raw = slurp_(p, NULL);+ if (!s->raw) return 0;+ jval *root = json_parse(s->raw, &s->arena);+ s->man = json_get(root, "tensors");++ snprintf(p, sizeof p, "%s/tiny_k3.bin", dir);+ long n = 0;+ char *bytes = slurp_(p, &n);+ if (!bytes) return 0;+ s->blob = (float *)bytes;+ return s->man != NULL;+}++/* Look a tensor up by name. Returns NULL when absent, which the caller must treat+ * as fatal: a silently-missing weight would be read as zeros and the model would+ * still run, producing plausible garbage. */+static const float *W(Store *s, const char *fmt, ...)+{+ char key[160];+ va_list ap; va_start(ap, fmt); vsnprintf(key, sizeof key, fmt, ap); va_end(ap);+ jval *e = json_get(s->man, key);+ if (!e) { fprintf(stderr, "MISSING WEIGHT: %s\n", key); return NULL; }+ jval *o = json_get(e, "offset");+ return s->blob + (size_t)o->num;+}+++/* ---------------------------------------------------------------- forward ---- */+typedef struct {+ K3KdaW kda[64]; K3MlaW mla[64]; K3MoeW moe[64]; K3LayerW lay[64];+ float *w1[64], *w3[64], *w2[64];+ const float *embed, *lm_head, *final_norm;+ const float *out_res_norm, *out_res_proj;+} Model;++/* Pack per-expert tensors contiguously per layer so the MoE can index expert e at a+ * fixed stride, which is also how a streaming engine will lay them out on disk. */+static float *pack(Store *s, int layer, const char *which, int n, size_t per)+{+ float *B = (float *)malloc(per * (size_t)n * sizeof(float));+ if (!B) return NULL;+ for (int e = 0; e < n; e++) {+ const float *a = W(s, "layers_%d_mlp_experts_%d_%s_weight", layer, e, which);+ if (!a) { free(B); return NULL; }+ memcpy(B + (size_t)e * per, a, per * sizeof(float));+ }+ return B;+}++static int model_bind(Model *m, Store *s, const K3Cfg *c)+{+ m->embed = W(s, "embed_tokens_weight");+ m->lm_head = W(s, "lm_head_weight");+ m->final_norm = W(s, "norm_weight");+ m->out_res_norm = W(s, "output_attn_res_norm_weight");+ m->out_res_proj = W(s, "output_attn_res_proj_weight");+ if (!m->embed || !m->lm_head || !m->final_norm) return 0;++ const size_t p13 = (size_t)c->moe_inter * (size_t)c->latent;+ const size_t p2 = (size_t)c->latent * (size_t)c->moe_inter;++ for (int L = 0; L < c->n_layers; L++) {+ K3LayerW *lw = &m->lay[L]; memset(lw, 0, sizeof *lw);+ lw->in_norm = W(s, "layers_%d_input_layernorm_weight", L);+ lw->post_norm = W(s, "layers_%d_post_attention_layernorm_weight", L);+ lw->attn_res_norm = W(s, "layers_%d_self_attention_res_norm_weight", L);+ lw->attn_res_proj = W(s, "layers_%d_self_attention_res_proj_weight", L);+ lw->mlp_res_norm = W(s, "layers_%d_mlp_res_norm_weight", L);+ lw->mlp_res_proj = W(s, "layers_%d_mlp_res_proj_weight", L);+ if (!lw->in_norm || !lw->mlp_res_proj) return 0;++ if (k3_is_mla(c, L)) {+ K3MlaW *w = &m->mla[L];+ w->q_a = W(s, "layers_%d_self_attn_q_a_proj_weight", L);+ w->q_a_norm = W(s, "layers_%d_self_attn_q_a_layernorm_weight", L);+ w->q_b = W(s, "layers_%d_self_attn_q_b_proj_weight", L);+ w->kv_a = W(s, "layers_%d_self_attn_kv_a_proj_with_mqa_weight", L);+ w->kv_a_norm = W(s, "layers_%d_self_attn_kv_a_layernorm_weight", L);+ w->kv_b = W(s, "layers_%d_self_attn_kv_b_proj_weight", L);+ w->o = W(s, "layers_%d_self_attn_o_proj_weight", L);+ w->g = W(s, "layers_%d_self_attn_g_proj_weight", L);+ if (!w->q_a || !w->kv_b || !w->o) return 0;+ lw->mla = w;+ } else {+ K3KdaW *w = &m->kda[L];+ w->q = W(s, "layers_%d_self_attn_q_proj_weight", L);+ w->k = W(s, "layers_%d_self_attn_k_proj_weight", L);+ w->v = W(s, "layers_%d_self_attn_v_proj_weight", L);+ w->q_conv = W(s, "layers_%d_self_attn_q_conv1d_weight", L);+ w->k_conv = W(s, "layers_%d_self_attn_k_conv1d_weight", L);+ w->v_conv = W(s, "layers_%d_self_attn_v_conv1d_weight", L);+ w->f_a = W(s, "layers_%d_self_attn_f_a_proj_weight", L);+ w->f_b = W(s, "layers_%d_self_attn_f_b_proj_weight", L);+ w->A_log = W(s, "layers_%d_self_attn_A_log", L);+ w->dt_bias = W(s, "layers_%d_self_attn_dt_bias", L);+ w->b = W(s, "layers_%d_self_attn_b_proj_weight", L);+ w->g = W(s, "layers_%d_self_attn_g_proj_weight", L);+ w->o_norm = W(s, "layers_%d_self_attn_o_norm_weight", L);+ w->o = W(s, "layers_%d_self_attn_o_proj_weight", L);+ if (!w->q || !w->f_b || !w->A_log || !w->o) return 0;+ lw->kda = w;+ }++ if (k3_is_dense(c, L)) {+ lw->dense_gate = W(s, "layers_%d_mlp_gate_proj_weight", L);+ lw->dense_up = W(s, "layers_%d_mlp_up_proj_weight", L);+ lw->dense_down = W(s, "layers_%d_mlp_down_proj_weight", L);+ if (!lw->dense_gate) return 0;+ } else {+ K3MoeW *w = &m->moe[L];+ w->gate = W(s, "layers_%d_mlp_gate_weight", L);+ w->bias = W(s, "layers_%d_mlp_e_score_correction_bias", L);+ w->down = W(s, "layers_%d_mlp_down_weight", L);+ w->up = W(s, "layers_%d_mlp_up_weight", L);+ w->latent_norm = W(s, "layers_%d_mlp_norm_weight", L);+ w->sh1 = W(s, "layers_%d_mlp_shared_w1_weight", L);+ w->sh3 = W(s, "layers_%d_mlp_shared_w3_weight", L);+ w->sh2 = W(s, "layers_%d_mlp_shared_w2_weight", L);+ m->w1[L] = pack(s, L, "w1", c->n_experts, p13);+ m->w3[L] = pack(s, L, "w3", c->n_experts, p13);+ m->w2[L] = pack(s, L, "w2", c->n_experts, p2);+ w->w1 = m->w1[L]; w->w3 = m->w3[L]; w->w2 = m->w2[L];+ if (!w->gate || !w->w1 || !w->w2) return 0;+ lw->moe = w;+ }+ }+ return 1;+}++static void forward(Model *m, const K3Cfg *c, const int *ids, int T, float *logits,+ float *scratch, float *h, float *br, float *kstate)+{+ const int E = c->hidden;+ const int maxb = c->n_layers / c->attn_res_block + 2;+ const int P = c->kda_heads * c->kda_head_dim;+ const size_t kper = (size_t)P * (size_t)c->kda_head_dim+ + (size_t)3 * (size_t)P * (size_t)(c->conv_k - 1);++ for (int t = 0; t < T; t++)+ memcpy(h + (size_t)t * E, m->embed + (size_t)ids[t] * E,+ (size_t)E * sizeof(float));++ memset(br, 0, (size_t)T * (size_t)maxb * (size_t)E * sizeof(float));+ memset(kstate, 0, kper * (size_t)c->n_layers * sizeof(float));+ int nb = 0;+ for (int L = 0; L < c->n_layers; L++)+ k3_decoder_layer(h, br, &nb, &m->lay[L], c, L, T,+ kstate + kper * (size_t)L, scratch);++ /* The MODEL-LEVEL aggregator. Beyond the 2 per layer there is one more:+ * output_attn_res_{norm,proj}. The tensor census counts exactly 1 of these.+ * Skipping it is silent. */+ if (m->out_res_norm && m->out_res_proj) {+ float *fold = scratch;+ float *src = fold + E;+ for (int i = 0; i < E; i++) fold[i] = m->out_res_norm[i] * m->out_res_proj[i];+ for (int t = 0; t < T; t++) {+ for (int b = 0; b < nb; b++)+ memcpy(src + (size_t)b * E, br + ((size_t)t * maxb + b) * E,+ (size_t)E * sizeof(float));+ memcpy(src + (size_t)nb * E, h + (size_t)t * E, (size_t)E * sizeof(float));+ k3_attn_res(h + (size_t)t * E, src, fold, nb + 1, E, c->rms_eps);+ }+ }++ float *nrm = scratch;+ for (int t = 0; t < T; t++) {+ k3_rmsnorm(nrm, h + (size_t)t * E, m->final_norm, E, c->rms_eps);+ k3_matmul(logits + (size_t)t * (size_t)c->vocab, nrm, m->lm_head, E, c->vocab);+ }+}++static 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; }++/* 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"+ * into "this program runs a different model and says nothing", which no test in this+ * file can detect, every fixture would still load, and every comparison would be+ * against the wrong architecture. */++int main(int argc, char **argv)+{+ const char *dir = (argc > 1) ? argv[1] : "../fixtures";++ /* Open BEFORE printing the banner. Printing it first made a failed run look like a+ * started one: the header and fixture path scrolled past, the error went to stderr,+ * and a captured transcript read as though the gates had been attempted. The first+ * argument is a DIRECTORY holding tiny_k3.json, tiny_k3.bin and ref_k3.json; passing+ * the .bin itself is the easy mistake, so say so. */+ Store st; memset(&st, 0, sizeof st);+ if (!store_open(&st, dir)) {+ fprintf(stderr, "GATE ABORTED: cannot load checkpoint from '%s'\n"+ " expected a DIRECTORY containing tiny_k3.json + tiny_k3.bin\n"+ " usage: k3_model <fixture_dir>\n", dir);+ return 2;+ }+ char p[512]; snprintf(p, sizeof p, "%s/ref_k3.json", dir);+ char *rtxt = slurp_(p, NULL);+ if (!rtxt) { fprintf(stderr, "GATE ABORTED: cannot read %s\n", p); return 2; }++ printf("Kimi K3 pure-C engine, full-model oracle gate\n");+ printf("fixtures: %s\n\n", dir);+ char *rar = NULL; jval *ref = json_parse(rtxt, &rar);++ jval *jc = json_get(ref, "config");+ jval *jp = json_get(ref, "prompt_ids");+ jval *jf = json_get(ref, "full_ids");+ jval *jt = json_get(ref, "tf_pred");+ if (!jc || !jp || !jf || !jt) { fprintf(stderr, "ref_k3.json incomplete\n"); return 2; }+++ /* One reader for both config shapes, and it refuses to default a field it cannot+ * find. The previous inline block read FLAT names only, so pointing this gate at+ * the released nested config.json would have silently produced an all-KDA model+ * with correct-looking SiTU betas. See k3_cfg.h. */+ K3Cfg c; static int fabuf[128];+ if (!k3_cfg_load(&c, fabuf, 128, jc, p)) {+ fprintf(stderr, "GATE ABORTED: config in %s could not be read with confidence\n", p);+ return 2;+ }++ printf("layer map (0-based): ");+ for (int i = 0; i < c.n_layers; i++) printf("%s", k3_is_mla(&c, i) ? "M" : "K");+ printf(" (M=MLA, K=KDA; dense layer = 0)\n");+ printf("attn_res boundaries at: ");+ for (int i = 0; i < c.n_layers; i++) if (i % c.attn_res_block == 0) printf("%d ", i);+ printf("\n\n");++ printf("checkpoint: %d tensors loaded\n", st.man->len);+ printf("prompt_ids %d, full_ids %d, tf_pred %d\n\n", jp->len, jf->len, jt->len);++ Model *m = (Model *)calloc(1, sizeof(Model));+ if (!model_bind(m, &st, &c)) { fprintf(stderr, "weight binding FAILED\n"); return 3; }+ printf("all layer weights bound\n\n");++ const int T = jf->len, np = jp->len;+ int *full = (int *)malloc((size_t)T * sizeof(int));+ for (int i = 0; i < T; i++) full[i] = (int)jf->kids[i]->num;++ const int maxb = c.n_layers / c.attn_res_block + 2;+ const int P = c.kda_heads * c.kda_head_dim;+ const size_t kper = (size_t)P * (size_t)c.kda_head_dim+ + (size_t)3 * (size_t)P * (size_t)(c.conv_k - 1);++ size_t need = k3_layer_scratch(&c, T);+ size_t alt = (size_t)(maxb + 2) * (size_t)c.hidden + (size_t)c.vocab;+ if (alt > need) need = alt;++ float *scratch = (float *)malloc(need * sizeof(float));+ float *h = (float *)malloc((size_t)T * (size_t)c.hidden * sizeof(float));+ float *br = (float *)malloc((size_t)T * (size_t)maxb * (size_t)c.hidden * sizeof(float));+ float *ks = (float *)malloc(kper * (size_t)c.n_layers * sizeof(float));+ float *lg = (float *)malloc((size_t)T * (size_t)c.vocab * sizeof(float));++ forward(m, &c, full, T, lg, scratch, h, br, ks);+ int tf_all = 0, tf_gen = 0, tf_gen_ok = 0;+ for (int i = 0; i < T; i++) {+ const int got = argmax_(lg + (size_t)i * (size_t)c.vocab, c.vocab);+ const int want = (int)jt->kids[i]->num;+ if (got == want) tf_all++;+ if (i >= np - 1 && i < T - 1) { tf_gen++; if (got == want) tf_gen_ok++; }+ }+ printf("GATE 1 teacher forcing : %d/%d positions match tf_pred\n", tf_all, T);+ printf(" generated span : %d/%d <- must be exact\n", tf_gen_ok, tf_gen);++ int *gen = (int *)malloc((size_t)T * sizeof(int));+ memcpy(gen, full, (size_t)np * sizeof(int));+ int cur = np, gok = 0;+ while (cur < T) {+ forward(m, &c, gen, cur, lg, scratch, h, br, ks);+ gen[cur] = argmax_(lg + (size_t)(cur - 1) * (size_t)c.vocab, c.vocab);+ if (gen[cur] == full[cur]) gok++;+ cur++;+ }+ printf("GATE 2 greedy decode : %d/%d generated tokens match full_ids\n",+ gok, T - np);++ /* ---- GATE 3: INCREMENTAL decode ----------------------------------------------+ * Gate 2 re-runs the whole prefix for every token, which is O(T^2) and, on the real+ * model, means the expert traffic grows with context. The incremental path instead+ * prefills once and then feeds ONE token at a time, carrying:+ * - the KDA recurrent matrix and ShortConv history, which k3_kda_layer already+ * updates in place, so the only change is to stop clearing them;+ * - an MLA KV cache, which is genuinely new state.+ * The attn-res block stack needs nothing carried: it is rebuilt per token from that+ * token's own hidden states.+ *+ * This must produce the SAME tokens. It is a pure restructuring of when work+ * happens, not what is computed, so anything other than an exact match is a bug in+ * the state carrying, and that is exactly the failure this gate exists to catch. */+ {+ const int H = c.n_heads, kvd = c.qk_nope + c.v_head;+ const size_t kvper = (size_t)T * H * kvd; /* per layer */+ const size_t rpper = (size_t)T * c.qk_rope;+ float *kvc = (float *)calloc(kvper * (size_t)c.n_layers, sizeof(float));+ float *rpc = (float *)calloc(rpper * (size_t)c.n_layers, sizeof(float));+ size_t need_i = k3_mla_scratch_cached(&c, T, T, 1);+ size_t li = k3_layer_scratch(&c, T);+ if (li > need_i) need_i = li;+ if (alt > need_i) need_i = alt;+ float *sc_i = (float *)malloc(need_i * sizeof(float));+ float *h_i = (float *)malloc((size_t)T * (size_t)c.hidden * sizeof(float));+ float *br_i = (float *)malloc((size_t)T * (size_t)maxb * (size_t)c.hidden * sizeof(float));+ float *ks_i = (float *)malloc(kper * (size_t)c.n_layers * sizeof(float));+ float *lg_i = (float *)malloc((size_t)c.vocab * sizeof(float));+ int *gi = (int *)malloc((size_t)T * sizeof(int));+ int iok = 0;++ if (kvc && rpc && sc_i && h_i && br_i && ks_i && lg_i && gi) {+ memcpy(gi, full, (size_t)np * sizeof(int));+ memset(ks_i, 0, kper * (size_t)c.n_layers * sizeof(float));+ int cached = 0;+ for (int step = 0; cached < T - 1 || step == 0; step++) {+ /* 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);++ cached = base + nT;+ if (cached >= T) break;+ gi[cached] = argmax_(lg_i, c.vocab);+ }+ for (int i = np; i < T; i++) if (gi[i] == full[i]) iok++;+ }+ 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 */+ free(kvc); free(rpc); free(sc_i); free(h_i); free(br_i); free(ks_i); free(lg_i); free(gi);+ }++ const int pass = (tf_gen_ok == tf_gen) && (gok == T - np);+ printf("\nVERDICT: %s\n", pass ? "ENGINE MATCHES THE REFERENCE EXACTLY"+ : "MISMATCH, see the counts above");+ if (!pass) {+ printf("\n ref ");+ for (int i = np; i < T && i < np + 14; i++) printf("%4d", full[i]);+ printf("\n got ");+ for (int i = np; i < T && i < np + 14; i++) printf("%4d", gen[i]);+ printf("\n");+ }++ free(full); free(gen); free(scratch); free(h); free(br); free(ks); free(lg);+ for (int L = 0; L < c.n_layers; L++) { free(m->w1[L]); free(m->w3[L]); free(m->w2[L]); }+ free(m);++ free(rtxt); free(rar); free(st.raw); free(st.arena); free(st.blob);+ /* Return the VERDICT, not 0.+ * Propagate the gate result as the exit status so the top-level+ * correctness gate could never go red: `pass` was computed, printed, and thrown+ * away. `make oracle` reported success whether the banner said ENGINE MATCHES THE+ * REFERENCE EXACTLY or MISMATCH, so the exit=0 recorded next to that banner in+ * fixtures/gates/gates.txt carried no information at all. The careful line above,+ * `gok = (iok == T - np) ? gok : -1;`, existed only to poison a value that was then+ * discarded. Both sibling harnesses already propagated (test_ops.c and+ * scale_test.c); this one was left out. */+ return pass ? 0 : 1;+}diff --git a/tests/unit/scale_test.c b/tests/unit/scale_test.cnew file mode 100644index 0000000..49c2b01--- /dev/null+++ b/tests/unit/scale_test.c@@ -0,0 +1,220 @@+/* scale_test.c - does the engine hold up at REAL Kimi K3 dimensions?+ *+ * Everything validated so far ran at hidden 128 with 13 layers. The real model is+ * 7168 wide with 93 layers, 96 heads, 896 experts. The mathematics is identical, but+ * three classes of failure only appear at scale and all of them are silent:+ *+ * 1. INTEGER OVERFLOW. 12288 * 7168 = 88,080,384 fits in int32, but+ * 12288 * 7168 * 4 bytes = 352 MB does not fit comfortably once multiplied by a+ * layer count, and an expert bank is 92 * 896 * 33,030,144 elements. Any product+ * computed in int rather than size_t wraps and produces a wrong pointer.+ * 2. SCRATCH SIZING. The k3_*_scratch helpers must return the right value at real+ * widths, not just tiny ones.+ * 3. EXECUTION. A full-width KDA layer is about 443M parameters; at fp32 that is+ * 1.8 GB of weights, which fits on an ordinary box and is worth running once.+ *+ * This does NOT load real weights. It allocates at real shapes with synthetic values+ * to prove the plumbing survives the dimensions.+ */+/* -std=c99 hides the POSIX clock API; request it before any include. */+#define _POSIX_C_SOURCE 199309L++#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <time.h>++#include "k3.h"++static double now_s(void)+{+ struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t);+ return t.tv_sec + t.tv_nsec * 1e-9;+}++static void fill(float *p, size_t n, unsigned seed)+{+ unsigned s = seed ? seed : 1u;+ for (size_t i = 0; i < n; i++) {+ s ^= s << 13; s ^= s >> 17; s ^= s << 5;+ p[i] = ((float)(s >> 8) / 8388608.0f - 1.0f) * 0.02f;+ }+}++static void human(double bytes, char *out, size_t n)+{+ const char *u[] = {"B", "KB", "MB", "GB", "TB"};+ int i = 0; while (bytes >= 1000.0 && i < 4) { bytes /= 1000.0; i++; }+ snprintf(out, n, "%.2f %s", bytes, u[i]);+}++int main(void)+{+ K3Cfg c; memset(&c, 0, sizeof c);+ c.hidden = 7168; c.n_layers = 93; c.vocab = 163840; c.rms_eps = 1e-5f;+ c.kda_heads = 96; c.kda_head_dim = 128; c.conv_k = 4; c.gate_lb = -5.0f;+ c.n_heads = 96; c.q_lora = 1536; c.kv_lora = 512;+ c.qk_nope = 128; c.qk_rope = 64; c.v_head = 128; c.mla_out_gate = 1;+ c.n_experts = 896; c.topk = 16; c.n_shared = 2;+ c.latent = 3584; c.moe_inter = 3072; c.routed_scale = 1.0f;+ c.moe_renorm = 1; c.latent_norm = 1;+ c.first_dense = 1; c.dense_inter = 33792;+ c.attn_res_block = 12;+ c.situ_b1 = 4.0f; c.situ_b2 = 25.0f;++ static int fa[24];+ int nfa = 0;+ for (int i = 4; i <= 93; i += 4) fa[nfa++] = i;+ fa[nfa++] = 93; /* the trailing extra MLA layer */+ c.n_full_attn = nfa; c.full_attn = fa;++ char b1[32], b2[32];+ printf("Kimi K3 scale test, REAL dimensions\n");+ printf("hidden %d, layers %d, heads %d, experts %d top-%d, latent %d\n\n",+ c.hidden, c.n_layers, c.kda_heads, c.n_experts, c.topk, c.latent);++ /* ---------- 1. layer map ---------- */+ int nk = 0, nm = 0;+ for (int i = 0; i < c.n_layers; i++) { if (k3_is_mla(&c, i)) nm++; else nk++; }+ printf("layer map: %d KDA + %d MLA = %d (expect 69 + 24 = 93) %s\n",+ nk, nm, nk + nm, (nk == 69 && nm == 24) ? "OK" : "WRONG");+ printf(" last five layers: ");+ for (int i = c.n_layers - 5; i < c.n_layers; i++)+ printf("%d=%s ", i, k3_is_mla(&c, i) ? "MLA" : "KDA");+ printf("\n layer 0 dense: %s\n\n", k3_is_dense(&c, 0) ? "yes" : "no");++ /* ---------- 2. scratch sizing, checked for overflow ---------- */+ printf("scratch requirements (floats), checked in size_t:\n");+ const int Ts[] = {1, 8, 512, 4096};+ int scratch_bad = 0;+ for (unsigned i = 0; i < sizeof Ts / sizeof *Ts; i++) {+ const int T = Ts[i];+ size_t mla = k3_mla_scratch(&c, T), kda = k3_kda_scratch(&c, T);+ size_t moe = k3_moe_scratch(&c), lay = k3_layer_scratch(&c, T);+ human((double)lay * 4, b1, sizeof b1);+ printf(" T=%-5d mla %-12zu kda %-12zu moe %-10zu layer %-12zu (%s)\n",+ T, mla, kda, moe, lay, b1);+ /* A scratch size of zero, or a layer buffer smaller than a sub-buffer it must+ * contain, is a heap overflow waiting for a caller that trusts it. Detecting one+ * is a FAILURE, not a remark, so it feeds the verdict at the end of main. */+ if (mla == 0 || kda == 0 || lay < mla || lay < kda) {+ printf(" OVERFLOW OR UNDERSIZE at T=%d\n", T);+ scratch_bad = 1;+ }+ }+ printf("\n");++ /* ---------- 3. parameter and byte budget ---------- */+ const size_t P = (size_t)c.kda_heads * c.kda_head_dim; /* 12288 */+ const size_t kda_par = 4 * P * c.hidden + (size_t)c.hidden * P+ + 3 * P * c.conv_k+ + (size_t)c.kda_head_dim * c.hidden + P * c.kda_head_dim+ + (size_t)c.kda_heads * c.hidden+ + c.kda_heads + P + c.kda_head_dim;+ const size_t exp_par = 3ull * (size_t)c.moe_inter * c.latent;+ const size_t all_exp = (size_t)(c.n_layers - 1) * c.n_experts * exp_par;++ human((double)kda_par * 2, b1, sizeof b1);+ printf("one KDA layer : %zu params (%s at bf16)\n", kda_par, b1);+ human((double)kda_par * 69 * 2, b1, sizeof b1);+ /* This figure covers KDA ATTENTION ONLY and is NOT the resident trunk. It omits the+ * 24 MLA layers and, more importantly, the shared experts, 6144 wide, shipped BF16+ * rather than MXFP4, dense, and fired on every token. The always-active set measured+ * from the 96 shard headers by tools/budget.py is 56,743,648,000 parameters,+ * 113.49 GB at bf16, of which this line is barely half. Reporting it as the trunk+ * understates the memory requirement by a factor of two. */+ printf("69 KDA layers : %s at bf16 (KDA attention ONLY, not the whole trunk)\n", b1);+ printf("full trunk : 113.49 GB at bf16, 56,743,648,000 always-active params\n"+ " (measured from the shard headers, not derived here)\n");+ human((double)exp_par * 0.53125, b1, sizeof b1);+ printf("one expert : %zu params (%s at MXFP4)\n", exp_par, b1);+ human((double)all_exp * 0.53125, b1, sizeof b1);+ printf("all %zu experts: %s at MXFP4 <- streamed from NVMe\n",+ (size_t)(c.n_layers - 1) * c.n_experts, b1);++ /* ---------- 4. per-sequence state ---------- */+ const size_t kstate = (size_t)69 * c.kda_heads * c.kda_head_dim * c.kda_head_dim;+ const size_t cstate = (size_t)69 * 3 * P * (c.conv_k - 1);+ human((double)kstate * 2, b1, sizeof b1);+ human((double)cstate * 2, b2, sizeof b2);+ printf("\nper-sequence state, FIXED regardless of context:\n");+ printf(" KDA recurrent : %s at bf16\n", b1);+ printf(" ShortConv : %s at bf16\n", b2);+ /* What the engine ACTUALLY caches, which is not the compressed latent. Re-expanding+ * the 576-float latent through kv_b for every cached position would cost an O(T)+ * sweep of 24576x512 matmuls per layer per token, so k3_mla_cached stores the+ * EXPANDED per-head keys and values plus the shared rope slot, in fp32. That is 42x+ * the latent, and quoting the latent figure here understated the cost by the same+ * factor. */+ const double kv_tok = ((double)c.n_heads * (c.qk_nope + c.v_head) + c.qk_rope) * 24 * 4;+ human(kv_tok, b1, sizeof b1);+ printf(" MLA KV : %s per position (24 MLA layers, EXPANDED k and v, fp32)\n", b1);+ for (long ctx = 8192; ctx <= 1048576; ctx *= 16) {+ human(kv_tok * (double)ctx, b1, sizeof b1);+ printf(" %s at %ld context\n", b1, ctx);+ }++ /* ---------- 5. actually run one full-width KDA layer ---------- */+ printf("\nallocating and running ONE full-width KDA layer (fp32)...\n");+ const int T = 4;+ K3KdaW w; memset(&w, 0, sizeof w);+ size_t need = 4 * P * c.hidden + (size_t)c.hidden * P + 3 * P * c.conv_k+ + (size_t)c.kda_head_dim * c.hidden + P * c.kda_head_dim+ + (size_t)c.kda_heads * c.hidden + c.kda_heads + P + c.kda_head_dim;+ human((double)need * 4, b1, sizeof b1);+ printf(" weights: %s\n", b1);+ float *W_ = (float *)malloc(need * sizeof(float));+ if (!W_) { printf(" ALLOCATION FAILED -- not enough RAM for the test\n"); return 1; }+ fill(W_, need, 12345u);++ size_t o = 0;+ w.q = W_ + o; o += P * c.hidden; w.k = W_ + o; o += P * c.hidden;+ w.v = W_ + o; o += P * c.hidden; w.g = W_ + o; o += P * c.hidden;+ w.o = W_ + o; o += (size_t)c.hidden * P;+ w.q_conv = W_ + o; o += P * c.conv_k;+ w.k_conv = W_ + o; o += P * c.conv_k;+ w.v_conv = W_ + o; o += P * c.conv_k;+ w.f_a = W_ + o; o += (size_t)c.kda_head_dim * c.hidden;+ w.f_b = W_ + o; o += P * c.kda_head_dim;+ w.b = W_ + o; o += (size_t)c.kda_heads * c.hidden;+ w.A_log = W_ + o; o += c.kda_heads;+ w.dt_bias = W_ + o; o += P;+ w.o_norm = W_ + o; o += c.kda_head_dim;++ float *x = (float *)malloc((size_t)T * c.hidden * sizeof(float));+ float *y = (float *)malloc((size_t)T * c.hidden * sizeof(float));+ float *sc = (float *)malloc(k3_kda_scratch(&c, T) * sizeof(float));+ float *st = (float *)calloc((size_t)P * c.kda_head_dim + 3 * P * (c.conv_k - 1),+ sizeof(float));+ if (!x || !y || !sc || !st) { printf(" scratch allocation FAILED\n"); return 1; }+ fill(x, (size_t)T * c.hidden, 999u);++ const double t0 = now_s();+ k3_kda_layer(y, x, &w, &c, T, st, sc);+ const double dt = now_s() - t0;++ int finite = 1; double mx = 0.0;+ for (size_t i = 0; i < (size_t)T * c.hidden; i++) {+ if (!isfinite(y[i])) { finite = 0; break; }+ if (fabs(y[i]) > mx) mx = fabs(y[i]);+ }+ printf(" ran %d tokens in %.2f s (%.0f ms/token)\n", T, dt, dt * 1000 / T);+ printf(" output all finite: %s, max |y| = %.6f\n", finite ? "YES" : "NO", mx);+ printf(" state non-zero : %s\n",+ st[0] != 0.0f || st[1] != 0.0f ? "yes" : "no (suspicious)");++ /* Every condition this file checks feeds the exit status. A test that prints an+ * alarming banner and then exits 0 is worse than no test: CI stays green and the+ * banner scrolls past. */+ const int ok = (nk == 69 && nm == 24 && finite && !scratch_bad);+ printf("\nSCALE TEST %s\n", ok ? "PASSED" : "FAILED");+ if (scratch_bad)+ printf(" a scratch size was zero or undersized see the table above\n");+ if (!finite)+ printf(" the KDA layer produced non-finite output at full width\n");+ if (nk != 69 || nm != 24)+ printf(" layer map is wrong: %d KDA + %d MLA, expected 69 + 24\n", nk, nm);+ free(W_); free(x); free(y); free(sc); free(st);+ return ok ? 0 : 1;+}diff --git a/tests/unit/test_cache.c b/tests/unit/test_cache.cnew file mode 100644index 0000000..c3829c1--- /dev/null+++ b/tests/unit/test_cache.c@@ -0,0 +1,186 @@+/* test_cache.c - the streaming expert cache, which nothing else tests.+ *+ * WHY THIS FILE EXISTS+ * Every op fixture and all three oracle gates drive the RESIDENT expert bank+ * (K3MoeW.w1/w3/w2). The streaming path (K3MoeW.src -> K3Cache) is reached only when+ * running the real 1.56 TB checkpoint. So the component the entire project depends on+ * had no test at all, and it showed: a batch-prefetch bug that handed one slot to+ * several experts simultaneously passed 22/22 fixtures and all three gates, and was+ * caught only because the real model emitted token 65 where it should have emitted+ * 2494. A test that cannot fail is worse than no test; a path with no test is worse+ * still.+ *+ * WHAT IS CHECKED+ * 1 IDENTITY every expert read back through the cache is byte-identical to the+ * same expert read straight off disk. This is the check the aliasing+ * bug fails.+ * 2 EQUIVALENCE the batch prefetch and the serial path return the SAME bytes. The+ * prefetch is an optimisation; if it changes a byte it is wrong.+ * 3 PRESSURE with a cache far smaller than the working set, so eviction runs+ * constantly and slots are recycled aggressively. The bug only+ * appeared under pressure, because with a roomy cache pick_victim+ * returns genuinely free slots and the aliasing never happens.+ * 4 ACCOUNTING requests, hits and prefetch_reads stay mutually consistent.+ *+ * usage: test_cache <fixture_dir> [n_experts]+ * fixture_dir comes from tools/make_cache_fixture.py+ */+#define _POSIX_C_SOURCE 200809L++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "k3.h"+#include "k3_cache.h"+#include "k3_load.h"+#include "k3_st.h"++static int g_fail = 0;++static void ck(int ok, const char *what, const char *detail)+{+ printf(" %s %-34s %s\n", ok ? "PASS" : "FAIL", what, detail ? detail : "");+ if (!ok) g_fail++;+}++/* Read an expert straight from the store, bypassing the cache entirely. This is the+ * ground truth the cache is measured against. */+static unsigned char *direct_read(const K3St *st, int layer, int e, int64_t *nb)+{+ K3ExpertRef r;+ if (k3_expert_ref(st, layer, e, &r) != 0) return NULL;+ unsigned char *b = (unsigned char *)malloc((size_t)r.nbytes);+ if (!b) return NULL;+ if (k3_expert_load(st, &r, b) != r.nbytes) { free(b); return NULL; }+ *nb = r.nbytes;+ return b;+}++/* The three (packed, scale) pairs the cache hands out must point at bytes equal to the+ * direct read. Compare through the SAME offsets the kernels use, so a wrong pad or a+ * wrong slot base is caught, not just a wrong buffer. */+static int same_expert(const K3St *st, int layer, int e, const K3ExpertQ *q)+{+ int64_t nb = 0;+ unsigned char *truth = direct_read(st, layer, e, &nb);+ if (!truth) return 0;+ K3ExpertRef r;+ if (k3_expert_ref(st, layer, e, &r) != 0) { free(truth); return 0; }++ const unsigned char *got[6] = { q->p1, q->s1, q->p2, q->s2, q->p3, q->s3 };+ int ok = 1;+ for (int i = 0; i < 3 && ok; i++) {+ const unsigned char *tp = truth + r.m[i].p_off, *ts = truth + r.m[i].s_off;+ const int64_t pn = (int64_t)r.m[i].rows * r.m[i].pcols;+ const int64_t sn = (int64_t)r.m[i].rows * r.m[i].scols;+ if (memcmp(got[i * 2], tp, (size_t)pn) != 0) ok = 0;+ if (memcmp(got[i * 2 + 1], ts, (size_t)sn) != 0) ok = 0;+ }+ free(truth);+ return ok;+}++int main(int argc, char **argv)+{+ const char *dir = argc > 1 ? argv[1] : "../fixtures/cache";+ const int NE = argc > 2 ? atoi(argv[2]) : 24;++ K3St st;+ if (k3_st_open(&st, dir) != 0) {+ fprintf(stderr, "TEST ABORTED: cannot open %s\n"+ " build it with: python3 tools/make_cache_fixture.py\n", dir);+ return 2;+ }+ printf("streaming expert cache, %d tensors from %d shard(s)\n\n", st.nt, st.nshard);++ K3Cfg c; memset(&c, 0, sizeof c);+ c.n_layers = 1; c.n_experts = NE; c.topk = 4;++ /* Size the budget by asking, not by arithmetic. The cache rounds a slot up to an+ * O_DIRECT-widened, page-aligned size, so for these deliberately tiny fixture+ * experts the requested budget and the usable slot count part company badly. Grow+ * until init accepts, then confirm PRESSURE remains: fewer slots than experts,+ * so eviction actually runs. A roomy cache hides slot-recycling bugs entirely. */+ K3ExpertRef probe;+ if (k3_expert_ref(&st, 0, 0, &probe) != 0) { fprintf(stderr, "no expert 0\n"); return 2; }+ K3Cache cache;+ int ok_init = 0;+ for (int64_t budget = probe.nbytes * 8; budget <= probe.nbytes * 4096; budget *= 2) {+ if (k3_cache_init(&cache, &st, &c, budget) == 0) { ok_init = 1; break; }+ }+ if (!ok_init) { fprintf(stderr, "cache init failed at every budget\n"); return 2; }+ { char b[80]; snprintf(b, sizeof b, "%d slots for %d experts, top-%d",+ cache.nslot, NE, c.topk);+ ck(cache.nslot >= c.topk + 1 && cache.nslot < NE, "cache under pressure", b); }++ /* ---- 1+3: serial path, every expert, under eviction pressure ---- */+ int bad = 0;+ for (int pass = 0; pass < 3; pass++)+ for (int e = 0; e < NE; e++) {+ K3ExpertQ q;+ if (cache.src.get(&cache.src, 0, e, &q) != 0) { bad++; continue; }+ if (!same_expert(&st, 0, e, &q)) bad++;+ }+ { char b[64]; snprintf(b, sizeof b, "%d of %d reads wrong", bad, 3 * NE);+ ck(bad == 0, "serial reads are byte-exact", b); }++ /* ---- 2: batch prefetch must agree with the serial path ----+ * This is the check the aliasing bug fails. Ask for a whole top-k at once, with the+ * cache too small to hold the previous batch, then verify EVERY expert. */+ k3_cache_reset_stats(&cache);+ int bad2 = 0, batches = 0;+ if (!cache.src.getmany) {+ ck(0, "batch prefetch present", "getmany is NULL");+ } else {+ for (int start = 0; start + c.topk <= NE; start += c.topk) {+ int ids[16];+ for (int j = 0; j < c.topk; j++) ids[j] = start + j;+ cache.src.getmany(&cache.src, 0, ids, c.topk);+ batches++;+ for (int j = 0; j < c.topk; j++) {+ K3ExpertQ q;+ if (cache.src.get(&cache.src, 0, ids[j], &q) != 0) { bad2++; continue; }+ if (!same_expert(&st, 0, ids[j], &q)) bad2++;+ }+ }+ char b[96];+ snprintf(b, sizeof b, "%d batches of %d, %d wrong", batches, c.topk, bad2);+ ck(bad2 == 0, "batch prefetch is byte-exact", b);++ /* ACCOUNTING, checked HERE and only here. The loop above is exactly the pattern+ * k3_moe uses -- prefetch a top-k, then consume that same top-k -- and for that+ * pattern every prefetched expert is still resident when get() asks, so it is+ * recorded as a hit and prefetch_reads can never exceed hits. If it does, the+ * report's "true resident hit rate" underflows and the whole figure is a lie.+ * The mixed test below deliberately prefetches sets it never consumes, so the+ * invariant does NOT hold there and asserting it would be wrong. */+ char a[128];+ snprintf(a, sizeof a, "requests %llu, hits %llu, prefetch %llu",+ (unsigned long long)(cache.hits + cache.misses),+ (unsigned long long)cache.hits,+ (unsigned long long)cache.prefetch_reads);+ ck(cache.prefetch_reads <= cache.hits, "prefetch_reads <= hits", a);+ }++ /* ---- 2b: interleaving the two paths must not corrupt either ---- */+ k3_cache_reset_stats(&cache);+ int bad3 = 0;+ for (int e = 0; e < NE; e++) {+ if (cache.src.getmany && (e % 2) == 0) {+ int ids[4];+ for (int j = 0; j < 4; j++) ids[j] = (e + j) % NE;+ cache.src.getmany(&cache.src, 0, ids, 4);+ }+ K3ExpertQ q;+ if (cache.src.get(&cache.src, 0, e, &q) != 0) { bad3++; continue; }+ if (!same_expert(&st, 0, e, &q)) bad3++;+ }+ { char b[64]; snprintf(b, sizeof b, "%d of %d wrong", bad3, NE);+ ck(bad3 == 0, "mixed batch and serial", b); }++ k3_cache_free(&cache);+ k3_st_close(&st);+ printf("\n%s\n", g_fail ? "CACHE TESTS FAILED" : "CACHE TESTS PASSED");+ return g_fail ? 1 : 0;+}diff --git a/tests/unit/test_cfg.c b/tests/unit/test_cfg.cnew file mode 100644index 0000000..bb6d65e--- /dev/null+++ b/tests/unit/test_cfg.c@@ -0,0 +1,120 @@+/* test_cfg.c - prove the config reader handles both shapes and refuses bad ones.+ *+ * Portable C: no weights, no Linux, no checkpoint. The point is that the reader that+ * decides which of 93 layers are MLA can be verified on any machine in a second.+ *+ * test_cfg real <config.json> released nested shape; asserts the K3 constants+ * test_cfg fixture <ref_k3.json> flat shape, config nested under "config"+ * test_cfg reject <file.json> expects the load to FAIL (negative test)+ */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include "k3_cfg.h"++static int fails = 0;++static void ck(int cond, const char *what, long got, long want)+{+ if (cond) { printf(" ok %-28s %ld\n", what, got); }+ else { printf(" FAIL %-28s got %ld, want %ld\n", what, got, want); fails++; }+}++int main(int argc, char **argv)+{+ if (argc < 3) { fprintf(stderr, "usage: test_cfg <real|fixture|reject> <path>\n"); return 2; }+ const char *mode = argv[1], *path = argv[2];++ K3Cfg c; static int fa[128];++ if (!strcmp(mode, "reject")) {+ int ok = k3_cfg_load_file(&c, fa, 128, path);+ if (ok) { printf(" FAIL expected rejection, but the config loaded\n"); return 1; }+ printf(" ok correctly rejected %s\n", path);+ return 0;+ }++ if (!strcmp(mode, "fixture")) {+ /* ref_k3.json wraps the config in a "config" member. */+ FILE *f = fopen(path, "rb");+ if (!f) { perror(path); return 2; }+ fseek(f, 0, SEEK_END); long n = ftell(f); fseek(f, 0, SEEK_SET);+ char *txt = (char *)malloc((size_t)n + 1);+ size_t got = fread(txt, 1, (size_t)n, f); fclose(f); txt[got] = 0;+ char *arena = NULL;+ jval *root = json_parse(txt, &arena);+ jval *cfg = json_get(root, "config");+ if (!cfg) { fprintf(stderr, "%s has no \"config\" member\n", path); return 2; }+ if (!k3_cfg_load(&c, fa, 128, cfg, path)) return 1;++ /* The tiny oracle's own numbers, from make_k3_oracle.py. */+ ck(c.hidden == 128, "hidden", c.hidden, 128);+ ck(c.n_layers == 13, "layers", c.n_layers, 13);+ ck(c.vocab == 256, "vocab", c.vocab, 256);+ ck(c.kda_heads == 4, "kda heads", c.kda_heads, 4);+ ck(c.kda_head_dim == 16, "kda head_dim", c.kda_head_dim, 16);+ ck(c.n_experts == 8, "experts", c.n_experts, 8);+ ck(c.topk == 2, "topk", c.topk, 2);+ ck(c.latent == 64, "latent", c.latent, 64);+ ck(c.attn_res_block == 3, "attn_res_block", c.attn_res_block, 3);+ ck(c.situ_b1 == 4.0f, "situ b1", (long)c.situ_b1, 4);+ ck(c.situ_b2 == 25.0f, "situ b2", (long)c.situ_b2, 25);+ ck(c.n_full_attn == 4, "full_attn count", c.n_full_attn, 4);+ ck(c.gate_lb == -5.0f, "gate_lb (x-1)", (long)(-c.gate_lb), 5);+ printf("\n%s\n", fails ? "FIXTURE CONFIG: FAIL" : "FIXTURE CONFIG: PASS");+ return fails ? 1 : 0;+ }++ if (!strcmp(mode, "real")) {+ if (!k3_cfg_load_file(&c, fa, 128, path)) return 1;++ /* Every one of these is independently attested in docs/the tech report, so a+ * silent config change shows up here rather than 93 layers later. */+ ck(c.hidden == 7168, "hidden", c.hidden, 7168);+ ck(c.n_layers == 93, "layers", c.n_layers, 93);+ ck(c.vocab == 163840, "vocab", c.vocab, 163840);+ ck(c.kda_heads == 96, "kda heads", c.kda_heads, 96);+ ck(c.kda_head_dim == 128, "kda head_dim", c.kda_head_dim, 128);+ ck(c.conv_k == 4, "short conv k", c.conv_k, 4);+ ck(c.n_heads == 96, "attn heads", c.n_heads, 96);+ ck(c.q_lora == 1536, "q_lora", c.q_lora, 1536);+ ck(c.kv_lora == 512, "kv_lora", c.kv_lora, 512);+ ck(c.qk_nope == 128, "qk_nope", c.qk_nope, 128);+ ck(c.qk_rope == 64, "qk_rope", c.qk_rope, 64);+ ck(c.v_head == 128, "v_head", c.v_head, 128);+ ck(c.n_experts == 896, "experts", c.n_experts, 896);+ ck(c.topk == 16, "topk", c.topk, 16);+ ck(c.n_shared == 2, "shared experts", c.n_shared, 2);+ ck(c.latent == 3584, "latent", c.latent, 3584);+ ck(c.moe_inter == 3072, "moe_inter", c.moe_inter, 3072);+ ck(c.first_dense == 1, "dense layers", c.first_dense, 1);+ ck(c.dense_inter == 33792, "dense_inter", c.dense_inter, 33792);+ ck(c.attn_res_block == 12, "attn_res_block", c.attn_res_block, 12);+ ck(c.situ_b1 == 4.0f, "situ b1", (long)c.situ_b1, 4);+ ck(c.situ_b2 == 25.0f, "situ b2", (long)c.situ_b2, 25);+ ck(c.gate_lb == -5.0f, "gate_lb (x-1)", (long)(-c.gate_lb), 5);++ /* THE check this file exists for. 24 MLA layers, one-based 4,8,...,92 plus a+ * final 93 so the last layer is global attention (tech report 2.1). If the+ * nesting were mishandled this count would be 0 and every layer would run KDA. */+ ck(c.n_full_attn == 24, "MLA layer count", c.n_full_attn, 24);+ ck(fa[0] == 4, "first MLA layer", fa[0], 4);+ ck(fa[22] == 92, "MLA layer 23", fa[22], 92);+ ck(fa[23] == 93, "last MLA layer", fa[23], 93);++ /* And the derived split the engine actually branches on. */+ int nmla = 0, nkda = 0;+ for (int i = 0; i < c.n_layers; i++) k3_is_mla(&c, i) ? nmla++ : nkda++;+ ck(nmla == 24, "k3_is_mla says", nmla, 24);+ ck(nkda == 69, "k3_is_kda says", nkda, 69);+ /* Layers 91 and 92 zero-based are BOTH MLA (one-based 92 and 93). */+ ck(k3_is_mla(&c, 91) && k3_is_mla(&c, 92), "layers 91,92 both MLA", 1, 1);+ ck(!k3_is_mla(&c, 0), "layer 0 is KDA", k3_is_mla(&c, 0) ? 1 : 0, 0);++ printf("\n%s\n", fails ? "REAL CONFIG: FAIL" : "REAL CONFIG: PASS");+ return fails ? 1 : 0;+ }++ fprintf(stderr, "unknown mode %s\n", mode);+ return 2;+}diff --git a/tests/unit/test_expert.c b/tests/unit/test_expert.cnew file mode 100644index 0000000..62dcb06--- /dev/null+++ b/tests/unit/test_expert.c@@ -0,0 +1,285 @@+/* test_expert.c - load real routed experts from the real checkpoint, and time it.+ *+ * TWO QUESTIONS, BOTH ANSWERED WITH THE RELEASED WEIGHTS ON LOCAL DISK.+ *+ * 1. CORRECTNESS. test_ops already proves k3_mxfp4_dequant is bit-exact against+ * fixtures/mxfp4.json, but that fixture was built from bytes pulled over HTTP by+ * tools/fetch_mxfp4.py. It proves the dequantiser, not the reader. This program+ * closes the last link: it reads the same expert out of a local shard through+ * k3_st/k3_load and dumps both the raw packed bytes and the dequantised floats, so+ * tools/verify_expert.py can check them against that independently fetched fixture.+ * If the reader computes an offset wrong, the bytes differ and it shows here.+ *+ * 2. SPEED, WHICH DECIDES WHETHER THE PROJECT WORKS AT ALL. A decode step routes to+ * top-16 experts in each of 92 MoE layers: 1,472 expert loads, 17.55 MB each,+ * 25.83 GB per token if nothing is cached. Whether that is 4 seconds or 400 is a+ * property of the storage, not of the code, and it has to be measured rather than+ * assumed. Three regimes are timed:+ * sequential cold - experts in file order, page cache dropped+ * random cold - experts in shuffled order, page cache dropped <- the real one+ * warm - the same reads served from page cache <- the cache ceiling+ * Random cold is what actually happens, because routing does not respect file order.+ *+ * usage: test_expert <shard_dir> [layer] [n_experts]+ */+/* glibc hides sync() behind __USE_MISC, which _POSIX_C_SOURCE alone does not set, so+ * it needs _DEFAULT_SOURCE too. Without it sync() is implicitly declared as returning+ * int when it returns void. */+#define _POSIX_C_SOURCE 200809L+#define _DEFAULT_SOURCE++#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <time.h>+#include <unistd.h>++#include "k3.h"+#include "k3_load.h"++/* Non-zero if any correctness check failed; becomes the exit status. */+static int g_bad = 0;++static double now_s(void)+{+ struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t);+ return t.tv_sec + t.tv_nsec * 1e-9;+}++static void drop_caches(void)+{+ /* Without this the second run reads from RAM and reports a storage bandwidth that+ * does not exist. Needs root; if it fails the timings are labelled warm. */+ sync();+ FILE *f = fopen("/proc/sys/vm/drop_caches", "w");+ if (f) { fputs("3\n", f); fclose(f); }+}++static int have_root(void) { FILE *f = fopen("/proc/sys/vm/drop_caches", "w");+ if (f) { fclose(f); return 1; } return 0; }++/* xorshift, so the shuffle is reproducible across runs and machines. */+static unsigned rs = 12345u;+static unsigned rnd(void) { rs ^= rs << 13; rs ^= rs >> 17; rs ^= rs << 5; return rs; }++int main(int argc, char **argv)+{+ if (argc < 2) { fprintf(stderr, "usage: test_expert <shard_dir> [layer] [n]\n"); return 2; }+ const char *dir = argv[1];+ const int layer = argc > 2 ? atoi(argv[2]) : 1;+ int n = argc > 3 ? atoi(argv[3]) : 64;++ K3St s;+ double t0 = now_s();+ if (k3_st_open(&s, dir) != 0) return 1;+ printf("indexed %d tensors from %d shard(s) in %.2f s\n\n", s.nt, s.nshard, now_s() - t0);++ /* ---- how many experts does this layer actually have? ---- */+ int have = 0;+ for (int e = 0; e < 1024; e++) {+ char nm[256];+ snprintf(nm, sizeof nm,+ "language_model.model.layers.%d.block_sparse_moe.experts.%d.w1.weight_packed",+ layer, e);+ if (!k3_st_find(&s, nm)) break;+ have++;+ }+ printf("layer %d has %d routed experts present in this shard set\n", layer, have);+ if (have == 0) { fprintf(stderr, "no experts for layer %d here\n", layer); k3_st_close(&s); return 1; }+ if (n > have) n = have;++ /* ---- geometry and contiguity, checked across every expert ---- */+ K3ExpertRef r0;+ if (k3_expert_ref(&s, layer, 0, &r0) != 0) { k3_st_close(&s); return 1; }+ printf("expert 0 geometry:\n");+ static const char *W[3] = { "w1", "w2", "w3" };+ for (int i = 0; i < 3; i++)+ printf(" %s packed [%d][%d] -> logical [%d][%d], scales [%d][%d], group %d\n",+ W[i], r0.m[i].rows, r0.m[i].pcols, r0.m[i].rows, r0.m[i].pcols * 2,+ r0.m[i].rows, r0.m[i].scols, K3_MXFP4_GROUP);+ printf(" run: shard %d, offset %lld, %lld bytes, contiguous %s\n",+ r0.shard, (long long)r0.off, (long long)r0.nbytes, r0.contiguous ? "YES" : "NO");++ int64_t params = 0;+ for (int i = 0; i < 3; i++) params += k3_qmat_numel(&r0.m[i]);+ printf(" %lld parameters in %lld bytes = %.6f bytes/param (MXFP4 predicts %.6f)\n",+ (long long)params, (long long)r0.nbytes, (double)r0.nbytes / (double)params,+ 0.5 + 1.0 / 32.0);++ int noncontig = 0, badgeom = 0;+ for (int e = 0; e < have; e++) {+ K3ExpertRef r;+ if (k3_expert_ref(&s, layer, e, &r) != 0) { badgeom++; continue; }+ if (!r.contiguous) noncontig++;+ if (r.nbytes != r0.nbytes) badgeom++;+ }+ printf(" across all %d experts: %d non-contiguous, %d with unexpected geometry%s\n\n",+ have, noncontig, badgeom, (noncontig || badgeom) ? " <-- INVESTIGATE" : "");++ /* Stop here if any expert differs in size from expert 0.+ *+ * Everything below loads experts into a buffer sized for expert 0. Continuing past a+ * detected geometry anomaly would write a larger expert into that buffer, a heap+ * overflow, in the code path whose entire purpose was to warn about the anomaly. A+ * non-uniform expert bank is also a legitimate failure in its own right: the streaming+ * cache sizes every slot from one probe and assumes the rest match. */+ if (badgeom) {+ fprintf(stderr,+ "FAIL: %d of %d experts do not match expert 0's geometry.\n"+ " The expert cache sizes all slots from a single probe, so a\n"+ " non-uniform bank cannot be streamed safely. Refusing to load.\n",+ badgeom, have);+ return 1;+ }++ unsigned char *buf = (unsigned char *)malloc((size_t)r0.nbytes);+ if (!buf) { fprintf(stderr, "cannot allocate %lld bytes\n", (long long)r0.nbytes); return 1; }++ /* ---- correctness dump for expert 0, w1 ---- */+ if (k3_expert_load(&s, &r0, buf) != r0.nbytes) { fprintf(stderr, "load failed\n"); return 1; }+ {+ const int rows = 64; /* what fetch_mxfp4.py recorded */+ const int64_t wid = (int64_t)r0.m[0].pcols * 2;+ float *w1 = (float *)malloc((size_t)rows * wid * sizeof(float));+ k3_mxfp4_dequant(w1, buf + r0.m[0].p_off, buf + r0.m[0].s_off,+ rows, r0.m[0].pcols, K3_MXFP4_GROUP);+ FILE *f = fopen("expert_dump.json", "w");+ fprintf(f, "{\"layer\":%d,\"expert\":0,\"rows\":%d,\"pcols\":%d,\"width\":%lld,",+ layer, rows, r0.m[0].pcols, (long long)wid);+ fprintf(f, "\"packed\":[");+ for (int64_t i = 0; i < (int64_t)rows * r0.m[0].pcols; i++)+ fprintf(f, "%s%u", i ? "," : "", buf[r0.m[0].p_off + i]);+ fprintf(f, "],\"scales\":[");+ for (int64_t i = 0; i < (int64_t)rows * r0.m[0].scols; i++)+ fprintf(f, "%s%u", i ? "," : "", buf[r0.m[0].s_off + i]);+ fprintf(f, "],\"bits\":[");+ for (int64_t i = 0; i < (int64_t)rows * wid; i++) {+ union { float f; uint32_t u; } b; b.f = w1[i];+ fprintf(f, "%s%u", i ? "," : "", b.u);+ }+ fprintf(f, "]}\n");+ fclose(f);+ double mn = 1e30, mx = -1e30, ss = 0.0; int64_t nz = 0;+ for (int64_t i = 0; i < (int64_t)rows * wid; i++) {+ if (w1[i] < mn) mn = w1[i];+ if (w1[i] > mx) mx = w1[i];+ ss += (double)w1[i] * w1[i];+ if (w1[i] != 0.0f) nz++;+ }+ printf("expert 0 w1, first %d rows dequantised:\n", rows);+ printf(" min %.6f max %.6f rms %.6f nonzero %.1f%%\n",+ mn, mx, sqrt(ss / ((double)rows * wid)), 100.0 * nz / ((double)rows * wid));+ printf(" wrote expert_dump.json for tools/verify_expert.py\n\n");+ free(w1);+ }++ /* ---- the fused MXFP4 matmul must equal dequantise-then-multiply ----+ * k3_matmul_mxfp4 is what lets a cached expert stay 17.55 MB instead of 132 MB, so+ * it sits on the critical path of every routed token. It is a second, independent+ * implementation of the same arithmetic as k3_mxfp4_dequant followed by k3_matmul,+ * and the two must agree. They accumulate in a different ORDER (the fused version+ * sums within a 32-element group before applying the shared scale), so the+ * comparison is against double-precision rounding, not against zero. */+ {+ const int rows = r0.m[0].rows, wid = r0.m[0].pcols * 2;+ float *W = (float *)malloc((size_t)rows * wid * sizeof(float));+ float *x = (float *)malloc((size_t)wid * sizeof(float));+ float *ya = (float *)malloc((size_t)rows * sizeof(float));+ float *yb = (float *)malloc((size_t)rows * sizeof(float));+ if (W && x && ya && yb) {+ for (int i = 0; i < wid; i++) {+ rs ^= rs << 13; rs ^= rs >> 17; rs ^= rs << 5;+ x[i] = (float)(rs >> 8) / 8388608.0f - 1.0f;+ }+ double t1 = now_s();+ k3_mxfp4_dequant(W, buf + r0.m[0].p_off, buf + r0.m[0].s_off,+ rows, r0.m[0].pcols, K3_MXFP4_GROUP);+ k3_matmul(ya, x, W, wid, rows);+ double t_deq = now_s() - t1;++ t1 = now_s();+ k3_matmul_mxfp4(yb, x, buf + r0.m[0].p_off, buf + r0.m[0].s_off,+ wid, rows, K3_MXFP4_GROUP);+ double t_fus = now_s() - t1;++ double maxabs = 0.0, maxrel = 0.0, scale = 0.0;+ for (int i = 0; i < rows; i++) {+ const double d = fabs((double)ya[i] - (double)yb[i]);+ if (d > maxabs) maxabs = d;+ if (fabs(ya[i]) > scale) scale = fabs(ya[i]);+ }+ maxrel = scale > 0 ? maxabs / scale : 0.0;+ printf("fused MXFP4 matmul vs dequantise-then-matmul, w1 [%d][%d]:\n", rows, wid);+ /* This comparison is the ONLY correctness assertion in this program: it is+ * what proves the fused MXFP4 matmul agrees with dequantise-then-multiply on+ * released checkpoint bytes. The comparison must assert, not merely print, or a broken+ * nibble order or a mis-biased E8M0 scale printed "DISAGREE <-- BUG" and the+ * process still exited 0. Record it so main can return it. */+ if (!(maxrel < 1e-6)) g_bad++;+ printf(" max abs diff %.3e, relative to max |y| %.3e %s\n",+ maxabs, maxrel, maxrel < 1e-6 ? "AGREE" : "DISAGREE <-- BUG");+ printf(" dequant+matmul %.1f ms (plus %.1f MB materialised), fused %.1f ms\n",+ t_deq * 1000.0, (double)rows * wid * 4 / 1e6, t_fus * 1000.0);+ printf(" fused reads %.2f MB instead of %.2f MB: %.1fx less memory traffic\n\n",+ (double)(r0.m[0].p_bytes + r0.m[0].s_bytes) / 1e6,+ (double)rows * wid * 4 / 1e6,+ (double)rows * wid * 4 / (double)(r0.m[0].p_bytes + r0.m[0].s_bytes));+ }+ free(W); free(x); free(ya); free(yb);+ }++ /* ---- build the access orders ---- */+ int *seq = (int *)malloc((size_t)n * sizeof(int));+ int *shuf = (int *)malloc((size_t)have * sizeof(int));+ for (int i = 0; i < n; i++) seq[i] = i;+ for (int i = 0; i < have; i++) shuf[i] = i;+ for (int i = have - 1; i > 0; i--) { int j = (int)(rnd() % (unsigned)(i + 1));+ int t = shuf[i]; shuf[i] = shuf[j]; shuf[j] = t; }++ const int root = have_root();+ printf("page cache control: %s\n", root ? "available (cold timings are genuine)"+ : "UNAVAILABLE, run as root for cold timings");++ struct { const char *label; int *order; int cold; } runs[] = {+ { "sequential, cold", seq, 1 },+ { "random, cold ", shuf, 1 },+ { "random, warm ", shuf, 0 },+ };++ printf("\n%-18s %8s %10s %12s %12s\n", "ACCESS PATTERN", "EXPERTS", "SECONDS", "MB/s", "EXPERTS/s");+ printf("%s\n", "----------------------------------------------------------------");+ double rand_cold_mbs = 0.0;+ for (unsigned k = 0; k < sizeof runs / sizeof *runs; k++) {+ if (runs[k].cold) { if (!root) continue; drop_caches(); }+ double best_t = 0.0;+ int64_t bytes = 0;+ double t1 = now_s();+ for (int i = 0; i < n; i++) {+ K3ExpertRef r;+ if (k3_expert_ref(&s, layer, runs[k].order[i], &r) != 0) continue;+ bytes += k3_expert_load(&s, &r, buf);+ }+ best_t = now_s() - t1;+ double mbs = (double)bytes / 1e6 / best_t;+ printf("%-18s %8d %10.3f %12.0f %12.1f\n",+ runs[k].label, n, best_t, mbs, n / best_t);+ if (k == 1) rand_cold_mbs = mbs;+ }++ /* ---- what that means per token ---- */+ if (rand_cold_mbs > 0.0) {+ const double per_tok_gb = 1472.0 * (double)r0.nbytes / 1e9; /* 92 layers x top-16 */+ printf("\nprojected, top-16 across 92 MoE layers, nothing cached:\n");+ printf(" %.2f GB of experts per token\n", per_tok_gb);+ printf(" at the measured random-cold %.0f MB/s: %.1f s/token (%.3f tok/s)\n",+ rand_cold_mbs, per_tok_gb * 1000.0 / rand_cold_mbs,+ rand_cold_mbs / (per_tok_gb * 1000.0));+ printf(" this is the FLOOR that caching and prefetch have to beat.\n");+ }++ free(buf); free(seq); free(shuf);+ k3_st_close(&s);+ if (g_bad) printf("\n%d CHECK(S) FAILED\n", g_bad);+ return g_bad ? 1 : 0;+}diff --git a/tests/unit/test_ops.c b/tests/unit/test_ops.cnew file mode 100644index 0000000..6a2d614--- /dev/null+++ b/tests/unit/test_ops.c@@ -0,0 +1,897 @@+/* test_ops.c - fixture-driven validation of the individual Kimi K3 kernels.+ *+ * Each fixture under tests/fixtures/ops/ is generated by tools/emit_fixtures.py from the+ * pure-torch reference and carries its own weights, inputs and expected outputs. This+ * binary reads them and reports pass or fail per operation.+ *+ * Per-op fixtures exist alongside the full-model oracle because the oracle localises+ * nothing: it reports that the stack is wrong, not which of ~40 kernels is responsible.+ * Every kernel is gated here individually so a failure names its own cause.+ *+ * Fixtures are parsed with the vendored json.h (Apache 2.0, see NOTICE).+ */+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "json.h"+#include "k3.h"++/* FALLBACKS ONLY. The authority is the tolerance block in MANIFEST.json, loaded by main+ * and applied to every comparison. These values are used only if the manifest cannot be+ * read, and they are deliberately looser than the published contract so that the+ * fallback can never be mistaken for a pass at the real tolerance.+ *+ * Tolerances live in the manifest rather than in this file so the fixture set and its+ * pass criteria cannot drift apart. A harness that grades itself more kindly than its+ * own manifest is worse than no manifest at all. */+static float ATOL = 1e-4f;+static float RTOL = 1e-3f;++static int g_pass = 0, g_fail = 0;+/* Skips are counted and surfaced in the summary. A test whose fixture is absent prints+ * returned without touching either counter, so the summary still read "21 passed, 0+ * failed" with a test silently missing. For t_mxfp4 that meant the ONLY check of the+ * expert quantisation format against released checkpoint bytes could vanish and the suite+ * would still report a clean sweep. Skips are now counted and are a non-zero exit. */+static int g_skip = 0;++/* ------------------------------------------------------------- utilities ---- */+static char *slurp(const char *path)+{+ FILE *f = fopen(path, "rb");+ if (!f) { fprintf(stderr, "cannot open %s\n", path); return NULL; }+ fseek(f, 0, SEEK_END); long n = ftell(f); fseek(f, 0, SEEK_SET);+ char *b = (char *)malloc((size_t)n + 1);+ if (!b) { fclose(f); return NULL; }+ if (fread(b, 1, (size_t)n, f) != (size_t)n) { free(b); fclose(f); return NULL; }+ b[n] = 0; fclose(f);+ return b;+}++/* like slurp but silent, for optional fixtures whose absence is not an error */+static char *slurp_quiet(const char *path)+{+ FILE *f = fopen(path, "rb");+ if (!f) return NULL;+ fseek(f, 0, SEEK_END); long n = ftell(f); fseek(f, 0, SEEK_SET);+ char *b = (char *)malloc((size_t)n + 1);+ if (!b || fread(b, 1, (size_t)n, f) != (size_t)n) { free(b); fclose(f); return NULL; }+ b[n] = 0; fclose(f);+ return b;+}++/* pull "key": {"shape": [...], "data": [...]} into a freshly allocated float array */+static float *arr(jval *root, const char *key, int *count)+{+ jval *o = json_get(root, key);+ if (!o) { fprintf(stderr, " missing key %s\n", key); return NULL; }+ jval *d = (o->t == J_OBJ) ? json_get(o, "data") : o;+ if (!d || d->t != J_ARR) { fprintf(stderr, " key %s has no data array\n", key); return NULL; }+ float *v = (float *)malloc((size_t)d->len * sizeof(float));+ if (!v) return NULL;+ for (int i = 0; i < d->len; i++) v[i] = (float)d->kids[i]->num;+ if (count) *count = d->len;+ return v;+}++static double num(jval *root, const char *key, double dflt)+{+ jval *v = json_get(root, key);+ return (v && v->t == J_NUM) ? v->num : dflt;+}++/* JSON booleans are J_BOOL, not J_NUM. Reading one with num() silently yields the+ * default, which is how layer_mla was first mistaken for a KDA layer and asked for+ * weights it does not have. */+static int boolean(jval *root, const char *key, int dflt)+{+ jval *v = json_get(root, key);+ if (!v) return dflt;+ if (v->t == J_BOOL) return v->boolean;+ if (v->t == J_NUM) return (int)v->num;+ return dflt;+}++/* read "key": {"shape": [...]} into dims[]; returns the rank, or 0 if absent.+ * Guessing row counts from element totals is how the first version of this file+ * went wrong; the fixtures carry the shape, so use it. */+static int shape(jval *root, const char *key, int *dims, int maxd)+{+ jval *o = json_get(root, key);+ if (!o || o->t != J_OBJ) return 0;+ jval *s = json_get(o, "shape");+ if (!s || s->t != J_ARR) return 0;+ const int r = s->len < maxd ? s->len : maxd;+ for (int i = 0; i < r; i++) dims[i] = (int)s->kids[i]->num;+ return r;+}++static void report(const char *name, const float *got, const float *want, int n)+{+ double worst = 0.0; int at = -1;+ for (int i = 0; i < n; i++) {+ const double a = fabs((double)got[i] - (double)want[i]);+ const double tol = ATOL + RTOL * fabs((double)want[i]);+ if (a / tol > worst) { worst = a / tol; at = i; }+ }+ if (worst <= 1.0) {+ printf(" PASS %-14s n=%-6d worst=%.2fx tol\n", name, n, worst);+ g_pass++;+ } else {+ printf(" FAIL %-14s n=%-6d worst=%.2fx tol at i=%d got %.7f want %.7f\n",+ name, n, worst, at, got[at], want[at]);+ g_fail++;+ }+}++/* ----------------------------------------------------------------- tests ---- */+static void t_rmsnorm(const char *dir)+{+ char p[512]; snprintf(p, sizeof(p), "%s/rmsnorm.json", dir);+ char *txt = slurp(p); if (!txt) { g_fail++; return; }+ char *ar = NULL; jval *r = json_parse(txt, &ar);+ int nw, ni, no;+ float *w = arr(r, "weight", &nw), *x = arr(r, "in", &ni), *e = arr(r, "out", &no);+ const float eps = (float)num(r, "eps", 1e-5);+ if (w && x && e) {+ const int rows = ni / nw;+ float *y = (float *)malloc((size_t)ni * sizeof(float));+ for (int i = 0; i < rows; i++) k3_rmsnorm(y + i * nw, x + i * nw, w, nw, eps);+ report("rmsnorm", y, e, no);+ free(y);+ }+ free(w); free(x); free(e); free(txt); free(ar);+}++static void t_situ(const char *dir)+{+ char p[512]; snprintf(p, sizeof(p), "%s/situ_glu.json", dir);+ char *txt = slurp(p); if (!txt) { g_fail++; return; }+ char *ar = NULL; jval *r = json_parse(txt, &ar);+ int ni, no;+ float *x = arr(r, "in", &ni), *e = arr(r, "out", &no);+ const float b1 = (float)num(r, "beta", 4.0), b2 = (float)num(r, "linear_beta", 25.0);+ int din[4] = {0}, dout[4] = {0};+ const int rin = shape(r, "in", din, 4), rout = shape(r, "out", dout, 4);+ if (x && e && rin == 2 && rout == 2) {+ const int R = dout[0]; /* rows */+ const int W = dout[1]; /* output width; input row is 2*W */+ if (din[1] != 2 * W || din[0] != R) {+ printf(" FAIL situ_glu shape mismatch: in=[%d,%d] out=[%d,%d], "+ "expected in=[%d,%d]\n", din[0], din[1], R, W, R, 2 * W);+ g_fail++;+ free(x); free(e); free(txt); free(ar);+ return;+ }+ float *y = (float *)malloc((size_t)no * sizeof(float));+ for (int i = 0; i < R; i++)+ k3_situ_glu(y + i * W, x + i * 2 * W, W, b1, b2);+ report("situ_glu", y, e, no);+ /* The soft cap is the one property SiTU-GLU guarantees: |out| <= b1*b2, for any+ * input whatsoever. Violating it means a tanh was dropped or applied to the+ * wrong operand, so this counts as a failure rather than printing a warning+ * nothing acts on. */+ float mx = 0.f; for (int i = 0; i < no; i++) if (fabsf(y[i]) > mx) mx = fabsf(y[i]);+ const int bound_ok = (mx <= b1 * b2 + 1e-2f);+ printf(" bound check |out|=%.3f must be <= b1*b2=%.1f : %s\n",+ mx, b1 * b2, bound_ok ? "ok" : "VIOLATED");+ if (!bound_ok) {+ printf(" SiTU-GLU's soft cap does not hold, a tanh is missing or "+ "applied to the wrong operand\n");+ g_fail++;+ }+ free(y);+ }+ free(x); free(e); free(txt); free(ar);+}++static void t_shortconv(const char *dir)+{+ char p[512]; snprintf(p, sizeof(p), "%s/shortconv.json", dir);+ char *txt = slurp(p); if (!txt) { g_fail++; return; }+ char *ar = NULL; jval *r = json_parse(txt, &ar);+ int nw, ni, no, ns;+ float *w = arr(r, "weight", &nw), *x = arr(r, "in", &ni), *e = arr(r, "out", &no);+ float *st = arr(r, "state_after", &ns);+ int nxi, nxo;+ float *xn = arr(r, "in_next", &nxi), *en = arr(r, "out_next", &nxo);+ const int K = (int)num(r, "kernel", 4), C = (int)num(r, "channels", 0);+ if (w && x && e && C) {+ const int T = ni / C;+ float *y = (float *)malloc((size_t)ni * sizeof(float));+ float *s = (float *)calloc((size_t)C * (K - 1), sizeof(float));+ k3_shortconv(y, x, w, s, C, K, T);+ report("shortconv", y, e, no);+ if (st) report("conv_state", s, st, ns);++ /* CONTINUATION. Both checks above start from a zero state, so they say nothing+ * about whether k3_shortconv READS the state it was handed. A version that wrote+ * state_after correctly but ignored the incoming history passed all of them, and+ * would then be wrong for every decode step after the first. The fixture has+ * carried this continuation pair all along and no test used it: feed the state+ * from the first call straight into a second call over in_next, and require+ * out_next. This is the only check in the suite that can see the read side. */+ if (xn && en) {+ const int T2 = nxi / C;+ float *y2 = (float *)malloc((size_t)nxi * sizeof(float));+ k3_shortconv(y2, xn, w, s, C, K, T2); /* s carries forward, deliberately */+ report("conv_continuation", y2, en, nxo);+ free(y2);+ } else {+ printf(" FAIL conv_continuation fixture lacks in_next/out_next\n");+ g_fail++;+ }+ free(y); free(s);+ }+ free(w); free(x); free(e); free(st); free(xn); free(en); free(txt); free(ar);+}++static void t_decay(const char *dir)+{+ char p[512]; snprintf(p, sizeof(p), "%s/kda_decay.json", dir);+ char *txt = slurp(p); if (!txt) { g_fail++; return; }+ char *ar = NULL; jval *r = json_parse(txt, &ar);+ int na, nb, ng, nal, nz;+ float *A = arr(r, "A_log", &na), *dt = arr(r, "dt_bias", &nb);+ float *eg = arr(r, "g", &ng), *ea = arr(r, "alpha", &nal);+ float *z = arr(r, "z", &nz);+ const float lb = (float)num(r, "lower_bound", -5.0);+ /* Drive the engine's own decay kernel and compare its output to torch elementwise.+ *+ * The weaker test this replaces only checked that the fixture's g values lay inside+ * (e^lb, 1]. That is a statement about the FIXTURE, not about the C: a k3_kda_decay+ * indexing A_log per channel instead of per head, or ignoring dt_bias entirely,+ * satisfies the range check. Exporting z lets the real function run forward from the+ * same inputs, which is the only version of this test that can fail. */+ if (A && dt && eg && ea && z) {+ const int H = na, D = nb / na, tok = ng / nb;+ float *gc = (float *)malloc((size_t)ng * sizeof(float));+ float *ac = (float *)malloc((size_t)nal * sizeof(float));+ double wg = 0.0, wa = 0.0;+ for (int t = 0; t < tok; t++)+ k3_kda_decay(gc + (size_t)t * nb, ac + (size_t)t * nb,+ z + (size_t)t * nb, A, dt, H, D, lb);+ for (int i = 0; i < ng; i++) {+ const double dg = fabs((double)gc[i] - eg[i]);+ const double da = fabs((double)ac[i] - ea[i]);+ if (dg > wg) wg = dg;+ if (da > wa) wa = da;+ }+ /* A_log spans linspace(-0.4, 1.2) across heads, so a per-CHANNEL misindex moves+ * every element and shows up here immediately. */+ const int ok = (wg <= 1e-5) && (wa <= 1e-5);+ printf(" %s kda_decay H=%d D=%d tok=%d max|dg|=%.3e max|dalpha|=%.3e "+ "(drives k3_kda_decay)\n", ok ? "PASS" : "FAIL", H, D, tok, wg, wa);+ if (ok) g_pass++; else g_fail++;+ free(gc); free(ac);+ } else {+ printf(" FAIL kda_decay fixture missing a required field%s\n",+ z ? "" : " (z absent: regenerate with tools/emit_fixtures.py)");+ g_fail++;+ }+ free(A); free(dt); free(eg); free(ea); free(z); free(txt); free(ar);+}++static void t_attnres(const char *dir)+{+ char p[512]; snprintf(p, sizeof(p), "%s/attnres.json", dir);+ char *txt = slurp(p); if (!txt) { g_fail++; return; }+ char *ar = NULL; jval *r = json_parse(txt, &ar);+ int npx, nbr, nf, no;+ float *px = arr(r, "prefix_sum", &npx), *br = arr(r, "block_residual", &nbr);+ float *fold = arr(r, "fold_hint", &nf), *e = arr(r, "out", &no);+ const float eps = (float)num(r, "eps", 1e-5);+ if (px && br && fold && e) {+ const int n = nf, rows = npx / n, nblk = nbr / (rows * n);+ const int nsrc = nblk + 1;+ float *src = (float *)malloc((size_t)nsrc * n * sizeof(float));+ float *y = (float *)malloc((size_t)rows * n * sizeof(float));+ for (int rw = 0; rw < rows; rw++) {+ for (int b = 0; b < nblk; b++)+ memcpy(src + (size_t)b * n,+ br + ((size_t)rw * nblk + b) * n, (size_t)n * sizeof(float));+ memcpy(src + (size_t)nblk * n, px + (size_t)rw * n, (size_t)n * sizeof(float));+ k3_attn_res(y + (size_t)rw * n, src, fold, nsrc, n, eps);+ }+ report("attn_res", y, e, no);+ free(src); free(y);+ }+ free(px); free(br); free(fold); free(e); free(txt); free(ar);+}++/* The isolated recurrence. This is where the ordering bug lives: decay, then the+ * rank-one delta write, then read the ALREADY UPDATED state. Any permutation runs+ * cleanly and produces a wrong model, so it gets its own test at T=1 and T=8. */+static void t_recur(const char *dir, const char *file)+{+ char p[512]; snprintf(p, sizeof(p), "%s/%s.json", dir, file);+ char *txt = slurp(p); if (!txt) { g_fail++; return; }+ char *ar = NULL; jval *r = json_parse(txt, &ar);++ const int T = (int)num(r, "T", 0), H = (int)num(r, "H", 0);+ const int dk = (int)num(r, "d_k", 0), dv = (int)num(r, "d_v", dk);+ const float qs = (float)num(r, "q_scale", 1.0);+ int nq, nk, nv, na, nb, no, nso;+ float *q = arr(r, "q", &nq), *k = arr(r, "k", &nk), *v = arr(r, "v", &nv);+ float *al = arr(r, "alpha", &na), *bt = arr(r, "beta", &nb);+ float *eo = arr(r, "out", &no), *es = arr(r, "state_out", &nso);++ if (q && k && v && al && bt && eo && es && T && H && dk) {+ float *S = (float *)calloc((size_t)H * dk * dv, sizeof(float));+ float *out = (float *)malloc((size_t)T * H * dv * sizeof(float));+ float *qs_ = (float *)malloc((size_t)dk * sizeof(float));+ for (int t = 0; t < T; t++) {+ for (int h = 0; h < H; h++) {+ const size_t off = ((size_t)t * H + h) * dk;+ for (int i = 0; i < dk; i++) qs_[i] = q[off + i] * qs; /* d_k^-0.5 */+ k3_kda_step(S + (size_t)h * dk * dv,+ out + ((size_t)t * H + h) * dv,+ qs_, k + off, v + off,+ al + ((size_t)t * H + h) * dk,+ bt[(size_t)t * H + h], dk, dv);+ }+ }+ char nm[32]; snprintf(nm, sizeof(nm), "%s_out", file);+ report(nm, out, eo, no);+ snprintf(nm, sizeof(nm), "%s_state", file);+ report(nm, S, es, nso);+ free(S); free(out); free(qs_);+ }+ free(q); free(k); free(v); free(al); free(bt); free(eo); free(es);+ free(txt); free(ar);+}++/* Router. The fixture's frozen bias reorders the top-k in 5 of 6 rows, so an engine+ * that ignored e_score_correction_bias, or that gathered the weights from the BIASED+ * scores, fails here rather than silently degrading. Indices are compared as SETS+ * because the reference uses topk(sorted=False), whose order is unspecified. */+static void t_router(const char *dir)+{+ char p[512]; snprintf(p, sizeof(p), "%s/router.json", dir);+ char *txt = slurp(p); if (!txt) { g_fail++; return; }+ char *ar = NULL; jval *r = json_parse(txt, &ar);++ int nw, nb, ni, nidx, nwt;+ float *W = arr(r, "gate_weight", &nw), *bias = arr(r, "bias", &nb);+ float *x = arr(r, "in", &ni);+ float *eidx = arr(r, "topk_idx", &nidx), *ewt = arr(r, "topk_weight", &nwt);+ const int K = (int)num(r, "top_k", 0), E = (int)num(r, "n_experts", 0);++ if (W && bias && x && eidx && ewt && K && E) {+ const int hidden = nw / E, rows = ni / hidden;+ int *gi = (int *)malloc((size_t)K * sizeof(int));+ float *gw = (float *)malloc((size_t)K * sizeof(float));+ int set_ok = 1; double worst_w = 0.0;++ for (int rw = 0; rw < rows; rw++) {+ k3_router(gi, gw, x + (size_t)rw * hidden, W, bias, hidden, E, K, 1, 1.0f);++ /* compare index SETS */+ for (int a = 0; a < K; a++) {+ int found = 0;+ for (int b = 0; b < K; b++)+ if ((int)eidx[(size_t)rw * K + b] == gi[a]) { found = 1; break; }+ if (!found) { set_ok = 0;+ printf(" row %d: C picked expert %d, reference did not\n", rw, gi[a]); }+ }+ /* match weights by expert id, since order is unspecified */+ for (int a = 0; a < K; a++) {+ for (int b = 0; b < K; b++) {+ if ((int)eidx[(size_t)rw * K + b] != gi[a]) continue;+ const double d = fabs((double)gw[a] - (double)ewt[(size_t)rw * K + b]);+ const double tol = ATOL + RTOL * fabs((double)ewt[(size_t)rw * K + b]);+ if (d / tol > worst_w) worst_w = d / tol;+ }+ }+ }+ if (set_ok && worst_w <= 1.0) {+ printf(" PASS router rows=%-4d k=%d index sets match, "+ "worst weight=%.2fx tol\n", rows, K, worst_w);+ g_pass++;+ } else {+ printf(" FAIL router index_sets=%s worst weight=%.2fx tol\n",+ set_ok ? "ok" : "MISMATCH", worst_w);+ g_fail++;+ }+ free(gi); free(gw);+ }+ free(W); free(bias); free(x); free(eidx); free(ewt); free(txt); free(ar);+}++/* Gated MLA. The fixture now ships all eight weight tensors, so this is genuinely+ * reproducible. Watch for: the 192-wide head (128 nope + 64 unrotated rope), the+ * scale over 192 not 128, the single-head k_rope broadcast, and the gate applied+ * BEFORE o_proj with no norm. */+static void t_mla(const char *dir)+{+ char p[512]; snprintf(p, sizeof(p), "%s/mla.json", dir);+ char *txt = slurp(p); if (!txt) { g_fail++; return; }+ char *ar = NULL; jval *r = json_parse(txt, &ar);++ K3Cfg c; memset(&c, 0, sizeof c);+ c.qk_nope = (int)num(r, "qk_nope", 0);+ c.qk_rope = (int)num(r, "qk_rope", 0);+ c.kv_lora = (int)num(r, "kv_lora", 0);+ c.q_lora = (int)num(r, "q_lora", 0);+ c.v_head = (int)num(r, "v_head", 0);+ c.n_heads = (int)num(r, "n_heads", 0);+ c.rms_eps = (float)num(r, "rms_eps", 1e-5);++ int n_in, n_out, dum;+ float *x = arr(r, "in", &n_in);+ float *eo = arr(r, "out", &n_out);+ /* Zeroed: wdt selects fp32 versus bf16 dispatch, and stack garbage there sends+ * fp32 fixture arrays into k3_matmul_bf16. That fails nondeterministically and+ * looks like an arithmetic bug in MLA rather than an initialisation bug here. */+ K3MlaW w; memset(&w, 0, sizeof w);+ w.q_a = arr(r, "q_a_proj_weight", &dum);+ w.q_a_norm = arr(r, "q_a_layernorm_weight", &dum);+ w.q_b = arr(r, "q_b_proj_weight", &dum);+ w.kv_a = arr(r, "kv_a_proj_with_mqa_weight", &dum);+ w.kv_a_norm= arr(r, "kv_a_layernorm_weight", &dum);+ w.kv_b = arr(r, "kv_b_proj_weight", &dum);+ w.o = arr(r, "o_proj_weight", &dum);+ w.g = arr(r, "g_proj_weight", &dum);++ if (x && eo && w.q_a && w.q_b && w.kv_a && w.kv_b && w.o) {+ int din[4] = {0};+ shape(r, "in", din, 4);+ const int T = din[1];+ c.hidden = din[2];+ float *scratch = (float *)malloc(k3_mla_scratch(&c, T) * sizeof(float));+ float *y = (float *)malloc((size_t)T * c.hidden * sizeof(float));+ if (scratch && y) {+ k3_mla(y, x, &w, &c, T, scratch);+ report("mla", y, eo, n_out);+ printf(" H=%d qh=%d (nope %d + rope %d) v=%d kv_lora=%d scale=%.6f\n",+ c.n_heads, c.qk_nope + c.qk_rope, c.qk_nope, c.qk_rope,+ c.v_head, c.kv_lora, 1.0 / sqrt((double)(c.qk_nope + c.qk_rope)));+ }+ free(scratch); free(y);+ }+ free(x); free(eo);+ free((void *)w.q_a); free((void *)w.q_a_norm); free((void *)w.q_b);+ free((void *)w.kv_a); free((void *)w.kv_a_norm); free((void *)w.kv_b);+ free((void *)w.o); free((void *)w.g);+ free(txt); free(ar);+}++/* Stable LatentMoE. The fixture drives SiTU into its caps and uses a routing bias+ * that genuinely reorders the top-k, so a wrong ordering (norming per expert instead+ * of on the aggregate, weighting the shared expert, routing on the latent instead of+ * the full width) fails here rather than degrading quietly. */+static void t_moe(const char *dir)+{+ char p[512]; snprintf(p, sizeof(p), "%s/moe.json", dir);+ char *txt = slurp(p); if (!txt) { g_fail++; return; }+ char *ar = NULL; jval *r = json_parse(txt, &ar);++ K3Cfg c; memset(&c, 0, sizeof c);+ c.hidden = (int)num(r, "hidden", 0);+ c.latent = (int)num(r, "latent", 0);+ c.moe_inter = (int)num(r, "moe_inter", 0);+ c.n_experts = (int)num(r, "n_experts", 0);+ c.topk = (int)num(r, "top_k", 0);+ c.n_shared = (int)num(r, "n_shared", 0);+ c.routed_scale = (float)num(r, "routed_scale", 1.0);+ c.moe_renorm = (int)num(r, "renorm", 1);+ c.latent_norm = (int)num(r, "latent_norm", 1);+ c.rms_eps = (float)num(r, "rms_eps", 1e-5);+ c.situ_b1 = (float)num(r, "situ_b1", 4.0);+ c.situ_b2 = (float)num(r, "situ_b2", 25.0);++ int n_in, n_out, d;+ float *x = arr(r, "in", &n_in);+ float *eo = arr(r, "out", &n_out);++ /* Zeroed, not merely assigned field by field: K3MoeW carries an optional expert+ * SOURCE, and a garbage src on an uninitialised stack struct is called as a+ * function pointer. */+ K3MoeW w; memset(&w, 0, sizeof w);+ w.gate = arr(r, "gate_weight", &d);+ w.bias = arr(r, "e_score_correction_bias", &d);+ w.down = arr(r, "down_weight", &d);+ w.up = arr(r, "up_weight", &d);+ w.latent_norm = arr(r, "norm_weight", &d);+ w.sh1 = arr(r, "shared_w1_weight", &d);+ w.sh3 = arr(r, "shared_w3_weight", &d);+ w.sh2 = arr(r, "shared_w2_weight", &d);++ /* routed experts arrive as experts_N_wK_weight; pack them contiguously */+ const size_t per13 = (size_t)c.moe_inter * c.latent;+ const size_t per2 = (size_t)c.latent * c.moe_inter;+ float *W1 = (float *)malloc(per13 * c.n_experts * sizeof(float));+ float *W3 = (float *)malloc(per13 * c.n_experts * sizeof(float));+ float *W2 = (float *)malloc(per2 * c.n_experts * sizeof(float));+ int packed = 1;+ for (int e = 0; e < c.n_experts && packed; e++) {+ char k1[64], k3[64], k2[64];+ snprintf(k1, sizeof k1, "experts_%d_w1_weight", e);+ snprintf(k3, sizeof k3, "experts_%d_w3_weight", e);+ snprintf(k2, sizeof k2, "experts_%d_w2_weight", e);+ float *a1 = arr(r, k1, &d), *a3 = arr(r, k3, &d), *a2 = arr(r, k2, &d);+ if (!a1 || !a3 || !a2) { packed = 0; free(a1); free(a3); free(a2); break; }+ memcpy(W1 + e * per13, a1, per13 * sizeof(float));+ memcpy(W3 + e * per13, a3, per13 * sizeof(float));+ memcpy(W2 + e * per2, a2, per2 * sizeof(float));+ free(a1); free(a3); free(a2);+ }+ w.w1 = W1; w.w3 = W3; w.w2 = W2;++ if (x && eo && packed && w.gate && w.down && w.up && w.sh1) {+ int din[4] = {0}; shape(r, "in", din, 4);+ const int T = din[1];+ int *idx = (int *)malloc((size_t)c.topk * sizeof(int));+ float *wt = (float *)malloc((size_t)c.topk * sizeof(float));+ float *sc = (float *)malloc(k3_moe_scratch(&c) * sizeof(float));+ float *y = (float *)malloc((size_t)T * c.hidden * sizeof(float));+ if (idx && wt && sc && y) {+ k3_moe(y, x, &w, &c, T, idx, wt, sc);+ report("moe", y, eo, n_out);+ printf(" hidden=%d latent=%d inter=%d experts=%d top%d shared=%d\n",+ c.hidden, c.latent, c.moe_inter, c.n_experts, c.topk, c.n_shared);+ }+ free(idx); free(wt); free(sc); free(y);+ } else if (!packed) {+ printf(" FAIL moe could not pack expert weights from fixture\n");+ g_fail++;+ }+ free(x); free(eo); free(W1); free(W3); free(W2);+ free((void *)w.gate); free((void *)w.bias); free((void *)w.down); free((void *)w.up);+ free((void *)w.latent_norm); free((void *)w.sh1); free((void *)w.sh3); free((void *)w.sh2);+ free(txt); free(ar);+}++/* The full KDA layer. This is the last and hardest component before the decoder+ * layer: projections, three depthwise convs with fused SiLU, L2Norm on q/k only,+ * the shared low-rank decay, the per-head beta, the recurrence, the head-wise norm+ * and the gate in THAT order, then the output projection. Run at T=1 (the decode+ * path) and T=8 (where an ordering bug compounds). */+static void t_kda_layer(const char *dir, const char *file)+{+ char p[512]; snprintf(p, sizeof(p), "%s/%s.json", dir, file);+ char *txt = slurp(p); if (!txt) { g_fail++; return; }+ char *ar = NULL; jval *r = json_parse(txt, &ar);++ K3Cfg c; memset(&c, 0, sizeof c);+ c.kda_heads = (int)num(r, "H", 0);+ c.kda_head_dim = (int)num(r, "d_k", 0);+ c.conv_k = (int)num(r, "conv_k", 4);+ c.gate_lb = (float)num(r, "lower_bound", -5.0);+ c.rms_eps = (float)num(r, "rms_eps", 1e-5);++ int n_in, n_out, n_st, d;+ float *x = arr(r, "in", &n_in);+ float *eo = arr(r, "out", &n_out);+ float *es = arr(r, "state_out", &n_st);++ K3KdaW w; memset(&w, 0, sizeof w); /* see the note in t_mla: wdt must not be garbage */+ w.q = arr(r, "q_proj", &d); w.k = arr(r, "k_proj", &d); w.v = arr(r, "v_proj", &d);+ w.q_conv = arr(r, "q_conv", &d); w.k_conv = arr(r, "k_conv", &d);+ w.v_conv = arr(r, "v_conv", &d);+ w.f_a = arr(r, "f_a", &d); w.f_b = arr(r, "f_b", &d);+ w.A_log = arr(r, "A_log", &d); w.dt_bias = arr(r, "dt_bias", &d);+ w.b = arr(r, "b_proj", &d); w.g = arr(r, "g_proj", &d);+ w.o_norm = arr(r, "o_norm", &d); w.o = arr(r, "o_proj", &d);++ if (x && eo && w.q && w.f_b && w.A_log && w.o) {+ int din[4] = {0}; shape(r, "in", din, 4);+ const int T = din[1];+ c.hidden = din[2];+ const int P = c.kda_heads * c.kda_head_dim, hist = c.conv_k - 1;+ float *st = (float *)calloc((size_t)P * c.kda_head_dim+ + (size_t)3 * P * hist, sizeof(float));+ float *sc = (float *)malloc(k3_kda_scratch(&c, T) * sizeof(float));+ float *y = (float *)malloc((size_t)T * c.hidden * sizeof(float));+ if (st && sc && y) {+ k3_kda_layer(y, x, &w, &c, T, st, sc);+ char nm[40]; snprintf(nm, sizeof nm, "%s_out", file);+ report(nm, y, eo, n_out);+ if (es) { snprintf(nm, sizeof nm, "%s_state", file);+ report(nm, st, es, n_st); }+ }+ free(st); free(sc); free(y);+ }+ free(x); free(eo); free(es);+ free((void*)w.q); free((void*)w.k); free((void*)w.v);+ free((void*)w.q_conv); free((void*)w.k_conv); free((void*)w.v_conv);+ free((void*)w.f_a); free((void*)w.f_b); free((void*)w.A_log);+ free((void*)w.dt_bias); free((void*)w.b); free((void*)w.g);+ free((void*)w.o_norm); free((void*)w.o);+ free(txt); free(ar);+}++/* A whole decoder layer: the AttnRes wiring plus attention plus the MoE. This is the+ * last stop before the full model. What it actually exercises that nothing else does:+ * the aggregate REPLACING the layer input, the snapshot push, and the prefix_sum+ * reset at a block boundary. layer_kda is index 1 (not a boundary, so the running+ * residual survives); layer_mla is index 3 (also not a boundary here, block size 3+ * means boundaries are 0,3,6,9,12 -- so index 3 IS one). Between them both paths run. */+static float *pack_experts(jval *r, const char *fmt, int n, size_t per)+{+ float *W = (float *)malloc(per * n * sizeof(float));+ if (!W) return NULL;+ for (int e = 0; e < n; e++) {+ char key[80]; int d;+ snprintf(key, sizeof key, fmt, e);+ float *a = arr(r, key, &d);+ if (!a) { free(W); return NULL; }+ memcpy(W + (size_t)e * per, a, per * sizeof(float));+ free(a);+ }+ return W;+}++static void t_layer(const char *dir, const char *file)+{+ char p[512]; snprintf(p, sizeof(p), "%s/%s.json", dir, file);+ char *txt = slurp(p); if (!txt) { g_fail++; return; }+ char *ar = NULL; jval *r = json_parse(txt, &ar);++ const int li = (int)num(r, "layer_idx", 0);+ const int is_mla = boolean(r, "is_mla", 0);++ K3Cfg c; memset(&c, 0, sizeof c);+ c.hidden = (int)num(r, "hidden", 0);+ c.rms_eps = (float)num(r, "rms_eps", 1e-5);+ c.attn_res_block = (int)num(r, "attn_res_block_size", 3);+ c.n_layers = 13;+ c.kda_heads = 4; c.kda_head_dim = 16; c.conv_k = 4; c.gate_lb = -5.0f;+ c.n_heads = 4; c.q_lora = 64; c.kv_lora = 32;+ c.qk_nope = 24; c.qk_rope = 8; c.v_head = 16;+ c.n_experts = 8; c.topk = 2; c.n_shared = 2;+ c.latent = 64; c.moe_inter = 48; c.routed_scale = 1.0f;+ c.moe_renorm = 1; c.latent_norm = 1;+ c.situ_b1 = 4.0f; c.situ_b2 = 25.0f;+ c.first_dense = 1; c.dense_inter = 96;++ int n_in, n_out, n_bri, d;+ float *x = arr(r, "in", &n_in);+ float *eo = arr(r, "out", &n_out);+ float *bri = arr(r, "block_residual_in", &n_bri);++ K3KdaW kw; K3MlaW mw; K3MoeW ow; K3LayerW lw;+ memset(&kw, 0, sizeof kw); memset(&mw, 0, sizeof mw);+ memset(&ow, 0, sizeof ow); memset(&lw, 0, sizeof lw);+ lw.in_norm = arr(r, "input_layernorm_weight", &d);+ lw.post_norm = arr(r, "post_attention_layernorm_weight", &d);+ lw.attn_res_norm = arr(r, "self_attention_res_norm_weight", &d);+ lw.attn_res_proj = arr(r, "self_attention_res_proj_weight", &d);+ lw.mlp_res_norm = arr(r, "mlp_res_norm_weight", &d);+ lw.mlp_res_proj = arr(r, "mlp_res_proj_weight", &d);++ if (is_mla) {+ mw.q_a = arr(r,"self_attn_q_a_proj_weight",&d);+ mw.q_a_norm = arr(r,"self_attn_q_a_layernorm_weight",&d);+ mw.q_b = arr(r,"self_attn_q_b_proj_weight",&d);+ mw.kv_a = arr(r,"self_attn_kv_a_proj_with_mqa_weight",&d);+ mw.kv_a_norm = arr(r,"self_attn_kv_a_layernorm_weight",&d);+ mw.kv_b = arr(r,"self_attn_kv_b_proj_weight",&d);+ mw.o = arr(r,"self_attn_o_proj_weight",&d);+ mw.g = arr(r,"self_attn_g_proj_weight",&d);+ lw.mla = &mw;+ } else {+ kw.q = arr(r,"self_attn_q_proj_weight",&d);+ kw.k = arr(r,"self_attn_k_proj_weight",&d);+ kw.v = arr(r,"self_attn_v_proj_weight",&d);+ kw.q_conv = arr(r,"self_attn_q_conv1d_weight",&d);+ kw.k_conv = arr(r,"self_attn_k_conv1d_weight",&d);+ kw.v_conv = arr(r,"self_attn_v_conv1d_weight",&d);+ kw.f_a = arr(r,"self_attn_f_a_proj_weight",&d);+ kw.f_b = arr(r,"self_attn_f_b_proj_weight",&d);+ kw.A_log = arr(r,"self_attn_A_log",&d);+ kw.dt_bias = arr(r,"self_attn_dt_bias",&d);+ kw.b = arr(r,"self_attn_b_proj_weight",&d);+ kw.g = arr(r,"self_attn_g_proj_weight",&d);+ kw.o_norm = arr(r,"self_attn_o_norm_weight",&d);+ kw.o = arr(r,"self_attn_o_proj_weight",&d);+ lw.kda = &kw;+ }++ ow.gate = arr(r,"mlp_gate_weight",&d);+ ow.bias = arr(r,"mlp_e_score_correction_bias",&d);+ ow.down = arr(r,"mlp_down_weight",&d);+ ow.up = arr(r,"mlp_up_weight",&d);+ ow.latent_norm = arr(r,"mlp_norm_weight",&d);+ ow.sh1 = arr(r,"mlp_shared_w1_weight",&d);+ ow.sh3 = arr(r,"mlp_shared_w3_weight",&d);+ ow.sh2 = arr(r,"mlp_shared_w2_weight",&d);+ ow.w1 = pack_experts(r,"mlp_experts_%d_w1_weight",c.n_experts,(size_t)c.moe_inter*c.latent);+ ow.w3 = pack_experts(r,"mlp_experts_%d_w3_weight",c.n_experts,(size_t)c.moe_inter*c.latent);+ ow.w2 = pack_experts(r,"mlp_experts_%d_w2_weight",c.n_experts,(size_t)c.latent*c.moe_inter);+ lw.moe = &ow;++ if (x && eo && bri && ow.w1 && ow.w2 && ow.w3 && lw.in_norm) {+ int din[4]={0}, dbr[4]={0};+ shape(r,"in",din,4); shape(r,"block_residual_in",dbr,4);+ const int T = din[1], nb_in = dbr[1];+ const int maxb = c.n_layers / c.attn_res_block + 2;++ float *h = (float*)malloc((size_t)T*c.hidden*sizeof(float));+ float *br = (float*)calloc((size_t)T*maxb*c.hidden,sizeof(float));+ float *sc = (float*)malloc(k3_layer_scratch(&c,T)*sizeof(float));+ const int P = c.kda_heads*c.kda_head_dim;+ float *st = (float*)calloc((size_t)P*c.kda_head_dim + (size_t)3*P*(c.conv_k-1),+ sizeof(float));+ int nb = nb_in;+ if (h && br && sc && st) {+ memcpy(h, x, (size_t)T*c.hidden*sizeof(float));+ for (int t=0;t<T;t++)+ for (int b=0;b<nb_in;b++)+ memcpy(br+((size_t)t*maxb+b)*c.hidden,+ bri+((size_t)t*nb_in+b)*c.hidden,+ (size_t)c.hidden*sizeof(float));+ k3_decoder_layer(h, br, &nb, &lw, &c, li, T, st, sc);+ char nm[40]; snprintf(nm,sizeof nm,"%s",file);+ report(nm, h, eo, n_out);+ printf(" layer %d (%s), blocks %d -> %d, boundary=%s\n",+ li, is_mla?"MLA":"KDA", nb_in, nb,+ (li % c.attn_res_block==0)?"YES, prefix_sum cleared":"no");+ }+ free(h); free(br); free(sc); free(st);+ }+ free(x); free(eo); free(bri);+ free((void*)ow.w1); free((void*)ow.w3); free((void*)ow.w2);+ free(txt); free(ar);+}++/* MXFP4 dequant, checked against REAL Kimi K3 checkpoint bytes. Every other fixture+ * uses synthetic values; this one cannot, because the point is to agree with how+ * Moonshot actually wrote the bytes. */+static void t_mxfp4(const char *dir)+{+ /* mxfp4.json sits BESIDE the ops/ directory, not inside it, because it is built+ * from released checkpoint bytes rather than from the reference implementation.+ * Both orderings are attempted. */+ char p[512];+ snprintf(p, sizeof(p), "%s/mxfp4.json", dir);+ char *txt = slurp_quiet(p);+ if (!txt) { snprintf(p, sizeof(p), "%s/../mxfp4.json", dir); txt = slurp_quiet(p); }+ if (!txt) {+ printf(" SKIP mxfp4 fixture absent; run tools/fetch_mxfp4.py\n");+ g_skip++;+ return;+ }+ char *ar = NULL; jval *r = json_parse(txt, &ar);++ const int rows = (int)num(r, "rows", 0);+ const int pcols = (int)num(r, "packed_cols", 0);+ const int grp = (int)num(r, "group_size", 32);+ int np_, ns_, ne_;+ float *pf = arr(r, "packed", &np_);+ float *sf = arr(r, "scales", &ns_);+ float *ef = arr(r, "expected", &ne_);++ if (pf && sf && ef && rows && pcols) {+ unsigned char *P = (unsigned char *)malloc((size_t)np_);+ unsigned char *S = (unsigned char *)malloc((size_t)ns_);+ float *y = (float *)malloc((size_t)ne_ * sizeof(float));+ for (int i = 0; i < np_; i++) P[i] = (unsigned char)pf[i];+ for (int i = 0; i < ns_; i++) S[i] = (unsigned char)sf[i];++ k3_mxfp4_dequant(y, P, S, rows, pcols, grp);++ /* exact equality: dequantisation is a table lookup times a power of two, so+ * there is no rounding anywhere and anything but a bit-exact match is a bug */+ int bad = 0; double worst = 0.0; int at = -1;+ for (int i = 0; i < ne_; i++) {+ const double d = fabs((double)y[i] - (double)ef[i]);+ if (d > worst) { worst = d; at = i; }+ if (d != 0.0) bad++;+ }+ if (bad == 0) {+ printf(" PASS mxfp4 %d rows x %d elems, EXACT on released checkpoint bytes\n",+ rows, pcols * 2);+ g_pass++;+ } else {+ printf(" FAIL mxfp4 %d of %d elements differ, worst %.7g at %d "+ "(got %.7f want %.7f)\n", bad, ne_, worst, at, y[at], ef[at]);+ g_fail++;+ }+ free(P); free(S); free(y);+ }+ free(pf); free(sf); free(ef); free(txt); free(ar);+}++/* k3_matmul_bf16 must equal k3_matmul EXACTLY, not approximately.+ *+ * Both widen the same bf16 values to the same float32 values (a left shift by 16, which+ * is lossless), then accumulate in double in the same order with the same four partial+ * sums. So the only way they can differ is if one of them is wrong. Comparing with a+ * tolerance here would hide precisely the bugs worth catching: a wrong stride, a+ * dropped tail element, a mis-shifted widen.+ *+ * This test needs no fixture. It generates bf16 bit patterns directly, which also means+ * it covers values a Gaussian sample would never produce - the checkpoint contains+ * denormals and very large exponents, and the widen must handle them by construction+ * rather than by luck.+ */+static void t_matmul_bf16(void)+{+ const int in = 257, out = 129; /* deliberately not multiples of 4 */+ uint16_t *Wb = (uint16_t *)malloc((size_t)in * out * sizeof(uint16_t));+ float *Wf = (float *)malloc((size_t)in * out * sizeof(float));+ float *x = (float *)malloc((size_t)in * sizeof(float));+ float *ya = (float *)malloc((size_t)out * sizeof(float));+ float *yb = (float *)malloc((size_t)out * sizeof(float));+ if (!Wb || !Wf || !x || !ya || !yb) { printf(" FAIL matmul_bf16 (alloc)\n"); g_fail++; return; }++ unsigned s = 0xC0FFEEu;+ for (size_t i = 0; i < (size_t)in * out; i++) {+ s ^= s << 13; s ^= s >> 17; s ^= s << 5;+ /* Any 16-bit pattern EXCEPT the NaN/Inf exponent, which would make every+ * comparison trivially NaN and prove nothing. */+ uint16_t h = (uint16_t)(s >> 8);+ if (((h >> 7) & 0xFF) == 0xFF) h &= 0x7F7Fu;+ Wb[i] = h;+ Wf[i] = k3_bf16f(h); /* the SAME value, stored wide */+ }+ for (int i = 0; i < in; i++) {+ s ^= s << 13; s ^= s >> 17; s ^= s << 5;+ x[i] = (float)(s >> 8) / 8388608.0f - 1.0f;+ }++ k3_matmul(ya, x, Wf, in, out);+ k3_matmul_bf16(yb, x, Wb, in, out);++ int bad = 0;+ for (int o = 0; o < out; o++) {+ union { float f; uint32_t u; } a, b;+ a.f = ya[o]; b.f = yb[o];+ if (a.u != b.u) bad++;+ }+ if (bad) { printf(" FAIL matmul_bf16 %d/%d rows differ from the fp32 path\n", bad, out); g_fail++; }+ else { printf(" PASS matmul_bf16 n=%d bit-identical to k3_matmul\n", out); g_pass++; }+ free(Wb); free(Wf); free(x); free(ya); free(yb);+}++int main(int argc, char **argv)+{+ const char *dir = (argc > 1) ? argv[1] : "../fixtures/ops";+ printf("Kimi K3 C ops, validated against the pure-torch reference\n");+ printf("fixtures: %s\n", dir);++ /* The manifest is the contract. Take its tolerances rather than hardcoded ones, and say out+ * loud which ones are in force so a future loosening cannot happen silently. */+ {+ char mp[512]; snprintf(mp, sizeof mp, "%s/MANIFEST.json", dir);+ char *mtxt = slurp_quiet(mp);+ if (!mtxt) {+ printf("tolerance: MANIFEST.json ABSENT, falling back to atol=%.1e rtol=%.1e\n\n",+ (double)ATOL, (double)RTOL);+ g_skip++;+ } else {+ char *mar = NULL; jval *m = json_parse(mtxt, &mar);+ jval *tolo = m ? json_get(m, "tolerance") : NULL;+ const double fa = tolo ? num(tolo, "fp32_abs", ATOL) : ATOL;+ const double fr = tolo ? num(tolo, "fp32_rel", RTOL) : RTOL;+ ATOL = (float)fa; RTOL = (float)fr;+ printf("tolerance: atol=%.1e rtol=%.1e (from MANIFEST.json)\n\n", fa, fr);+ free(mtxt); free(mar);+ }+ }++ t_rmsnorm(dir);+ t_situ(dir);+ t_shortconv(dir);+ t_decay(dir);+ t_recur(dir, "kda_recur1");+ t_recur(dir, "kda_recur8");+ t_router(dir);+ t_mla(dir);+ t_moe(dir);+ t_mxfp4(dir);+ t_matmul_bf16();+ t_kda_layer(dir, "kda_layer1");+ t_kda_layer(dir, "kda_layer8");+ t_layer(dir, "layer_kda");+ t_layer(dir, "layer_mla");+ t_attnres(dir);++ printf("\n%d passed, %d failed, %d skipped\n", g_pass, g_fail, g_skip);+ if (g_skip)+ printf("SUITE INCOMPLETE: %d test(s) did not run. A skip is not a pass.\n", g_skip);+ return (g_fail || g_skip) ? 1 : 0;+}diff --git a/tests/unit/test_real_layer.c b/tests/unit/test_real_layer.cnew file mode 100644index 0000000..2ae4374--- /dev/null+++ b/tests/unit/test_real_layer.c@@ -0,0 +1,267 @@+/* test_real_layer.c - run a REAL Kimi K3 layer, from the REAL checkpoint.+ *+ * WHAT IS ACTUALLY NEW HERE+ * The arithmetic is already validated: 20 op fixtures, the full-model oracle matching+ * token for token: the MLA implementation against the released KimiMLAAttention, KDA against the+ * released KimiDeltaAttention on GPU. All of that ran on weights this project+ * generated.+ *+ * What has never been tested is the BINDING: whether k3_bind attaches the right+ * checkpoint tensor to the right kernel argument. That failure mode is invisible to+ * every test above, because a transposed or swapped weight still has the right shape+ * and produces finite, plausible numbers. It can only be caught by running real+ * weights and comparing against an independent implementation reading the same file.+ *+ * So this dumps its input and its intermediate outputs in stages, and+ * tools/verify_real_layer.py reproduces each stage in torch from the same shards:+ * stage A KDA attention output -> the 15 attention tensors are wired correctly+ * stage B router indices/weights -> gate and e_score_correction_bias are correct+ * stage C MoE output -> latent down/up, shared experts, and the+ * streamed MXFP4 experts are all correct+ * Staging matters: a single end-to-end number that disagrees tells you nothing about+ * which of thirty tensors is wrong.+ *+ * usage: test_real_layer <shard_dir> [layer] [T] [cache_gb]+ */+#define _POSIX_C_SOURCE 200809L++#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <time.h>++#include "k3.h"+#include "k3_bind.h"+#include "k3_cache.h"++static double now_s(void)+{+ struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t);+ return t.tv_sec + t.tv_nsec * 1e-9;+}++static unsigned rs = 20260728u;+static float rnd_f(void)+{+ rs ^= rs << 13; rs ^= rs >> 17; rs ^= rs << 5;+ return ((float)(rs >> 8) / 8388608.0f - 1.0f);+}++static void dump_f32(FILE *f, const char *name, const float *v, int64_t n, int comma)+{+ fprintf(f, "%s\"%s\":[", comma ? "," : "", name);+ for (int64_t i = 0; i < n; i++) {+ union { float f; uint32_t u; } b; b.f = v[i];+ fprintf(f, "%s%u", i ? "," : "", b.u); /* bit patterns: exact, and NaN-safe */+ }+ fprintf(f, "]");+}++/* The real Kimi K3 configuration, from config.json and confirmed against the shipped+ * tensor shapes in every case. */+static void real_cfg(K3Cfg *c, int *fa, int *nfa)+{+ memset(c, 0, sizeof *c);+ c->hidden = 7168; c->n_layers = 93; c->vocab = 163840; c->rms_eps = 1e-5f;+ c->kda_heads = 96; c->kda_head_dim = 128; c->conv_k = 4; c->gate_lb = -5.0f;+ c->n_heads = 96; c->q_lora = 1536; c->kv_lora = 512;+ c->qk_nope = 128; c->qk_rope = 64; c->v_head = 128; c->mla_out_gate = 1;+ c->n_experts = 896; c->topk = 16; c->n_shared = 2;+ c->latent = 3584; c->moe_inter = 3072; c->routed_scale = 1.0f;+ c->moe_renorm = 1; c->latent_norm = 1;+ c->first_dense = 1; c->dense_inter = 33792;+ c->attn_res_block = 12;+ c->situ_b1 = 4.0f; c->situ_b2 = 25.0f;+ int n = 0;+ for (int i = 4; i <= 93; i += 4) fa[n++] = i; /* one-based in config */+ fa[n++] = 93;+ c->n_full_attn = n; c->full_attn = fa;+ *nfa = n;+}++int main(int argc, char **argv)+{+ if (argc < 2) { fprintf(stderr, "usage: test_real_layer <shard_dir> [layer] [T] [cache_gb]\n"); return 2; }+ const char *dir = argv[1];+ const int L = argc > 2 ? atoi(argv[2]) : 1;+ const int T = argc > 3 ? atoi(argv[3]) : 4;+ const double cache_gb = argc > 4 ? atof(argv[4]) : 2.0;++ K3Cfg c; static int fa[32]; int nfa;+ real_cfg(&c, fa, &nfa);++ printf("Kimi K3, released weights, layer %d, T=%d\n", L, T);+ printf(" layer %d is %s and %s\n", L,+ k3_is_mla(&c, L) ? "MLA" : "KDA", k3_is_dense(&c, L) ? "dense" : "MoE");++ K3St st;+ double t0 = now_s();+ if (k3_st_open(&st, dir) != 0) return 1;+ printf(" indexed %d tensors from %d shard(s) in %.2f s\n\n", st.nt, st.nshard, now_s() - t0);++ /* ---- bind ---- */+ const int64_t need = k3_bind_layer_bytes(&st, &c, L);+ if (need < 0) { fprintf(stderr, "binding plan FAILED, see errors above\n"); return 1; }+ printf("layer %d resident weights: %.2f GB in RAM, held in the checkpoint's own bf16\n",+ L, (double)need / 1e9);++ K3LayerBind b;+ t0 = now_s();+ if (k3_bind_layer(&st, &c, L, &b) != 0) { fprintf(stderr, "BIND FAILED\n"); return 1; }+ printf(" bound in %.2f s (%.0f MB/s)\n\n",+ now_s() - t0, (double)need / 1e6 / (now_s() - t0));++ /* ---- the expert cache ---- */+ K3Cache cache;+ if (k3_cache_init(&cache, &st, &c, (int64_t)(cache_gb * 1e9)) != 0) return 1;+ printf("expert cache: %d slots x %.2f MB = %.2f GB\n\n",+ cache.nslot, (double)cache.slot_bytes / 1e6,+ (double)cache.nslot * cache.slot_bytes / 1e9);+ b.moe.src = &cache.src;+ b.moe.layer = L;++ /* ---- input ---- */+ float *x = (float *)malloc((size_t)T * c.hidden * sizeof(float));+ for (int64_t i = 0; i < (int64_t)T * c.hidden; i++) x[i] = rnd_f() * 0.5f;++ FILE *f = fopen("real_layer.json", "w");+ fprintf(f, "{\"layer\":%d,\"T\":%d,\"hidden\":%d,\"topk\":%d,\"is_mla\":%d",+ L, T, c.hidden, c.topk, k3_is_mla(&c, L));+ dump_f32(f, "x", x, (int64_t)T * c.hidden, 1);++ /* ---- stage A: attention ---- */+ float *att = (float *)malloc((size_t)T * c.hidden * sizeof(float));+ float *xn = (float *)malloc((size_t)T * c.hidden * sizeof(float));+ for (int t = 0; t < T; t++)+ k3_rmsnorm(xn + (size_t)t * c.hidden, x + (size_t)t * c.hidden,+ b.lay.in_norm, c.hidden, c.rms_eps);+ dump_f32(f, "x_norm", xn, (int64_t)T * c.hidden, 1);++ const size_t P = (size_t)c.kda_heads * c.kda_head_dim;+ float *state = (float *)calloc(P * c.kda_head_dim + 3 * P * (c.conv_k - 1), sizeof(float));+ float *scr = (float *)malloc(k3_layer_scratch(&c, T) * sizeof(float));+ if (!state || !scr) { fprintf(stderr, "scratch allocation failed\n"); return 1; }++ /* KDA and MLA are different code paths with entirely different weight sets, and+ * only one of them has ever been checked against real weights. Run whichever this+ * layer actually is. */+ const int is_mla = k3_is_mla(&c, L);+ t0 = now_s();+ if (is_mla) k3_mla(att, xn, &b.mla, &c, T, scr);+ else k3_kda_layer(att, xn, &b.kda, &c, T, state, scr);+ const double t_attn = now_s() - t0;+ dump_f32(f, "attn_out", att, (int64_t)T * c.hidden, 1);+ printf("stage A %s attention : %.2f s for %d tokens (%.0f ms/token)\n",+ is_mla ? "MLA" : "KDA", t_attn, T, t_attn * 1000 / T);++ /* ---- stage B: routing, on the post-attention normalised hidden ---- */+ float *hn = (float *)malloc((size_t)T * c.hidden * sizeof(float));+ for (int t = 0; t < T; t++)+ k3_rmsnorm(hn + (size_t)t * c.hidden, att + (size_t)t * c.hidden,+ b.lay.post_norm, c.hidden, c.rms_eps);+ dump_f32(f, "moe_in", hn, (int64_t)T * c.hidden, 1);++ /* LAYER 0 IS DENSE and has no router at all: k3_bind sets lay.moe to NULL for it+ * (k3_bind.c:295) because the checkpoint carries mlp.gate_proj / up_proj / down_proj+ * instead of block_sparse_moe.*. Falling into the routing code below dereferenced a+ * null gate and SEGFAULTED, which is why layer 0 -- the ONLY layer with this code+ * path, a 33792-wide dense MLP -- had never once been conformance-checked against+ * torch. Run the path the engine actually runs for it. */+ if (k3_is_dense(&c, L)) {+ const int DI = c.dense_inter;+ float *dgu = (float *)malloc((size_t)2 * DI * sizeof(float));+ float *dsub = (float *)malloc((size_t)DI * sizeof(float));+ float *dout = (float *)malloc((size_t)T * c.hidden * sizeof(float));+ if (!dgu || !dsub || !dout) { fprintf(stderr, "dense scratch failed\n"); return 1; }+ t0 = now_s();+ for (int t = 0; t < T; t++) {+ k3_mmw(dgu, hn + (size_t)t * c.hidden, b.lay.dense_gate, b.lay.wdt,+ c.hidden, DI);+ k3_mmw(dgu + DI, hn + (size_t)t * c.hidden, b.lay.dense_up, b.lay.wdt,+ c.hidden, DI);+ k3_situ_glu(dsub, dgu, DI, c.situ_b1, c.situ_b2);+ k3_mmw(dout + (size_t)t * c.hidden, dsub, b.lay.dense_down, b.lay.wdt,+ DI, c.hidden);+ }+ const double t_dense = now_s() - t0;+ dump_f32(f, "dense_out", dout, (int64_t)T * c.hidden, 1);+ fprintf(f, "}\n");+ fclose(f);+ printf("stage B (skipped: dense layer, no router)\n");+ printf("stage C dense MLP, inter %d: %.2f s for %d tokens (%.0f ms/token)\n\n",+ DI, t_dense, T, t_dense * 1000 / T);+ int dfin = 1; double dmx = 0.0;+ for (int64_t i = 0; i < (int64_t)T * c.hidden; i++) {+ if (!isfinite(dout[i])) { dfin = 0; break; }+ if (fabs(dout[i]) > dmx) dmx = fabs(dout[i]);+ }+ printf("output finite: %s, max |y| = %.6f\n", dfin ? "YES" : "NO", dmx);+ printf("wrote real_layer.json for tools/verify_real_layer.py\n");+ free(dgu); free(dsub); free(dout); free(hn); free(att); free(x); free(scr);+ k3_cache_free(&cache); k3_bind_free(&b); k3_st_close(&st);+ return dfin ? 0 : 1;+ }++ int *idx = (int *)malloc((size_t)c.topk * sizeof(int));+ float *wt = (float *)malloc((size_t)c.topk * sizeof(float));+ fprintf(f, ",\"route_idx\":[");+ float *allw = (float *)malloc((size_t)T * c.topk * sizeof(float));+ for (int t = 0; t < T; t++) {+ k3_router(idx, wt, hn + (size_t)t * c.hidden, b.moe.gate, b.moe.bias,+ c.hidden, c.n_experts, c.topk, c.moe_renorm, c.routed_scale);+ for (int j = 0; j < c.topk; j++) {+ fprintf(f, "%s%d", (t || j) ? "," : "", idx[j]);+ allw[t * c.topk + j] = wt[j];+ }+ if (t == 0) {+ printf("stage B router, token 0: experts");+ for (int j = 0; j < 8; j++) printf(" %d(%.4f)", idx[j], wt[j]);+ printf(" ...\n");+ }+ }+ fprintf(f, "]");+ dump_f32(f, "route_wt", allw, (int64_t)T * c.topk, 1);++ /* ---- stage C: MoE with STREAMED experts ---- */+ float *moe_out = (float *)malloc((size_t)T * c.hidden * sizeof(float));+ float *mscr = (float *)malloc(k3_moe_scratch(&c) * sizeof(float));+ if (!moe_out || !mscr) { fprintf(stderr, "moe scratch allocation failed\n"); return 1; }++ k3_cache_reset_stats(&cache);+ t0 = now_s();+ k3_moe(moe_out, hn, &b.moe, &c, T, idx, wt, mscr);+ const double t_moe = now_s() - t0;+ dump_f32(f, "moe_out", moe_out, (int64_t)T * c.hidden, 1);+ fprintf(f, "}\n");+ fclose(f);++ printf("stage C MoE (streamed): %.2f s for %d tokens (%.0f ms/token)\n\n",+ t_moe, T, t_moe * 1000 / T);+ k3_cache_report(&cache, "after one layer, cold");++ /* Second pass: same tokens, so every expert is already resident. The gap between+ * the two is exactly what caching buys. */+ k3_cache_reset_stats(&cache);+ t0 = now_s();+ k3_moe(moe_out, hn, &b.moe, &c, T, idx, wt, mscr);+ const double t_moe2 = now_s() - t0;+ printf("\nsecond pass, fully cached: %.2f s (%.0f ms/token), %.1fx faster\n",+ t_moe2, t_moe2 * 1000 / T, t_moe / t_moe2);+ k3_cache_report(&cache, "second pass");++ int finite = 1; double mx = 0.0;+ for (int64_t i = 0; i < (int64_t)T * c.hidden; i++) {+ if (!isfinite(moe_out[i])) { finite = 0; break; }+ if (fabs(moe_out[i]) > mx) mx = fabs(moe_out[i]);+ }+ printf("\noutput finite: %s, max |y| = %.6f\n", finite ? "YES" : "NO", mx);+ printf("wrote real_layer.json for tools/verify_real_layer.py\n");++ k3_cache_dump_hist(&cache, "expert_hist.json");+ k3_cache_dump_trace(&cache, "expert_trace.bin");+ k3_cache_free(&cache);+ k3_bind_free(&b);+ k3_st_close(&st);+ return finite ? 0 : 1;+}diff --git a/tests/unit/test_st.c b/tests/unit/test_st.cnew file mode 100644index 0000000..a5c6771--- /dev/null+++ b/tests/unit/test_st.c@@ -0,0 +1,210 @@+/* test_st.c - exercise the safetensors reader and emit its index for external checking.+ *+ * The point of this program is NOT to print a pass/fail of its own opinion. It dumps+ * exactly what the C parser believes about every tensor, so tools/verify_st.py can+ * reparse the same files with Python's json and safetensors and compare field by+ * field. A parser that agrees with itself proves nothing.+ *+ * usage: test_st <dir> [index.json] [tensor_name ...]+ * <dir> directory of .safetensors shards+ * index.json where to write the full index (default st_index.json)+ * tensor_name zero or more tensors to read and dump values for+ */+#define _POSIX_C_SOURCE 200809L++#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <time.h>++#include "k3_st.h"++static double now_s(void)+{+ struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t);+ return t.tv_sec + t.tv_nsec * 1e-9;+}++static const char *dt_name(K3Dtype d)+{+ switch (d) {+ case K3_DT_U8: return "U8";+ case K3_DT_BF16: return "BF16";+ case K3_DT_F16: return "F16";+ case K3_DT_F32: return "F32";+ default: return "?";+ }+}++static const char *base_name(const char *p)+{+ const char *s = strrchr(p, '/');+ return s ? s + 1 : p;+}++/* Names may legally contain a quote or a backslash. Emitting them raw produces a file+ * that Python then fails to parse, which would look like a reader bug when it is only+ * a dumper bug. Escape on the way out. */+static void put_json_str(FILE *f, const char *s)+{+ fputc('"', f);+ for (; *s; s++) {+ unsigned char c = (unsigned char)*s;+ if (c == '"' || c == '\\') { fputc('\\', f); fputc(c, f); }+ else if (c < 0x20) fprintf(f, "\\u%04x", c);+ else fputc(c, f);+ }+ fputc('"', f);+}++int main(int argc, char **argv)+{+ if (argc < 2) { fprintf(stderr, "usage: test_st <dir> [index.json] [tensor ...]\n"); return 2; }+ const char *dir = argv[1];+ const char *out = argc > 2 ? argv[2] : "st_index.json";++ printf("opening %s\n", dir);+ K3St s;+ double t0 = now_s();+ if (k3_st_open(&s, dir) != 0) { fprintf(stderr, "OPEN FAILED\n"); return 1; }+ double t_open = now_s() - t0;++ int64_t total = 0;+ int64_t by_dt[8] = {0};+ for (int i = 0; i < s.nt; i++) { total += s.t[i].nbytes; by_dt[s.t[i].dtype]++; }++ printf(" shards : %d\n", s.nshard);+ printf(" tensors : %d\n", s.nt);+ printf(" indexed bytes : %.2f GB\n", (double)total / 1e9);+ printf(" index built in: %.3f s (%.1f us/tensor)\n",+ t_open, 1e6 * t_open / (s.nt ? s.nt : 1));+ printf(" dtypes : U8 %lld, BF16 %lld, F16 %lld, F32 %lld\n",+ (long long)by_dt[K3_DT_U8], (long long)by_dt[K3_DT_BF16],+ (long long)by_dt[K3_DT_F16], (long long)by_dt[K3_DT_F32]);+ printf(" hash buckets : %d for %d tensors (load %.2f)\n",+ s.nbucket, s.nt, (double)s.nt / s.nbucket);++ /* ---- round trip: every name must find its own entry, not a neighbour ---- */+ t0 = now_s();+ int bad = 0;+ for (int i = 0; i < s.nt; i++) {+ const K3Tensor *f = k3_st_find(&s, s.t[i].name);+ if (f != &s.t[i]) bad++;+ }+ double t_look = now_s() - t0;+ printf(" round trip : %d/%d resolve to themselves%s\n",+ s.nt - bad, s.nt, bad ? " <-- COLLISION BUG" : "");+ printf(" lookup cost : %.0f ns each (%d lookups in %.3f s)\n",+ 1e9 * t_look / (s.nt ? s.nt : 1), s.nt, t_look);++ /* ---- a name that is not present must return NULL, not a near miss ---- */+ const char *ghosts[] = { "", "no.such.tensor",+ "language_model.model.layers.999.self_attn.A_log" };+ int ghost_bad = 0;+ for (unsigned i = 0; i < sizeof ghosts / sizeof *ghosts; i++)+ if (k3_st_find(&s, ghosts[i])) ghost_bad++;+ printf(" absent names : %d/%zu correctly return NULL\n",+ (int)(sizeof ghosts / sizeof *ghosts) - ghost_bad, sizeof ghosts / sizeof *ghosts);++ /* ---- dump the index ---- */+ FILE *f = fopen(out, "w");+ if (!f) { fprintf(stderr, "cannot write %s\n", out); k3_st_close(&s); return 1; }+ fprintf(f, "{\"nshard\":%d,\"nt\":%d,\"tensors\":{", s.nshard, s.nt);+ for (int i = 0; i < s.nt; i++) {+ const K3Tensor *t = &s.t[i];+ if (i) fputc(',', f);+ put_json_str(f, t->name);+ fprintf(f, ":{\"shard\":\"%s\",\"dtype\":\"%s\",\"shape\":[",+ base_name(s.path[t->shard]), dt_name(t->dtype));+ for (int d = 0; d < t->ndim; d++)+ fprintf(f, "%s%lld", d ? "," : "", (long long)t->shape[d]);+ fprintf(f, "],\"off\":%lld,\"nbytes\":%lld}",+ (long long)t->off, (long long)t->nbytes);+ }+ fprintf(f, "}}\n");+ fclose(f);+ printf(" wrote %s\n", out);++ /* ---- read the named tensors and dump values for comparison ---- */+ if (argc > 3) {+ FILE *v = fopen("st_values.json", "w");+ fprintf(v, "{");+ for (int a = 3; a < argc; a++) {+ const K3Tensor *t = k3_st_find(&s, argv[a]);+ if (!t) { printf(" MISSING: %s\n", argv[a]); continue; }+ int64_t n = k3_st_numel(t);+ int64_t nd = n < 4096 ? n : 4096; /* a prefix is enough to catch a shift */+ float *buf = (float *)malloc((size_t)n * sizeof(float));+ if (!buf) { printf(" alloc failed for %s\n", argv[a]); continue; }+ double t1 = now_s();+ int64_t got = k3_st_read_f32(&s, t, buf);+ double dt = now_s() - t1;++ double mn = 1e300, mx = -1e300, sum = 0.0;+ int nonfinite = 0;+ for (int64_t i = 0; i < got; i++) {+ if (!isfinite(buf[i])) { nonfinite++; continue; }+ if (buf[i] < mn) mn = buf[i];+ if (buf[i] > mx) mx = buf[i];+ sum += buf[i];+ }+ /* The min/max/mean above are computed over the FINITE values only (the loop+ * `continue`s past the rest), so a bare "NON-FINITE VALUES" banner sitting+ * beside perfectly finite statistics reads like a contradiction and has+ * already been reported as one. It is not: the tensor genuinely contains+ * non-finite entries AND finite ones. Print the count and say which set the+ * statistics describe, so the line is unambiguous on its own.+ *+ * `tricky.f16.1d` in the fixture set carries inf/nan deliberately, so this+ * firing is the reader working, not failing. */+ printf(" %s\n", argv[a]);+ if (nonfinite) {+ printf(" %s %lld elems, %.2f MB in %.3f s (%.0f MB/s), "+ "min %.6g max %.6g mean %.6g "+ "<-- %d of %lld values are non-finite (stats cover the other %lld)\n",+ dt_name(t->dtype), (long long)got, (double)t->nbytes / 1e6, dt,+ (double)t->nbytes / 1e6 / (dt > 0 ? dt : 1e-9), mn, mx,+ (got - nonfinite) ? sum / (got - nonfinite) : 0.0,+ nonfinite, (long long)got, (long long)(got - nonfinite));+ } else {+ printf(" %s %lld elems, %.2f MB in %.3f s (%.0f MB/s), "+ "min %.6g max %.6g mean %.6g\n",+ dt_name(t->dtype), (long long)got, (double)t->nbytes / 1e6, dt,+ (double)t->nbytes / 1e6 / (dt > 0 ? dt : 1e-9), mn, mx,+ got ? sum / got : 0.0);+ }++ /* Values go out as raw float32 BIT PATTERNS, not decimals. Three reasons:+ * printf writes "nan" and "-inf", which Python's json rejects; %.9g cannot+ * distinguish -0.0 from 0.0; and a NaN payload vanishes entirely. Bits make+ * the comparison exact and turn every one of those into a visible mismatch. */+ if (a > 3) fputc(',', v);+ put_json_str(v, argv[a]);+ fprintf(v, ":{\"n\":%lld,\"first_bits\":[", (long long)got);+ for (int64_t i = 0; i < nd; i++) {+ union { float f; uint32_t u; } b; b.f = buf[i];+ fprintf(v, "%s%u", i ? "," : "", b.u);+ }+ /* The tail matters as much as the head: an off-by-one in the offset shifts+ * everything, but a wrong nbytes only shows up at the end. */+ fprintf(v, "],\"last_bits\":[");+ const int64_t tail = got > 64 ? got - 64 : 0;+ for (int64_t i = tail; i < got; i++) {+ union { float f; uint32_t u; } b; b.f = buf[i];+ fprintf(v, "%s%u", i == tail ? "" : ",", b.u);+ }+ fprintf(v, "],\"tail_start\":%lld}", (long long)tail);+ free(buf);+ }+ fprintf(v, "}\n");+ fclose(v);+ printf(" wrote st_values.json\n");+ }++ k3_st_close(&s);+ printf("\n%s\n", (bad == 0 && ghost_bad == 0)+ ? "READER SELF-CHECKS PASSED (now run tools/verify_st.py for the external check)"+ : "READER SELF-CHECKS FAILED");+ return (bad == 0 && ghost_bad == 0) ? 0 : 1;+}diff --git a/tests/unit/test_tok.c b/tests/unit/test_tok.cnew file mode 100644index 0000000..ab162df--- /dev/null+++ b/tests/unit/test_tok.c@@ -0,0 +1,117 @@+/* test_tok.c - exercise the C tokenizer against the Python oracle (tools/tok.py).+ *+ * The engine proper is Linux-only (O_DIRECT, posix_memalign, sys/resource). The+ * tokenizer is not: tok.h, k3_tok.h and json.h are portable C99 over stdio/stdlib/+ * string only. So this harness builds and runs anywhere, which is the point --+ * tokenizer parity can be established without a Linux box or a single model weight.+ *+ * test_tok <files_dir> encode "text" -> comma-separated ids, one line+ * test_tok <files_dir> encodefile <path> -> same, but text read as raw bytes+ * test_tok <files_dir> decode 1,2,3 -> the text+ * test_tok <files_dir> roundtrip <path> -> encode then decode; PASS/FAIL on+ * byte-exact recovery of the input+ *+ * `encode` output is deliberately byte-identical in format to `tok.py encode` so the+ * two can be diffed directly with no post-processing.+ *+ * USE encodefile FOR ANYTHING NON-ASCII. argv is re-encoded by the host shell -- on+ * Windows it arrives in the active code page, so "ÿ" reaches main() as one byte+ * rather than the two UTF-8 bytes the tokenizer must see. That is a property of the+ * process boundary, not of the tokenizer, and it makes argv useless as a parity+ * channel. encodefile reads the bytes verbatim and is the one that can fail.+ */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include "k3_tok.h"++#define MAXIDS (1 << 20)+#define MAXTEXT (1 << 22)++static int parse_ids(const char *s, int *out, int max)+{+ int n = 0;+ while (*s && n < max) {+ while (*s == ',' || *s == ' ') s++;+ if (!*s) break;+ out[n++] = atoi(s);+ while (*s && *s != ',') s++;+ }+ return n;+}++int main(int argc, char **argv)+{+ if (argc < 3) {+ fprintf(stderr,+ "usage: test_tok <files_dir> encode \"text\"\n"+ " test_tok <files_dir> decode 1,2,3\n"+ " test_tok <files_dir> roundtrip <textfile>\n");+ return 2;+ }+ const char *dir = argv[1], *mode = argv[2];++ Tok T;+ k3_tok_load(&T, dir);++ static int ids[MAXIDS];+ static char text[MAXTEXT];++ if (!strcmp(mode, "encode") && argc > 3) {+ int n = tok_encode(&T, argv[3], (int)strlen(argv[3]), ids, MAXIDS);+ for (int i = 0; i < n; i++) printf("%s%d", i ? "," : "", ids[i]);+ printf("\n");+ return 0;+ }++ if (!strcmp(mode, "encodefile") && argc > 3) {+ FILE *f = fopen(argv[3], "rb");+ if (!f) { perror(argv[3]); return 1; }+ size_t n = fread(text, 1, MAXTEXT - 1, f);+ fclose(f);+ text[n] = 0;+ int m = tok_encode(&T, text, (int)n, ids, MAXIDS);+ for (int i = 0; i < m; i++) printf("%s%d", i ? "," : "", ids[i]);+ printf("\n");+ return 0;+ }++ if (!strcmp(mode, "decode") && argc > 3) {+ int n = parse_ids(argv[3], ids, MAXIDS);+ int m = tok_decode(&T, ids, n, text, MAXTEXT - 1);+ text[m] = 0;+ fwrite(text, 1, (size_t)m, stdout);+ printf("\n");+ return 0;+ }++ if (!strcmp(mode, "roundtrip") && argc > 3) {+ FILE *f = fopen(argv[3], "rb");+ if (!f) { perror(argv[3]); return 1; }+ size_t n = fread(text, 1, MAXTEXT - 1, f);+ fclose(f);+ text[n] = 0;++ int ni = tok_encode(&T, text, (int)n, ids, MAXIDS);+ static char back[MAXTEXT];+ int nb = tok_decode(&T, ids, ni, back, MAXTEXT - 1);++ /* Byte-exact recovery is the bar. A tokenizer that loses a byte somewhere is+ * a tokenizer that will silently corrupt a prompt. */+ int ok = (nb == (int)n) && !memcmp(back, text, n);+ printf("roundtrip: %d bytes -> %d ids -> %d bytes : %s\n",+ (int)n, ni, nb, ok ? "PASS" : "FAIL");+ if (!ok) {+ int lim = nb < (int)n ? nb : (int)n;+ int d = 0; while (d < lim && back[d] == text[d]) d++;+ fprintf(stderr, "first divergence at byte %d\n", d);+ fprintf(stderr, " in : %.40s\n", text + d);+ fprintf(stderr, " out: %.40s\n", back + d);+ return 1;+ }+ return 0;+ }++ fprintf(stderr, "unknown mode '%s'\n", mode);+ return 2;+}