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
feat(core): add the public API and the configuration reader
FareedKhan-dev5fca44a75487
diff --git a/include/k3/k3.h b/include/k3/k3.hnew file mode 100644index 0000000..cf644ad--- /dev/null+++ b/include/k3/k3.h@@ -0,0 +1,526 @@+/* SPDX-License-Identifier: Apache-2.0 */+/*+ * k3.h, Kimi K3 inference engine: public configuration and core types.+ *+ * OVERVIEW+ * Kimi K3 is a 2.78-trillion-parameter mixture-of-experts model. This engine runs it+ * on a single CPU by treating memory as a dial rather than a floor:+ *+ * - the dense trunk (108.81 GB) is either held resident or streamed from disk in a+ * fixed layer order, so the next read is always known in advance;+ * - the 1.45 TB of routed experts are never resident. They stream on demand and are+ * multiplied straight out of their packed MXFP4 form, never widened to fp32.+ *+ * THE THREE WEIGHT FIGURES, since they are easy to confuse+ * 108.81 GB the 93 per-layer trunk runs, at bf16. Streamable, and re-read IN FULL+ * on every token, which is why docs/TUNING.md says to feed the trunk+ * before the expert cache.+ * 4.70 GB embed and lm_head. Always resident; not part of the streamed trunk.+ * 113.49 GB the two together: 56,743,648,000 always-active parameters at bf16, the+ * figure tools/budget.py reports from the shard headers. Doubles to+ * ~227 GB if anything widens this to fp32, which is why nothing does.+ * 1.45 TB the routed experts, at MXFP4. Never resident at any budget.+ *+ * The practical consequence is that the model runs in 8 GB of RAM and in 224 GB, and+ * produces byte-identical output at both. See docs/PERFORMANCE.md.+ *+ * ARCHITECTURE (all values verified against the released config.json)+ * 93 layers: 69 Kimi Delta Attention (KDA) + 24 Gated MLA, plus one dense layer.+ * Hidden 7168, 96 heads, 896 routed experts with top-16 selection and 2 shared,+ * latent width 3584, SiTU-GLU activation, MXFP4 expert weights.+ * docs/ARCHITECTURE.md maps each of these onto the technical report.+ *+ * FIVE INVARIANTS THAT MUST HOLD+ * Each of these is a place where a plausible-looking implementation produces a model+ * that runs, emits fluent text, and is wrong. They are asserted by the test-suite and+ * restated at their point of use.+ *+ * 1. A_log is indexed PER HEAD, not per channel. The checkpoint ships head_dim floats+ * but only the first num_heads are meaningful; the remainder are padding.+ * 2. The UT-transform inverse is (I + Akk)^-1. The sign is not a convention.+ * 3. Aqk retains its diagonal; Akk does not.+ * 4. MLA uses NoPE, yet the 64 rope dimensions still exist and are still cached.+ * Only the rotation is absent. Dropping the slots changes the head width.+ * 5. The MoE routing bias steers SELECTION only. Combining weights come from the+ * UNBIASED sigmoid scores.+ */+#ifndef K3_H+#define K3_H++#include <stddef.h>+#include <stdint.h>++#ifdef __cplusplus+extern "C" {+#endif++/* ---------------------------------------------------------------- config ---- */+typedef struct {+ int hidden; /* 7168 */+ int n_layers; /* 93 */+ int vocab; /* 163840 */+ float rms_eps; /* 1e-5 */++ /* Kimi Delta Attention. 69 of the 93 layers. */+ int kda_heads; /* 96 */+ int kda_head_dim; /* 128, and d_k == d_v */+ int conv_k; /* 4, depthwise, causal, SiLU fused */+ float gate_lb; /* -5.0, the decay lower bound */++ /* Gated MLA. 24 of the 93 layers. */+ int n_heads; /* 96 */+ int q_lora; /* 1536 */+ int kv_lora; /* 512 */+ int qk_nope; /* 128 */+ int qk_rope; /* 64, PRESENT BUT NEVER ROTATED */+ int v_head; /* 128 */+ int mla_out_gate; /* 1 */++ /* Stable LatentMoE. 92 of the 93 layers. */+ int n_experts; /* 896 */+ int topk; /* 16 */+ int n_shared; /* 2, full width, added UNWEIGHTED */+ int latent; /* 3584, the routed-expert width */+ int moe_inter; /* 3072 */+ float routed_scale; /* 1.0 */+ int moe_renorm; /* 1 */+ int latent_norm; /* 1, RMSNorm on the AGGREGATE, not per expert */++ /* the single dense layer, layer 0 */+ int first_dense; /* 1 */+ int dense_inter; /* 33792 */++ /* Block Attention Residuals */+ int attn_res_block; /* 12. Boundaries fire when layer_idx % this == 0. */++ /* SiTU-GLU. The sigmoid takes the UNCAPPED gate. Bound is b1*b2 = 100. */+ float situ_b1; /* 4.0 */+ float situ_b2; /* 25.0 */++ /* Layer map. The released config lists these ONE-BASED and+ * configuration_kimi_k3.py:152-156 tests (layer_idx + 1), so zero-based MLA+ * layers are 3,7,11,...,87,91,92 and layers 91 and 92 are BOTH MLA. */+ int n_full_attn;+ int *full_attn; /* one-based layer indices */+} K3Cfg;++int k3_is_mla(const K3Cfg *c, int layer); /* layer is ZERO-based */+int k3_is_kda(const K3Cfg *c, int layer);+int k3_is_dense(const K3Cfg *c, int layer);++/* ------------------------------------------------------------------ ops ---- */++/* y = w * x / sqrt(mean(x^2) + eps). Accumulate in double: the reference upcasts+ * to float32 from bf16 and sums 7168 terms. eps is INSIDE the rsqrt. */+void k3_rmsnorm(float *y, const float *x, const float *w, int n, float eps);++/* SiTU-GLU over a 2*n input laid out as [gate | up].+ * a = b1 * tanh(gate / b1) * sigmoid(gate) sigmoid sees the UNCAPPED gate+ * u = b2 * tanh(up / b2)+ * y = a * u |y| <= b1*b2+ * modeling_kimi_linear.py:75-82 */+void k3_situ_glu(float *y, const float *x, int n, float b1, float b2);++/* Causal depthwise convolution with a fused SiLU.+ * w is [channels][k]; state holds the (k-1) previous inputs per channel and is+ * UPDATED IN PLACE. Passing state = NULL treats history as zero (start of sequence).+ * This state is a second piece of per-sequence memory beyond the recurrent matrix+ * and is the piece a decode loop forgets. modeling_kimi_linear.py:504-518 */+void k3_shortconv(float *y, const float *x, const float *w, float *state,+ int channels, int k, int T);++/* Decay chain, per head h and channel d:+ * z = f_b(f_a(x))[h][d] + dt_bias[h*D + d]+ * g = lb * sigmoid(exp(A_log[h]) * z) in (lb, 0]+ * alpha = exp(g) in (e^lb, 1]+ * A_log is indexed BY HEAD. In float32 sigmoid underflows to 0 once its argument+ * falls below about -87.3, so alpha == 1.0 exactly is legitimate saturation+ * meaning perfect retention, not an error. fla/ops/kda/gate.py:60-69 */+void k3_kda_decay(float *g, float *alpha, const float *z, const float *A_log,+ const float *dt_bias, int H, int D, float lb);++/* One KDA recurrence step for one head. S is [d_k][d_v], row-major.+ * ORDER IS LOAD BEARING (fla/ops/kda/naive.py:59-63):+ * 1. decay S[i][:] *= alpha[i]+ * 2. read u = S^T k+ * 3. write S += k (beta*(v-u))^T+ * 4. output o = S^T q from the ALREADY UPDATED state+ * q must arrive pre-scaled by d_k^-0.5. */+void k3_kda_step(float *S, float *o, const float *q, const float *k,+ const float *v, const float *alpha, float beta, int dk, int dv);++/* y[out] = W[out][in] . x[in]. W is row-major, no bias anywhere in this model. */+void k3_matmul(float *y, const float *x, const float *W, int in, int out);++/* Gated MLA, NoPE. One full sequence, no cache. modeling_kimi_linear.py:405-474.+ *+ * Shapes, with H heads:+ * q = q_b(q_a_norm(q_a(x))) [T, H, qk_nope + qk_rope]+ * c = kv_a(x) [T, kv_lora + qk_rope] ONE projection+ * kv = kv_b(kv_a_norm(c[:kv_lora])) [T, H, qk_nope + v_head]+ * k_rope = c[kv_lora:] [T, qk_rope] ONE head, broadcast to all+ *+ * NoPE: no rotation is ever applied, yet the qk_rope slots STILL EXIST and are+ * still concatenated onto both query and key. Dropping them changes the head width+ * from 192 to 128 and silently produces a different model.+ * modeling_kimi_linear.py:396 asserts use_nope; :403 sets rotary_emb = None.+ *+ * The softmax scale is (qk_nope + qk_rope)^-0.5, i.e. 192^-0.5, NOT qk_nope^-0.5.+ * modeling_kimi_linear.py:359.+ *+ * Causality is the caller's responsibility in the reference implementation, which+ * applies a mask only when one is supplied. It is applied unconditionally here: this is+ * a decoder-only engine and an unmasked position would leak future context.+ *+ * The output gate multiplies the attention output BEFORE o_proj, with no norm,+ * unlike KDA which norms first then gates. :470-473.+ *+ * scratch must hold at least+ * T*H*(qk_nope+qk_rope) q+ * + T*H*(qk_nope+v_head) kv+ * + T*(kv_lora+qk_rope) compressed latent plus the shared rope slot+ * + q_lora transient+ * + 2*H*v_head attention accumulator and gate buffer+ * + T scores+ * floats. Use k3_mla_scratch() rather than recomputing this.+ */+typedef struct {+ /* Tagged by wdt: fp32 when zero (every fixture), bf16 for the real checkpoint. */+ const void *q_a, *q_b;+ const void *kv_a, *kv_b;+ const void *o, *g; /* g may be NULL when the gate is disabled */+ const float *q_a_norm, *kv_a_norm; /* elementwise in k3_rmsnorm: stays fp32 */+ int wdt;+} K3MlaW;++size_t k3_mla_scratch(const K3Cfg *c, int T);+/* Scratch when a KV cache supplies the keys and values. cap is the cache capacity. */+size_t k3_mla_scratch_cached(const K3Cfg *c, int T, int cap, int cached_mode);++/* MLA with an optional KV cache. kvc is [cap][n_heads*(qk_nope+v_head)] and ropec is+ * [cap][qk_rope]; pass NULL for both to get the self-contained behaviour k3_mla has.+ * See the definition for why the EXPANDED keys are cached rather than the latent. */+void k3_mla_cached(float *out, const float *x, const K3MlaW *w, const K3Cfg *c,+ int T, float *scratch,+ float *kvc, float *ropec, int cached, int cap);+void k3_mla(float *out, const float *x, const K3MlaW *w, const K3Cfg *c,+ int T, float *scratch);++/* MoE routing, one token. modeling_kimi_linear.py:703-759.+ *+ * logits = W x float32, no bias, W is [n_experts, hidden]+ * scores = sigmoid(logits) independent; they do NOT sum to 1+ * sel = topk(scores + bias) the frozen bias steers SELECTION ONLY+ * w = scores[sel] gathered from the UNBIASED scores+ * w /= sum(w) + 1e-20 when renorm+ * w *= routed_scale+ *+ * Reading the weights from the biased scores instead is the classic silent error:+ * it still routes to the same experts and only perturbs the mixture.+ *+ * The router reads the FULL hidden width, before the latent down-projection.+ * Grouped routing is dead code for K3 (num_expert_group == 1) and is not implemented.+ *+ * idx and w are written in DESCENDING score order. Fills at most topk entries.+ */+void k3_router(int *idx, float *w, const float *x, const float *W,+ const float *bias, int hidden, int n_experts, int topk,+ int renorm, float routed_scale);++/* AttnRes aggregation over nsrc sources of width n.+ * keys = RMSNorm(sources) normalised+ * score = dot(key, fold) fold = norm.weight * proj.weight, ONE vector+ * out = softmax(score) @ sources the RAW, UNNORMALISED sources+ * Fold the two weight vectors at load time. modeling_kimi_linear.py:1075-1088 */+void k3_attn_res(float *out, const float *src, const float *fold,+ int nsrc, int n, float eps);++/* ---- weight storage format -------------------------------------------------------+ * The always-active weights ship as bf16 and total 113.49 GB; held as fp32 they are+ * ~227 GB (see the three figures at the top of this file). Since these+ * kernels are bandwidth bound, storing bf16 and widening inside the matmul both halves+ * the memory and should run faster. Small vectors (norms, biases, A_log, dt_bias, the+ * conv kernels) stay fp32: together they are well under 0.1% of the bytes, and several+ * are read ELEMENTWISE rather than through a matmul, where a silent type change would+ * be read as garbage.+ *+ * A weight matrix is therefore a tagged pointer. K3_WF32 is zero, so a struct that has+ * been memset keeps the fp32 behaviour every existing fixture and the oracle rely on.+ */+enum { K3_WF32 = 0, K3_WBF16 = 1 };++/* bf16 -> f32 is a pure left shift: bf16 IS the top 16 bits of an f32. No rounding,+ * no table, no exponent rebias. */+static inline float k3_bf16f(uint16_t h)+{+ union { uint32_t u; float f; } v;+ v.u = (uint32_t)h << 16;+ return v.f;+}++void k3_matmul_bf16(float *y, const float *x, const uint16_t *W, int in, int out);++/* The one call every trunk matmul goes through. Dispatch is a predictable branch on a+ * per-layer flag, outside the inner loops, so it costs nothing measurable. */+static inline void k3_mmw(float *y, const float *x, const void *W, int wdt,+ int in, int out)+{+ if (wdt == K3_WBF16) k3_matmul_bf16(y, x, (const uint16_t *)W, in, out);+ else k3_matmul(y, x, (const float *)W, in, out);+}++/* Byte stride of one weight element, for pointer arithmetic on tagged matrices. */+static inline size_t k3_wsz(int wdt) { return wdt == K3_WBF16 ? 2u : 4u; }++/* ZERO-INITIALISE EVERY WEIGHT STRUCT BEFORE FILLING IT. K3MoeW holds an optional+ * expert source, which is a function pointer; K3LayerW and K3MlaW hold pointers whose+ * NULL-ness selects a code path (dense versus MoE, gated versus ungated MLA). An+ * uninitialised stack struct therefore does not merely read wrong weights, it jumps to+ * a garbage address. memset first, then assign.+ *+ * Stable LatentMoE weights. Routed experts are stored contiguously:+ * w1[expert][moe_inter][latent] gate+ * w3[expert][moe_inter][latent] up+ * w2[expert][latent][moe_inter] down+ * The shared expert is ONE wider MLP at FULL width, intermediate moe_inter*n_shared.+ */++/* ---- streamed experts -------------------------------------------------------------+ * One routed expert as it sits in the cache: still MXFP4, never widened. A dequantised+ * expert is 132 MB against 17.55 MB packed, and a token touches 1,472 of them, so+ * widening on load would need 194 GB per token. k3_matmul_mxfp4 consumes these directly.+ */+typedef struct {+ const unsigned char *p1, *s1; /* w1 gate, packed and E8M0 scales */+ const unsigned char *p3, *s3; /* w3 up */+ const unsigned char *p2, *s2; /* w2 down */+} K3ExpertQ;++/* A source of experts. get() must leave the returned pointers valid until the caller+ * finishes the token; a cache satisfies that by pinning what the current token needs+ * before evicting anything. Returns 0 on success. */+typedef struct K3ExpertSrc {+ int (*get)(struct K3ExpertSrc *self, int layer, int expert, K3ExpertQ *out);+ /* OPTIONAL batch prefetch: bring all n experts resident, issuing their reads+ * concurrently. May be NULL, and callers MUST cope with that by falling back to+ * get() alone -- which is always correct, just slower.+ *+ * WHY IT EXISTS. k3_moe walks the top-16 calling get() one at a time, so each miss+ * is a blocking 17.55 MB pread and the drive sees one request in flight. On a+ * 92-layer decode that is 1,472 serial round trips. Handing the whole top-k over at+ * once lets the reads overlap, which is the difference between a queue depth of 1+ * and one of 16 on hardware that needs depth to reach its rated bandwidth.+ *+ * Returns the number brought resident, or -1. A short return is NOT fatal: get()+ * will simply miss on the remainder and read it the slow way.+ *+ * ZERO THIS FIELD. It is a function pointer in a struct that callers build on the+ * stack; an uninitialised one is a jump to garbage. See the warning below. */+ int (*getmany)(struct K3ExpertSrc *self, int layer, const int *experts, int n);+ void *ctx;+} K3ExpertSrc;++typedef struct {+ /* gate stays fp32 on purpose. k3_router carries its own inline matmul rather than+ * calling k3_matmul, so tagging it would change that function's signature and its+ * fixture, to save 1.18 GB out of about 114 GB. Not worth the churn.+ * w1/w3/w2 also stay fp32: that resident bank is indexed by pointer arithmetic and+ * is only ever used by the fixtures, because the real model streams experts+ * through src and multiplies them straight out of MXFP4. */+ const float *gate, *bias; /* router: [n_experts][hidden], [n_experts] */+ const float *w1, *w3, *w2; /* resident expert bank, fixtures only */+ const float *latent_norm; /* [latent], elementwise: stays fp32 */+ const void *down, *up; /* [latent][hidden], [hidden][latent] */+ const void *sh1, *sh3, *sh2; /* shared expert, full width */+ int wdt; /* applies to down/up/sh1/sh3/sh2 */+ /* When src is non-NULL the resident w1/w3/w2 bank is ignored and experts are+ * fetched per token. layer identifies this layer to the source. Both default to+ * zero, so every existing caller keeps the resident path unchanged. */+ struct K3ExpertSrc *src;+ int layer;+} K3MoeW;++size_t k3_moe_scratch(const K3Cfg *c);++/* Number of routed experts that failed to load and were dropped from a MoE sum.+ * Non-zero means some token was computed with part of its routed contribution missing,+ * which is silent numerical corruption: the run still finishes and still prints a+ * plausible token. Callers MUST check this and fail. Defined in k3_ops.c. */+extern long k3_expert_drops;++/* Context ceilings, a sanity bound, not the binding constraint.+ *+ * Prompt, sequence and output buffers are heap-allocated and sized from the actual+ * request, so these limits exist only to reject implausible input early.+ *+ * The binding constraint is the MLA KV cache, which costs ~2.37 MB per position+ * (24 MLA layers x expanded k and v, fp32):+ *+ * 4,096 positions -> 9.7 GB+ * 16,384 positions -> 38.8 GB+ * 32,768 positions -> 77.7 GB+ * 131,072 positions -> 310.6 GB+ * 1,048,576 positions -> 2485.0 GB the model's advertised 1M context+ *+ * The CLI computes the requirement for the request it was given and refuses, with both+ * figures side by side, when it will not fit in available memory. Reaching the model's+ * full 1M context is a hardware question, not an engine limit.+ *+ * Note that long prompts are also bounded in practice by prefill cost: attention in the+ * MLA layers is quadratic in sequence length, and prefill is not yet chunked. See+ * docs/ROADMAP.md. */+#define K3_MAX_PROMPT 32768+#define K3_MAX_GEN 4096++/* Bytes of MLA KV cache per position, measured on the released checkpoint. */+#define K3_KV_BYTES_PER_POS 2370000.0++/* idx and wt must each hold topk entries. */+void k3_moe(float *out, const float *x, const K3MoeW *w, const K3Cfg *c,+ int T, int *idx, float *wt, float *scratch);++/* Kimi Delta Attention, one full layer, one sequence, no cache.+ * Verified against modeling_kimi_linear.py:543-663 and fla/ops/kda/naive.py.+ *+ * Order, and every step of it is load bearing:+ * 1. q,k,v = Linear(x) separate projections+ * 2. ShortConv on each, SiLU FUSED inside :504-518+ * 3. L2Norm on q and k ONLY, never on v Eq 2. sum of squares, not mean.+ * 4. beta = sigmoid(b_proj(x)) PER-HEAD SCALAR, not per channel+ * 5. z = f_b(f_a(x)) + dt_bias ONE shared low-rank pair, all heads+ * g = lb*sigmoid(exp(A_log[h]) * z) A_log indexed BY HEAD+ * alpha = exp(g)+ * 6. recurrence, q pre-scaled by d_k^-0.5 decay, delta write, read UPDATED+ * 7. head-wise RMSNorm on the output over d_v, per head+ * 8. multiply by sigmoid(g_proj(x)) norm FIRST, then gate :651-656+ * 9. o_proj+ *+ * Step 8 is the opposite order to MLA, which gates before its projection with no+ * norm at all. Sharing one code path between them is wrong.+ */+typedef struct {+ const void *q, *k, *v; /* [H*D][hidden] each */+ /* The conv kernels, A_log and dt_bias are read ELEMENTWISE by k3_shortconv and+ * k3_kda_decay, not through a matmul, so they stay fp32. They are also tiny: the+ * three conv kernels are 49k values each and A_log is 96. */+ const float *q_conv, *k_conv, *v_conv; /* [H*D][conv_k] depthwise */+ const void *f_a, *f_b; /* [D][hidden], [H*D][D] */+ const float *A_log; /* [H] PER HEAD */+ const float *dt_bias; /* [H*D] per (head, channel) */+ const void *b; /* [H][hidden] -> per-head scalar */+ const void *g; /* [H*D][hidden] full-rank gate */+ const float *o_norm; /* [D] head-wise norm gain */+ const void *o; /* [hidden][H*D] */+ int wdt; /* q,k,v,g,o,f_a,f_b,b */+} K3KdaW;++size_t k3_kda_scratch(const K3Cfg *c, int T);+/* state may be NULL (fresh sequence). If non-NULL it must hold+ * H*D*D recurrent floats followed by 3*H*D*(conv_k-1) convolution floats, and it is+ * UPDATED IN PLACE so a decode loop can carry it. */+void k3_kda_layer(float *out, const float *x, const K3KdaW *w, const K3Cfg *c,+ int T, float *state, float *scratch);++/* One decoder layer, reproducing _forward_attn_residual (modeling_kimi_linear.py+ * :984-1046) statement for statement.+ *+ * prefix_sum = h+ * if block_residual is NON-EMPTY:+ * h = attn_res([blocks..., prefix_sum], self_attention_res) <- REPLACES h+ * if layer_idx % attn_res_block == 0:+ * push prefix_sum onto block_residual+ * prefix_sum = NONE <- the reset+ * h = input_layernorm(h)+ * h = attention(h)+ * prefix_sum = (prefix_sum == NONE) ? h : prefix_sum + h+ * h = attn_res([blocks..., prefix_sum], mlp_res) <- UNCONDITIONAL+ * h = post_attention_layernorm(h)+ * h = moe(h) or dense_mlp(h)+ * prefix_sum = (prefix_sum == NONE) ? h : prefix_sum + h+ * return prefix_sum+ *+ * THE SUBTLETY: on a boundary layer the running residual is pushed into the snapshot+ * stack and then CLEARED, so it does NOT also survive as a separate softmax source+ * there. On every other layer it does. Getting this wrong is silent.+ *+ * The second aggregation has NO emptiness guard, unlike the first. That is safe only+ * because layer 0 is itself a boundary and has already pushed one snapshot.+ *+ * block_residual is [T][max_blocks][hidden]; *n_blocks is read and updated.+ */+typedef struct {+ const float *in_norm, *post_norm; /* [hidden] */+ const float *attn_res_norm, *attn_res_proj; /* [hidden] each, folded at load */+ const float *mlp_res_norm, *mlp_res_proj;+ const K3KdaW *kda; /* exactly one of kda/mla is non-NULL */+ const K3MlaW *mla;+ const K3MoeW *moe; /* NULL on the dense layer */+ const void *dense_gate, *dense_up, *dense_down; /* used when moe is NULL */+ int wdt; /* applies to the three dense_* only */+} K3LayerW;++size_t k3_layer_scratch(const K3Cfg *c, int T);+void k3_decoder_layer(float *h, float *block_residual, int *n_blocks,+ const K3LayerW *w, const K3Cfg *c, int layer_idx,+ int T, float *state, float *scratch);++/* Incremental form: identical except that MLA attends over a KV cache of `cached`+ * earlier positions and appends its own. KDA and the attn-res stack need nothing+ * carried, because KDA updates its state in place and the block stack is per token.+ * Pass kvc = NULL for the full-recompute behaviour. */+void k3_decoder_layer_inc(float *h, float *block_residual, int *n_blocks,+ const K3LayerW *w, const K3Cfg *c, int layer_idx,+ int T, float *state, float *scratch,+ float *kvc, float *ropec, int cached, int cap);++/* ---------------------------------------------------------------- MXFP4 ---- */+/* Dequantise OCP MX FP4, the format Kimi K3 ships its routed experts in.+ *+ * packed [rows][pcols] uint8, TWO 4-bit elements per byte+ * scales [rows][pcols*2/32] uint8, one E8M0 exponent per 32 elements+ * out [rows][pcols*2] float32+ *+ * value = E2M1[nibble] * 2^(scale - 127)+ *+ * E2M1 is 1 sign, 2 exponent, 1 mantissa, so exactly sixteen values:+ * 0, 0.5, 1, 1.5, 2, 3, 4, 6 and their negatives.+ * E8M0 is a bare biased exponent; 255 is NaN by spec and is mapped to zero here so a+ * single bad byte cannot poison a whole row.+ *+ * NIBBLE ORDER IS A CONVENTION, NOT A RULE. The low nibble of each byte is the EVEN+ * element. Reversing it yields a matrix with exactly the right values in the wrong+ * places: every statistic looks perfect and the model is wrong. Verified against real+ * checkpoint bytes in fixtures/mxfp4.json, which also records the swapped result.+ *+ * Bytes on disk per element are 0.5 for the nibble plus 1/32 for the shared scale,+ * i.e. 0.53125, which is why one 33,030,144-parameter expert occupies 17,547,264+ * bytes exactly.+ */+/* config.json: quantization_config.group_size = 32. Named rather than spelled 32 at+ * each call site so a checkpoint that changed it fails at one place, and so k3_load.c+ * can check the shipped scale count against it per tensor. */+#define K3_MXFP4_GROUP 32++/* Upper bound on num_experts_per_token, and therefore on the fixed-size top-k arrays in+ * k3_decoder_layer and the cache's batch-prefetch work list. K3 selects 16.+ *+ * This is a HARD limit, not a hint: k3_router fills the caller's idx[] with cfg->topk+ * entries and those arrays are stack allocated, so a config with a larger top-k would+ * overflow them. k3_cfg.h validates topk against this so the failure is a clear message+ * at load time rather than a corrupted stack mid-decode. */+#define K3_MAX_TOPK 64++void k3_mxfp4_dequant(float *out, const unsigned char *packed,+ const unsigned char *scales, int rows, int pcols, int group);++/* y[rows] = W[rows][in] . x[in], with W read directly as MXFP4. Never materialises the+ * fp32 matrix, which is what allows a streamed expert to stay 17.55 MB instead of+ * becoming 132 MB. See the comment on the definition. */+void k3_matmul_mxfp4(float *y, const float *x, const unsigned char *packed,+ const unsigned char *scales, int in, int rows, int group);++#ifdef __cplusplus+}+#endif++#endif /* K3_H */diff --git a/include/k3/k3_cfg.h b/include/k3/k3_cfg.hnew file mode 100644index 0000000..48e4cad--- /dev/null+++ b/include/k3/k3_cfg.h@@ -0,0 +1,276 @@+/* SPDX-License-Identifier: Apache-2.0 */+/* k3_cfg.h - build a K3Cfg from a config JSON, in either shape, without ever guessing.+ *+ * TWO SHAPES, ONE READER+ * Two different JSON layouts describe this model, and the engine must read both:+ *+ * released config.json nested. The language model lives under "text_config",+ * and the KDA/MLA layer map under+ * text_config.linear_attn_config. The SiTU betas are named+ * activation_situ_beta / activation_situ_linear_beta.+ *+ * ref_k3.json flat. make_k3_oracle.py hoists everything to one level+ * and shortens the betas to situ_beta / situ_linear_beta.+ *+ * Every lookup here tries both spellings, so callers never branch on which shape they+ * were handed and the test fixtures exercise the same code path as the real model.+ *+ * THE ONE RULE: AN ABSENT FIELD IS AN ERROR, NEVER A DEFAULT.+ * This is worth stating plainly because the alternative fails in the worst possible+ * way. Point a flat-only reader at the released nested config and every lookup misses.+ * If each miss took a default:+ * - situ_beta/situ_linear_beta would default to 4.0/25.0, which are CORRECT, so the+ * activation looks right and inspires confidence;+ * - full_attn_layers would come back empty, so k3_is_mla() answers 0 for every layer+ * and all 93 layers run as KDA.+ * The result is a model that loads, streams, decodes, and prints fluent-looking tokens+ * from the wrong architecture. Nothing crashes and no number looks out of place.+ *+ * So a missing key fails the load. Every missing key is collected and reported+ * together rather than one per run, because rediscovering them one at a time across a+ * 93-layer load wastes an enormous amount of operator time.+ *+ * Both shapes are covered by the test suite: tests/unit/test_cfg.c reads the flat+ * fixture, and the nested path is exercised by any run against a released checkpoint.+ */+#ifndef K3_CFG_H+#define K3_CFG_H++#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include "json.h"+#include "k3.h"++/* ---------------------------------------------------------------- lookup ---- */+/* Candidate objects, searched in order: the nested language-model config, the nested+ * linear-attention block, then the root (which IS the config in the flat fixture).+ * Candidate names cover the released spelling and the fixture spelling. */+typedef struct {+ jval *txt; /* text_config, or NULL in the flat shape */+ jval *lin; /* text_config.linear_attn_config, or NULL */+ jval *root; /* the document root; also the config object when flat */+ int nested; /* 1 = released shape, 0 = flat fixture shape */+ /* Missing required keys accumulate here so one run reports all of them. */+ const char *missing[32];+ int nmissing;+} K3CfgSrc;++static inline jval *k3cfg_find(K3CfgSrc *s, const char *primary, const char *alias)+{+ jval *objs[3] = { s->txt, s->lin, s->root };+ const char *names[2] = { primary, alias };+ for (int i = 0; i < 3; i++) {+ if (!objs[i]) continue;+ for (int j = 0; j < 2; j++) {+ if (!names[j]) continue;+ jval *v = json_get(objs[i], names[j]);+ if (v) return v;+ }+ }+ return NULL;+}++static inline void k3cfg_miss(K3CfgSrc *s, const char *name)+{+ if (s->nmissing < (int)(sizeof s->missing / sizeof s->missing[0]))+ s->missing[s->nmissing] = name;+ s->nmissing++;+}++static inline int k3cfg_i(K3CfgSrc *s, const char *primary, const char *alias)+{+ jval *v = k3cfg_find(s, primary, alias);+ if (!v || v->t != J_NUM) { k3cfg_miss(s, primary); return 0; }+ return (int)v->num;+}++static inline float k3cfg_f(K3CfgSrc *s, const char *primary, const char *alias)+{+ jval *v = k3cfg_find(s, primary, alias);+ if (!v || v->t != J_NUM) { k3cfg_miss(s, primary); return 0.0f; }+ return (float)v->num;+}++/* Booleans are written as JSON true/false in the released config and as Python-ish+ * true/false in the fixture; both parse to J_BOOL. A numeric 0/1 is also accepted+ * because hand-edited configs use it. */+static inline int k3cfg_b(K3CfgSrc *s, const char *primary, const char *alias, int dflt)+{+ jval *v = k3cfg_find(s, primary, alias);+ if (!v) return dflt; /* genuinely optional: has a real default */+ if (v->t == J_BOOL) return v->boolean ? 1 : 0;+ if (v->t == J_NUM) return v->num != 0.0;+ return dflt;+}++/* ------------------------------------------------------------------ load ---- */+/* fa receives the ONE-BASED full-attention (MLA) layer list, as both config shapes+ * store it; k3_is_mla() compares against layer+1. Returns 1 on success.+ *+ * On failure it prints every missing key and returns 0. Callers must not proceed:+ * a half-filled K3Cfg is exactly the silent-wrong-model case this file exists to stop.+ */+static inline int k3_cfg_load(K3Cfg *c, int *fa, int fa_max, jval *root, const char *whence)+{+ memset(c, 0, sizeof *c);++ K3CfgSrc s; memset(&s, 0, sizeof s);+ s.root = root;+ s.txt = json_get(root, "text_config");+ s.nested = (s.txt != NULL);+ jval *base = s.txt ? s.txt : root;+ s.lin = json_get(base, "linear_attn_config");++ c->hidden = k3cfg_i(&s, "hidden_size", NULL);+ c->n_layers = k3cfg_i(&s, "num_hidden_layers", NULL);+ c->vocab = k3cfg_i(&s, "vocab_size", NULL);+ c->rms_eps = k3cfg_f(&s, "rms_norm_eps", NULL);++ /* KDA. Released: linear_attn_config.num_heads / .head_dim. Fixture: kda_num_heads /+ * kda_head_dim at top level. Searching lin before root is what disambiguates+ * num_heads, which would otherwise collide with nothing but reads ambiguously. */+ c->kda_heads = k3cfg_i(&s, "num_heads", "kda_num_heads");+ c->kda_head_dim = k3cfg_i(&s, "head_dim", "kda_head_dim");+ c->conv_k = k3cfg_i(&s, "short_conv_kernel_size", NULL);+ c->gate_lb = k3cfg_f(&s, "gate_lower_bound", NULL);++ /* Gated MLA */+ c->n_heads = k3cfg_i(&s, "num_attention_heads", NULL);+ c->q_lora = k3cfg_i(&s, "q_lora_rank", NULL);+ c->kv_lora = k3cfg_i(&s, "kv_lora_rank", NULL);+ c->qk_nope = k3cfg_i(&s, "qk_nope_head_dim", NULL);+ c->qk_rope = k3cfg_i(&s, "qk_rope_head_dim", NULL);+ c->v_head = k3cfg_i(&s, "v_head_dim", NULL);+ c->mla_out_gate = k3cfg_b(&s, "mla_use_output_gate", NULL, 1);++ /* Stable LatentMoE */+ c->n_experts = k3cfg_i(&s, "num_experts", NULL);+ c->topk = k3cfg_i(&s, "num_experts_per_token", NULL);+ c->n_shared = k3cfg_i(&s, "num_shared_experts", NULL);+ c->latent = k3cfg_i(&s, "routed_expert_hidden_size", NULL);+ c->moe_inter = k3cfg_i(&s, "moe_intermediate_size", NULL);+ c->routed_scale = k3cfg_f(&s, "routed_scaling_factor", NULL);+ c->moe_renorm = k3cfg_b(&s, "moe_renormalize", NULL, 1);+ c->latent_norm = k3cfg_b(&s, "latent_moe_use_norm", NULL, 1);++ c->first_dense = k3cfg_i(&s, "first_k_dense_replace", NULL);+ c->dense_inter = k3cfg_i(&s, "intermediate_size", NULL);+ c->attn_res_block = k3cfg_i(&s, "attn_res_block_size", NULL);++ /* SiTU-GLU. The released and fixture spellings differ; both are accepted, and+ * neither is defaulted. These two are the most dangerous fields in the file to+ * default, because 4.0/25.0 are the correct values: a defaulting reader produces a+ * plausible activation and hides the fact that it read nothing else either. */+ c->situ_b1 = k3cfg_f(&s, "activation_situ_beta", "situ_beta");+ c->situ_b2 = k3cfg_f(&s, "activation_situ_linear_beta", "situ_linear_beta");++ /* Layer map. Released: text_config.linear_attn_config.full_attn_layers.+ * Fixture: full_attn_layers at top level. */+ jval *fal = k3cfg_find(&s, "full_attn_layers", NULL);+ if (!fal || fal->t != J_ARR || fal->len == 0) {+ k3cfg_miss(&s, "full_attn_layers");+ } else if (fal->len > fa_max) {+ fprintf(stderr, "k3_cfg: %s lists %d full-attention layers, buffer holds %d\n",+ whence, fal->len, fa_max);+ return 0;+ } else {+ for (int i = 0; i < fal->len; i++) {+ if (fal->kids[i]->t != J_NUM) {+ fprintf(stderr, "k3_cfg: %s full_attn_layers[%d] is not a number\n",+ whence, i);+ return 0;+ }+ fa[i] = (int)fal->kids[i]->num;+ }+ c->n_full_attn = fal->len;+ c->full_attn = fa;+ }++ if (s.nmissing) {+ fprintf(stderr, "k3_cfg: %s is missing %d required field(s):\n", whence, s.nmissing);+ int shown = s.nmissing;+ int cap = (int)(sizeof s.missing / sizeof s.missing[0]);+ if (shown > cap) shown = cap;+ for (int i = 0; i < shown; i++) fprintf(stderr, " %s\n", s.missing[i]);+ if (s.nmissing > shown) fprintf(stderr, " ... and %d more\n", s.nmissing - shown);+ fprintf(stderr, " refusing to substitute defaults: a config this reader cannot\n"+ " fully understand would silently produce a DIFFERENT model.\n");+ return 0;+ }++ /* ---- structural checks ----+ * These catch a config that parses cleanly but cannot describe this architecture.+ * Each has been seen or is one typo away. */+ if (c->n_layers <= 0 || c->hidden <= 0 || c->vocab <= 0) {+ fprintf(stderr, "k3_cfg: %s has non-positive layers/hidden/vocab\n", whence);+ return 0;+ }+ if (c->n_full_attn >= c->n_layers) {+ fprintf(stderr, "k3_cfg: %s marks %d of %d layers as full attention, leaving no "+ "KDA layers\n", whence, c->n_full_attn, c->n_layers);+ return 0;+ }+ for (int i = 0; i < c->n_full_attn; i++) {+ if (fa[i] < 1 || fa[i] > c->n_layers) {+ fprintf(stderr, "k3_cfg: %s full_attn_layers[%d] = %d is outside 1..%d "+ "(the list is ONE-based)\n", whence, i, fa[i], c->n_layers);+ return 0;+ }+ }+ if (c->topk > K3_MAX_TOPK) {+ fprintf(stderr, "k3_cfg: %s selects top-%d, but this build supports at most %d\n"+ " (K3_MAX_TOPK in k3.h bounds the fixed-size routing arrays)\n",+ whence, c->topk, K3_MAX_TOPK);+ return 0;+ }+ if (c->topk > c->n_experts) {+ fprintf(stderr, "k3_cfg: %s selects %d of %d experts\n",+ whence, c->topk, c->n_experts);+ return 0;+ }+ if (c->attn_res_block <= 0) {+ fprintf(stderr, "k3_cfg: %s has attn_res_block_size %d; layer_idx %% 0 would "+ "divide by zero\n", whence, c->attn_res_block);+ return 0;+ }+ if (c->conv_k < 1) {+ fprintf(stderr, "k3_cfg: %s has short_conv_kernel_size %d\n", whence, c->conv_k);+ return 0;+ }++ printf("config: %s (%s shape) | hidden=%d layers=%d vocab=%d | %d MLA + %d KDA | "+ "experts %d top%d shared%d | latent=%d\n",+ whence, s.nested ? "nested" : "flat", c->hidden, c->n_layers, c->vocab,+ c->n_full_attn, c->n_layers - c->n_full_attn,+ c->n_experts, c->topk, c->n_shared, c->latent);+ return 1;+}++/* Convenience: read and parse a config file, then load it. The returned arena is left+ * allocated because K3Cfg does not copy the strings it does not own; callers keep it+ * for the process lifetime, which every caller here does. */+static inline int k3_cfg_load_file(K3Cfg *c, int *fa, int fa_max, const char *path)+{+ FILE *f = fopen(path, "rb");+ if (!f) { perror(path); return 0; }+ if (fseek(f, 0, SEEK_END) != 0) { perror(path); fclose(f); return 0; }+ long n = ftell(f);+ if (n < 0 || n > (1L << 28)) {+ fprintf(stderr, "%s: implausible config size %ld\n", path, n);+ fclose(f); return 0;+ }+ if (fseek(f, 0, SEEK_SET) != 0) { perror(path); fclose(f); return 0; }+ char *txt = (char *)malloc((size_t)n + 1);+ if (!txt) { fprintf(stderr, "OOM reading %s\n", path); fclose(f); return 0; }+ size_t got = fread(txt, 1, (size_t)n, f);+ fclose(f);+ txt[got] = 0;++ char *arena = NULL;+ jval *root = json_parse(txt, &arena);+ if (!root) { fprintf(stderr, "%s: not valid JSON\n", path); free(txt); return 0; }+ return k3_cfg_load(c, fa, fa_max, root, path);+}++#endif /* K3_CFG_H */