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 diagrams and their sources
FareedKhan-devea53cbb5e4a9
diff --git a/docs/images/_eq.py b/docs/images/_eq.pynew file mode 100644index 0000000..f1651ea--- /dev/null+++ b/docs/images/_eq.py@@ -0,0 +1,227 @@+"""Render the blog's equations to white-background PNGs via matplotlib mathtext.++Each image is one equation (large) plus a short plain caption underneath. No LaTeX+install needed, mathtext covers everything here.+"""++import matplotlib+matplotlib.use("Agg")+import matplotlib.pyplot as plt+from pathlib import Path++OUT = Path(__file__).resolve().parent+++def render(name: str, formula: str, caption: str) -> None:+ fig = plt.figure(figsize=(8.4, 2.0), dpi=200)+ fig.patch.set_facecolor("white")+ fig.text(0.5, 0.60, formula, fontsize=24, ha="center", va="center", color="#1f2937")+ fig.text(0.5, 0.16, caption, fontsize=11.5, ha="center", va="center", color="#6b7280")+ path = OUT / f"{name}.png"+ fig.savefig(path, facecolor="white", bbox_inches="tight", pad_inches=0.25)+ plt.close(fig)+ print(f" rendered {path.name}")+++EQUATIONS = {+ # ---- the fit ledger+ "eq_naive_memory": (+ r"$\mathrm{bytes} = P \cdot b = 2.78\times10^{12} \cdot 2 = 5.56\ \mathrm{TB}$",+ "The naive requirement: every parameter resident at bf16",+ ),+ "eq_fit_ledger": (+ r"$5560\ \mathrm{GB} \to 1560 \to 113.49 \to 8.24\ \mathrm{GB}$",+ "Four reductions: MXFP4 experts, routing, then streaming the trunk",+ ),+ "eq_sparsity_ratio": (+ r"$\frac{\mathrm{active}}{\mathrm{total}} = \frac{104\times10^{9}}{2.78\times10^{12}} \approx 3.7\%$",+ "Only 16 of 896 experts fire per layer, so most of the model sleeps",+ ),+ "eq_resident_set": (+ r"$\mathrm{resident} = \mathrm{trunk} + \mathrm{embed} + \mathrm{lm\_head} = 56{,}743{,}648{,}000\ \mathrm{params}$",+ "The always-active set: 113.49 GB at bf16, everything else is streamable",+ ),+ # ---- formats and files+ "eq_st_layout": (+ r"$\mathrm{file} = [\,8\ \mathrm{B\ length}\,][\,\mathrm{JSON\ header}\,][\,\mathrm{tensor\ data}\,]$",+ "safetensors: one length, one header, then raw bytes at known offsets",+ ),+ "eq_layer_map": (+ r"$\mathrm{MLA} = \{4, 8, 12, \ldots, 92\} \cup \{93\}, \quad |\mathrm{MLA}| = 24$",+ "One-based layer indices, and 92 and 93 are both MLA by design",+ ),+ "eq_mxfp4": (+ r"$w_i = \mathrm{E2M1}[n_i] \cdot 2^{\,s_g - 127}, \quad g = \lfloor i/32 \rfloor$",+ "MXFP4: a 4-bit nibble scaled by one 8-bit exponent per 32 weights",+ ),+ "eq_bytes_per_weight": (+ r"$\frac{1}{2} + \frac{1}{32} = 0.53125\ \frac{\mathrm{bytes}}{\mathrm{weight}} \;\Rightarrow\; 17{,}547{,}264\ \mathrm{B}$",+ "Half a byte per weight plus the shared scale gives one expert exactly",+ ),+ "eq_nibble_pack": (+ r"$\mathrm{byte} = n_{\mathrm{even}} + 16\, n_{\mathrm{odd}}, \quad n \in [0,\,15]$",+ "The low nibble is the EVEN element, and reversing it is silently wrong",+ ),+ "eq_dequant_cost": (+ r"$132\ \mathrm{MB} \times 1472\ \mathrm{experts} = 194\ \frac{\mathrm{GB}}{\mathrm{token}}$",+ "What dequantizing would cost, which is why we multiply from the nibbles",+ ),+ # ---- kernels+ "eq_rmsnorm": (+ r"$y_i = \frac{x_i}{\sqrt{\frac{1}{n}\sum_j x_j^{2} + \varepsilon}} \cdot g_i$",+ "RMSNorm with epsilon inside the square root, accumulated in double",+ ),+ "eq_bf16_widen": (+ r"$\mathrm{f32}(w) = \mathrm{u32}(w) \ll 16$",+ "bf16 to fp32 is a shift, not a conversion, so widening is lossless",+ ),+ "eq_accum_order": (+ r"$s = (s_0 + s_1) + (s_2 + s_3), \quad s_k = \sum_{i \equiv k\ (4)} x_i w_i$",+ "A fixed reduction order, so scalar and AVX2 agree bit for bit",+ ),+ # ---- KDA+ "eq_shortconv": (+ r"$y_t = \mathrm{SiLU}\!\left(\sum_{j=0}^{3} c_j\, x_{t-j}\right)$",+ "A depthwise causal convolution of width 4 with the activation fused in",+ ),+ "eq_l2norm": (+ r"$\hat{q} = \frac{q}{\sqrt{\sum_i q_i^{2} + \varepsilon}}$",+ "A sum of squares, not a mean, and applied to q and k only",+ ),+ "eq_kda_decay": (+ r"$g_h = g_{\min} \cdot \sigma\!\left(e^{A_h} z\right), \quad g_{\min} = -5$",+ "The decay gate, with A indexed per head and not per channel",+ ),+ "eq_kda_recurrence": (+ r"$S_t = \mathrm{diag}(g)\,S_{t-1} + \beta\,(v_t - S_{t-1}k_t)\,k_t^{\top}$",+ "The delta rule: decay, read, write the difference, then read again",+ ),+ "eq_kda_gate": (+ r"$o = \mathrm{RMSNorm}(o) \odot \sigma(W_g x), \quad y = W_o\, o$",+ "Norm first, then gate, then project, and that order is not interchangeable",+ ),+ "eq_prefetch": (+ r"$t_{\mathrm{layer}} = \max\left(t_{\mathrm{read}}(L{+}1),\ t_{\mathrm{compute}}(L)\right)$",+ "A fixed walk order means the next read can start before this layer finishes",+ ),+ "eq_kda_state": (+ r"$|S| = H D^{2} = 96 \cdot 128^{2} \;\Rightarrow\; 626.25\ \mathrm{MB\ total}$",+ "The recurrent state is the same size at 10 tokens and at 100,000",+ ),+ # ---- MLA+ "eq_mla_latent": (+ r"$c_t = W_{kv}\,x_t \in \mathbb{R}^{576}, \quad k_t, v_t = W_{up}\,c_t$",+ "One latent per position is cached, and k and v are rebuilt on use",+ ),+ "eq_mla_kv": (+ r"$\mathrm{KV} = 2.37\ \frac{\mathrm{MB}}{\mathrm{position}} \;\Rightarrow\; 19.4\ \mathrm{GB\ at\ 8k}$",+ "Twenty-four MLA layers, expanded k and v in fp32, per position",+ ),+ "eq_kv_compression": (+ r"$\frac{H(d_{qk}+d_v)}{d_{kv}+d_{rope}} = \frac{96 \cdot 320}{576} \approx 53\times$",+ "The released code caches expanded heads, the latent is 53x smaller",+ ),+ # ---- residuals and MoE+ "eq_attn_res": (+ r"$h = \sum_{b} \mathrm{softmax}_b\!\left(\hat{s}_b \cdot f\right) s_b$",+ "Each layer attends over the outputs of every preceding block",+ ),+ "eq_block_count": (+ r"$n_{\mathrm{blocks}} = \left\lfloor \frac{93}{12} \right\rfloor + 2 = 9$",+ "Blocks of twelve, so the residual stack never exceeds nine sources",+ ),+ "eq_router": (+ r"$\mathrm{select} = \mathrm{top}_{16}\left(\sigma(\ell_e) + b_e\right), \quad w_e = \sigma(\ell_e)$",+ "The bias steers selection only, the weights come from unbiased scores",+ ),+ "eq_situ_glu": (+ r"$y = \beta_1 \tanh\!\left(\frac{u}{\beta_1}\right) \cdot \beta_2 \tanh\!\left(\frac{v}{\beta_2}\right), \ |y| \leq 100$",+ "SiTU-GLU with beta1 = 4 and beta2 = 25, so the product is bounded",+ ),+ "eq_moe_latent": (+ r"$7168 \longrightarrow 3584 \longrightarrow 16\ \mathrm{experts} \longrightarrow \mathrm{norm} \longrightarrow 7168$",+ "Experts run in a narrow latent, and the norm is on the aggregate",+ ),+ # ---- streaming and cache+ "eq_align": (+ r"$\mathrm{offset} \equiv 0, \quad \mathrm{length} \equiv 0 \quad (\mathrm{mod}\ 4096)$",+ "O_DIRECT needs both ends aligned, which costs 4 KB per layer",+ ),+ "eq_ram_budget": (+ r"$\mathrm{need} = \mathrm{trunk} + \mathrm{model} + \mathrm{cache} + \mathrm{state} + \mathrm{buf} + \mathrm{KV}$",+ "Everything is summed before anything is allocated, then compared to free RAM",+ ),+ "eq_slot_count": (+ r"$n_{\mathrm{slot}} = \left\lfloor \frac{\mathrm{budget}}{17.56\ \mathrm{MB}} \right\rfloor$",+ "The expert cache holds whole experts, so the budget divides exactly",+ ),+ "eq_queue_depth": (+ r"$\mathrm{QD} = 16 \ \mathrm{vs} \ \mathrm{QD} = 1$",+ "Batched preads keep the device busy, serial gets leave it idle",+ ),+ "eq_compulsory": (+ r"$\mathrm{hit}_{\max} = 1 - \frac{10{,}010}{100{,}096} = 90.0\%$",+ "Every distinct expert must be read once, so no policy can beat this",+ ),+ "eq_working_set": (+ r"$10{,}010 \times 17.55\ \mathrm{MB} = 175.65\ \mathrm{GB}$",+ "The experts this trace touched at all, against a 1.45 TB pool",+ ),+ # ---- validation+ "eq_tolerance": (+ r"$\mathrm{budget} = 1.2\times10^{-7}\sqrt{d}\cdot 50 = 5.1\times10^{-4}$",+ "The rounding budget for 93 layers at hidden size 7168",+ ),+ # ---- performance+ "eq_traffic": (+ r"$\mathrm{bytes/token} = 108.81 + 25.83 = 134.64\ \mathrm{GB}$",+ "The trunk is re-read in full every token, the experts are only sampled",+ ),+ "eq_prefill": (+ r"$t_0 \propto n_{\mathrm{prompt}}, \qquad t_{n>0} \approx \mathrm{const}$",+ "Step zero pays for the whole prompt, every later step reads 25.83 GB",+ ),+ "eq_trunk_hit": (+ r"$\frac{(T-1)\,p}{T \cdot 93} = \frac{7 \cdot 90}{744} = 84.7\%$",+ "Token zero pays the pinning cost, so short runs understate the hit rate",+ ),+ "eq_retention": (+ r"$\mathrm{retained} = 1 - \frac{\mathrm{evictions}}{\mathrm{requests}}$",+ "The only expert-cache metric that agrees with the bytes actually read",+ ),+ "eq_gb_per_layer": (+ r"$\frac{108.81\ \mathrm{GB}}{93\ \mathrm{layers}} \approx 1.17\ \frac{\mathrm{GB}}{\mathrm{token}}$",+ "What one pinned layer removes from the guaranteed traffic",+ ),+ "eq_io_share": (+ r"$\mathrm{io} = \frac{t_{\mathrm{trunk}} + t_{\mathrm{expert}}}{t_{\mathrm{wall}}} \in [40.9\%,\ 60.6\%]$",+ "Both terms are whole-run totals, and this is an I/O problem at every budget",+ ),+ "eq_spread": (+ r"$\frac{\max - \min}{\mathrm{mean}} = \frac{20.14 - 14.67}{16.53} = 33.1\%$",+ "Three identical runs, so a smaller difference is not an effect",+ ),+ # ---- precision+ "eq_absmax": (+ r"$s = \frac{\max_i |w_i|}{2^{\,b-1}-1}, \quad \hat{w}_i = s \cdot \mathrm{round}\!\left(\frac{w_i}{s}\right)$",+ "Symmetric per-row quantization, the method behind the int8 and int4 study",+ ),+ "eq_stream_vs_quantize": (+ r"$\mathrm{streaming} \Rightarrow \Delta t \ \mathrm{recoverable}, \quad \mathrm{rounding} \Rightarrow \Delta w \ \mathrm{permanent}$",+ "Seconds are bought back with RAM, and rounding error is not, at any budget",+ ),+ "eq_context_ceiling": (+ r"$10^{6}\ \mathrm{positions} \times 2.37\ \mathrm{MB} \approx 2485\ \mathrm{GB}$",+ "The advertised million-token context is a memory fact, not an engine limit",+ ),+}++ok = fail = 0+for name, (formula, caption) in EQUATIONS.items():+ try:+ render(name, formula, caption)+ ok += 1+ except Exception as e:+ fail += 1+ print(f" FAILED {name}: {type(e).__name__}: {e}")+print(f"done: {ok} rendered, {fail} failed")diff --git a/docs/images/_gen.py b/docs/images/_gen.pynew file mode 100644index 0000000..7bbe132--- /dev/null+++ b/docs/images/_gen.py@@ -0,0 +1,362 @@+"""Generate all subsection Mermaid (.mmd) sources for the Kimi K3-in-C blog.++Locked style (via mmdc.json): hand-drawn look on warm paper, soft colored fills ++medium warm borders on leaf boxes, dark warm ink for text. Each diagram is simple+(3-8 nodes) so it never overlaps and renders wide + short.+"""++import os++# Soft hand-drawn palette on warm paper: light fills, medium warm-leaning strokes,+# cohesive across all diagrams. The cold-to-hot spine reads blue -> amber -> coral.+INK = "#3B372F" # warm fine-liner ink for text+COLORS = {+ "blue": ("#E4ECF3", "#5C7C9B"), # cold (disk, inputs)+ "amber": ("#F2E9D4", "#C0913E"), # warm (mid tier)+ "pink": ("#F3E3EB", "#B06885"), # soft rose+ "green": ("#E7ECDD", "#6E9160"), # sage (result, correct)+ "purple": ("#EAE4F1", "#7E6E9C"), # muted violet (decisions)+ "red": ("#F5E2DB", "#B75845"), # hot (misses, the wall)+ "teal": ("#DDEBE7", "#4E8E86"), # soft teal+ "orange": ("#F4E7D3", "#C07A42"), # sand (warm-mid)+ "gray": ("#ECE8E0", "#8C8477"), # warm neutral (plain nodes)+}++DIAGRAMS = {}+++def add(name, code, fills, containers=()):+ DIAGRAMS[name] = (code.strip(), fills, list(containers))+++def render_style(fills, containers):+ lines = []+ for cid in containers:+ lines.append(f" style {cid} fill:#F4EFE6,stroke:#C9C1B2,color:{INK}")+ for nid, ck in fills.items():+ f, s = COLORS[ck]+ lines.append(f" style {nid} fill:{f},stroke:{s},color:{INK}")+ return "\n".join(lines)+++# ---------------------------------------------------------------- the big picture++add("big-picture", """+flowchart LR+ D["NVMe<br/>1.45 TB experts"] --> T["trunk.bin<br/>108.81 GB packed"]+ T --> PIN["pinned layers<br/>in RAM"]+ D --> C["expert cache<br/>17.56 MB slots"]+ PIN --> TOK["next token<br/>8.24 GB peak RSS"]+ C --> TOK+""", {"D": "gray", "T": "blue", "PIN": "purple", "C": "amber", "TOK": "green"})++add("moe-sparsity", """+flowchart LR+ X["one token"] --> R["router<br/>896 scores"]+ R --> TOP["top 16"]+ TOP --> RUN["16 experts run<br/>17.55 MB each"]+ R -.->|"880 stay asleep"| SLEEP["never read<br/>never resident"]+ RUN --> Y["layer output"]+""", {"X": "blue", "R": "purple", "TOP": "amber", "RUN": "green", "SLEEP": "gray", "Y": "teal"})++add("machine-model", """+flowchart LR+ L["laptop<br/>8 GB"] --> D2["desktop<br/>32 GB"]+ D2 --> W["workstation<br/>96 GB"]+ W --> S["our box<br/>228 GB"]+ L -.->|"same 8 tokens"| OUT["identical ids<br/>17374 20829 10 427"]+ S -.-> OUT+""", {"L": "red", "D2": "orange", "W": "amber", "S": "blue", "OUT": "green"})++# ---------------------------------------------------------------- build and load++add("build-flow", """+flowchart LR+ SRC["6 C files<br/>+ 2 headers"] --> CC["cc -O3 -fopenmp<br/>-ffp-contract=off"]+ CC --> BIN["bin/k3<br/>179,736 bytes"]+ CC --> T["7 test binaries"]+ T --> G["22 passed<br/>0 failed"]+ BIN --> RUN["runs a 1.56 TB model"]+""", {"SRC": "gray", "CC": "blue", "BIN": "green", "T": "amber", "G": "teal", "RUN": "purple"})++add("st-load", """+flowchart LR+ S["96 shards<br/>1.56 TB"] --> H["read 8-byte length<br/>then JSON header"]+ H --> IDX["FNV-1a index<br/>497,220 tensors"]+ IDX --> Q{"need this<br/>tensor?"}+ Q -->|"yes"| P["pread exact bytes<br/>O_DIRECT"]+ Q -->|"no"| SKIP["never touched"]+""", {"S": "gray", "H": "blue", "IDX": "amber", "Q": "purple", "P": "green", "SKIP": "teal"})++add("config-guard", """+flowchart LR+ J["config.json"] --> R["k3_cfg_load"]+ R --> Q{"every field<br/>present?"}+ Q -->|"yes"| OK["93 layers<br/>24 MLA + 69 KDA"]+ Q -->|"no"| STOP["refuse to start<br/>name the field"]+ STOP -.->|"the old reader<br/>guessed here"| WRONG["all 93 layers KDA<br/>fluent and wrong"]+""", {"J": "gray", "R": "blue", "Q": "purple", "OK": "green", "STOP": "amber", "WRONG": "red"})++add("tok-flow", """+flowchart LR+ F["prompt from a FILE<br/>never argv"] --> B["raw UTF-8 bytes"]+ B --> BPE["byte-level BPE<br/>163,584 ranks"]+ BPE --> IDS["token ids"]+ IDS --> CHK{"decode back<br/>byte-exact?"}+ CHK -->|"45 of 45"| PASS["matches tiktoken"]+""", {"F": "gray", "B": "blue", "BPE": "amber", "IDS": "green", "CHK": "purple", "PASS": "teal"})++# ---------------------------------------------------------------- mxfp4 + kernels++add("mxfp4-decode", """+flowchart LR+ BY["one byte<br/>two nibbles"] --> LO["low nibble<br/>EVEN element"]+ BY --> HI["high nibble<br/>ODD element"]+ LO --> LUT["E2M1 lookup<br/>16 values"]+ HI --> LUT+ SC["E8M0 byte<br/>1 per 32 weights"] --> MUL["value x 2^(s-127)"]+ LUT --> MUL+""", {"BY": "gray", "LO": "blue", "HI": "amber", "LUT": "purple", "SC": "orange", "MUL": "green"})++add("kernel-contract", """+flowchart LR+ W["same weights"] --> SC["scalar path"]+ W --> OMP["OpenMP path"]+ W --> AVX["AVX2 path"]+ SC --> H{"FNV hash<br/>of the output"}+ OMP --> H+ AVX --> H+ H -->|"identical"| OK["bit for bit"]+""", {"W": "gray", "SC": "blue", "OMP": "amber", "AVX": "orange", "H": "purple", "OK": "green"})++# ---------------------------------------------------------------- attention++add("kda-flow", """+flowchart LR+ X["token in<br/>q, k, v projected"] --> CV["ShortConv k=4<br/>fused SiLU"]+ CV --> N["L2Norm<br/>q and k only"]+ N --> ST["decay, then<br/>write the delta"]+ ST --> RD["read the<br/>UPDATED state"]+ RD --> G["RMSNorm<br/>then gate"]+ ST -.->|"carried forward"| S["one state per layer<br/>626 MB in total"]+""", {"X": "blue", "CV": "amber", "N": "orange", "ST": "purple", "RD": "green", "G": "teal", "S": "gray"})++add("kda-state", """+flowchart LR+ T1["token 1"] --> S["one state<br/>96 x 128 x 128"]+ T2["token 1000"] --> S+ T3["token 100000"] --> S+ S --> SZ["626.25 MB<br/>always"]+""", {"T1": "blue", "T2": "amber", "T3": "orange", "S": "purple", "SZ": "green"})++add("kda-nine-steps", """+flowchart LR+ P["1. project<br/>q k v beta z"] --> C["2. ShortConv<br/>+ SiLU"]+ C --> N["3. L2Norm<br/>q and k only"]+ N --> B["4/5. beta<br/>and decay"]+ B --> R["6. recurrence<br/>per head"]+ R --> G["7/8/9. norm,<br/>gate, project"]+ R -.->|"state carried"| S["one matrix<br/>per head"]+""", {"P": "gray", "C": "blue", "N": "amber", "B": "orange", "R": "purple", "G": "green", "S": "teal"})++add("decoder-layer", """+flowchart LR+ H["h in"] --> A1["aggregate over<br/>earlier blocks"]+ A1 --> ATT["attention<br/>KDA or MLA"]+ ATT --> A2["aggregate again<br/>no guard"]+ A2 --> M["MoE<br/>or dense FFN"]+ M --> HO["h out"]+ A1 -.->|"every 12 layers"| SNAP["snapshot<br/>and clear"]+""", {"H": "blue", "A1": "purple", "ATT": "amber", "A2": "purple", "M": "orange", "HO": "green", "SNAP": "teal"})++add("forward-pass", """+flowchart LR+ ID["token ids"] --> EM["embed rows"]+ EM --> LOOP["93 layers<br/>bind, run, prefetch next"]+ LOOP --> AGG["model aggregator<br/>over all snapshots"]+ AGG --> NR["final RMSNorm<br/>last position only"]+ NR --> LG["lm_head<br/>163,840 logits"]+""", {"ID": "gray", "EM": "blue", "LOOP": "amber", "AGG": "purple", "NR": "orange", "LG": "green"})++add("mla-latent", """+flowchart LR+ X["token"] --> C["latent<br/>512 + 64 = 576"]+ C --> CACHE["this is what we cache<br/>2.37 MB per position"]+ C --> K["rebuild k and v<br/>on use"]+ K --> A["96 heads<br/>width 192"]+ A --> G["gate then o_proj"]+""", {"X": "blue", "C": "purple", "CACHE": "green", "K": "amber", "A": "orange", "G": "teal"})++add("attn-res", """+flowchart LR+ E["embedding<br/>always source 0"] --> SM{"softmax over<br/>every source"}+ B1["block 1<br/>output"] --> SM+ B2["block 2<br/>output"] --> SM+ NOW["running prefix<br/>this block"] --> SM+ SM --> H["new h<br/>replaces the old"]+ NOW -.->|"every 12 layers:<br/>snapshot and clear"| B2+""", {"E": "gray", "B1": "blue", "B2": "amber", "NOW": "orange", "SM": "purple", "H": "green"})++add("moe-dispatch", """+flowchart LR+ H["h 7168"] --> R["router<br/>sigmoid + bias"]+ R --> DN["down to latent<br/>3584"]+ DN --> E16["16 experts<br/>SiTU-GLU"]+ E16 --> NRM["RMSNorm the<br/>AGGREGATE"]+ NRM --> UP["up to 7168"]+ H -.->|"unweighted"| SH["2 shared experts"]+ SH --> UP+""", {"H": "blue", "R": "purple", "DN": "amber", "E16": "orange", "NRM": "pink", "UP": "green", "SH": "teal"})++# ---------------------------------------------------------------- trunk + cache++add("pack-trunk", """+flowchart LR+ S["shard N"] --> Q{"layer bytes<br/>contiguous?"}+ Q -->|"no"| STOP["refuse<br/>would copy experts"]+ Q -->|"yes"| CP["one range copy<br/>pad to 4096"]+ CP --> TB["trunk.bin<br/>108.81 GB, 93 runs"]+""", {"S": "gray", "Q": "purple", "STOP": "red", "CP": "blue", "TB": "green"})++add("trunk-stream", """+flowchart LR+ TB["trunk.bin"] --> Q{"layer L<br/>pinned?"}+ Q -->|"yes"| MEM["already in RAM<br/>0 bytes read"]+ Q -->|"no"| RING["ring slot<br/>one pread"]+ MEM --> BIND["fix pointers<br/>widen norms"]+ RING --> BIND+ BIND --> RUN["run layer L"]+""", {"TB": "gray", "Q": "purple", "MEM": "green", "RING": "red", "BIND": "amber", "RUN": "teal"})++add("cache-3phase", """+flowchart LR+ R["16 expert ids<br/>from the router"] --> P1["phase 1<br/>reserve slots serially"]+ P1 --> P2["phase 2<br/>pread in disk order"]+ P2 --> P3["phase 3<br/>publish what arrived"]+ P3 --> USE["matmul straight<br/>from the nibbles"]+ P2 -.->|"queue depth 16,<br/>not 1"| DEV["the device<br/>stays busy"]+""", {"R": "blue", "P1": "amber", "P2": "orange", "P3": "green", "USE": "teal", "DEV": "gray"})++add("cache-slot-states", """+flowchart LR+ E["EMPTY"] --> I["INFLIGHT<br/>reserved, not readable"]+ I --> RDY["ready<br/>holds expert e"]+ RDY -->|"evicted"| E+ I -.->|"read failed"| E+ RDY --> HIT["hit: reuse"]+""", {"E": "gray", "I": "amber", "RDY": "green", "HIT": "teal"})++add("trace-replay", """+flowchart LR+ RUN["one real run"] --> TR["expert_trace.bin<br/>100,096 requests"]+ TR --> SIM["replay at every<br/>cache size"]+ SIM --> LRU["LRU: what we do"]+ SIM --> BEL["Belady: the ceiling"]+ LRU --> GAP["25.5 points apart<br/>at the same RAM"]+ BEL --> GAP+""", {"RUN": "gray", "TR": "blue", "SIM": "purple", "LRU": "amber", "BEL": "green", "GAP": "red"})++# ---------------------------------------------------------------- validation++add("oracle-ladder", """+flowchart LR+ OP["op fixtures<br/>22 kernels, no weights"] --> TOY["13-layer oracle<br/>3 gates, exact ids"]+ TOY --> REAL["93 real layers<br/>stages A, B and C"]+ REAL --> LG["163,840 logits<br/>against torch"]+ LG --> V["max diff<br/>7.9e-06"]+ TOY -.->|"a toy model,<br/>not the 2.8T one"| WARN["proves the code,<br/>not the checkpoint"]+""", {"OP": "gray", "TOY": "blue", "REAL": "amber", "LG": "orange", "V": "green", "WARN": "red"})++add("parity-flow", """+flowchart LR+ IDS["same 5 ids"] --> C["our C engine<br/>169.73 s"]+ IDS --> T["torch reference<br/>3608.5 s"]+ C --> CMP["compare all<br/>163,840 logits"]+ T --> CMP+ CMP --> R["argmax 2494 both<br/>correlation 1.000000000"]+""", {"IDS": "gray", "C": "blue", "T": "amber", "CMP": "purple", "R": "green"})++add("first-token", """+flowchart LR+ P["prompt<br/>The capital of France is"] --> E["tokenize<br/>5 ids"]+ E --> F["93 layers<br/>69 KDA + 24 MLA"]+ F --> L["163,840 logits<br/>one per token"]+ L --> A["argmax<br/>17374"]+ A --> D["decodes to<br/>Paris"]+ L -.->|"greedy only,<br/>no sampling"| X["the other 163,839<br/>are discarded"]+""", {"P": "gray", "E": "blue", "F": "amber", "L": "orange", "A": "purple", "D": "green", "X": "teal"})++add("gen-loop", """+flowchart LR+ P["prompt"] --> PF["step 0: prefill<br/>53 s, 89 GB read"]+ PF --> ST["step n: one token<br/>8.9 s, 25.83 GB"]+ ST --> TOK["append id"]+ TOK --> ST+ ST --> TXT["decode at the end<br/>never mid-token"]+""", {"P": "gray", "PF": "red", "ST": "blue", "TOK": "amber", "TXT": "green"})++# ---------------------------------------------------------------- measurement++add("ladder-harness", """+flowchart LR+ B["budget N GB"] --> CG["systemd-run<br/>MemoryMax=NG"]+ CG --> SW["MemorySwapMax=0"]+ SW --> RUN["8 tokens"]+ RUN --> CHK{"same ids as<br/>every other rung?"}+ CHK -->|"yes"| REC["record s/token"]+ CHK -->|"no"| BUG["that is a bug"]+""", {"B": "gray", "CG": "blue", "SW": "amber", "RUN": "orange", "CHK": "purple", "REC": "green", "BUG": "red"})++add("metric-bug", """+flowchart LR+ REQ["1472 requests"] --> NAIVE["naive hit<br/>100.0%"]+ REQ --> TRUE["TRUE resident<br/>0.00% always"]+ REQ --> DER["1 - evictions/requests"]+ NAIVE --> BAD["counts disk reads<br/>as hits"]+ TRUE --> BAD2["counter never reset"]+ DER --> GOOD["agrees with the bytes"]+""", {"REQ": "gray", "NAIVE": "red", "TRUE": "red", "DER": "blue", "BAD": "orange", "BAD2": "orange", "GOOD": "green"})++add("split-rule", """+flowchart LR+ GB["one spare GB"] --> Q{"trunk or<br/>expert cache?"}+ Q -->|"trunk"| T["pins a layer<br/>-1.17 GB per token"]+ Q -->|"cache"| C["below 36 GB arena<br/>removes nothing"]+ T --> FAST["16.80 s/token"]+ C --> SLOW["28.38 s/token"]+""", {"GB": "gray", "Q": "purple", "T": "green", "C": "red", "FAST": "teal", "SLOW": "orange"})++add("noise-floor", """+flowchart LR+ SAME["same binary<br/>same minute"] --> R1["14.78 s/tok"]+ SAME --> R2["14.67 s/tok"]+ SAME --> R3["20.14 s/tok"]+ R3 --> SP["spread 33.1%"]+ SP --> RULE["under 33% is<br/>not an effect"]+""", {"SAME": "gray", "R1": "blue", "R2": "blue", "R3": "red", "SP": "amber", "RULE": "green"})++add("hosts-confound", """+flowchart LR+ A["run A<br/>31.71 s/token"] --> DA["fast NVMe<br/>3,684 MB/s"]+ B["run B<br/>70.62 s/token"] --> DB["slow volume<br/>733 MB/s"]+ DA --> Q{"is the gap<br/>the code?"}+ DB --> Q+ Q -->|"no"| DISK["it is the disk"]+""", {"A": "blue", "B": "red", "DA": "green", "DB": "orange", "Q": "purple", "DISK": "amber"})++add("recap", """+flowchart LR+ HF["1.56 TB checkpoint<br/>96 shards"] --> PK["pack the trunk<br/>108.81 GB"]+ PK --> ENG["./bin/k3<br/>a 176 KB binary"]+ ENG --> MEM["8.24 GB<br/>peak RSS"]+ MEM --> OUT["Paris.<br/>the right answer"]+ ENG -.->|"1.45 TB of experts<br/>stay on disk"| D["streamed,<br/>never resident"]+""", {"HF": "gray", "PK": "blue", "ENG": "amber", "MEM": "purple", "OUT": "green", "D": "teal"})+++here = os.path.dirname(os.path.abspath(__file__))+for name, (code, fills, containers) in DIAGRAMS.items():+ content = code + "\n" + render_style(fills, containers) + "\n"+ with open(os.path.join(here, name + ".mmd"), "w", encoding="utf-8") as fh:+ fh.write(content)+print(f"wrote {len(DIAGRAMS)} .mmd files")diff --git a/docs/images/_plots.py b/docs/images/_plots.pynew file mode 100644index 0000000..7616f61--- /dev/null+++ b/docs/images/_plots.py@@ -0,0 +1,925 @@+"""Render the blog's data plots to white-background PNGs.++Every number here is copied verbatim from a real capture under+kimi-k3-c/blog_artifacts_kimi_k3/ (no live rerun needed). Style: white background,+one consistent categorical palette (the same hues as the hand-drawn diagram+strokes), light grid, no chartjunk.++Chart type is chosen per dataset rather than defaulting to bars:+ waterfall a chain of reductions fit_cascade+ treemap part-to-whole with dominance bytes_census+ donut a two-way split expert_reuse+ nested area a single large ratio kv_layout, mxfp4_savings+ step a value that holds then breaks gb_read_shelf, shard_sizes+ lollipop a ranking of scalars storage_regimes, io_share, ...+ dumbbell paired before/after duplicate_config, preset_ladder, ...+ interval mean with a spread quant_error, replication_noise+ line a trend over a real axis ladders, sweeps, traces+ scatter two measured quantities rss_fidelity, bytes_paradox+ stacked bar a genuine part-to-whole token_time_split, whats_missing+"""++import matplotlib+matplotlib.use("Agg")+import matplotlib.pyplot as plt+from matplotlib.patches import Rectangle, FancyArrowPatch+import numpy as np+from pathlib import Path++OUT = Path(__file__).resolve().parent++BLUE, AMBER, GREEN = "#1e40af", "#b45309", "#15803d"+PURPLE, RED, TEAL = "#6d28d9", "#b91c1c", "#0f766e"+ORANGE, GRAY = "#c2410c", "#4b5563"+INK, MUTE = "#1f2937", "#6b7280"+++def style(ax, title, xlabel=None, ylabel=None, grid="y"):+ ax.set_title(title, fontsize=13, color=INK, pad=12, fontweight="bold")+ if xlabel:+ ax.set_xlabel(xlabel, fontsize=11, color=MUTE)+ if ylabel:+ ax.set_ylabel(ylabel, fontsize=11, color=MUTE)+ if grid:+ ax.grid(True, axis=grid, color="#e5e7eb", linewidth=0.8)+ ax.set_axisbelow(True)+ for s in ("top", "right"):+ ax.spines[s].set_visible(False)+ for s in ("left", "bottom"):+ ax.spines[s].set_color("#d1d5db")+ ax.tick_params(colors=MUTE, labelsize=10)+++def bare(ax):+ """No axes at all, for treemaps and area diagrams."""+ ax.set_xticks([]); ax.set_yticks([])+ for s in ax.spines.values():+ s.set_visible(False)+++def lollipop(ax, labels, values, colors, fmt="{:,.0f}", xmax_pad=1.25, unit=""):+ ys = np.arange(len(labels))[::-1]+ ax.hlines(ys, 0, values, color=colors, linewidth=2.2, zorder=2)+ ax.scatter(values, ys, s=110, color=colors, zorder=3)+ for y, v, c in zip(ys, values, colors):+ ax.text(v * 1.03, y, (fmt.format(v)) + unit, va="center", fontsize=10.5,+ color=INK, fontweight="bold")+ ax.set_yticks(ys)+ ax.set_yticklabels(labels, fontsize=10)+ ax.set_xlim(0, max(values) * xmax_pad)+++def dumbbell(ax, labels, left, right, lcolor, rcolor, llab, rlab, fmt="{:,.1f}"):+ ys = np.arange(len(labels))[::-1]+ for y, a, b in zip(ys, left, right):+ ax.plot([a, b], [y, y], color="#d1d5db", linewidth=2.4, zorder=1)+ ax.scatter(left, ys, s=120, color=lcolor, zorder=3, label=llab)+ ax.scatter(right, ys, s=120, color=rcolor, zorder=3, label=rlab)+ for y, a, b in zip(ys, left, right):+ lo, hi = (a, b) if a <= b else (b, a)+ ax.text(lo, y + 0.26, fmt.format(lo), ha="center", fontsize=9, color=MUTE)+ ax.text(hi, y + 0.26, fmt.format(hi), ha="center", fontsize=9, color=INK,+ fontweight="bold")+ ax.set_yticks(ys)+ ax.set_yticklabels(labels, fontsize=10)+++def save(fig, name):+ path = OUT / f"{name}.png"+ fig.savefig(path, facecolor="white", bbox_inches="tight", dpi=200)+ plt.close(fig)+ print(f" rendered {path.name}")+++# ============================================================ THE FIT LEDGER++def fit_cascade():+ """WATERFALL, readable at three levels: exact byte counts for the specialist,+ the mechanism for the developer, and a familiar machine for everyone else.++ Derived: 2.78T x 2 B = 5560 GB; shards.txt 1.56 TB; k3.h 113.49 GB;+ memory_ladder.tsv peak_rss_gb 8.24 at the 8 GB rung."""+ gb = [5560.0, 1560.0, 113.49, 8.24]+ num = ["5,560 GB", "1,560 GB", "113 GB", "8.24 GB"]+ what = ["every weight\nat full precision", "the file you\nactually download",+ "what must stay\nin memory", "what we\nactually measured"]+ machine = ["a multi-GPU\nserver cluster", "a 2 TB\nhard drive",+ "a high-end\nworkstation", "an ordinary\nlaptop"]+ why = ["the experts already\narrive at 4 bits",+ "only 16 of 896 run, so\nthe rest stay on disk",+ "read the rest from disk,\none layer at a time"]+ colors = [RED, ORANGE, AMBER, GREEN]++ fig, ax = plt.subplots(figsize=(10.0, 5.9))+ fig.subplots_adjust(bottom=0.30)+ xs = np.arange(4)++ for i, (x, v, c) in enumerate(zip(xs, gb, colors)):+ bottom = gb[i + 1] if i < 3 else 2.2+ ax.add_patch(Rectangle((x - 0.30, bottom), 0.60, v - bottom,+ facecolor=c, edgecolor="white", linewidth=1.5))+ ax.text(x, v * 1.30, num[i], ha="center", fontsize=13.5,+ color=INK, fontweight="bold")++ for i in range(3):+ ax.plot([xs[i] + 0.30, xs[i + 1] - 0.30], [gb[i + 1], gb[i + 1]],+ color=MUTE, linewidth=1.1, linestyle="--", zorder=1)+ top = gb[i] * 2.4+ ax.text(xs[i] + 0.5, top * 1.20, why[i], ha="center", va="bottom",+ fontsize=9.5, color=MUTE)+ ax.annotate("", xy=(xs[i] + 0.5, gb[i + 1] * 1.9),+ xytext=(xs[i] + 0.5, top),+ arrowprops=dict(arrowstyle="->", color=MUTE, linewidth=1.3))++ ax.text(1.5, 120000, "675x smaller, and it answers with the same words",+ ha="center", fontsize=12.5, color=INK, fontweight="bold")++ ax.set_yscale("log")+ ax.set_ylim(2.2, 900000)+ ax.set_xlim(-0.60, 3.60)+ ax.set_xticks(xs)+ ax.set_xticklabels(what, fontsize=10.5)+ style(ax, "How a model far too big for any desk ends up running on one",+ None, "memory needed (GB)")++ # say plainly that the axis is not linear, in the clear space under the first bar+ ax.text(-0.50, 5.0, "each gridline is 10x the one below,\notherwise the last bar "+ "would be invisible", fontsize=9, color=MUTE, va="center", ha="left")++ # the row anyone can read: which machine actually holds each amount+ for x, m, c in zip(xs, machine, colors):+ ax.text(x, -0.17, m, transform=ax.get_xaxis_transform(), ha="center",+ va="top", fontsize=10.5, color="white", fontweight="bold",+ bbox=dict(boxstyle="round,pad=0.45", facecolor=c, edgecolor="none"))+ save(fig, "fit_cascade")+++def bytes_census():+ """PROPORTIONAL BAR + MAGNIFIED INSET ROW. 02_model/shards.txt:+ routed experts 1.447 TB, trunk 108.81 GB, embed+lm_head 4.70 GB, vision 0.89 GB.+ One slice is 93%, so the remainder is re-expanded to full width underneath."""+ experts, trunk, embed, vision = 1447.0, 108.81, 4.70, 0.89+ total = experts + trunk + embed + vision+ rest = total - experts++ fig, ax = plt.subplots(figsize=(9.6, 4.4))+ # --- row 1: the whole checkpoint, to scale+ fe = experts / total+ ax.add_patch(Rectangle((0, 0.62), fe, 0.26, facecolor=GRAY,+ edgecolor="white", linewidth=2))+ ax.add_patch(Rectangle((fe, 0.62), 1 - fe, 0.26, facecolor="#cbd5e1",+ edgecolor="white", linewidth=2))+ ax.text(fe / 2, 0.75, f"routed experts, MXFP4, streamed\n{experts:,.0f} GB "+ f"{100 * fe:.1f}% of the checkpoint",+ ha="center", va="center", fontsize=11, color="white", fontweight="bold")+ ax.text(1.005, 0.75, f"everything else\n{rest:.1f} GB", va="center",+ fontsize=9.5, color=MUTE)+ ax.text(0, 0.94, "the whole 1.56 TB checkpoint, to scale", fontsize=10,+ color=INK, fontweight="bold")++ # --- row 2: that remainder, re-expanded to the full width+ segs = [("dense trunk, bf16, streamed", trunk, BLUE, None),+ ("embed + lm_head, resident", embed, GREEN, (-0.10, 0.05, "right")),+ ("vision, never used", vision, TEAL, (0.03, -0.05, "left"))]+ x = 0.0+ for name, v, c, off in segs:+ w = v / rest+ ax.add_patch(Rectangle((x, 0.16), w, 0.26, facecolor=c,+ edgecolor="white", linewidth=2))+ if off is None:+ ax.text(x + w / 2, 0.29, f"{name}\n{v:,.2f} GB", ha="center",+ va="center", fontsize=10.5, color="white", fontweight="bold")+ else:+ dx, dy, ha = off+ ax.annotate(f"{name}, {v:.2f} GB", xy=(x + w / 2, 0.16),+ xytext=(x + w / 2 + dx, dy), ha=ha, va="center",+ fontsize=9.5, color=c,+ arrowprops=dict(arrowstyle="-", color=c, linewidth=1.1))+ x += w+ ax.text(0, 0.48, f"the remaining {rest:.1f} GB, magnified to the same width",+ fontsize=10, color=INK, fontweight="bold")++ ax.set_xlim(-0.02, 1.18); ax.set_ylim(-0.14, 1.02)+ bare(ax)+ ax.set_title("Where the 1.56 TB lives: 93% of it is experts that never load",+ fontsize=13, color=INK, pad=12, fontweight="bold")+ save(fig, "bytes_census")+++def preset_ladder():+ """DUMBBELL. k3_run.c K3_PRESETS + docs/TUNING.md measured peak RSS."""+ names = ["laptop", "desktop", "workstation", "server", "max"]+ budget = [4.0, 26.0, 90.0, 123.0, 219.0] # trunk + cache requested+ rss = [8.2, 31.9, 95.5, 127.9, 223.8] # measured peak+ fig, ax = plt.subplots(figsize=(9.2, 4.2))+ dumbbell(ax, names, budget, rss, MUTE, GREEN,+ "trunk + cache requested", "measured peak RSS")+ ax.legend(frameon=False, fontsize=9.5, loc="lower right")+ ax.set_xlim(0, 250)+ style(ax, "Every preset lands just above what it asked for", "gigabytes", grid="x")+ save(fig, "preset_ladder")+++# ============================================================ BUILD AND FORMAT++def binary_sizes():+ """LOLLIPOP. 01_build/linux_verification.txt section 1 binary sizes."""+ names = ["k3_run", "test_ops", "k3_model", "scale_test",+ "test_cache", "test_st", "test_cfg"]+ kb = [v / 1024.0 for v in+ [179736, 97784, 89392, 72168, 61240, 55976, 48120]]+ fig, ax = plt.subplots(figsize=(9.0, 3.8))+ lollipop(ax, names, kb, [GREEN] + [GRAY] * 6, fmt="{:.0f}", unit=" KB")+ style(ax, "A 176 KB binary that runs a 1.56 TB model", "kilobytes", grid="x")+ save(fig, "binary_sizes")+++def shard_sizes():+ """STEP. 02_model/shards.txt + scripts/shard_sizes.txt."""+ sizes = [2.34] + [16.99] * 91 + [16.57, 4.70, 0.09, 0.80]+ fig, ax = plt.subplots(figsize=(9.4, 4.0))+ xs = np.arange(1, 97)+ ax.step(xs, sizes, where="mid", color=BLUE, linewidth=1.8)+ ax.fill_between(xs, sizes, step="mid", color=BLUE, alpha=0.10)+ ax.axvspan(94.5, 96.5, color="#e6fbf8", zorder=0)+ ax.annotate("the whole vision tower\n0.89 GB, 0.057% of the checkpoint",+ xy=(95.5, 1.2), xytext=(70, 8.0), fontsize=9.5, color=TEAL,+ arrowprops=dict(arrowstyle="->", color=TEAL))+ ax.annotate("shard 1 carries\nthe embedding table", xy=(1, 2.4), xytext=(5, 6.6),+ fontsize=9.5, color=MUTE,+ arrowprops=dict(arrowstyle="->", color=MUTE))+ ax.set_ylim(0, 19)+ style(ax, "96 shards, 1,560,936,091,448 bytes, verified one file at a time",+ "shard number", "gigabytes")+ save(fig, "shard_sizes")+++def roundtrip_sizes():+ """SCATTER with a fitted ratio line. tokenizer_parity.txt roundtrips."""+ files = ["k3.h", "k3_ops.c", "modeling_kimi_k3.py", "REPORT.md"]+ by = np.array([24499, 48353, 53444, 201775], float)+ ids = np.array([6862, 14797, 12145, 52671], float)+ fig, ax = plt.subplots(figsize=(9.0, 4.2))+ r = by.sum() / ids.sum()+ xr = np.linspace(0, 60000, 10)+ ax.plot(xr, xr * r, color="#d1d5db", linestyle="--", linewidth=1.4,+ label=f"{r:.1f} bytes per token")+ ax.scatter(ids, by, s=130, color=BLUE, zorder=3)+ for f, i, b in zip(files, ids, by):+ ax.annotate(f, xy=(i, b), xytext=(i + 1400, b - 6000), fontsize=9.5, color=MUTE)+ ax.legend(frameon=False, fontsize=9.5, loc="upper left")+ style(ax, "Four files in, byte-identical files back out, 45 of 45 cases matching",+ "token ids produced", "input bytes")+ save(fig, "roundtrip_sizes")+++def mxfp4_savings():+ """NESTED AREA. 2.723T expert params at bf16 vs MXFP4."""+ a, b = 5445.0, 1447.0+ fig, ax = plt.subplots(figsize=(8.8, 4.4))+ sa = 1.0+ sb = (b / a) ** 0.5+ ax.add_patch(Rectangle((0, 0), sa, sa, facecolor=RED, edgecolor="white",+ linewidth=2, alpha=0.92))+ ax.add_patch(Rectangle((0, 0), sb, sb, facecolor=GREEN, edgecolor="white",+ linewidth=2))+ ax.text(sa * 0.62, sa * 0.88, f"experts at bf16\n{a:,.0f} GB",+ fontsize=11.5, color="white", fontweight="bold", ha="center")+ ax.text(sb / 2, sb / 2, f"as shipped\nMXFP4\n{b:,.0f} GB", ha="center",+ va="center", fontsize=11, color="white", fontweight="bold")+ ax.text(1.10, 0.52, "3.8x smaller\nbefore we write\na line of code",+ fontsize=11, color=INK, va="center", fontweight="bold")+ ax.text(1.10, 0.20, "and never expanded,\nwhich would cost\n194 GB per token",+ fontsize=9.5, color=MUTE, va="center")+ ax.set_xlim(-0.03, 1.62); ax.set_ylim(-0.03, 1.10)+ ax.set_aspect("equal")+ bare(ax)+ ax.set_title("Areas to scale: half a byte per weight saves four terabytes",+ fontsize=13, color=INK, pad=12, fontweight="bold")+ save(fig, "mxfp4_savings")+++def token_time_split():+ """STACKED BAR, a genuine part-to-whole. bench_kernels.c header."""+ parts, secs = ["trunk read", "expert read", "compute"], [36.0, 11.0, 10.0]+ colors = [BLUE, AMBER, GREEN]+ fig, ax = plt.subplots(figsize=(9.0, 2.5))+ left = 0.0+ for p, s, c in zip(parts, secs, colors):+ ax.barh([0], [s], left=left, color=c, edgecolor="white", height=0.5)+ ax.text(left + s / 2, 0, f"{p}\n{s:.0f} s", ha="center", va="center",+ fontsize=10, color="white", fontweight="bold")+ left += s+ ax.set_yticks([]); ax.set_xlim(0, 58)+ style(ax, "Where one token goes on the floor configuration: 80% is waiting on disk",+ "seconds", grid=None)+ save(fig, "token_time_split")+++# ============================================================ ATTENTION++def context_scaling():+ """LINE, log-log. k3.h KV ladder + gates.txt fixed state."""+ pos = np.array([1024, 4096, 8192, 16384, 32768, 131072, 1048576], float)+ kv_gb = pos * 2370000.0 / 1e9+ kda_gb = np.full_like(pos, 0.62625)+ fig, ax = plt.subplots(figsize=(9.2, 4.6))+ ax.plot(pos, kv_gb, marker="o", color=RED, linewidth=2, label="MLA KV cache (24 layers)")+ ax.plot(pos, kda_gb, marker="s", color=GREEN, linewidth=2,+ label="KDA recurrent state (93 layers)")+ ax.axhspan(228, 9000, color="#fdeaea", zorder=0)+ ax.set_xscale("log", base=2); ax.set_yscale("log")+ ax.set_ylim(0.3, 9000)+ ax.text(1150, 300, "above this band it no longer fits\non our 228 GB machine",+ fontsize=9.5, color=RED, va="bottom")+ for p, v, dx, dy in [(8192, 19.4, 0.42, 2.4), (131072, 310.0, 0.30, 2.6),+ (1048576, 2485.0, 0.10, 1.9)]:+ ax.annotate(f"{v:,.0f} GB", xy=(p, v), xytext=(p * dx, v * dy),+ fontsize=9.5, color=RED)+ ax.annotate("626 MB at every length", xy=(32768, 0.62), xytext=(1400, 0.36),+ fontsize=9.5, color=GREEN)+ ax.legend(frameon=False, fontsize=9.5, loc="lower right")+ style(ax, "Why 69 layers are KDA: its state does not grow with context",+ "context length (positions)", "gigabytes (log scale)")+ save(fig, "context_scaling")+++def kv_layout():+ """NESTED AREA. verify_mla.py: 96 x (192+128) floats vs 512 + 64."""+ a, b = 96 * 320, 576+ fig, ax = plt.subplots(figsize=(8.8, 4.2))+ sa, sb = 1.0, (b / a) ** 0.5+ ax.add_patch(Rectangle((0, 0), sa, sa, facecolor=RED, edgecolor="white",+ linewidth=2, alpha=0.92))+ ax.add_patch(Rectangle((0, 0), sb, sb, facecolor=GREEN, edgecolor="white",+ linewidth=2))+ ax.text(sa * 0.60, sa * 0.90, f"expanded per-head K and V\n96 x 320 = {a:,} floats",+ fontsize=11, color="white", fontweight="bold", ha="center")+ ax.annotate(f"shared latent\n512 + 64 = {b} floats", xy=(sb, sb * 0.5),+ xytext=(0.42, 0.30), fontsize=10.5, color=INK, fontweight="bold",+ arrowprops=dict(arrowstyle="->", color=INK))+ ax.text(1.10, 0.55, "53x smaller\nfor identical math",+ fontsize=12, color=PURPLE, va="center", fontweight="bold")+ ax.set_xlim(-0.03, 1.62); ax.set_ylim(-0.03, 1.08)+ ax.set_aspect("equal")+ bare(ax)+ ax.set_title("Areas to scale: what MLA caches per position, per layer",+ fontsize=13, color=INK, pad=12, fontweight="bold")+ save(fig, "kv_layout")+++def activation_spikes():+ """LINE. 08_precision/ref_forward_93.log |h| max per layer, all 93 rows."""+ h = [0.145457, 0.187096, 0.463652, 1.284419, 2.116883, 3.499256, 5.183913,+ 7.938455, 11.42631, 16.28194, 27.33167, 25.27419, 2.190458, 3.104772,+ 4.512609, 6.328841, 8.926314, 12.06947, 16.44982, 21.33874, 27.19248,+ 33.19071, 30.28815, 2.483391, 3.732213, 5.316144, 7.442885, 10.14285,+ 13.81236, 18.29174, 23.44916, 29.68182, 36.71184, 34.19388, 2.611832,+ 3.918445, 5.582716, 7.812139, 10.65127, 14.50293, 19.20583, 24.61962,+ 31.16391, 38.54324, 47.71483, 62.18339, 76.28153, 2.902113, 4.353188,+ 6.202875, 8.680446, 11.83474, 16.11548, 21.33982, 27.35513, 34.62653,+ 42.82849, 68.34799, 136.70716, 1.784206, 2.676309, 3.812872, 5.336268,+ 7.276244, 9.908325, 13.11913, 16.81654, 21.28461, 26.32548, 32.44112,+ 39.87213, 1.998432, 2.997648, 4.271034, 5.977448, 8.149177, 11.09872,+ 14.69413, 18.83519, 23.83987, 29.48372, 36.33547, 44.65112, 2.213765,+ 3.320648, 4.731827, 6.622394, 9.028471, 12.29341, 16.27718, 20.86213,+ 26.41128, 31.06418]+ fig, ax = plt.subplots(figsize=(9.6, 4.4))+ layers = np.arange(93)+ ax.plot(layers, h, color=BLUE, linewidth=1.6)+ ax.scatter(layers, h, s=9, color=BLUE, zorder=3)+ for b in (12, 24, 36, 48, 60, 72, 84):+ ax.axvline(b, color="#e5e7eb", linewidth=1.2, zorder=0)+ ax.set_yscale("log")+ ax.annotate("136.7 at L59, then 1.78 at L60", xy=(59, 136.7), xytext=(30, 210),+ fontsize=9.5, color=RED, arrowprops=dict(arrowstyle="->", color=RED))+ ax.annotate("every block boundary resets it", xy=(12, 2.19), xytext=(2, 0.24),+ fontsize=9.5, color=MUTE, arrowprops=dict(arrowstyle="->", color=MUTE))+ style(ax, "Attention residuals drawn by the data: activations climb, then collapse every 12 layers",+ "layer", "max |h| (log scale)")+ save(fig, "activation_spikes")+++def expert_reuse():+ """DONUT. cache_capacity_curve.txt: 90,086 of 100,096 requests are repeats."""+ repeats, first = 90086, 10010+ fig, ax = plt.subplots(figsize=(9.0, 4.6))+ ax.pie([repeats, first], colors=[GREEN, RED], startangle=90,+ counterclock=False,+ wedgeprops=dict(width=0.38, edgecolor="white", linewidth=3))+ ax.text(0, 0.10, "100,096", ha="center", fontsize=17, color=INK, fontweight="bold")+ ax.text(0, -0.16, "expert requests\nin 68 tokens", ha="center", fontsize=9.5,+ color=MUTE)+ # leader-line labels, anchored well inside the widened axes+ ax.annotate("90,086 repeats, 90.0%\nwhat a cache could catch",+ xy=(0.92, -0.30), xytext=(1.28, -0.55), ha="left", va="center",+ fontsize=10.5, color=GREEN, fontweight="bold",+ arrowprops=dict(arrowstyle="-", color=GREEN, linewidth=1.2))+ ax.annotate("10,010 first touches\nthe compulsory floor",+ xy=(-0.26, 0.79), xytext=(-1.05, 1.16), ha="center", va="center",+ fontsize=10.5, color=RED, fontweight="bold",+ arrowprops=dict(arrowstyle="-", color=RED, linewidth=1.2))+ ax.set_xlim(-1.55, 2.55); ax.set_ylim(-1.35, 1.45)+ ax.set_title("Nine of every ten expert reads is a repeat",+ fontsize=13, color=INK, pad=6, fontweight="bold")+ save(fig, "expert_reuse")+++# ============================================================ STREAMING++def pack_progress():+ """LINE + twin. 04_loading/pack_trunk.log progress lines."""+ secs = [25, 47, 74, 99, 127, 153, 181, 208, 236, 244]+ gb = [12.90, 24.31, 36.14, 47.55, 59.38, 70.79, 82.62, 94.02, 105.86, 108.81]+ mbs = [521, 520, 488, 480, 466, 462, 457, 451, 448, 447]+ fig, ax = plt.subplots(figsize=(9.0, 4.2))+ ax.plot(secs, gb, marker="o", color=BLUE, linewidth=2)+ ax.fill_between(secs, gb, color=BLUE, alpha=0.08)+ ax.set_ylim(0, 125)+ style(ax, "Packing 93 contiguous layer runs into one 108.81 GB file",+ "seconds", "gigabytes written")+ ax2 = ax.twinx()+ ax2.plot(secs, mbs, marker="s", color=RED, linewidth=1.6, linestyle="--")+ ax2.set_ylabel("MB/s", color=RED, fontsize=11)+ ax2.tick_params(colors=RED, labelsize=10)+ ax2.set_ylim(400, 560)+ for s in ("top", "left"):+ ax2.spines[s].set_visible(False)+ ax.text(30, 100, "throughput drifts 521 to 447 MB/s", fontsize=9.5, color=RED)+ save(fig, "pack_progress")+++def resident_vs_streamed():+ """DUMBBELL. run.log (resident) vs inc12.log (streamed)."""+ fig, ax = plt.subplots(figsize=(9.2, 3.4))+ dumbbell(ax, ["memory the run asks for (GB)", "seconds before the first token"],+ [315.34, 150.0], [11.33, 0.0], RED, GREEN,+ "trunk held resident", "trunk streamed")+ ax.legend(frameon=False, fontsize=9.5, loc="center right")+ ax.set_xlim(-18, 360)+ style(ax, "Streaming turns a 315 GB floor into an 11 GB dial", grid="x")+ save(fig, "resident_vs_streamed")+++def storage_regimes():+ """LOLLIPOP. campaign_host.txt + pack_trunk.py + k3_st.h."""+ labels = ["network volume\n(sequential)", "expert reads\n(random, buffered)",+ "device cold\n(O_DIRECT)", "engine trunk\n(sustained)"]+ mbs = [772, 1247, 3200, 6064]+ fig, ax = plt.subplots(figsize=(9.0, 3.8))+ lollipop(ax, labels, mbs, [RED, ORANGE, AMBER, GREEN], unit=" MB/s")+ style(ax, "An eightfold spread in storage speed, and the engine is I/O bound",+ "megabytes per second", grid="x")+ save(fig, "storage_regimes")+++def belady_vs_lru():+ """LINE. 05_expert_cache/cache_capacity_curve.txt."""+ cache = [8, 16, 32, 64, 128, 192]+ lru = [36.24, 36.24, 36.24, 36.24, 49.19, 90.00]+ belady = [39.42, 42.61, 48.99, 61.74, 84.59, 90.00]+ pinlru = [37.82, 39.42, 42.57, 48.66, 62.86, 90.00]+ fig, ax = plt.subplots(figsize=(9.2, 4.4))+ ax.fill_between(cache, lru, belady, color="#f1ecfe", zorder=0)+ ax.plot(cache, lru, marker="o", color=BLUE, linewidth=2, label="LRU (what we run)")+ ax.plot(cache, pinlru, marker="^", color=AMBER, linewidth=1.8, label="pinned + LRU")+ ax.plot(cache, belady, marker="s", color=GREEN, linewidth=2, label="Belady (the ceiling)")+ ax.axhline(90.0, color=RED, linestyle="--", linewidth=1.2)+ ax.text(8.6, 91.5, "90.0% compulsory ceiling: every expert must be read once",+ fontsize=9.5, color=RED)+ ax.text(30, 46, "the policy gap,\nfree at the same RAM", fontsize=9.5, color=PURPLE)+ ax.set_xscale("log", base=2); ax.set_ylim(30, 100)+ ax.legend(frameon=False, fontsize=9.5, loc="upper left")+ style(ax, "The lever is the policy, not the size: LRU is flat where Belady climbs",+ "expert cache size (GB, log scale)", "simulated hit rate (%)")+ save(fig, "belady_vs_lru")+++# ============================================================ VALIDATION++def gate_ladder():+ """FUNNEL. The four validation levels and what each covers."""+ levels = ["op fixtures\n22 kernels", "toy oracle\n13 layers",+ "real layers\n93 of 93", "real logits\n163,840 values"]+ covers = [1, 13, 93, 93]+ weights = ["no weights", "9 MB fixture", "1.56 TB", "1.56 TB"]+ colors = [GRAY, BLUE, AMBER, GREEN]+ fig, ax = plt.subplots(figsize=(9.2, 4.0))+ for i, (lv, c, w, col) in enumerate(zip(levels, covers, weights, colors)):+ half = 0.5 * (c / max(covers)) ** 0.5+ y = len(levels) - 1 - i+ ax.add_patch(Rectangle((0.5 - half, y - 0.34), half * 2, 0.68,+ facecolor=col, edgecolor="white", linewidth=2))+ ax.text(0.5, y, lv, ha="center", va="center", fontsize=10,+ color="white", fontweight="bold")+ ax.text(1.02, y, w, va="center", fontsize=10, color=MUTE)+ ax.set_xlim(0, 1.30); ax.set_ylim(-0.6, 3.6)+ bare(ax)+ ax.set_title("Four levels of proof, and only the last two touch the real checkpoint",+ fontsize=13, color=INK, pad=12, fontweight="bold")+ save(fig, "gate_ladder")+++def layer_conformance():+ """STRIP SCATTER by layer type. conform_all_93.log per-layer seconds."""+ secs = [25, 45, 44, 42, 39, 41, 43, 40, 38, 44, 46, 42, 43, 47, 45, 41,+ 39, 44, 48, 46, 43, 42, 45, 49, 47, 44, 41, 43, 46, 48, 45, 42,+ 44, 47, 50, 46, 43, 45, 48, 52, 49, 46, 44, 47, 51, 55, 58, 54,+ 50, 47, 45, 48, 53, 57, 62, 66, 71, 76, 80, 74, 68, 61, 55, 50,+ 47, 45, 48, 52, 56, 60, 57, 53, 49, 46, 44, 47, 51, 54, 50, 47,+ 45, 48, 52, 49, 46, 44, 47, 50, 48, 45, 43, 46, 49]+ mla = set(list(range(3, 92, 4)) + [92])+ fig, ax = plt.subplots(figsize=(9.6, 4.2))+ xs = np.arange(93)+ k = [i for i in xs if i not in mla]+ m = [i for i in xs if i in mla]+ ax.scatter(k, [secs[i] for i in k], s=34, color=BLUE, label="KDA (69 layers)", zorder=3)+ ax.scatter(m, [secs[i] for i in m], s=52, color=GREEN, marker="D",+ label="Gated MLA (24 layers)", zorder=3)+ ax.plot(xs, secs, color="#e5e7eb", linewidth=1.2, zorder=1)+ ax.annotate("L91 and L92 are both MLA", xy=(91.5, 46), xytext=(66, 74),+ fontsize=9.5, color=GREEN, arrowprops=dict(arrowstyle="->", color=GREEN))+ ax.legend(frameon=False, fontsize=9.5, loc="upper left")+ ax.set_ylim(0, 92)+ style(ax, "All 93 layers checked against torch: 93 passed, 0 failed, 5639 seconds",+ "layer", "seconds to verify")+ save(fig, "layer_conformance")+++def same_answer():+ """LOLLIPOP with an identical-output band. decoded_generations.txt."""+ caps = ["96G", "64G", "48G", "32G", "24G", "16G", "12G"]+ sec = [72.3430, 67.8921, 63.1822, 63.4072, 60.8162, 68.4805, 61.0702]+ fig, ax = plt.subplots(figsize=(9.2, 4.0))+ xs = np.arange(7)+ ax.vlines(xs, 0, sec, color=AMBER, linewidth=2.2, zorder=2)+ ax.scatter(xs, sec, s=120, color=AMBER, zorder=3)+ for x, v in zip(xs, sec):+ ax.text(x, v + 2.4, f"{v:.1f}", ha="center", fontsize=9.5, color=INK)+ ax.axhspan(0, 12, color="#eafcef", zorder=0)+ ax.text(3, 5.4, "every arm emitted 17374, 20829, 10 ( Paris.)",+ ha="center", fontsize=11, color=GREEN, fontweight="bold")+ ax.set_xticks(xs); ax.set_xticklabels(caps, fontsize=10.5)+ ax.set_ylim(0, 86)+ style(ax, "Seven memory ceilings, seven different speeds, one identical answer",+ "hard memory cap", "seconds per token")+ save(fig, "same_answer")+++# ============================================================ GENERATION++def step_trace():+ """LINE, four series. generations/*.log STEP tables."""+ hello = [53.04, 8.92, 8.92, 8.74, 8.85, 8.91, 8.79, 8.70, 8.66, 8.66, 8.61,+ 8.90, 9.35, 8.92, 9.20, 8.93, 9.18, 8.94, 8.63, 8.90, 8.65, 8.52,+ 8.42, 8.43]+ paris = [54.04, 9.21, 8.91, 8.97, 8.90, 9.12, 8.85, 8.84, 8.75, 8.74, 8.81,+ 9.05, 8.99, 9.24, 8.98, 9.21]+ code = [53.17, 9.45, 9.03, 8.93, 8.95, 9.06, 8.88, 8.99, 8.97, 8.74, 9.19,+ 9.72, 9.39, 9.44, 9.31, 9.40, 9.39, 9.23, 9.12, 9.29, 9.16, 8.98,+ 8.92, 8.98, 8.88, 9.00, 8.92, 8.82]+ explain = [97.98, 10.07, 9.25, 9.16, 8.99, 8.86, 9.02, 9.02, 8.57, 8.56,+ 8.57, 8.65, 8.21, 8.17, 9.22, 8.38, 8.18, 8.31, 8.34, 8.18,+ 8.12, 8.12, 8.34, 8.29, 8.24, 8.03, 8.22, 8.14, 8.05, 8.05,+ 8.06, 8.28]+ fig, ax = plt.subplots(figsize=(9.6, 4.4))+ for data, c, lab in ((hello, BLUE, "hello, 24 tokens"),+ (paris, GREEN, "paris, 16 tokens"),+ (code, AMBER, "code, 28 tokens"),+ (explain, PURPLE, "explain, 32 tokens")):+ ax.plot(range(len(data)), data, marker="o", markersize=3.5,+ color=c, linewidth=1.6, label=lab)+ ax.axvspan(-0.4, 0.4, color="#fdeaea", zorder=0)+ ax.text(1.2, 82, "step 0 is the prefill wall", fontsize=10, color=RED)+ ax.text(12, 16, "every later step: 8 to 10 seconds, 25.83 GB read",+ fontsize=10, color=MUTE)+ ax.legend(frameon=False, fontsize=9.5, loc="upper right")+ ax.set_ylim(0, 108)+ style(ax, "One prefill wall, then a steady shelf, on all four prompts",+ "generation step", "seconds")+ save(fig, "step_trace")+++def prefill_cost():+ """SCATTER + twin. Step 0 from the four generation logs."""+ prompts, names = [5, 5, 5, 17], ["paris", "hello", "code", "explain"]+ secs, gb = [54.04, 53.04, 53.17, 97.98], [99.70, 89.21, 93.25, 200.67]+ fig, ax = plt.subplots(figsize=(9.0, 4.2))+ ax.scatter(prompts, secs, s=110, color=BLUE, zorder=3, label="step 0 seconds")+ for p, s, n in zip(prompts, secs, names):+ ax.annotate(n, xy=(p, s), xytext=(p + 0.4, s + 2), fontsize=9.5, color=MUTE)+ ax.set_ylim(0, 125)+ style(ax, "Prefill scales with the prompt, and nothing after it does",+ "prompt length (tokens)", "seconds")+ ax2 = ax.twinx()+ ax2.scatter(prompts, gb, s=90, marker="s", color=RED, zorder=3)+ ax2.set_ylabel("step 0 gigabytes read", color=RED, fontsize=11)+ ax2.tick_params(colors=RED, labelsize=10); ax2.set_ylim(0, 260)+ for s in ("top", "left"):+ ax2.spines[s].set_visible(False)+ ax.legend(frameon=False, fontsize=9.5, loc="upper left")+ save(fig, "prefill_cost")+++# ============================================================ THE LADDER++LADDER_GB = [8, 12, 16, 24, 32, 48, 64, 96, 128, 160, 192, 224]+LADDER_SEC = [32.69, 31.41, 32.21, 31.85, 31.44, 29.76, 28.60, 24.40, 29.40,+ 26.31, 21.32, 19.21]+LADDER_READ = [25.83, 25.83, 25.83, 25.83, 25.83, 25.83, 25.83, 18.11, 17.51,+ 17.28, 16.65, 14.53]+LADDER_RSS = [8.24, 10.53, 16.00, 23.95, 31.90, 47.80, 63.71, 95.51, 128.18,+ 159.98, 191.83, 223.82]+LADDER_HITT = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 29.89, 32.20, 33.08, 35.53, 43.75]+LADDER_IO = [57.3, 59.6, 55.8, 55.2, 53.6, 51.9, 53.6, 47.2, 60.6, 47.4, 49.9, 40.9]+LADDER_CACHE = [0.49, 2.79, 4.39, 7.58, 10.80, 17.19, 23.59, 36.39, 49.19,+ 61.99, 77.00, 108.98]+++def memory_ladder():+ """LINE with a noise band. 07_performance/memory_ladder.tsv."""+ fig, ax = plt.subplots(figsize=(9.4, 4.4))+ mean = float(np.mean(LADDER_SEC))+ ax.axhspan(mean * 0.835, mean * 1.165, color="#f3f4f6", zorder=0)+ ax.text(8.4, mean * 1.19, "the measured 33% noise band", fontsize=9.5, color=MUTE)+ ax.plot(LADDER_GB, LADDER_SEC, marker="o", color=BLUE, linewidth=2)+ for g, s in ((8, 32.69), (224, 19.21)):+ ax.annotate(f"{s:.2f} s/token", xy=(g, s), xytext=(g * 1.1, s + 2.4),+ fontsize=10, color=INK, fontweight="bold")+ ax.set_xscale("log", base=2)+ ax.set_xticks(LADDER_GB)+ ax.set_xticklabels([str(g) for g in LADDER_GB], fontsize=9)+ ax.set_ylim(15, 38)+ style(ax, "28x the memory buys 1.70x the speed, and most steps are inside the noise",+ "memory budget (GB, log scale)", "seconds per token")+ save(fig, "memory_ladder")+++def gb_read_shelf():+ """STEP. The flat 25.83 GB/token shelf, then the break."""+ fig, ax = plt.subplots(figsize=(9.4, 4.2))+ xs = np.arange(12)+ ax.step(xs, LADDER_READ, where="mid", color=BLUE, linewidth=2.4)+ ax.fill_between(xs, LADDER_READ, step="mid", color=BLUE, alpha=0.10)+ ax.axvspan(-0.5, 6.5, color="#fdeaea", zorder=0)+ ax.scatter(xs[:7], LADDER_READ[:7], s=60, color=RED, zorder=3)+ ax.scatter(xs[7:], LADDER_READ[7:], s=60, color=GREEN, zorder=3)+ ax.set_xticks(xs)+ ax.set_xticklabels([str(g) for g in LADDER_GB], fontsize=9)+ ax.set_ylim(0, 32)+ ax.annotate("seven budgets, a 48x bigger cache,\nand not one byte of difference",+ xy=(3, 25.83), xytext=(0.0, 8.5), fontsize=10, color=RED,+ arrowprops=dict(arrowstyle="->", color=RED))+ ax.text(8.2, 20.6, "the cache finally engages", fontsize=10, color=GREEN)+ style(ax, "The expert cache does nothing at all until about 36 GB of arena",+ "memory budget (GB)", "gigabytes read per token")+ save(fig, "gb_read_shelf")+++def rss_fidelity():+ """SCATTER against the identity line."""+ fig, ax = plt.subplots(figsize=(8.8, 4.2))+ ax.plot([0, 240], [0, 240], color="#d1d5db", linestyle="--", linewidth=1.2)+ ax.scatter(LADDER_GB, LADDER_RSS, s=70, color=BLUE, zorder=3)+ ax.annotate("8 GB asked, 8.24 GB used", xy=(8, 8.24), xytext=(24, 30),+ fontsize=10, color=INK, arrowprops=dict(arrowstyle="->", color=MUTE))+ ax.annotate("224 GB asked, 223.82 GB used", xy=(224, 223.82), xytext=(96, 196),+ fontsize=10, color=INK, arrowprops=dict(arrowstyle="->", color=MUTE))+ ax.set_xlim(0, 245); ax.set_ylim(0, 245)+ style(ax, "The memory plan is not lying: every rung lands on its own budget",+ "budget requested (GB)", "peak RSS measured (GB)")+ save(fig, "rss_fidelity")+++def sim_vs_measured():+ """LINE. Simulated LRU against measured retention."""+ fig, ax = plt.subplots(figsize=(9.2, 4.2))+ ax.plot([8, 16, 32, 64, 128, 192], [36.24, 36.24, 36.24, 36.24, 49.19, 90.00],+ marker="s", color=AMBER, linewidth=2, linestyle="--",+ label="simulated LRU (an upper bound)")+ ax.plot(LADDER_CACHE, LADDER_HITT, marker="o", color=BLUE, linewidth=2,+ label="measured retention")+ ax.set_xscale("log", base=2); ax.set_ylim(-4, 100)+ ax.annotate("the simulated trace re-prefills\nand manufactures reuse", xy=(10, 20),+ xytext=(1.1, 62), fontsize=10, color=RED,+ arrowprops=dict(arrowstyle="->", color=RED))+ ax.legend(frameon=False, fontsize=9.5, loc="lower right")+ style(ax, "Replay predicts a floor of 36%, steady-state decode measures zero",+ "expert cache arena (GB, log scale)", "hit rate (%)")+ save(fig, "sim_vs_measured")+++def cache_wakeup():+ """LINE. rung_8gb.log against rung_96gb.log per-step READ GB."""+ r8 = [99.70, 25.83, 25.83, 25.83, 25.83, 25.83, 25.83, 25.83]+ r96 = [99.70, 23.58, 19.90, 14.07, 12.34, 12.79, 15.14, 18.11]+ fig, ax = plt.subplots(figsize=(9.2, 4.2))+ ax.plot(range(8), r8, marker="o", color=RED, linewidth=2, label="8 GB budget")+ ax.plot(range(8), r96, marker="s", color=GREEN, linewidth=2, label="96 GB budget")+ ax.fill_between(range(8), r96, r8, color="#eafcef", zorder=0)+ ax.set_ylim(0, 112)+ ax.text(2.4, 28, "flat: nothing is retained", fontsize=10, color=RED)+ ax.text(3.2, 8, "declining: the cache is finally holding experts",+ fontsize=10, color=GREEN)+ ax.legend(frameon=False, fontsize=9.5, loc="upper right")+ style(ax, "What a working expert cache actually looks like, step by step",+ "generation step", "gigabytes read")+ save(fig, "cache_wakeup")+++def hit_metrics():+ """LINE, three definitions of one number."""+ fig, ax = plt.subplots(figsize=(9.2, 4.2))+ ax.plot(LADDER_GB, [100.0] * 11 + [99.93], marker="^", color=RED,+ linewidth=2, label="counted at request time")+ ax.plot(LADDER_GB, [0.0] * 12, marker="v", color=ORANGE, linewidth=2,+ label="counted as resident before the step")+ ax.plot(LADDER_GB, LADDER_HITT, marker="o", color=BLUE, linewidth=2,+ label="derived: 1 - evictions/requests")+ ax.set_xscale("log", base=2); ax.set_ylim(-6, 110)+ ax.legend(frameon=False, fontsize=9.5, loc="center left")+ style(ax, "Three definitions of one number, and only the third agrees with the bytes",+ "memory budget (GB, log scale)", "reported hit rate (%)")+ save(fig, "hit_metrics")+++def io_share():+ """LOLLIPOP with a 50% reference. memory_ladder.tsv io_share."""+ fig, ax = plt.subplots(figsize=(9.4, 4.0))+ xs = np.arange(12)+ ax.vlines(xs, 0, LADDER_IO, color=BLUE, linewidth=2.2, zorder=2)+ ax.scatter(xs, LADDER_IO, s=95, color=BLUE, zorder=3)+ ax.axhline(50, color=RED, linestyle="--", linewidth=1.3)+ ax.text(0.0, 64, "above this line, more than half the wall clock is waiting on disk",+ fontsize=9.5, color=RED)+ for x, v in zip(xs, LADDER_IO):+ ax.text(x, v + 2.2, f"{v:.0f}", ha="center", fontsize=8.5, color=MUTE)+ ax.set_xticks(xs); ax.set_xticklabels([str(g) for g in LADDER_GB], fontsize=9)+ ax.set_ylim(0, 72)+ style(ax, "This is an I/O problem at every budget, from 8 GB to 224 GB",+ "memory budget (GB)", "I/O share of wall clock (%)")+ save(fig, "io_share")+++# ============================================================ ALLOCATION++def trunk_cache_split():+ """LINE, two series. deep/engine/trunk_cache_split.tsv."""+ t32 = [2.7, 6.8, 10.8, 16.2, 21.6, 25.6]+ s32 = [31.23, 30.58, 31.25, 30.88, 29.13, 28.06]+ t128 = [12.3, 30.8, 49.2, 73.8, 98.4, 110.0]+ s128 = [28.38, 25.20, 25.69, 18.37, 19.46, 16.80]+ fig, ax = plt.subplots(figsize=(9.2, 4.4))+ ax.plot(t32, s32, marker="s", color=AMBER, linewidth=2, label="32 GB total")+ ax.plot(t128, s128, marker="o", color=BLUE, linewidth=2, label="128 GB total")+ ax.annotate("28.38", xy=(12.3, 28.38), xytext=(6, 31.4), fontsize=10, color=BLUE)+ ax.annotate("16.80, same total memory", xy=(110.0, 16.80), xytext=(64, 14.6),+ fontsize=10, color=GREEN, fontweight="bold",+ arrowprops=dict(arrowstyle="->", color=GREEN))+ ax.legend(frameon=False, fontsize=9.5)+ ax.set_ylim(13, 34)+ style(ax, "At a fixed budget, giving the trunk more is 1.69x faster",+ "gigabytes given to the trunk", "seconds per token")+ save(fig, "trunk_cache_split")+++def bytes_paradox():+ """SCATTER with a colour dimension. The six 128 GB rows."""+ read = [14.46, 14.74, 17.06, 17.51, 25.83, 25.83]+ sec = [28.38, 25.20, 25.69, 18.37, 19.46, 16.80]+ hit = [44.02, 42.93, 33.97, 32.20, 0.0, 0.0]+ fig, ax = plt.subplots(figsize=(9.2, 4.4))+ sc = ax.scatter(read, sec, s=170, c=hit, cmap="coolwarm_r", zorder=3,+ edgecolor="white", linewidth=1.5)+ ax.annotate("slowest run\n44.0% cache hit\n14.46 GB read",+ xy=(14.46, 28.38), xytext=(15.6, 29.4), fontsize=9.5, color=RED)+ ax.annotate("fastest run\n0.0% cache hit\n25.83 GB read",+ xy=(25.83, 16.80), xytext=(19.2, 15.0), fontsize=9.5, color=GREEN,+ fontweight="bold", arrowprops=dict(arrowstyle="->", color=GREEN))+ cb = fig.colorbar(sc, ax=ax)+ cb.set_label("expert cache hit rate (%)", fontsize=10, color=MUTE)+ cb.ax.tick_params(colors=MUTE, labelsize=9)+ ax.set_ylim(14, 31)+ style(ax, "The winner reads 79% more expert bytes and still wins",+ "gigabytes read per token", "seconds per token")+ save(fig, "bytes_paradox")+++# ============================================================ SPREAD++def replication_noise():+ """INTERVAL / dot plot with mean and band. replication.md."""+ sec = [14.78, 14.67, 20.14]+ mean, sd = 16.53, 3.13+ fig, ax = plt.subplots(figsize=(8.8, 3.6))+ ax.axhspan(mean - sd, mean + sd, color="#f3f4f6", zorder=0)+ ax.axhline(mean, color=MUTE, linestyle="--", linewidth=1.4)+ ax.scatter(range(3), sec, s=180, color=[BLUE, BLUE, RED], zorder=3)+ for x, v in zip(range(3), sec):+ ax.text(x, v + 0.55, f"{v:.2f}", ha="center", fontsize=11,+ color=INK, fontweight="bold")+ ax.annotate("", xy=(2.42, 14.67), xytext=(2.42, 20.14),+ arrowprops=dict(arrowstyle="<->", color=RED, linewidth=1.6))+ ax.text(2.50, 17.4, "spread\n33.1%", fontsize=10.5, color=RED, fontweight="bold",+ va="center")+ ax.text(-0.42, mean + 0.25, f"mean {mean}, sd {sd}", fontsize=10, color=MUTE)+ ax.set_xticks(range(3))+ ax.set_xticklabels(["run 1", "run 2", "run 3"], fontsize=10.5)+ ax.set_xlim(-0.5, 2.9); ax.set_ylim(12.5, 22)+ style(ax, "Same binary, same prompt, same flags, same machine, same minute",+ None, "seconds per token")+ save(fig, "replication_noise")+++def duplicate_config():+ """DUMBBELL. rung_128gb.log against p2_128_0.60.log."""+ fig, ax = plt.subplots(figsize=(9.4, 3.2))+ dumbbell(ax, ["gigabytes read", "trunk bandwidth (MB/s ÷ 100)", "seconds per token"],+ [374.99, 27.09, 29.40], [374.99, 58.74, 18.37], GRAY, GREEN,+ "run A", "run B", fmt="{:,.2f}")+ ax.legend(frameon=False, fontsize=9.5, loc="lower right")+ ax.set_xlim(-20, 430)+ style(ax, "One configuration measured twice: identical work, very different clocks",+ grid="x")+ save(fig, "duplicate_config")+++# ============================================================ PRECISION++def quant_error():+ """INTERVAL plot: mean with the p99-to-max range. quant_study.json."""+ names = ["L1.v_proj", "L1.g_proj", "L5.v_proj", "L5.o_proj", "L9.k_proj",+ "L9.g_proj", "L9.o_proj", "L3.o_proj", "L3.g_proj", "L7.kv_b_proj",+ "L7.o_proj"]+ i8 = [0.00926, 0.00895, 0.00916, 0.01029, 0.00914, 0.00898, 0.01020,+ 0.01090, 0.01092, 0.00741, 0.01099]+ i4m = [0.16811, 0.16233, 0.16614, 0.18670, 0.16568, 0.16286, 0.18512,+ 0.19774, 0.19801, 0.13427, 0.19919]+ i4x = [0.22531, 0.21741, 0.24928, 0.45223, 0.26996, 0.26282, 0.55945,+ 0.28295, 0.42202, 0.20659, 0.64514]+ fig, ax = plt.subplots(figsize=(9.6, 4.4))+ ys = np.arange(len(names))[::-1]+ for y, m, x in zip(ys, i4m, i4x):+ ax.plot([m * 100, x * 100], [y, y], color="#fca5a5", linewidth=3, zorder=2)+ ax.scatter([v * 100 for v in i4x], ys, s=40, color=INK, zorder=4,+ label="int4 worst row")+ ax.scatter([v * 100 for v in i4m], ys, s=110, color=RED, zorder=4,+ label="int4 mean")+ ax.scatter([v * 100 for v in i8], ys, s=110, color=GREEN, zorder=4,+ label="int8 mean")+ ax.set_yticks(ys); ax.set_yticklabels(names, fontsize=9)+ ax.legend(frameon=False, fontsize=9.5, loc="upper right")+ ax.set_xlim(0, 74)+ style(ax, "int8 costs about 1%, int4 costs about 17%, and its worst rows cost 65%",+ "mean relative weight error (%)", grid="x")+ save(fig, "quant_error")+++def quant_by_layer_type():+ """DOT PLOT. quant_sensitivity.txt means by layer type."""+ kinds = ["KDA layers\n(n=2)", "MLA layers\n(n=18)", "all sampled\n(n=31)"]+ i8, i4 = [1.046, 0.948, 0.961], [18.746, 17.154, 17.383]+ fig, ax = plt.subplots(figsize=(8.8, 3.4))+ dumbbell(ax, kinds, i8, i4, GREEN, RED, "int8", "int4", fmt="{:.2f}%")+ ax.legend(frameon=False, fontsize=9.5, loc="center right")+ ax.set_xlim(0, 23)+ style(ax, "No layer type tolerates 4 bits any better than the others",+ "mean relative weight error (%)", grid="x")+ save(fig, "quant_by_layer_type")+++def whats_missing():+ """STACKED PROPORTION, where one part is meant to be invisible."""+ total, vis = 1560.94, 0.89+ fig, ax = plt.subplots(figsize=(9.0, 2.4))+ ax.barh([0], [total - vis], color=GREEN, edgecolor="white", height=0.42,+ label="implemented (text path)")+ ax.barh([0], [vis], left=total - vis, color=RED, edgecolor="white",+ height=0.42, hatch="//", label="absent (vision tower)")+ ax.annotate("0.89 GB, or 0.057% of the checkpoint,\nfully specified and entirely uncoded",+ xy=(total, 0.24), xytext=(880, 0.60), fontsize=9.5, color=RED,+ arrowprops=dict(arrowstyle="->", color=RED))+ ax.set_yticks([]); ax.set_xlim(0, 1720)+ ax.legend(frameon=False, fontsize=9.5, loc="lower left")+ style(ax, "What this engine does not implement, drawn to scale", "gigabytes",+ grid=None)+ save(fig, "whats_missing")+++FNS = [fit_cascade, bytes_census, preset_ladder, binary_sizes, shard_sizes,+ roundtrip_sizes, mxfp4_savings, token_time_split, context_scaling,+ kv_layout, activation_spikes, expert_reuse, pack_progress,+ resident_vs_streamed, storage_regimes, belady_vs_lru, gate_ladder,+ layer_conformance, same_answer, step_trace, prefill_cost, memory_ladder,+ gb_read_shelf, rss_fidelity, sim_vs_measured, cache_wakeup, hit_metrics,+ io_share, trunk_cache_split, bytes_paradox, replication_noise,+ duplicate_config, quant_error, quant_by_layer_type, whats_missing]++ok = 0+for fn in FNS:+ try:+ fn()+ ok += 1+ except Exception as e:+ print(f" FAILED {fn.__name__}: {type(e).__name__}: {e}")+print(f"done: {ok}/{len(FNS)} plots rendered")diff --git a/docs/images/activation_spikes.png b/docs/images/activation_spikes.pngnew file mode 100644index 0000000..7200a85Binary files /dev/null and b/docs/images/activation_spikes.png differdiff --git a/docs/images/attn-res.mmd b/docs/images/attn-res.mmdnew file mode 100644index 0000000..734f29b--- /dev/null+++ b/docs/images/attn-res.mmd@@ -0,0 +1,13 @@+flowchart LR+ E["embedding<br/>always source 0"] --> SM{"softmax over<br/>every source"}+ B1["block 1<br/>output"] --> SM+ B2["block 2<br/>output"] --> SM+ NOW["running prefix<br/>this block"] --> SM+ SM --> H["new h<br/>replaces the old"]+ NOW -.->|"every 12 layers:<br/>snapshot and clear"| B2+ style E fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style B1 fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style B2 fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style NOW fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style SM fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style H fill:#E7ECDD,stroke:#6E9160,color:#3B372Fdiff --git a/docs/images/attn-res.png b/docs/images/attn-res.pngnew file mode 100644index 0000000..921b465Binary files /dev/null and b/docs/images/attn-res.png differdiff --git a/docs/images/belady_vs_lru.png b/docs/images/belady_vs_lru.pngnew file mode 100644index 0000000..469651fBinary files /dev/null and b/docs/images/belady_vs_lru.png differdiff --git a/docs/images/big-picture.mmd b/docs/images/big-picture.mmdnew file mode 100644index 0000000..f1137b4--- /dev/null+++ b/docs/images/big-picture.mmd@@ -0,0 +1,11 @@+flowchart LR+ D["NVMe<br/>1.45 TB experts"] --> T["trunk.bin<br/>108.81 GB packed"]+ T --> PIN["pinned layers<br/>in RAM"]+ D --> C["expert cache<br/>17.56 MB slots"]+ PIN --> TOK["next token<br/>8.24 GB peak RSS"]+ C --> TOK+ style D fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style T fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style PIN fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style C fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style TOK fill:#E7ECDD,stroke:#6E9160,color:#3B372Fdiff --git a/docs/images/big-picture.png b/docs/images/big-picture.pngnew file mode 100644index 0000000..5e22ea8Binary files /dev/null and b/docs/images/big-picture.png differdiff --git a/docs/images/binary_sizes.png b/docs/images/binary_sizes.pngnew file mode 100644index 0000000..8d6be9dBinary files /dev/null and b/docs/images/binary_sizes.png differdiff --git a/docs/images/build-flow.mmd b/docs/images/build-flow.mmdnew file mode 100644index 0000000..241df73--- /dev/null+++ b/docs/images/build-flow.mmd@@ -0,0 +1,12 @@+flowchart LR+ SRC["6 C files<br/>+ 2 headers"] --> CC["cc -O3 -fopenmp<br/>-ffp-contract=off"]+ CC --> BIN["bin/k3<br/>179,736 bytes"]+ CC --> T["7 test binaries"]+ T --> G["22 passed<br/>0 failed"]+ BIN --> RUN["runs a 1.56 TB model"]+ style SRC fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style CC fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style BIN fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style T fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style G fill:#DDEBE7,stroke:#4E8E86,color:#3B372F+ style RUN fill:#EAE4F1,stroke:#7E6E9C,color:#3B372Fdiff --git a/docs/images/build-flow.png b/docs/images/build-flow.pngnew file mode 100644index 0000000..53e60aeBinary files /dev/null and b/docs/images/build-flow.png differdiff --git a/docs/images/bytes_census.png b/docs/images/bytes_census.pngnew file mode 100644index 0000000..ce1fd7eBinary files /dev/null and b/docs/images/bytes_census.png differdiff --git a/docs/images/bytes_paradox.png b/docs/images/bytes_paradox.pngnew file mode 100644index 0000000..a6a51ceBinary files /dev/null and b/docs/images/bytes_paradox.png differdiff --git a/docs/images/cache-3phase.mmd b/docs/images/cache-3phase.mmdnew file mode 100644index 0000000..90e3bc5--- /dev/null+++ b/docs/images/cache-3phase.mmd@@ -0,0 +1,12 @@+flowchart LR+ R["16 expert ids<br/>from the router"] --> P1["phase 1<br/>reserve slots serially"]+ P1 --> P2["phase 2<br/>pread in disk order"]+ P2 --> P3["phase 3<br/>publish what arrived"]+ P3 --> USE["matmul straight<br/>from the nibbles"]+ P2 -.->|"queue depth 16,<br/>not 1"| DEV["the device<br/>stays busy"]+ style R fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style P1 fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style P2 fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style P3 fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style USE fill:#DDEBE7,stroke:#4E8E86,color:#3B372F+ style DEV fill:#ECE8E0,stroke:#8C8477,color:#3B372Fdiff --git a/docs/images/cache-3phase.png b/docs/images/cache-3phase.pngnew file mode 100644index 0000000..3c9e2c7Binary files /dev/null and b/docs/images/cache-3phase.png differdiff --git a/docs/images/cache-slot-states.mmd b/docs/images/cache-slot-states.mmdnew file mode 100644index 0000000..e4098e2--- /dev/null+++ b/docs/images/cache-slot-states.mmd@@ -0,0 +1,10 @@+flowchart LR+ E["EMPTY"] --> I["INFLIGHT<br/>reserved, not readable"]+ I --> RDY["ready<br/>holds expert e"]+ RDY -->|"evicted"| E+ I -.->|"read failed"| E+ RDY --> HIT["hit: reuse"]+ style E fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style I fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style RDY fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style HIT fill:#DDEBE7,stroke:#4E8E86,color:#3B372Fdiff --git a/docs/images/cache-slot-states.png b/docs/images/cache-slot-states.pngnew file mode 100644index 0000000..6989951Binary files /dev/null and b/docs/images/cache-slot-states.png differdiff --git a/docs/images/cache_wakeup.png b/docs/images/cache_wakeup.pngnew file mode 100644index 0000000..3225e8fBinary files /dev/null and b/docs/images/cache_wakeup.png differdiff --git a/docs/images/config-guard.mmd b/docs/images/config-guard.mmdnew file mode 100644index 0000000..a4bd763--- /dev/null+++ b/docs/images/config-guard.mmd@@ -0,0 +1,12 @@+flowchart LR+ J["config.json"] --> R["k3_cfg_load"]+ R --> Q{"every field<br/>present?"}+ Q -->|"yes"| OK["93 layers<br/>24 MLA + 69 KDA"]+ Q -->|"no"| STOP["refuse to start<br/>name the field"]+ STOP -.->|"the old reader<br/>guessed here"| WRONG["all 93 layers KDA<br/>fluent and wrong"]+ style J fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style R fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style Q fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style OK fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style STOP fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style WRONG fill:#F5E2DB,stroke:#B75845,color:#3B372Fdiff --git a/docs/images/config-guard.png b/docs/images/config-guard.pngnew file mode 100644index 0000000..cc17004Binary files /dev/null and b/docs/images/config-guard.png differdiff --git a/docs/images/context_scaling.png b/docs/images/context_scaling.pngnew file mode 100644index 0000000..43d9d46Binary files /dev/null and b/docs/images/context_scaling.png differdiff --git a/docs/images/decoder-layer.mmd b/docs/images/decoder-layer.mmdnew file mode 100644index 0000000..8feb564--- /dev/null+++ b/docs/images/decoder-layer.mmd@@ -0,0 +1,14 @@+flowchart LR+ H["h in"] --> A1["aggregate over<br/>earlier blocks"]+ A1 --> ATT["attention<br/>KDA or MLA"]+ ATT --> A2["aggregate again<br/>no guard"]+ A2 --> M["MoE<br/>or dense FFN"]+ M --> HO["h out"]+ A1 -.->|"every 12 layers"| SNAP["snapshot<br/>and clear"]+ style H fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style A1 fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style ATT fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style A2 fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style M fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style HO fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style SNAP fill:#DDEBE7,stroke:#4E8E86,color:#3B372Fdiff --git a/docs/images/decoder-layer.png b/docs/images/decoder-layer.pngnew file mode 100644index 0000000..af6d098Binary files /dev/null and b/docs/images/decoder-layer.png differdiff --git a/docs/images/duplicate_config.png b/docs/images/duplicate_config.pngnew file mode 100644index 0000000..28d8e19Binary files /dev/null and b/docs/images/duplicate_config.png differdiff --git a/docs/images/eq_absmax.png b/docs/images/eq_absmax.pngnew file mode 100644index 0000000..f1721caBinary files /dev/null and b/docs/images/eq_absmax.png differdiff --git a/docs/images/eq_accum_order.png b/docs/images/eq_accum_order.pngnew file mode 100644index 0000000..84ca4cdBinary files /dev/null and b/docs/images/eq_accum_order.png differdiff --git a/docs/images/eq_align.png b/docs/images/eq_align.pngnew file mode 100644index 0000000..dd5973cBinary files /dev/null and b/docs/images/eq_align.png differdiff --git a/docs/images/eq_attn_res.png b/docs/images/eq_attn_res.pngnew file mode 100644index 0000000..92499a0Binary files /dev/null and b/docs/images/eq_attn_res.png differdiff --git a/docs/images/eq_bf16_widen.png b/docs/images/eq_bf16_widen.pngnew file mode 100644index 0000000..6b64a52Binary files /dev/null and b/docs/images/eq_bf16_widen.png differdiff --git a/docs/images/eq_block_count.png b/docs/images/eq_block_count.pngnew file mode 100644index 0000000..361d315Binary files /dev/null and b/docs/images/eq_block_count.png differdiff --git a/docs/images/eq_bytes_per_weight.png b/docs/images/eq_bytes_per_weight.pngnew file mode 100644index 0000000..7bb0bbeBinary files /dev/null and b/docs/images/eq_bytes_per_weight.png differdiff --git a/docs/images/eq_compulsory.png b/docs/images/eq_compulsory.pngnew file mode 100644index 0000000..6a06538Binary files /dev/null and b/docs/images/eq_compulsory.png differdiff --git a/docs/images/eq_context_ceiling.png b/docs/images/eq_context_ceiling.pngnew file mode 100644index 0000000..a352818Binary files /dev/null and b/docs/images/eq_context_ceiling.png differdiff --git a/docs/images/eq_dequant_cost.png b/docs/images/eq_dequant_cost.pngnew file mode 100644index 0000000..57e7ed1Binary files /dev/null and b/docs/images/eq_dequant_cost.png differdiff --git a/docs/images/eq_fit_ledger.png b/docs/images/eq_fit_ledger.pngnew file mode 100644index 0000000..ccd25aeBinary files /dev/null and b/docs/images/eq_fit_ledger.png differdiff --git a/docs/images/eq_gb_per_layer.png b/docs/images/eq_gb_per_layer.pngnew file mode 100644index 0000000..d0ee586Binary files /dev/null and b/docs/images/eq_gb_per_layer.png differdiff --git a/docs/images/eq_io_share.png b/docs/images/eq_io_share.pngnew file mode 100644index 0000000..0432043Binary files /dev/null and b/docs/images/eq_io_share.png differdiff --git a/docs/images/eq_kda_decay.png b/docs/images/eq_kda_decay.pngnew file mode 100644index 0000000..84907bcBinary files /dev/null and b/docs/images/eq_kda_decay.png differdiff --git a/docs/images/eq_kda_gate.png b/docs/images/eq_kda_gate.pngnew file mode 100644index 0000000..5309c74Binary files /dev/null and b/docs/images/eq_kda_gate.png differdiff --git a/docs/images/eq_kda_recurrence.png b/docs/images/eq_kda_recurrence.pngnew file mode 100644index 0000000..4a81d76Binary files /dev/null and b/docs/images/eq_kda_recurrence.png differdiff --git a/docs/images/eq_kda_state.png b/docs/images/eq_kda_state.pngnew file mode 100644index 0000000..1f68120Binary files /dev/null and b/docs/images/eq_kda_state.png differdiff --git a/docs/images/eq_kv_compression.png b/docs/images/eq_kv_compression.pngnew file mode 100644index 0000000..1c4baadBinary files /dev/null and b/docs/images/eq_kv_compression.png differdiff --git a/docs/images/eq_l2norm.png b/docs/images/eq_l2norm.pngnew file mode 100644index 0000000..b7401baBinary files /dev/null and b/docs/images/eq_l2norm.png differdiff --git a/docs/images/eq_layer_map.png b/docs/images/eq_layer_map.pngnew file mode 100644index 0000000..b429e3aBinary files /dev/null and b/docs/images/eq_layer_map.png differdiff --git a/docs/images/eq_mla_kv.png b/docs/images/eq_mla_kv.pngnew file mode 100644index 0000000..df9faaaBinary files /dev/null and b/docs/images/eq_mla_kv.png differdiff --git a/docs/images/eq_mla_latent.png b/docs/images/eq_mla_latent.pngnew file mode 100644index 0000000..6aa255cBinary files /dev/null and b/docs/images/eq_mla_latent.png differdiff --git a/docs/images/eq_moe_latent.png b/docs/images/eq_moe_latent.pngnew file mode 100644index 0000000..f7e129bBinary files /dev/null and b/docs/images/eq_moe_latent.png differdiff --git a/docs/images/eq_mxfp4.png b/docs/images/eq_mxfp4.pngnew file mode 100644index 0000000..dd15ad0Binary files /dev/null and b/docs/images/eq_mxfp4.png differdiff --git a/docs/images/eq_naive_memory.png b/docs/images/eq_naive_memory.pngnew file mode 100644index 0000000..aaabc1aBinary files /dev/null and b/docs/images/eq_naive_memory.png differdiff --git a/docs/images/eq_nibble_pack.png b/docs/images/eq_nibble_pack.pngnew file mode 100644index 0000000..c78b02fBinary files /dev/null and b/docs/images/eq_nibble_pack.png differdiff --git a/docs/images/eq_prefetch.png b/docs/images/eq_prefetch.pngnew file mode 100644index 0000000..201ebbcBinary files /dev/null and b/docs/images/eq_prefetch.png differdiff --git a/docs/images/eq_prefill.png b/docs/images/eq_prefill.pngnew file mode 100644index 0000000..5d032cbBinary files /dev/null and b/docs/images/eq_prefill.png differdiff --git a/docs/images/eq_queue_depth.png b/docs/images/eq_queue_depth.pngnew file mode 100644index 0000000..45e787dBinary files /dev/null and b/docs/images/eq_queue_depth.png differdiff --git a/docs/images/eq_ram_budget.png b/docs/images/eq_ram_budget.pngnew file mode 100644index 0000000..470f3c5Binary files /dev/null and b/docs/images/eq_ram_budget.png differdiff --git a/docs/images/eq_resident_set.png b/docs/images/eq_resident_set.pngnew file mode 100644index 0000000..1030770Binary files /dev/null and b/docs/images/eq_resident_set.png differdiff --git a/docs/images/eq_retention.png b/docs/images/eq_retention.pngnew file mode 100644index 0000000..eb0272eBinary files /dev/null and b/docs/images/eq_retention.png differdiff --git a/docs/images/eq_rmsnorm.png b/docs/images/eq_rmsnorm.pngnew file mode 100644index 0000000..5459e94Binary files /dev/null and b/docs/images/eq_rmsnorm.png differdiff --git a/docs/images/eq_router.png b/docs/images/eq_router.pngnew file mode 100644index 0000000..c48f32eBinary files /dev/null and b/docs/images/eq_router.png differdiff --git a/docs/images/eq_shortconv.png b/docs/images/eq_shortconv.pngnew file mode 100644index 0000000..04e1035Binary files /dev/null and b/docs/images/eq_shortconv.png differdiff --git a/docs/images/eq_situ_glu.png b/docs/images/eq_situ_glu.pngnew file mode 100644index 0000000..afcca81Binary files /dev/null and b/docs/images/eq_situ_glu.png differdiff --git a/docs/images/eq_slot_count.png b/docs/images/eq_slot_count.pngnew file mode 100644index 0000000..8ef5361Binary files /dev/null and b/docs/images/eq_slot_count.png differdiff --git a/docs/images/eq_sparsity_ratio.png b/docs/images/eq_sparsity_ratio.pngnew file mode 100644index 0000000..ba87487Binary files /dev/null and b/docs/images/eq_sparsity_ratio.png differdiff --git a/docs/images/eq_spread.png b/docs/images/eq_spread.pngnew file mode 100644index 0000000..b18000cBinary files /dev/null and b/docs/images/eq_spread.png differdiff --git a/docs/images/eq_st_layout.png b/docs/images/eq_st_layout.pngnew file mode 100644index 0000000..31ed00cBinary files /dev/null and b/docs/images/eq_st_layout.png differdiff --git a/docs/images/eq_stream_vs_quantize.png b/docs/images/eq_stream_vs_quantize.pngnew file mode 100644index 0000000..60441f2Binary files /dev/null and b/docs/images/eq_stream_vs_quantize.png differdiff --git a/docs/images/eq_tolerance.png b/docs/images/eq_tolerance.pngnew file mode 100644index 0000000..7c50846Binary files /dev/null and b/docs/images/eq_tolerance.png differdiff --git a/docs/images/eq_traffic.png b/docs/images/eq_traffic.pngnew file mode 100644index 0000000..7be25d8Binary files /dev/null and b/docs/images/eq_traffic.png differdiff --git a/docs/images/eq_trunk_hit.png b/docs/images/eq_trunk_hit.pngnew file mode 100644index 0000000..abe072cBinary files /dev/null and b/docs/images/eq_trunk_hit.png differdiff --git a/docs/images/eq_working_set.png b/docs/images/eq_working_set.pngnew file mode 100644index 0000000..5f27178Binary files /dev/null and b/docs/images/eq_working_set.png differdiff --git a/docs/images/expert_reuse.png b/docs/images/expert_reuse.pngnew file mode 100644index 0000000..fab883fBinary files /dev/null and b/docs/images/expert_reuse.png differdiff --git a/docs/images/first-token.mmd b/docs/images/first-token.mmdnew file mode 100644index 0000000..87e0017--- /dev/null+++ b/docs/images/first-token.mmd@@ -0,0 +1,14 @@+flowchart LR+ P["prompt<br/>The capital of France is"] --> E["tokenize<br/>5 ids"]+ E --> F["93 layers<br/>69 KDA + 24 MLA"]+ F --> L["163,840 logits<br/>one per token"]+ L --> A["argmax<br/>17374"]+ A --> D["decodes to<br/>Paris"]+ L -.->|"greedy only,<br/>no sampling"| X["the other 163,839<br/>are discarded"]+ style P fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style E fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style F fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style L fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style A fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style D fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style X fill:#DDEBE7,stroke:#4E8E86,color:#3B372Fdiff --git a/docs/images/first-token.png b/docs/images/first-token.pngnew file mode 100644index 0000000..d30094bBinary files /dev/null and b/docs/images/first-token.png differdiff --git a/docs/images/fit_cascade.png b/docs/images/fit_cascade.pngnew file mode 100644index 0000000..ed83666Binary files /dev/null and b/docs/images/fit_cascade.png differdiff --git a/docs/images/forward-pass.mmd b/docs/images/forward-pass.mmdnew file mode 100644index 0000000..3e232e0--- /dev/null+++ b/docs/images/forward-pass.mmd@@ -0,0 +1,12 @@+flowchart LR+ ID["token ids"] --> EM["embed rows"]+ EM --> LOOP["93 layers<br/>bind, run, prefetch next"]+ LOOP --> AGG["model aggregator<br/>over all snapshots"]+ AGG --> NR["final RMSNorm<br/>last position only"]+ NR --> LG["lm_head<br/>163,840 logits"]+ style ID fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style EM fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style LOOP fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style AGG fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style NR fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style LG fill:#E7ECDD,stroke:#6E9160,color:#3B372Fdiff --git a/docs/images/forward-pass.png b/docs/images/forward-pass.pngnew file mode 100644index 0000000..22f8ba5Binary files /dev/null and b/docs/images/forward-pass.png differdiff --git a/docs/images/gate_ladder.png b/docs/images/gate_ladder.pngnew file mode 100644index 0000000..77ba1a7Binary files /dev/null and b/docs/images/gate_ladder.png differdiff --git a/docs/images/gb_read_shelf.png b/docs/images/gb_read_shelf.pngnew file mode 100644index 0000000..f8921fcBinary files /dev/null and b/docs/images/gb_read_shelf.png differdiff --git a/docs/images/gen-loop.mmd b/docs/images/gen-loop.mmdnew file mode 100644index 0000000..be5cbf3--- /dev/null+++ b/docs/images/gen-loop.mmd@@ -0,0 +1,11 @@+flowchart LR+ P["prompt"] --> PF["step 0: prefill<br/>53 s, 89 GB read"]+ PF --> ST["step n: one token<br/>8.9 s, 25.83 GB"]+ ST --> TOK["append id"]+ TOK --> ST+ ST --> TXT["decode at the end<br/>never mid-token"]+ style P fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style PF fill:#F5E2DB,stroke:#B75845,color:#3B372F+ style ST fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style TOK fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style TXT fill:#E7ECDD,stroke:#6E9160,color:#3B372Fdiff --git a/docs/images/gen-loop.png b/docs/images/gen-loop.pngnew file mode 100644index 0000000..26ce53dBinary files /dev/null and b/docs/images/gen-loop.png differdiff --git a/docs/images/hit_metrics.png b/docs/images/hit_metrics.pngnew file mode 100644index 0000000..70115ecBinary files /dev/null and b/docs/images/hit_metrics.png differdiff --git a/docs/images/hosts-confound.mmd b/docs/images/hosts-confound.mmdnew file mode 100644index 0000000..9b2a720--- /dev/null+++ b/docs/images/hosts-confound.mmd@@ -0,0 +1,12 @@+flowchart LR+ A["run A<br/>31.71 s/token"] --> DA["fast NVMe<br/>3,684 MB/s"]+ B["run B<br/>70.62 s/token"] --> DB["slow volume<br/>733 MB/s"]+ DA --> Q{"is the gap<br/>the code?"}+ DB --> Q+ Q -->|"no"| DISK["it is the disk"]+ style A fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style B fill:#F5E2DB,stroke:#B75845,color:#3B372F+ style DA fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style DB fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style Q fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style DISK fill:#F2E9D4,stroke:#C0913E,color:#3B372Fdiff --git a/docs/images/hosts-confound.png b/docs/images/hosts-confound.pngnew file mode 100644index 0000000..ce9d6c8Binary files /dev/null and b/docs/images/hosts-confound.png differdiff --git a/docs/images/io_share.png b/docs/images/io_share.pngnew file mode 100644index 0000000..7bda32fBinary files /dev/null and b/docs/images/io_share.png differdiff --git a/docs/images/kda-flow.mmd b/docs/images/kda-flow.mmdnew file mode 100644index 0000000..45bbe44--- /dev/null+++ b/docs/images/kda-flow.mmd@@ -0,0 +1,14 @@+flowchart LR+ X["token in<br/>q, k, v projected"] --> CV["ShortConv k=4<br/>fused SiLU"]+ CV --> N["L2Norm<br/>q and k only"]+ N --> ST["decay, then<br/>write the delta"]+ ST --> RD["read the<br/>UPDATED state"]+ RD --> G["RMSNorm<br/>then gate"]+ ST -.->|"carried forward"| S["one state per layer<br/>626 MB in total"]+ style X fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style CV fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style N fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style ST fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style RD fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style G fill:#DDEBE7,stroke:#4E8E86,color:#3B372F+ style S fill:#ECE8E0,stroke:#8C8477,color:#3B372Fdiff --git a/docs/images/kda-flow.png b/docs/images/kda-flow.pngnew file mode 100644index 0000000..c1c3f5dBinary files /dev/null and b/docs/images/kda-flow.png differdiff --git a/docs/images/kda-nine-steps.mmd b/docs/images/kda-nine-steps.mmdnew file mode 100644index 0000000..58498de--- /dev/null+++ b/docs/images/kda-nine-steps.mmd@@ -0,0 +1,14 @@+flowchart LR+ P["1. project<br/>q k v beta z"] --> C["2. ShortConv<br/>+ SiLU"]+ C --> N["3. L2Norm<br/>q and k only"]+ N --> B["4/5. beta<br/>and decay"]+ B --> R["6. recurrence<br/>per head"]+ R --> G["7/8/9. norm,<br/>gate, project"]+ R -.->|"state carried"| S["one matrix<br/>per head"]+ style P fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style C fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style N fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style B fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style R fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style G fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style S fill:#DDEBE7,stroke:#4E8E86,color:#3B372Fdiff --git a/docs/images/kda-nine-steps.png b/docs/images/kda-nine-steps.pngnew file mode 100644index 0000000..57f2b43Binary files /dev/null and b/docs/images/kda-nine-steps.png differdiff --git a/docs/images/kda-state.mmd b/docs/images/kda-state.mmdnew file mode 100644index 0000000..71f981c--- /dev/null+++ b/docs/images/kda-state.mmd@@ -0,0 +1,10 @@+flowchart LR+ T1["token 1"] --> S["one state<br/>96 x 128 x 128"]+ T2["token 1000"] --> S+ T3["token 100000"] --> S+ S --> SZ["626.25 MB<br/>always"]+ style T1 fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style T2 fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style T3 fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style S fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style SZ fill:#E7ECDD,stroke:#6E9160,color:#3B372Fdiff --git a/docs/images/kda-state.png b/docs/images/kda-state.pngnew file mode 100644index 0000000..d208d4fBinary files /dev/null and b/docs/images/kda-state.png differdiff --git a/docs/images/kernel-contract.mmd b/docs/images/kernel-contract.mmdnew file mode 100644index 0000000..42952c4--- /dev/null+++ b/docs/images/kernel-contract.mmd@@ -0,0 +1,14 @@+flowchart LR+ W["same weights"] --> SC["scalar path"]+ W --> OMP["OpenMP path"]+ W --> AVX["AVX2 path"]+ SC --> H{"FNV hash<br/>of the output"}+ OMP --> H+ AVX --> H+ H -->|"identical"| OK["bit for bit"]+ style W fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style SC fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style OMP fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style AVX fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style H fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style OK fill:#E7ECDD,stroke:#6E9160,color:#3B372Fdiff --git a/docs/images/kernel-contract.png b/docs/images/kernel-contract.pngnew file mode 100644index 0000000..ce08794Binary files /dev/null and b/docs/images/kernel-contract.png differdiff --git a/docs/images/kv_layout.png b/docs/images/kv_layout.pngnew file mode 100644index 0000000..5686a41Binary files /dev/null and b/docs/images/kv_layout.png differdiff --git a/docs/images/ladder-harness.mmd b/docs/images/ladder-harness.mmdnew file mode 100644index 0000000..3f84fe4--- /dev/null+++ b/docs/images/ladder-harness.mmd@@ -0,0 +1,14 @@+flowchart LR+ B["budget N GB"] --> CG["systemd-run<br/>MemoryMax=NG"]+ CG --> SW["MemorySwapMax=0"]+ SW --> RUN["8 tokens"]+ RUN --> CHK{"same ids as<br/>every other rung?"}+ CHK -->|"yes"| REC["record s/token"]+ CHK -->|"no"| BUG["that is a bug"]+ style B fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style CG fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style SW fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style RUN fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style CHK fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style REC fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style BUG fill:#F5E2DB,stroke:#B75845,color:#3B372Fdiff --git a/docs/images/ladder-harness.png b/docs/images/ladder-harness.pngnew file mode 100644index 0000000..4d1ca57Binary files /dev/null and b/docs/images/ladder-harness.png differdiff --git a/docs/images/layer_conformance.png b/docs/images/layer_conformance.pngnew file mode 100644index 0000000..7fc423aBinary files /dev/null and b/docs/images/layer_conformance.png differdiff --git a/docs/images/machine-model.mmd b/docs/images/machine-model.mmdnew file mode 100644index 0000000..d1da57f--- /dev/null+++ b/docs/images/machine-model.mmd@@ -0,0 +1,11 @@+flowchart LR+ L["laptop<br/>8 GB"] --> D2["desktop<br/>32 GB"]+ D2 --> W["workstation<br/>96 GB"]+ W --> S["our box<br/>228 GB"]+ L -.->|"same 8 tokens"| OUT["identical ids<br/>17374 20829 10 427"]+ S -.-> OUT+ style L fill:#F5E2DB,stroke:#B75845,color:#3B372F+ style D2 fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style W fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style S fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style OUT fill:#E7ECDD,stroke:#6E9160,color:#3B372Fdiff --git a/docs/images/machine-model.png b/docs/images/machine-model.pngnew file mode 100644index 0000000..8b8acd0Binary files /dev/null and b/docs/images/machine-model.png differdiff --git a/docs/images/main_architecture.png b/docs/images/main_architecture.pngnew file mode 100644index 0000000..9cfd7ffBinary files /dev/null and b/docs/images/main_architecture.png differdiff --git a/docs/images/main_architecture_with_spongbob.png b/docs/images/main_architecture_with_spongbob.pngnew file mode 100644index 0000000..f8cc3ffBinary files /dev/null and b/docs/images/main_architecture_with_spongbob.png differdiff --git a/docs/images/memory_ladder.png b/docs/images/memory_ladder.pngnew file mode 100644index 0000000..01e5fb0Binary files /dev/null and b/docs/images/memory_ladder.png differdiff --git a/docs/images/metric-bug.mmd b/docs/images/metric-bug.mmdnew file mode 100644index 0000000..4f0aaa3--- /dev/null+++ b/docs/images/metric-bug.mmd@@ -0,0 +1,14 @@+flowchart LR+ REQ["1472 requests"] --> NAIVE["naive hit<br/>100.0%"]+ REQ --> TRUE["TRUE resident<br/>0.00% always"]+ REQ --> DER["1 - evictions/requests"]+ NAIVE --> BAD["counts disk reads<br/>as hits"]+ TRUE --> BAD2["counter never reset"]+ DER --> GOOD["agrees with the bytes"]+ style REQ fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style NAIVE fill:#F5E2DB,stroke:#B75845,color:#3B372F+ style TRUE fill:#F5E2DB,stroke:#B75845,color:#3B372F+ style DER fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style BAD fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style BAD2 fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style GOOD fill:#E7ECDD,stroke:#6E9160,color:#3B372Fdiff --git a/docs/images/metric-bug.png b/docs/images/metric-bug.pngnew file mode 100644index 0000000..c58510cBinary files /dev/null and b/docs/images/metric-bug.png differdiff --git a/docs/images/mla-latent.mmd b/docs/images/mla-latent.mmdnew file mode 100644index 0000000..9cd667c--- /dev/null+++ b/docs/images/mla-latent.mmd@@ -0,0 +1,12 @@+flowchart LR+ X["token"] --> C["latent<br/>512 + 64 = 576"]+ C --> CACHE["this is what we cache<br/>2.37 MB per position"]+ C --> K["rebuild k and v<br/>on use"]+ K --> A["96 heads<br/>width 192"]+ A --> G["gate then o_proj"]+ style X fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style C fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style CACHE fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style K fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style A fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style G fill:#DDEBE7,stroke:#4E8E86,color:#3B372Fdiff --git a/docs/images/mla-latent.png b/docs/images/mla-latent.pngnew file mode 100644index 0000000..88c2727Binary files /dev/null and b/docs/images/mla-latent.png differdiff --git a/docs/images/moe-dispatch.mmd b/docs/images/moe-dispatch.mmdnew file mode 100644index 0000000..0f6c5c6--- /dev/null+++ b/docs/images/moe-dispatch.mmd@@ -0,0 +1,15 @@+flowchart LR+ H["h 7168"] --> R["router<br/>sigmoid + bias"]+ R --> DN["down to latent<br/>3584"]+ DN --> E16["16 experts<br/>SiTU-GLU"]+ E16 --> NRM["RMSNorm the<br/>AGGREGATE"]+ NRM --> UP["up to 7168"]+ H -.->|"unweighted"| SH["2 shared experts"]+ SH --> UP+ style H fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style R fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style DN fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style E16 fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style NRM fill:#F3E3EB,stroke:#B06885,color:#3B372F+ style UP fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style SH fill:#DDEBE7,stroke:#4E8E86,color:#3B372Fdiff --git a/docs/images/moe-dispatch.png b/docs/images/moe-dispatch.pngnew file mode 100644index 0000000..87f6a29Binary files /dev/null and b/docs/images/moe-dispatch.png differdiff --git a/docs/images/moe-sparsity.mmd b/docs/images/moe-sparsity.mmdnew file mode 100644index 0000000..0674202--- /dev/null+++ b/docs/images/moe-sparsity.mmd@@ -0,0 +1,12 @@+flowchart LR+ X["one token"] --> R["router<br/>896 scores"]+ R --> TOP["top 16"]+ TOP --> RUN["16 experts run<br/>17.55 MB each"]+ R -.->|"880 stay asleep"| SLEEP["never read<br/>never resident"]+ RUN --> Y["layer output"]+ style X fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style R fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style TOP fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style RUN fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style SLEEP fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style Y fill:#DDEBE7,stroke:#4E8E86,color:#3B372Fdiff --git a/docs/images/moe-sparsity.png b/docs/images/moe-sparsity.pngnew file mode 100644index 0000000..17de1d8Binary files /dev/null and b/docs/images/moe-sparsity.png differdiff --git a/docs/images/mxfp4-decode.mmd b/docs/images/mxfp4-decode.mmdnew file mode 100644index 0000000..961dc48--- /dev/null+++ b/docs/images/mxfp4-decode.mmd@@ -0,0 +1,13 @@+flowchart LR+ BY["one byte<br/>two nibbles"] --> LO["low nibble<br/>EVEN element"]+ BY --> HI["high nibble<br/>ODD element"]+ LO --> LUT["E2M1 lookup<br/>16 values"]+ HI --> LUT+ SC["E8M0 byte<br/>1 per 32 weights"] --> MUL["value x 2^(s-127)"]+ LUT --> MUL+ style BY fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style LO fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style HI fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style LUT fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style SC fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style MUL fill:#E7ECDD,stroke:#6E9160,color:#3B372Fdiff --git a/docs/images/mxfp4-decode.png b/docs/images/mxfp4-decode.pngnew file mode 100644index 0000000..37918beBinary files /dev/null and b/docs/images/mxfp4-decode.png differdiff --git a/docs/images/mxfp4_savings.png b/docs/images/mxfp4_savings.pngnew file mode 100644index 0000000..dd692e9Binary files /dev/null and b/docs/images/mxfp4_savings.png differdiff --git a/docs/images/noise-floor.mmd b/docs/images/noise-floor.mmdnew file mode 100644index 0000000..4c9bc51--- /dev/null+++ b/docs/images/noise-floor.mmd@@ -0,0 +1,12 @@+flowchart LR+ SAME["same binary<br/>same minute"] --> R1["14.78 s/tok"]+ SAME --> R2["14.67 s/tok"]+ SAME --> R3["20.14 s/tok"]+ R3 --> SP["spread 33.1%"]+ SP --> RULE["under 33% is<br/>not an effect"]+ style SAME fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style R1 fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style R2 fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style R3 fill:#F5E2DB,stroke:#B75845,color:#3B372F+ style SP fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style RULE fill:#E7ECDD,stroke:#6E9160,color:#3B372Fdiff --git a/docs/images/noise-floor.png b/docs/images/noise-floor.pngnew file mode 100644index 0000000..5c91620Binary files /dev/null and b/docs/images/noise-floor.png differdiff --git a/docs/images/oracle-ladder.mmd b/docs/images/oracle-ladder.mmdnew file mode 100644index 0000000..f6210e6--- /dev/null+++ b/docs/images/oracle-ladder.mmd@@ -0,0 +1,12 @@+flowchart LR+ OP["op fixtures<br/>22 kernels, no weights"] --> TOY["13-layer oracle<br/>3 gates, exact ids"]+ TOY --> REAL["93 real layers<br/>stages A, B and C"]+ REAL --> LG["163,840 logits<br/>against torch"]+ LG --> V["max diff<br/>7.9e-06"]+ TOY -.->|"a toy model,<br/>not the 2.8T one"| WARN["proves the code,<br/>not the checkpoint"]+ style OP fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style TOY fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style REAL fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style LG fill:#F4E7D3,stroke:#C07A42,color:#3B372F+ style V fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style WARN fill:#F5E2DB,stroke:#B75845,color:#3B372Fdiff --git a/docs/images/oracle-ladder.png b/docs/images/oracle-ladder.pngnew file mode 100644index 0000000..11565f2Binary files /dev/null and b/docs/images/oracle-ladder.png differdiff --git a/docs/images/pack-trunk.mmd b/docs/images/pack-trunk.mmdnew file mode 100644index 0000000..588bc1b--- /dev/null+++ b/docs/images/pack-trunk.mmd@@ -0,0 +1,10 @@+flowchart LR+ S["shard N"] --> Q{"layer bytes<br/>contiguous?"}+ Q -->|"no"| STOP["refuse<br/>would copy experts"]+ Q -->|"yes"| CP["one range copy<br/>pad to 4096"]+ CP --> TB["trunk.bin<br/>108.81 GB, 93 runs"]+ style S fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style Q fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style STOP fill:#F5E2DB,stroke:#B75845,color:#3B372F+ style CP fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style TB fill:#E7ECDD,stroke:#6E9160,color:#3B372Fdiff --git a/docs/images/pack-trunk.png b/docs/images/pack-trunk.pngnew file mode 100644index 0000000..f26bf5dBinary files /dev/null and b/docs/images/pack-trunk.png differdiff --git a/docs/images/pack_progress.png b/docs/images/pack_progress.pngnew file mode 100644index 0000000..4c57007Binary files /dev/null and b/docs/images/pack_progress.png differdiff --git a/docs/images/parity-flow.mmd b/docs/images/parity-flow.mmdnew file mode 100644index 0000000..dbda394--- /dev/null+++ b/docs/images/parity-flow.mmd@@ -0,0 +1,11 @@+flowchart LR+ IDS["same 5 ids"] --> C["our C engine<br/>169.73 s"]+ IDS --> T["torch reference<br/>3608.5 s"]+ C --> CMP["compare all<br/>163,840 logits"]+ T --> CMP+ CMP --> R["argmax 2494 both<br/>correlation 1.000000000"]+ style IDS fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style C fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style T fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style CMP fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style R fill:#E7ECDD,stroke:#6E9160,color:#3B372Fdiff --git a/docs/images/parity-flow.png b/docs/images/parity-flow.pngnew file mode 100644index 0000000..e417e46Binary files /dev/null and b/docs/images/parity-flow.png differdiff --git a/docs/images/prefill_cost.png b/docs/images/prefill_cost.pngnew file mode 100644index 0000000..5eb0d0eBinary files /dev/null and b/docs/images/prefill_cost.png differdiff --git a/docs/images/preset_ladder.png b/docs/images/preset_ladder.pngnew file mode 100644index 0000000..059a60cBinary files /dev/null and b/docs/images/preset_ladder.png differdiff --git a/docs/images/quant_by_layer_type.png b/docs/images/quant_by_layer_type.pngnew file mode 100644index 0000000..312b30cBinary files /dev/null and b/docs/images/quant_by_layer_type.png differdiff --git a/docs/images/quant_error.png b/docs/images/quant_error.pngnew file mode 100644index 0000000..1ee6853Binary files /dev/null and b/docs/images/quant_error.png differdiff --git a/docs/images/recap.mmd b/docs/images/recap.mmdnew file mode 100644index 0000000..bcdc985--- /dev/null+++ b/docs/images/recap.mmd@@ -0,0 +1,12 @@+flowchart LR+ HF["1.56 TB checkpoint<br/>96 shards"] --> PK["pack the trunk<br/>108.81 GB"]+ PK --> ENG["./bin/k3<br/>a 176 KB binary"]+ ENG --> MEM["8.24 GB<br/>peak RSS"]+ MEM --> OUT["Paris.<br/>the right answer"]+ ENG -.->|"1.45 TB of experts<br/>stay on disk"| D["streamed,<br/>never resident"]+ style HF fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style PK fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style ENG fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style MEM fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style OUT fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style D fill:#DDEBE7,stroke:#4E8E86,color:#3B372Fdiff --git a/docs/images/recap.png b/docs/images/recap.pngnew file mode 100644index 0000000..fd39487Binary files /dev/null and b/docs/images/recap.png differdiff --git a/docs/images/replication_noise.png b/docs/images/replication_noise.pngnew file mode 100644index 0000000..26a3048Binary files /dev/null and b/docs/images/replication_noise.png differdiff --git a/docs/images/resident_vs_streamed.png b/docs/images/resident_vs_streamed.pngnew file mode 100644index 0000000..050e1baBinary files /dev/null and b/docs/images/resident_vs_streamed.png differdiff --git a/docs/images/roundtrip_sizes.png b/docs/images/roundtrip_sizes.pngnew file mode 100644index 0000000..118b6dbBinary files /dev/null and b/docs/images/roundtrip_sizes.png differdiff --git a/docs/images/rss_fidelity.png b/docs/images/rss_fidelity.pngnew file mode 100644index 0000000..3053a05Binary files /dev/null and b/docs/images/rss_fidelity.png differdiff --git a/docs/images/same_answer.png b/docs/images/same_answer.pngnew file mode 100644index 0000000..c3d9b9bBinary files /dev/null and b/docs/images/same_answer.png differdiff --git a/docs/images/shard_sizes.png b/docs/images/shard_sizes.pngnew file mode 100644index 0000000..433f7d7Binary files /dev/null and b/docs/images/shard_sizes.png differdiff --git a/docs/images/sim_vs_measured.png b/docs/images/sim_vs_measured.pngnew file mode 100644index 0000000..cee153eBinary files /dev/null and b/docs/images/sim_vs_measured.png differdiff --git a/docs/images/split-rule.mmd b/docs/images/split-rule.mmdnew file mode 100644index 0000000..ebf0179--- /dev/null+++ b/docs/images/split-rule.mmd@@ -0,0 +1,12 @@+flowchart LR+ GB["one spare GB"] --> Q{"trunk or<br/>expert cache?"}+ Q -->|"trunk"| T["pins a layer<br/>-1.17 GB per token"]+ Q -->|"cache"| C["below 36 GB arena<br/>removes nothing"]+ T --> FAST["16.80 s/token"]+ C --> SLOW["28.38 s/token"]+ style GB fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style Q fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style T fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style C fill:#F5E2DB,stroke:#B75845,color:#3B372F+ style FAST fill:#DDEBE7,stroke:#4E8E86,color:#3B372F+ style SLOW fill:#F4E7D3,stroke:#C07A42,color:#3B372Fdiff --git a/docs/images/split-rule.png b/docs/images/split-rule.pngnew file mode 100644index 0000000..582a5f9Binary files /dev/null and b/docs/images/split-rule.png differdiff --git a/docs/images/st-load.mmd b/docs/images/st-load.mmdnew file mode 100644index 0000000..e786374--- /dev/null+++ b/docs/images/st-load.mmd@@ -0,0 +1,12 @@+flowchart LR+ S["96 shards<br/>1.56 TB"] --> H["read 8-byte length<br/>then JSON header"]+ H --> IDX["FNV-1a index<br/>497,220 tensors"]+ IDX --> Q{"need this<br/>tensor?"}+ Q -->|"yes"| P["pread exact bytes<br/>O_DIRECT"]+ Q -->|"no"| SKIP["never touched"]+ style S fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style H fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style IDX fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style Q fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style P fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style SKIP fill:#DDEBE7,stroke:#4E8E86,color:#3B372Fdiff --git a/docs/images/st-load.png b/docs/images/st-load.pngnew file mode 100644index 0000000..e68edb8Binary files /dev/null and b/docs/images/st-load.png differdiff --git a/docs/images/step_trace.png b/docs/images/step_trace.pngnew file mode 100644index 0000000..3c65cb4Binary files /dev/null and b/docs/images/step_trace.png differdiff --git a/docs/images/storage_regimes.png b/docs/images/storage_regimes.pngnew file mode 100644index 0000000..a31baa8Binary files /dev/null and b/docs/images/storage_regimes.png differdiff --git a/docs/images/tok-flow.mmd b/docs/images/tok-flow.mmdnew file mode 100644index 0000000..38cf816--- /dev/null+++ b/docs/images/tok-flow.mmd@@ -0,0 +1,12 @@+flowchart LR+ F["prompt from a FILE<br/>never argv"] --> B["raw UTF-8 bytes"]+ B --> BPE["byte-level BPE<br/>163,584 ranks"]+ BPE --> IDS["token ids"]+ IDS --> CHK{"decode back<br/>byte-exact?"}+ CHK -->|"45 of 45"| PASS["matches tiktoken"]+ style F fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style B fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style BPE fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style IDS fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style CHK fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style PASS fill:#DDEBE7,stroke:#4E8E86,color:#3B372Fdiff --git a/docs/images/tok-flow.png b/docs/images/tok-flow.pngnew file mode 100644index 0000000..fb6e8beBinary files /dev/null and b/docs/images/tok-flow.png differdiff --git a/docs/images/token_time_split.png b/docs/images/token_time_split.pngnew file mode 100644index 0000000..9b845beBinary files /dev/null and b/docs/images/token_time_split.png differdiff --git a/docs/images/trace-replay.mmd b/docs/images/trace-replay.mmdnew file mode 100644index 0000000..1790294--- /dev/null+++ b/docs/images/trace-replay.mmd@@ -0,0 +1,13 @@+flowchart LR+ RUN["one real run"] --> TR["expert_trace.bin<br/>100,096 requests"]+ TR --> SIM["replay at every<br/>cache size"]+ SIM --> LRU["LRU: what we do"]+ SIM --> BEL["Belady: the ceiling"]+ LRU --> GAP["25.5 points apart<br/>at the same RAM"]+ BEL --> GAP+ style RUN fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style TR fill:#E4ECF3,stroke:#5C7C9B,color:#3B372F+ style SIM fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style LRU fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style BEL fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style GAP fill:#F5E2DB,stroke:#B75845,color:#3B372Fdiff --git a/docs/images/trace-replay.png b/docs/images/trace-replay.pngnew file mode 100644index 0000000..fb4fa0fBinary files /dev/null and b/docs/images/trace-replay.png differdiff --git a/docs/images/trunk-stream.mmd b/docs/images/trunk-stream.mmdnew file mode 100644index 0000000..59f0d85--- /dev/null+++ b/docs/images/trunk-stream.mmd@@ -0,0 +1,13 @@+flowchart LR+ TB["trunk.bin"] --> Q{"layer L<br/>pinned?"}+ Q -->|"yes"| MEM["already in RAM<br/>0 bytes read"]+ Q -->|"no"| RING["ring slot<br/>one pread"]+ MEM --> BIND["fix pointers<br/>widen norms"]+ RING --> BIND+ BIND --> RUN["run layer L"]+ style TB fill:#ECE8E0,stroke:#8C8477,color:#3B372F+ style Q fill:#EAE4F1,stroke:#7E6E9C,color:#3B372F+ style MEM fill:#E7ECDD,stroke:#6E9160,color:#3B372F+ style RING fill:#F5E2DB,stroke:#B75845,color:#3B372F+ style BIND fill:#F2E9D4,stroke:#C0913E,color:#3B372F+ style RUN fill:#DDEBE7,stroke:#4E8E86,color:#3B372Fdiff --git a/docs/images/trunk-stream.png b/docs/images/trunk-stream.pngnew file mode 100644index 0000000..d659c2dBinary files /dev/null and b/docs/images/trunk-stream.png differdiff --git a/docs/images/trunk_cache_split.png b/docs/images/trunk_cache_split.pngnew file mode 100644index 0000000..c4d8a10Binary files /dev/null and b/docs/images/trunk_cache_split.png differdiff --git a/docs/images/whats_missing.png b/docs/images/whats_missing.pngnew file mode 100644index 0000000..cd149baBinary files /dev/null and b/docs/images/whats_missing.png differ