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
docs: add the reference documentation set
FareedKhan-devb4a7b3f873a0
diff --git a/docs/API.md b/docs/API.mdnew file mode 100644index 0000000..be94da9--- /dev/null+++ b/docs/API.md@@ -0,0 +1,160 @@+# C API++For embedding the engine rather than using the `k3` binary. The public surface is+`include/k3/k3.h` and `include/k3/k3_cfg.h`.++```c+#include <k3/k3.h>+#include <k3/k3_cfg.h>+```++The API is deliberately small: a configuration struct, weight-binding structs, and the+kernels. There is no context object and no hidden global state, everything a call needs+is passed to it.++## Configuration++```c+K3Cfg cfg;+int full_attn[128];++if (!k3_cfg_load_file(&cfg, full_attn, 128, "model/config.json")) {+ /* Do not proceed. A partially-populated K3Cfg describes a different model. */+ return 1;+}+```++`k3_cfg_load_file` reads the checkpoint's own configuration and populates every field.++**It never substitutes a default for a missing field.** If a key is absent it collects+every such key, reports them together, and returns 0. This matters more than it appears:+a configuration reader that defaults silently produces an engine that loads, streams,+decodes, and emits fluent text from the wrong architecture, with nothing to indicate it.++Both layouts are accepted, the released nested form (`text_config.*`) and the flat form+used by the test fixtures.++Layer roles:++```c+k3_is_mla(&cfg, layer) /* Gated MLA layer */+k3_is_kda(&cfg, layer) /* Kimi Delta Attention */+k3_is_dense(&cfg, layer) /* the single dense layer */+```++`full_attn` holds ONE-BASED layer indices, matching the checkpoint's own convention.++## Scratch memory++Every kernel takes caller-provided scratch. Sizes come from the engine, not from your+own arithmetic, recomputing them by hand is the easiest way to overrun a buffer+silently.++```c+size_t n = k3_layer_scratch(&cfg, n_tokens);+float *scratch = malloc(n * sizeof(float));+```++| function | covers |+|---|---|+| `k3_layer_scratch(cfg, T)` | a whole decoder layer |+| `k3_kda_scratch(cfg, T)` | a KDA layer |+| `k3_mla_scratch(cfg, T)` | an MLA layer, no KV cache |+| `k3_mla_scratch_cached(cfg, T, cap, mode)` | an MLA layer with a KV cache |+| `k3_moe_scratch(cfg)` | the MoE block |++## Weight structures++`K3KdaW`, `K3MlaW`, `K3MoeW` and `K3LayerW` describe where a layer's tensors live.++> **Zero every weight struct before filling it.** These hold function pointers+> (`K3MoeW::src`) and pointers whose NULL-ness selects a code path, dense versus MoE,+> gated versus ungated MLA. An uninitialised stack struct does not merely read the wrong+> weights; it can jump to an arbitrary address.++```c+K3MoeW moe;+memset(&moe, 0, sizeof moe); /* required, not defensive */+```++Weight matrices are tagged pointers: `K3_WF32` (0) or `K3_WBF16` (1). Because `K3_WF32`+is zero, a `memset` struct defaults to fp32. Dispatch through `k3_mmw()` rather than+calling the typed matmuls directly.++## Running a layer++```c+k3_decoder_layer(hidden, block_residual, &n_blocks, &weights, &cfg,+ layer_idx, n_tokens, kda_state, scratch);+```++`k3_decoder_layer_inc()` is the incremental form: MLA attends over a KV cache of earlier+positions and appends its own. KDA needs nothing carried, it updates its recurrent state+in place, and the Attention-Residual block stack is per token.++Both must produce identical tokens. The test suite asserts this rather than assuming it.++## Streaming experts++Provide a `K3ExpertSrc` and the MoE block will fetch experts on demand instead of reading+a resident bank:++```c+typedef struct K3ExpertSrc {+ int (*get)(struct K3ExpertSrc *, int layer, int expert, K3ExpertQ *out);+ int (*getmany)(struct K3ExpertSrc *, int layer, const int *experts, int n);+ void *ctx;+} K3ExpertSrc;+```++- `get` must keep the returned pointers valid until the caller finishes the token.+- `getmany` is an optional batch hint. It may be NULL, and callers must cope, falling+ back to `get` alone is always correct, only slower. It exists because issuing the whole+ top-k at once lets the reads overlap; serial `get` calls give the device a queue depth+ of one, which most NVMe hardware needs depth to saturate.++Experts stay in packed MXFP4 throughout. `k3_matmul_mxfp4` consumes nibbles directly and+never materialises a dequantised matrix, one expert is 17.5 MB packed against 132 MB+expanded, and a token touches 1,472 of them.++## Error handling++Two failure modes need explicit attention from callers.++**`k3_expert_drops`** is a global counter incremented whenever a streamed expert could+not be loaded. Non-zero means some token was computed with part of its routed+contribution missing, silent numerical corruption. The run completes and prints a+plausible token.++```c+if (k3_expert_drops) {+ fprintf(stderr, "%ld experts failed to load; output is corrupt\n", k3_expert_drops);+ return 1; /* fail the run; do not report success */+}+```++**Configuration load failure** must abort, as above. There is no safe partial state.++## Thread safety++The kernels are reentrant and parallelise internally with OpenMP. They hold no global+state except `k3_expert_drops`.++The cache, the trunk reader, and the safetensors index are **not** thread-safe. One+inference at a time per instance.++## Minimal example++```c+K3Cfg cfg; int fa[128];+if (!k3_cfg_load_file(&cfg, fa, 128, "model/config.json")) return 1;++float *scratch = malloc(k3_layer_scratch(&cfg, T) * sizeof(float));++for (int L = 0; L < cfg.n_layers; L++)+ k3_decoder_layer(h, block_res, &nblocks, &layer_w[L], &cfg, L, T, kstate, scratch);++if (k3_expert_drops) return 1; /* check before trusting the output */+```++See `src/cli/k3_run.c` for the complete path, including trunk streaming and the KV cache.diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdnew file mode 100644index 0000000..9cf8ecc--- /dev/null+++ b/docs/ARCHITECTURE.md@@ -0,0 +1,145 @@+# Architecture++How Kimi K3 maps onto this codebase. The model's own technical report is in+[kimi-k3-tech-report.pdf](kimi-k3-tech-report.pdf); section numbers below refer to it.++## The model++| | |+|---|---|+| Parameters | 2.78T total, ~104B active per token |+| Layers | 93: 69 KDA + 24 Gated MLA. Layer 0 has a dense FFN instead of a MoE block, so 92 layers route. |+| Hidden | 7168 |+| Attention heads | 96 |+| Routed experts | 896 per layer, top-16 selected |+| Shared experts | 2, full width |+| Latent MoE width | 3584 |+| Expert intermediate | 3072 |+| Vocabulary | 163,840 |+| Activation | SiTU-GLU (β₁ = 4, β₂ = 25) |+| Expert weights | native MXFP4 |++Every one of these is **read from the checkpoint's own `config.json`** at startup, not+hardcoded. The reader (`include/k3/k3_cfg.h`) refuses to substitute a default for a+missing field, because a config it half-understands produces a model that runs and is+architecturally wrong.++The MLA layers sit at one-based positions 4, 8, 12, … 92, **and 93**, the last two+layers are both MLA, so the final layer always performs global attention (§2.1).++## Where the memory goes++| component | size | residency |+|---|---:|---|+| Routed experts | 1.45 TB | never resident, streamed, MXFP4 |+| Dense trunk | 108.81 GB | resident *or* streamed |+| Embed + final norm + lm_head | 4.70 GB | always resident |+| Recurrent state (93 layers) | 626 MB | always resident |+| MLA KV cache | 2.37 MB/position | only with `--incremental` |++This table is the whole design. The 1.45 TB never lands in RAM; the 108.81 GB is the+dial; the 5.3 GB is the floor.++## Module map++```+include/k3/+ k3.h public types, config, and the five invariants that must hold+ k3_cfg.h config reader, never defaults a missing field++src/core/+ k3_ops.c every kernel: RMSNorm, SiTU-GLU, ShortConv, KDA recurrence,+ Gated MLA, AttnRes, MoE, MXFP4 matmul, bf16 matmul++src/io/+ k3_st.c safetensors reader, hand-written, no dependency+ k3_load.c one coalesced pread per expert+ k3_trunk.c trunk streaming: ring buffer plus a pinned prefix++src/cache/+ k3_cache.c routed-expert LRU with batch prefetch++src/model/+ k3_bind.c binds tensors by name onto layer structures++src/tokenizer/+ k3_tok.h loads the released tiktoken.model directly++src/cli/+ k3_run.c the k3 binary+```++## Attention: two mechanisms++**KDA** (69 layers, §2.1.1) is a linear-attention recurrence with a channel-wise forget+gate. Per layer: separate q/k/v projections → ShortConv with fused SiLU → L2Norm on q and+k only → per-head β from a sigmoid → decay `g = g_min · sigmoid(e^A · z)` with+`g_min = −5` and **A indexed per head** → the recurrence → head-wise RMSNorm → a+full-rank output gate.++The recurrence order is load-bearing: decay the state, read from it, write the delta,+*then* read the output from the already-updated state.++**Gated MLA** (24 layers, §2.1.2) compresses keys and values into a low-rank latent. It+uses **NoPE**, no positional encoding at all, yet the 64 rope dimensions still exist+and are still cached. Only the rotation is absent. Dropping the slots would change the+head width from 192 to 128 and silently produce a different model.++## Attention Residuals (§2.2)++Instead of accumulating one residual through depth, each layer attends over the outputs+of preceding *blocks*. Layers are partitioned into blocks of 12; at a block boundary the+running residual is snapshotted and cleared. The token embedding is always the first+source, because layer 0 is itself a boundary.++## Stable LatentMoE (§2.3)++The routed path projects down to a 3584-wide latent, dispatches to 16 of 896 experts,+RMSNorms the **aggregate** (not each expert), then projects back to full width. Two+shared experts process the input at full width and are added unweighted.++The router computes independent sigmoid scores; they do not sum to 1, and a frozen+per-expert bias steers **selection only**. Combining weights come from the *unbiased*+scores. Using the biased scores for the weights still routes to the same experts and only+perturbs the mixture, which is exactly why it is easy to get wrong and hard to notice.++## MXFP4 experts++Expert weights ship in OCP MX FP4 and are **never dequantised**. `k3_matmul_mxfp4`+consumes packed nibbles directly:++```+value = E2M1[nibble] · 2^(E8M0_scale − 127)+```++with one shared 8-bit exponent per 32 elements. One expert is 33,030,144 parameters in+17,547,264 bytes, 0.53125 bytes per weight.++Dequantising would turn a 17.5 MB expert into 132 MB, and a token touches 1,472 of them+(92 routing layers × top-16): 194 GB per token of pure widening. The whole streaming+design depends on not doing that.++Nibble order is a convention, not a rule: the low nibble is the even element. Reversing+it yields a matrix with the right values in the wrong places: every statistic looks+correct and the model is wrong. There is a fixture for exactly this.++## Trunk streaming++Each layer's trunk tensors form one contiguous run inside its shard, so+`tools/pack_trunk.py` copies them into a single file as 93 sequential range copies, and+loading a layer later is one `pread` from a known offset.++The trunk is walked in the same fixed order every token, which makes prefetch perfect and+lets the read overlap compute. Given enough budget, layers are *pinned* rather than+cycled. A cyclic scan defeats LRU, so a pinned prefix is used instead.++## Correctness++- **op level**: every kernel against reference values at a declared tolerance+- **layer level**: all 93 layers of the released checkpoint individually+- **model level**: teacher forcing, greedy decode, and incremental decode must all match+ a reference exactly on a tiny model with the same tensor graph+- **numeric level**: logits from the released 93-layer checkpoint compared elementwise+ against a torch reference++See [TESTING.md](TESTING.md).diff --git a/docs/BENCHMARKING.md b/docs/BENCHMARKING.mdnew file mode 100644index 0000000..eab9052--- /dev/null+++ b/docs/BENCHMARKING.md@@ -0,0 +1,66 @@+# Benchmarking++## The one rule++**The measured run-to-run spread on an identical configuration is 33%.** Three runs of+the same binary, same prompt, same flags, in the same minute:++| run | s/token |+|---:|---:|+| 1 | 14.78 |+| 2 | 14.67 |+| 3 | 20.14 |++mean 16.53, sd 3.13, spread 33.1%.++If your A/B differs by less than that, you have measured nothing. This is not a caution+in the abstract: on this project, replication was run *last*, and it retracted results+that had already been written down and reasoned about.++## Procedure++```bash+# 3 runs per arm, minimum.+for r in 1 2 3; do+ ./bin/k3 $MODEL --trunk $TRUNK --preset server --ids 1008,10484,318,15383,387 \+ --gen 8 --incremental --out /tmp/arm_a_$r.json | grep 's/token average'+done+```++Then report every run, not the best one:++| arm | run 1 | run 2 | run 3 | mean |+|---|---|---|---|---|++## Things that will contaminate a measurement++Each of these was observed on this project.++- **Background updates.** `unattended-upgrades` was consuming ~63% of a core during one+ run. Stop it: `sudo systemctl stop unattended-upgrades apt-daily.timer`.+- **Two engines at once.** A kill that takes the wrapper but not the child leaves both+ competing for disk and CPU. Check `pgrep -x k3` before starting.+- **Cold vs warm page cache.** A repeat run reads a warm cache. Either drop caches+ between runs (`echo 3 | sudo tee /proc/sys/vm/drop_caches`) or state that you did not.+- **Cold start.** Token 0 pays the full trunk-pinning cost. An 8-token run is dominated+ by it; a 64-token run is not. Never compare runs of different lengths.+- **Different storage.** This workload moves ~135 GB per token, so device bandwidth+ dominates. Comparing two runs from different disks compares the disks.++## What to measure instead of wall clock++Timing is the noisiest thing the engine reports. These are counts, and they do not move:++- `GB read/token`, bytes actually pulled from disk+- `requests` / `evictions`, cache retention, derived as `1 - evictions/requests`+- `pinned N/93 layers`, how much trunk is resident+- generated token ids, for correctness, exact++If a change is supposed to reduce I/O, **measure the bytes**. It is a far stronger claim+than a second-count and it needs no replication.++## Reporting++`docs/PERFORMANCE.md` is the template: state the machine, state the noise floor, mark+single-sample rows as single-sample, and separate what survives the floor from what does+not.diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.mdnew file mode 100644index 0000000..786acf3--- /dev/null+++ b/docs/PERFORMANCE.md@@ -0,0 +1,217 @@+# Performance++All figures measured on a single machine: AMD EPYC 7763, 124 vCPU (2×62, no SMT),+228 GiB RAM, NVMe measured at 3.2 GB/s O_DIRECT, Ubuntu 24.04, GCC 13.3, AVX2 without+AVX-512. Background auto-updates were disabled before measurement.++**Every table on this page is transcribed from raw output in [data/](data/).** The full+machine capture is [data/environment.txt](data/environment.txt). Nothing here is quoted+from memory or rounded by hand, if a table and its data file disagree, the data file is+right and this page has a bug.++> **Read [the noise floor](#the-noise-floor) before quoting any single number.** Three+> runs of an *identical* configuration span 33%. Differences smaller than that are not+> effects.++## The memory ladder++Twelve budgets, each enforced by a hard cgroup cap, same prompt, same binary.+Raw: [data/memory-ladder.tsv](data/memory-ladder.tsv).++| RAM | pinned layers | expert cache | s/token | vs 8 GB | expert hit | trunk hit | GB read/tok | peak RSS |+|---:|---:|---:|---:|---:|---:|---:|---:|---:|+| 8 | 0 | 0.49 | 32.69 | 1.00× | 0.0% | 0.0% | 25.83 | 8.24 |+| 12 | 0 | 2.79 | 31.41 | 1.04× | 0.0% | 0.0% | 25.83 | 10.53 |+| 16 | 3 | 4.39 | 32.21 | 1.01× | 0.0% | 2.8% | 25.83 | 16.00 |+| 24 | 7 | 7.58 | 31.85 | 1.03× | 0.0% | 6.6% | 25.83 | 23.95 |+| 32 | 11 | 10.80 | 31.44 | 1.04× | 0.0% | 10.3% | 25.83 | 31.90 |+| 48 | 19 | 17.19 | 29.76 | 1.10× | 0.0% | 17.9% | 25.83 | 47.80 |+| 64 | 27 | 23.59 | 28.60 | 1.14× | 0.0% | 25.4% | 25.83 | 63.71 |+| 96 | 43 | 36.39 | 24.40 | 1.34× | 29.9% | 40.5% | 18.11 | 95.51 |+| 128 | 60 | 49.19 | 29.40 | 1.11× | 32.2% | 56.5% | 17.51 | 128.18 |+| 160 | 76 | 61.99 | 26.31 | 1.24× | 33.1% | 71.5% | 17.28 | 159.98 |+| 192 | 90 | 77.00 | 21.32 | 1.53× | 35.5% | 84.7% | 16.65 | 191.83 |+| 224 | 90 | 108.98 | 19.21 | 1.70× | 43.8% | 84.7% | 14.53 | 223.82 |++**Every row produced byte-identical output**: `17374, 20829, 10, 427, 414, 1008, 606,+142957`. 28x the memory changes the speed and nothing else.++## Two caches, and only one of them matters below 96 GB++The engine has two independent caches. They do not behave alike.++**The expert cache does nothing below ~36 GB of arena.** From 28 slots to 1,344 slots the+retention stays at 0.0% and the bytes read per token stay pinned at *exactly* 25.83 GB.+Seven consecutive budgets, a 48× increase in cache size, zero change in bytes moved.++This is a property of the model, not a defect in the cache. K3's router is trained with+Quantile Balancing, which deliberately flattens expert usage across the pool. With 16 of+896 experts selected per layer and no hot subset to exploit, there is nothing for an LRU+to retain.++**The trunk ring is the one that responds.** Its hit rate tracks pinned layers almost+exactly:++| pinned | predicted (n/93) | measured |+|---:|---:|---:|+| 3 | 3.2% | 2.8% |+| 7 | 7.5% | 6.6% |+| 11 | 11.8% | 10.3% |+| 27 | 29.0% | 25.4% |+| 90 | 96.8% | 96.8%¹ |++¹ steady state. The 8-token runs report 84.7% because token 0 pays the pinning cost and+tokens 1 to 7 each hit 90 layers: 7 × 90 / 744 = 84.7%.++The mechanism is simply arithmetic: per token the engine reads **108.81 GB of trunk**+against **25.83 GB of experts**, 4.2× the bytes and 2.9× the time. A gigabyte given to+the trunk removes ~1.17 GB/token of guaranteed traffic. A gigabyte given to the expert+cache removes, below the knee, nothing.++### How much cache would be enough++The ladder can only answer this where it happened to sample. Replaying the recorded+request trace answers it everywhere, for free+[data/expert-cache-capacity.txt](data/expert-cache-capacity.txt), regenerated by:++```bash+python3 tools/sim_cache.py tests/fixtures/expert_trace.bin+```++100,096 recorded expert requests, 10,010 distinct experts (12.1% of the pool):++| cache | slots | LRU | Belady | GB read/token |+|---:|---:|---:|---:|---:|+| 8 GB | 455 | 36.2% | 39.4% | 16.47 |+| 32 GB | 1,823 | 36.2% | 49.0% | 16.47 |+| 64 GB | 3,647 | 36.2% | 61.7% | 16.47 |+| 128 GB | 7,294 | 49.2% | 84.6% | 13.12 |+| **192 GB** | 10,941 | **90.0%** | 90.0% | **2.58** |+| 1450 GB | 82,633 | 90.0% | 90.0% | 2.58 |++**LRU is flat from 8 GB to 64 GB**, an 8× increase in capacity buying nothing, then+saturates at 192 GB, which is where the working set finally fits. Belady's optimal+policy climbs steadily over the same range, so the flatness is LRU's, not the workload's:+there is exploitable locality, and LRU cannot reach it.++Two things to hold onto:++- **This x-axis is cache size; the ladder's is total budget.** The ladder's 8 GB row has+ only 0.49 GB of cache (28 slots), which is why it shows 0.0% retention and this table+ shows 36.2% at 455 slots. They do not disagree.+- **These are upper bounds, not forecasts.** The trace was recorded during full-recompute+ decode, which re-touches the same experts ~68 times. Steady-state incremental decode+ has far less reuse and will do worse. The file says so itself.++The practical reading: below ~192 GB of *cache alone*, capacity is not the lever. That is+the same conclusion the fixed-budget sweep below reaches from the opposite direction.++## Allocation beats capacity++At a **fixed** total budget, varying only the split. All twelve rows, from+[data/trunk-cache-split.tsv](data/trunk-cache-split.tsv):++| total | trunk | cache | s/token | | total | trunk | cache | s/token |+|---:|---:|---:|---:|---|---:|---:|---:|---:|+| 128 | 12.3 | 110.7 | 28.38 | | 32 | 2.7 | 24.3 | 31.23 |+| 128 | 30.8 | 92.2 | 25.20 | | 32 | 6.8 | 20.2 | 30.58 |+| 128 | 49.2 | 73.8 | 25.69 | | 32 | 10.8 | 16.2 | 31.25 |+| 128 | 73.8 | 49.2 | 18.37 | | 32 | 16.2 | 10.8 | 30.88 |+| 128 | 98.4 | 24.6 | 19.46 | | 32 | 21.6 | 5.4 | 29.13 |+| 128 | **110.0** | **13.0** | **16.80** | | 32 | **25.6** | **1.4** | **28.06** |++**1.69× faster at identical total memory** (28.38 → 16.80 at 128 GB). Note that the+*fastest* configuration has 0.0% expert-cache retention.++**How far this goes.** Each row is a single sample against a 33% noise floor, so the+endpoint comparison alone would not settle it, and the trend is **not** strictly+monotonic. There are two inversions at 128 GB (+1.9% at 30.8→49.2, +5.9% at 73.8→98.4)+and one at 32 GB (+2.2%). Every one of them is far inside the noise floor, so none is+evidence against the trend; equally, no individual step is evidence for it.++What carries the conclusion is the rank correlation over twelve points across **two+independent budgets**: Spearman ρ = −0.886 at 128 GB and −0.714 at 32 GB. Two separately+run sweeps, at a 4× difference in total memory, both order the splits the same way.++The magnitude is a different matter. 1.69× is one endpoint comparison of single samples+and is **not** replicated to the three-run standard this project asks for elsewhere (see+CONTRIBUTING.md). Treat the direction as established and the factor as approximate;+`benchmarks/split-sweep.sh` re-runs it with repetitions.++128 GB allocated well (16.80 s/token) beats 224 GB allocated badly (19.21). If you take+one tuning decision from this document, take that one. It is also the one the mechanism+predicts independently of any measurement: the trunk is re-read in full every token and+the experts are not.++## The noise floor++Three runs of an identical configuration, back to back, on a quiet machine.+Raw: [data/replication.tsv](data/replication.tsv).++| run | s/token |+|---:|---:|+| 1 | 14.78 |+| 2 | 14.67 |+| 3 | 20.14 |++mean **16.53**, sd **3.13**, spread **33.1%**.++Same binary, same prompt, same flags, same minute. A third of the measurement is noise.++**What this means for every table above.** Each row is a *single sample*. Any difference+under ~33% is not an established effect. Concretely:++- The 128 GB row (29.40) sitting above its neighbours (24.40, 26.31) is **inside the+ band**. It is dispersion, not an anomaly, and it needs no explanation.+- Individual step-to-step differences in the middle of the ladder are not resolvable.++**What survives**, being larger than the floor:++- the ladder's overall span, 8 GB → 224 GB, a **70%** change;+- trunk-first at 128 GB, a **69%** change.++**What is untouched by noise entirely**, these are counts and byte totals, not stopwatch+readings, and no amount of scheduling jitter moves them:++- byte-identical output at all twelve budgets;+- `GB read/token` pinned at exactly 25.83 across seven of them;+- expert retention of 0.0% from 28 to 1,344 slots;+- trunk hit ≈ pinned/93.++So the *mechanism* rests on counts and stands. What is soft is the precise second-count+attached to any one configuration.++Likely contributors to the variance, none isolated: virtualised NVMe latency on a+workload that moves ~135 GB per token; page-cache interaction at 128 GB RSS on a 228 GiB+box; NUMA effects across two sockets; and cold-start amortisation, every ladder run is+only 8 tokens, and token 0 pays the full pinning cost. The last is supported by the+end-to-end generations at 16 to 32 tokens, which spread only 10% (10.66 to 11.79 s/token)+against this run's 33%.++## Longer runs are faster++Because cold start is amortised:++| tokens | s/token |+|---:|---:|+| 8 (ladder, best) | 19.21 |+| 16 to 32 (sustained generations) | **10.66 to 11.79** |++The ladder understates sustained throughput. Quote it as a *comparison across budgets*,+not as the engine's speed.++## Reproducing++```bash+make -j+./scripts/k3-doctor.sh ~/k3model # what this machine should manage+./benchmarks/memory-ladder.sh ~/k3model ~/k3trunk out/ # the full sweep+```++See [BENCHMARKING.md](BENCHMARKING.md), in particular, **replicate before you+conclude**. Replication is not a formality here: on a 33% noise floor, a single-sample+difference of 20% is indistinguishable from dispersion, and treating one as a finding is+the easiest mistake to make with this engine.++The raw output of the run these tables come from is in [data/](data/), so a new run can+be compared against it directly rather than against the numbers as transcribed.diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.mdnew file mode 100644index 0000000..0d16126--- /dev/null+++ b/docs/QUICKSTART.md@@ -0,0 +1,88 @@+# Quickstart++From nothing to generated text.++## 1. Check the machine++```bash+./scripts/k3-doctor.sh+```++Reports whether this machine can run the model, which preset fits its memory, and how+fast its storage is. Storage matters more than you would expect, the engine moves+~135 GB per token at small budgets.++## 2. Build++```bash+make -j+```++No dependencies beyond a C compiler and OpenMP. If `-march=native` is a problem (you are+building for a different machine), use `make portable`.++## 3. Verify++```bash+make test+```++Seconds, and **no model weights required**. Op kernels, the streaming cache, the+safetensors reader, the config reader, the tokenizer, and the end-to-end oracle gates.++## 4. Get the weights++```bash+export HF_TOKEN=... # a HuggingFace token with access to the model+./scripts/download-model.sh ~/k3model+```++1.56 TB across 96 shards; roughly 30 minutes at 1 GB/s. The script verifies the byte+total against the published figure afterwards, because a partial download does not fail+loudly, it produces wrong tokens.++## 5. Pack the trunk++```bash+./scripts/pack-trunk.sh ~/k3model ~/k3trunk+```++A few minutes. This is what allows the trunk to stream, and therefore what makes the+memory budget adjustable rather than fixed at ~115 GB.++## 6. Run++```bash+./bin/k3 ~/k3model \+ --trunk ~/k3trunk --preset server \+ --tok ~/k3model \+ --prompt "The capital of France is" --gen 16 --incremental+```++```+--- generated text ---+ Paris.+----------------------+```++## Where to go next++- [TUNING.md](TUNING.md), pick a budget and a split; one decision dominates+- [PERFORMANCE.md](PERFORMANCE.md), the full memory ladder and its noise floor+- `examples/`, runnable scripts, including one that proves output is identical across+ memory budgets++## Troubleshooting++**"REFUSING: the KV cache for N positions needs X"**, the context you asked for does not+fit. Shorten it, or drop `--incremental` (full recompute carries no KV cache, but is+O(T²) in time).++**Very slow with a long prompt**, expected. Prefill is not chunked and MLA attention is+quadratic in sequence length. See [ROADMAP.md](ROADMAP.md).++**"config could not be read with confidence"**, the reader found a config it does not+fully understand and refused rather than guessing. The message lists every missing field.++**Output is a continuation, not an answer**, correct. There is no chat template; the+model completes your prompt.diff --git a/docs/README.md b/docs/README.mdnew file mode 100644index 0000000..1c3a6b4--- /dev/null+++ b/docs/README.md@@ -0,0 +1,55 @@+# Documentation++## Start here++| | |+|---|---|+| [QUICKSTART.md](QUICKSTART.md) | from nothing to generated text |+| [TUNING.md](TUNING.md) | choosing a memory budget, one decision dominates |++## Reference++| | |+|---|---|+| [ARCHITECTURE.md](ARCHITECTURE.md) | how the model maps onto the code |+| [API.md](API.md) | the C interface, for embedding the engine |+| [PERFORMANCE.md](PERFORMANCE.md) | the memory ladder, measured, with its noise floor |+| [TESTING.md](TESTING.md) | what each gate proves |+| [BENCHMARKING.md](BENCHMARKING.md) | how to measure without fooling yourself |+| [ROADMAP.md](ROADMAP.md) | what is missing, in priority order |+| [data/](data/) | the raw measurement output every table is transcribed from |++## Upstream material++| | |+|---|---|+| [kimi-k3-tech-report.pdf](kimi-k3-tech-report.pdf) | the model's technical report, as published |++Reproduced for reference; it remains the property of its authors. Every architectural+claim in [ARCHITECTURE.md](ARCHITECTURE.md) cites the section of this report it comes+from, so the two can be checked against each other.++## The three claims worth checking first++If you are evaluating whether this project is worth your time, these are the load-bearing+claims and where each is substantiated:++1. **A 2.78T-parameter model runs in 8 GB of RAM.**+ [PERFORMANCE.md](PERFORMANCE.md), twelve budgets, measured peak RSS at each.+ Raw: [data/memory-ladder.tsv](data/memory-ladder.tsv).++2. **Output is byte-identical across memory budgets.** Memory buys speed, not+ capability. [PERFORMANCE.md](PERFORMANCE.md), and `examples/02-memory-budgets.sh`+ reproduces it in three runs. The `ids` column of+ [data/memory-ladder.tsv](data/memory-ladder.tsv) is the claim in raw form: twelve+ rows, one identical token sequence.++3. **The engine matches a reference implementation exactly.** Teacher forcing, greedy+ decode, and incremental decode, on a model with the released tensor graph.+ [TESTING.md](TESTING.md); `make test` runs it in seconds with no weights.++Claims about *speed* carry a caveat that [PERFORMANCE.md](PERFORMANCE.md) states up+front: run-to-run variance on identical configurations is 33%+([data/replication.tsv](data/replication.tsv)), so single-sample differences below that+are not effects. Claims about *output* carry no such caveat, those are exact, and they+are counts rather than stopwatch readings.diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdnew file mode 100644index 0000000..0c83103--- /dev/null+++ b/docs/ROADMAP.md@@ -0,0 +1,64 @@+# Roadmap++Ordered by value, with the reasoning stated so the order can be argued with.++## 1. Chunked prefill, the highest-value missing piece++Prefill currently runs as a single forward pass over the whole prompt, and attention in+the 24 MLA layers is quadratic in sequence length. The practical effect: the context+ceiling is 32k tokens, but a 21k-token prompt does not complete in reasonable time.++Raising the ceiling was necessary and is done. This is the part that makes it usable.++## 2. Re-run the published campaign under the replicating harness++The measured noise floor is 33%, and almost every published figure is a single sample.+The harness itself is done, `benchmarks/memory-ladder.sh` and `benchmarks/split-sweep.sh`+already default to 3 repeats and report mean, sd and spread. What remains is re-running+the 12 ladder rungs and the 12 splits under it and replacing the single-sample tables in+docs/data/ with replicated ones.++## 3. Thread scaling++`OMP_NUM_THREADS` has never been swept on this engine. The workload is I/O bound at low+memory budgets, so the useful thread count is probably well below the core count, and+on memory-bound workloads throughput often *declines* past a point. Unknown here.++## 4. SIMD in the KDA recurrence++The bf16 trunk matmul and the MXFP4 expert matmul already have hand-written AVX2 paths+(`src/core/k3_ops.c`), each written to reproduce the scalar reduction order exactly. The+KDA recurrence does not: it is still plain scalar C, and it is the largest remaining+un-vectorised kernel on the non-I/O path.++## 5. Sampling++Greedy only today. Adding temperature and top-p is small, but note the trade-off: greedy+decoding is what makes output identical across memory budgets, which is a property the+test-suite depends on. Sampling must be opt-in and off by default.++## 6. Chat template++K3 ships an XTML chat format. Without it the engine produces base-model continuations,+which is why asking a question gets the question completed rather than answered.++## 7. Vision++K3 is natively multimodal. The vision tower is 27 layers and ~0.4B parameters, small,+and its weights are ~0.9 GB, a fraction of a percent of the checkpoint. Self-contained+enough to be tractable.++## 8. Serving++No HTTP API. Deliberately last: it is product surface, and everything above changes what+would be served.++## Explicitly not planned++**A precision dial for the trunk.** The trunk is streamed losslessly rather than+quantised, and that is a design decision, not an omission. Post-hoc int4 measures ~17%+mean relative weight error on K3 attention tensors against ~1% for int8; streaming+costs time, which more memory buys back, while rounding costs accuracy, which nothing+buys back.++**GPU support.** Out of scope for this project.diff --git a/docs/TESTING.md b/docs/TESTING.mdnew file mode 100644index 0000000..217a46f--- /dev/null+++ b/docs/TESTING.md@@ -0,0 +1,57 @@+# Testing++Every test in `make test` runs **without model weights**. The checkpoint is 1.56 TB; if+correctness depended on having it, correctness would not get checked.++```bash+make test # everything below, seconds+make test-all SHARD_DIR=~/k3model # adds the checkpoint-dependent tests+```++## What each gate proves++**`test_ops`**, every kernel against reference values, at a tolerance declared in the+fixture manifest rather than hardcoded. Several fixtures are adversarial by construction:+the router fixture reorders its top-2 on 5 of 6 rows, so an implementation that ignores+the routing bias fails; the SiTU-GLU fixture drives the activation to its exact+analytic cap.++**`test_cache`**, the streaming expert cache: prefetch, eviction, and mixed batch/serial+access. Uses a synthetic shard of structurally faithful experts, a few KB.++**`test_st`**, the safetensors reader: dtype widening, offsets, tail bytes, escaped+tensor names, and a tensor deliberately containing non-finite values.++**`test_cfg`**, the config reader against both supported layouts, plus three malformed+configs it must **refuse**. This matters more than it looks: a config reader that+substitutes defaults for missing fields produces a model that loads, runs, and is+architecturally wrong, with nothing to indicate it.++**`test_tok`**, byte-exact roundtrip (encode then decode recovers the input exactly).+With `tools/tok_parity.py` it also compares token-for-token against the reference+tokenizer across CJK, emoji, ZWJ sequences, accents, contractions and whitespace runs.++**`k3_model`**, the end-to-end gate, on a tiny model whose tensor graph matches the released+architecture exactly:++- teacher forcing: every position matches the reference+- greedy decode: every generated token matches+- incremental decode: same tokens as full recompute, with KV cache and carried+ recurrent state++All three must be *exact*. There is no tolerance on token identity.++## Checkpoint-dependent tests++Need `SHARD_DIR`:++- **`test_expert`**, reads an expert from released shards and compares against+ independently fetched bytes.+- **`test_real_layer`**, runs one released layer at full width against the reference.+- **`tools/conform_all.py`**, all 93 layers individually against the reference.++## Adding a test++Fixtures are generated by `tools/emit_fixtures.py` and carry their own tolerance in a+manifest. A test that cannot fail is not a test, make the fixture adversarial: if a+plausible wrong implementation would pass, change the input until it would not.diff --git a/docs/TUNING.md b/docs/TUNING.mdnew file mode 100644index 0000000..1c7bcde--- /dev/null+++ b/docs/TUNING.md@@ -0,0 +1,119 @@+# Tuning++## The short version++1. Run `./scripts/k3-doctor.sh` and use the preset it names.+2. If you tune by hand: **fill the trunk before you feed the expert cache.**+3. Use `--incremental` unless you are validating against full recompute.++Everything below is why.++## One decision matters more than the rest++The engine splits your memory budget between two caches:++- `--trunk-gb`, the ring buffer and pinned layers for the **dense trunk**+- `--cache-gb`, the arena for **routed experts**++These are not interchangeable, and the asymmetry is large.++Per token the engine re-reads the **entire 108.81 GB trunk**, all 93 layers, in a fixed+order, every single token. It reads only **~25.8 GB of routed experts**, because just 16+of 896 are selected per layer.++So a gigabyte given to the trunk removes about **1.17 GB/token of guaranteed traffic**+(one pinned layer, never read again). A gigabyte given to the expert cache removes,+below roughly 36 GB of arena, **nothing measurable**.++Measured at a fixed 128 GB budget, endpoints of a six-point sweep:++| trunk | cache | s/token |+|---:|---:|---:|+| 12.3 | 110.7 | 28.38 |+| **110.0** | **13.0** | **16.80** |++**1.69× from allocation alone.** The faster configuration has a *smaller* expert cache+and 0.0% expert retention.++These are single samples against a 33% noise floor, so read the *direction*, not the+exact factor. The direction is supported by twelve points across two independent budgets+(Spearman ρ = −0.886 at 128 GB, −0.714 at 32 GB) and by the mechanism above; the+magnitude is not replicated. All twelve rows and the caveats are in+[PERFORMANCE.md](PERFORMANCE.md#allocation-beats-capacity), raw data in+[data/trunk-cache-split.tsv](data/trunk-cache-split.tsv), and+`benchmarks/split-sweep.sh` re-runs the experiment with repetitions.++## Why the expert cache is so weak++This is the model's design, not a shortcoming of the implementation.++K3's router is trained with **Quantile Balancing**, which deliberately flattens expert+usage so that no expert is favoured. Flat usage is precisely what defeats a+least-recently-used cache: with no hot subset, a few gigabytes retain nothing worth+keeping. Measurements bear this out, retention stays at exactly 0.0% from 28 slots all+the way to 1,344, and the bytes read per token do not move by a single decimal.++It does eventually engage. Somewhere around 36 GB of arena, retention jumps to ~30% and+bytes/token fall from 25.83 to 18.11. But by then you could have pinned most of the trunk+for the same memory and gone faster.++## Presets++```console+$ ./bin/k3 --list-presets+```++| preset | trunk | cache | total | expect |+|---|---:|---:|---:|---|+| `laptop` | 3 | 1 | ~10 GB | ~32 s/token |+| `desktop` | 16 | 10 | ~32 GB | ~31 s/token |+| `workstation` | 60 | 30 | ~96 GB | ~24 s/token |+| `server` | 110 | 13 | ~128 GB | ~17 s/token |+| `max` | 110 | 109 | ~224 GB | ~19 s/token |++`server` is the best value: the trunk is fully pinned at 110 GB and everything beyond+that is spent on a cache that contributes little. Note `max` is not faster than `server`+in these measurements, the extra 96 GB buys nothing outside the noise floor.++Flags after `--preset` override it, so `--preset server --cache-gb 40` works.++## Other options++**`--incremental`** carries a KV cache and the recurrent state between tokens instead of+recomputing the prefix. Verified to produce identical tokens to full recompute. Use it+unless you are specifically testing that equivalence.++Note it allocates ~2.37 MB of KV cache **per position**, so long contexts cost+memory: 16k positions is ~39 GB. The engine computes the requirement up front and refuses+with both numbers rather than being OOM-killed an hour in.++**`--trunk DIR`** enables trunk streaming and is what makes memory a dial. Without it the+trunk is fully resident and the floor is ~115 GB. Pack it once with+`tools/pack_trunk.py`.++**`--layers N`** binds only the first N layers. Useful for testing the machinery on a+partial download; the output is not the full model and the engine says so.++## Storage matters more than you expect++The engine moves ~135 GB per token at low budgets. Storage bandwidth is usually the+ceiling, not the CPU.++- Put the checkpoint and the packed trunk on the **fastest local NVMe** available.+- Network or spinning storage will dominate everything else. A 6× difference in device+ bandwidth is a 6× difference in throughput on this workload, which is larger than any+ tuning decision in this document.+- `./scripts/k3-doctor.sh` measures your device so you know which regime you are in.++## Threads++`OMP_NUM_THREADS` defaults to your core count. The workload is I/O bound at low memory+budgets, so more threads help less than you would expect once the trunk is streaming.++This has not been swept systematically on this engine see [ROADMAP.md](ROADMAP.md).++## Before you conclude a change helped++The measured run-to-run spread on an identical configuration is **33%**. Differences+smaller than that are not effects. Run each arm at least three times.+[BENCHMARKING.md](BENCHMARKING.md) has the procedure.diff --git a/docs/kimi-k3-tech-report.pdf b/docs/kimi-k3-tech-report.pdfnew file mode 100644index 0000000..5eedb10Binary files /dev/null and b/docs/kimi-k3-tech-report.pdf differ