Skip to content

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.

feat(tools): add the verification and analysis tools

FareedKhan-dev224dfda330d2
diff --git a/tools/budget.py b/tools/budget.py
new file mode 100644
index 0000000..5497d27
--- /dev/null
+++ b/tools/budget.py
@@ -0,0 +1,221 @@
+#!/usr/bin/env python
+"""
+budget.py - the resident-versus-streamable budget, measured from the real shard headers.
+
+WHY MEASURE RATHER THAN DERIVE
+ The obvious way to size the resident set is to multiply config values by hand. It
+ gives the wrong answer, and the way it goes wrong is instructive: the shared experts
+ are 6144 wide (num_shared_experts 2 x moe_intermediate 3072, fused into one KimiMLP
+ at modeling_kimi_linear.py:797-799) and they ship BF16, not MXFP4. They are dense and
+ active on every token, so they belong in the resident set, but they look like
+ experts, so hand arithmetic files them under "streamable" and understates the floor.
+
+ This script sums the actual bytes of every tensor in the checkpoint, classified by
+ what the engine must do with each one, and assumes nothing about the layer count or
+ the expert count.
+
+ Classification rule: a tensor is STREAMABLE only if it is a ROUTED expert, because
+ only routed experts are selected per token. Everything else runs on every token and
+ must be resident, or paged in and out on every token, which is not streaming but
+ thrashing.
+
+HOW IT READS THE CHECKPOINT
+ Only the header block at the front of each .safetensors shard, which is a JSON
+ dictionary of tensor names, dtypes and shapes. That is a few MB in total against
+ 1.56 TB of shards, so this runs in seconds and needs no GPU, no torch, and no
+ complete download, a partial checkout still gives an exact answer for the shards
+ that are present.
+
+usage: budget.py <model_dir>
+ budget.py (reads $K3_MODEL_DIR)
+"""
+from __future__ import annotations
+
+import collections
+import glob
+import json
+import os
+import re
+import struct
+import sys
+
+WIDTH = {"U8": 1, "BF16": 2, "F16": 2, "F32": 4}
+# MXFP4 stores half a byte per weight plus one E8M0 byte per 32-element group.
+MXFP4_BYTES_PER_PARAM = 0.5 + 1.0 / 32.0
+
+
+def classify(name: str) -> str:
+ if ".block_sparse_moe.experts." in name:
+ return "routed experts (STREAMABLE)"
+ if ".block_sparse_moe.shared_experts." in name:
+ return "shared experts (resident, dense)"
+ if ".block_sparse_moe.routed_expert_" in name:
+ return "MoE latent up/down/norm (resident)"
+ if ".block_sparse_moe.gate" in name:
+ return "MoE router (resident)"
+ if ".self_attn." in name:
+ return "attention (resident)"
+ if "_res_norm" in name or "_res_proj" in name:
+ return "attn-res aggregators (resident)"
+ if "layernorm" in name or name.endswith(".norm.weight"):
+ return "layer norms (resident)"
+ if "embed_tokens" in name or "lm_head" in name:
+ return "embedding / lm_head (resident)"
+ if name.startswith("language_model."):
+ return "other text tower (resident)"
+ return "vision / other (not used by the text path)"
+
+
+def human(b: float) -> str:
+ for u in ("B", "KB", "MB", "GB", "TB"):
+ if abs(b) < 1000.0:
+ return "%7.2f %s" % (b, u)
+ b /= 1000.0
+ return "%7.2f PB" % b
+
+
+def read_header(path: str) -> dict:
+ """Return one shard's tensor index.
+
+ A safetensors file starts with an 8-byte little-endian length followed by that many
+ bytes of JSON. Only those bytes are read, so this touches a few hundred KB of a
+ 17 GB shard.
+
+ The length is bounds-checked before it is used as a read size: it comes from a file
+ that may have been fetched from a mirror, and an absurd value would otherwise turn
+ into an absurd allocation.
+ """
+ with open(path, "rb") as f:
+ raw = f.read(8)
+ if len(raw) != 8:
+ raise ValueError("%s: too short to be a safetensors file" % path)
+ n = struct.unpack("<Q", raw)[0]
+ if not 0 < n < (1 << 30):
+ raise ValueError("%s: implausible header length %d" % (path, n))
+ blob = f.read(n)
+ if len(blob) != n:
+ raise ValueError("%s: header truncated (%d of %d bytes)" % (path, len(blob), n))
+ return json.loads(blob.decode("utf-8"))
+
+
+def main():
+ root = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("K3_MODEL_DIR", "")
+ if not root:
+ print("usage: budget.py <model_dir>")
+ print(" or set K3_MODEL_DIR")
+ return 2
+
+ files = sorted(glob.glob(os.path.join(root, "*.safetensors")))
+ if not files:
+ print("no .safetensors shards in %s" % root)
+ print("Point this at the directory holding the released checkpoint. A partial")
+ print("download is fine: the totals below will simply cover the shards present.")
+ return 1
+ print("reading %d shard headers from %s\n" % (len(files), root))
+
+ by_class = collections.Counter()
+ cnt_class = collections.Counter()
+ by_dtype = collections.Counter()
+ ntensor = 0
+ total = 0
+ # routed expert params, counted from the packed shapes rather than assumed
+ routed_params = 0
+ routed_bytes = 0
+ per_layer_expert_bytes = collections.Counter()
+ kda_layers, mla_layers = set(), set()
+
+ for fp in files:
+ h = read_header(fp)
+ # safetensors puts tensor entries at the top level, alongside an optional
+ # "__metadata__" key. Older extracts nested them under "tensors"; accept both so
+ # a previously-extracted header still works.
+ entries = h.get("tensors", h)
+ for name, e in entries.items():
+ if name == "__metadata__" or not isinstance(e, dict):
+ continue
+ a, b = e["data_offsets"]
+ nb = b - a
+ ntensor += 1
+ total += nb
+ c = classify(name)
+ by_class[c] += nb
+ cnt_class[c] += 1
+ by_dtype[e["dtype"]] += nb
+
+ m = re.search(r"layers\.(\d+)\.self_attn\.(\w+)", name)
+ if m:
+ # A KDA layer has A_log and conv1d weights; an MLA layer has kv_a_proj.
+ if m.group(2) in ("A_log",):
+ kda_layers.add(int(m.group(1)))
+ if "kv_a_proj" in m.group(2) or "kv_b_proj" in m.group(2):
+ mla_layers.add(int(m.group(1)))
+
+ if ".block_sparse_moe.experts." in name:
+ routed_bytes += nb
+ if name.endswith("weight_packed"):
+ routed_params += e["shape"][0] * e["shape"][1] * 2
+ lm = re.search(r"layers\.(\d+)\.", name)
+ if lm:
+ per_layer_expert_bytes[int(lm.group(1))] += nb
+
+ print("%-42s %8s %12s %s" % ("CLASS", "TENSORS", "BYTES", "SHARE"))
+ print("-" * 82)
+ for c, b in by_class.most_common():
+ print("%-42s %8d %12s %5.2f%%" % (c, cnt_class[c], human(b), 100.0 * b / total))
+ print("-" * 82)
+ print("%-42s %8d %12s 100.00%%" % ("TOTAL CHECKPOINT", ntensor, human(total)))
+
+ print("\nby dtype:")
+ for d, b in by_dtype.most_common():
+ print(" %-5s %12s %5.2f%%" % (d, human(b), 100.0 * b / total))
+
+ stream = by_class["routed experts (STREAMABLE)"]
+ resident = total - stream - by_class.get("vision / other (not used by the text path)", 0)
+ vision = by_class.get("vision / other (not used by the text path)", 0)
+
+ print("\n" + "=" * 82)
+ print("THE NUMBER THAT MATTERS")
+ print("=" * 82)
+ print(" resident (text path, must stay in RAM) : %s" % human(resident))
+ print(" streamable (routed experts, from NVMe) : %s" % human(stream))
+ print(" vision tower (text-only inference) : %s" % human(vision))
+ print(" full checkpoint on disk : %s" % human(total))
+
+ print("\nrouted experts, measured:")
+ print(" parameters : %s" % format(routed_params, ","))
+ print(" bytes : %s" % human(routed_bytes))
+ print(" bytes per parameter : %.6f (MXFP4 predicts %.6f)"
+ % (routed_bytes / routed_params, MXFP4_BYTES_PER_PARAM))
+ nlayers_moe = len(per_layer_expert_bytes)
+ if nlayers_moe:
+ per = sorted(set(per_layer_expert_bytes.values()))
+ print(" MoE layers : %d" % nlayers_moe)
+ print(" bytes per MoE layer : %s%s"
+ % (human(per[0]), "" if len(per) == 1 else " (VARIES: %d distinct)" % len(per)))
+ nexp = 896
+ print(" bytes per expert : %s (%d experts per layer)"
+ % (human(per[0] / nexp), nexp))
+
+ print("\nlayer map from the checkpoint itself:")
+ print(" layers with A_log (KDA) : %d" % len(kda_layers))
+ print(" layers with kv_a/kv_b (MLA) : %d" % len(mla_layers))
+ both = kda_layers & mla_layers
+ print(" layers claiming both : %d%s" % (len(both), " <-- WRONG" if both else ""))
+ allmoe = sorted(per_layer_expert_bytes)
+ if allmoe:
+ missing = [i for i in range(93) if i not in per_layer_expert_bytes]
+ print(" layers WITHOUT routed experts: %s (expect [0], the dense layer)" % missing)
+
+ print("\nwhat this means for hardware:")
+ for ram in (32, 48, 64, 96, 128, 192, 256):
+ fits = ram * 1e9 - resident
+ n = int(fits / (routed_bytes / (nlayers_moe * 896))) if fits > 0 else 0
+ pct = 100.0 * n * (routed_bytes / (nlayers_moe * 896)) / stream if n > 0 else 0.0
+ print(" %3d GB RAM -> %s for experts, about %6d of %d cached (%.1f%%)"
+ % (ram, human(fits) if fits > 0 else " DOES NOT FIT",
+ max(n, 0), nlayers_moe * 896, pct))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tools/cmp_logits.py b/tools/cmp_logits.py
new file mode 100644
index 0000000..a2d517a
--- /dev/null
+++ b/tools/cmp_logits.py
@@ -0,0 +1,133 @@
+#!/usr/bin/env python
+"""
+cmp_logits.py - compare the C engine's final-position logits against the torch reference.
+
+This is the definitive conformance check for the real model. Everything else compares
+either tokens (argmax, which hides near-ties) or single layers in isolation. Two engines
+can emit identical tokens for a whole generation while their logit vectors differ by a
+large systematic amount, because argmax only cares which entry is biggest. Comparing the
+full 163,840-wide vector elementwise is what actually catches an error in the final norm,
+the lm_head, or the model-level AttnRes aggregator.
+
+Inputs:
+ c_logits.bin raw float32 from k3_run --dump-logits
+ ref.json from tools/ref_forward.py
+
+The tolerance is the same yardstick tools/verify_real_layer.py uses: float32 resolution
+scaled by the square root of the accumulation width, times a slack factor. The lm_head
+is a dot product of length hidden_size, and the hidden state arriving at it has already
+accumulated error through 93 layers, so the budget is generous by design. What it is
+looking for is a STRUCTURAL error, not the last bit.
+
+usage: cmp_logits.py <c_logits.bin> <ref.json> [hidden]
+"""
+from __future__ import annotations
+
+import json
+import os
+import sys
+
+import numpy as np
+
+
+def main():
+ if len(sys.argv) < 3:
+ print(__doc__)
+ return 2
+ cbin, refp = sys.argv[1], sys.argv[2]
+ hidden = int(sys.argv[3]) if len(sys.argv) > 3 else 7168
+
+ # The first argument is normally k3_run's raw float32 dump, but accepting a
+ # ref_forward JSON too lets this same comparator score one REFERENCE variant against
+ # another -- for example an int8 simulation against the bf16 golden vector -- without
+ # a second, subtly different comparison script.
+ if cbin.endswith(".json"):
+ C = json.load(open(cbin))
+ c = np.array(C["logits_bits"], dtype=np.uint32).view(np.float32)
+ else:
+ C = {}
+ c = np.fromfile(cbin, dtype=np.float32)
+ R = json.load(open(refp))
+ r = np.array(R["logits_bits"], dtype=np.uint32).view(np.float32)
+
+ if c.shape != r.shape:
+ print("SHAPE MISMATCH: C has %d logits, reference has %d" % (c.size, r.size))
+ return 1
+
+ # Cross-check that both sides ran the SAME prompt. The C dump is a bare headerless
+ # float32 blob, so nothing in the two files otherwise ties them together: comparing a
+ # C run on one prompt against a reference on another would produce a confident,
+ # meaningless mismatch. k3_run writes its prompt to the --out JSON; if that file is
+ # alongside the dump, require agreement rather than assuming it.
+ ref_ids = R.get("prompt_ids")
+ if C.get("prompt_ids") is not None:
+ if list(C["prompt_ids"]) != list(ref_ids or []):
+ print("PROMPT MISMATCH: %s vs %s" % (C["prompt_ids"], ref_ids)); return 1
+ print("prompt cross-check : both sides ran %s" % (list(ref_ids),))
+ crun = None
+ else:
+ crun = os.path.join(os.path.dirname(os.path.abspath(cbin)), "c_run.json")
+ if crun is not None and ref_ids is not None and os.path.exists(crun):
+ try:
+ c_ids = json.load(open(crun)).get("prompt_ids")
+ except Exception:
+ c_ids = None
+ if c_ids is not None:
+ if list(c_ids) != list(ref_ids):
+ print("PROMPT MISMATCH: C ran %s, reference ran %s" % (c_ids, ref_ids))
+ print("These two runs are not comparable. Aborting rather than reporting "
+ "a meaningless difference.")
+ return 1
+ print("prompt cross-check : both sides ran %s" % (list(c_ids),))
+ elif crun is not None:
+ print("prompt cross-check : SKIPPED (no c_run.json beside the dump)")
+
+ d = np.abs(c.astype(np.float64) - r.astype(np.float64))
+ scale = max(float(np.abs(r).max()), 1e-30)
+ rel = float(d.max()) / scale
+ budget = 1.2e-7 * np.sqrt(hidden) * 50
+
+ ca, ra = int(np.argmax(c)), int(np.argmax(r))
+ # Rank correlation on the top of the distribution is the property that actually
+ # decides generated text, so report it separately from the raw elementwise diff.
+ ctop = set(np.argsort(-c)[:10].tolist())
+ rtop = set(np.argsort(-r)[:10].tolist())
+
+ print("vocab : %d" % c.size)
+ print("C argmax : %d (logit %.6f)" % (ca, c[ca]))
+ print("reference argmax : %d (logit %.6f)" % (ra, r[ra]))
+ print("top-10 overlap : %d/10" % len(ctop & rtop))
+ print("max |diff| : %.6e" % float(d.max()))
+ print("relative to max|ref| : %.6e (budget %.1e)" % (rel, budget))
+ print("mean |diff| : %.6e" % float(d.mean()))
+ print("correlation : %.9f"
+ % float(np.corrcoef(c.astype(np.float64), r.astype(np.float64))[0, 1]))
+
+ ok_tok = ca == ra
+ ok_num = rel <= budget
+ # A genuine near-tie can flip argmax between two numerically-agreeing engines, so an
+ # argmax difference is only damning when the logits themselves also disagree. Report
+ # the gap so a tie is distinguishable from a real divergence rather than silently
+ # failing a correct engine.
+ if not ok_tok:
+ gap = abs(float(r[ra]) - float(r[ca])) / max(abs(float(r[ra])), 1e-30)
+ print("argmax differs; reference gap between the two candidates: %.3e relative"
+ % gap)
+ print()
+ if ok_tok and ok_num:
+ print("VERIFIED: the C engine's logits match the torch reference over the FULL "
+ "93-layer stack on the real checkpoint, elementwise, and the argmax token "
+ "agrees. Composition, the AttnRes aggregator, the final norm and the "
+ "lm_head are all correct.")
+ return 0
+ if not ok_tok:
+ print("TOKEN MISMATCH: C would emit %d, the reference would emit %d" % (ca, ra))
+ if not ok_num:
+ print("NUMERIC MISMATCH: relative error %.3e exceeds the %.1e budget" % (rel, budget))
+ i = int(np.argmax(d))
+ print(" worst at index %d: C=%.9g reference=%.9g" % (i, c[i], r[i]))
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/conform_all.py b/tools/conform_all.py
new file mode 100644
index 0000000..880fba8
--- /dev/null
+++ b/tools/conform_all.py
@@ -0,0 +1,117 @@
+#!/usr/bin/env python
+"""
+conform_all.py - run the real-weights layer conformance check across ALL 93 layers.
+
+WHY THIS EXISTS
+ The rest of the test suite covers two extremes and leaves a gap between them. The op
+ fixtures and the full-model oracle use a TINY model (hidden 128, 13 layers) built by
+ this project: they prove the arithmetic and the composition, but say nothing about
+ the real checkpoint. test_real_layer proves the BINDING for ONE layer of the real
+ model. Neither covers whether the binding is right for all 93 layers, whether the
+ layer map places KDA and MLA correctly across the whole stack, or whether any single
+ layer's weights are transposed, swapped, or off by one shard.
+
+ That gap matters because the failure mode is invisible. A layer bound to the wrong
+ tensor of the right shape still produces finite, plausible numbers. Only comparison
+ against an independent implementation reading the same bytes can see it.
+
+WHAT IT DOES
+ For each layer L in 0..92:
+ 1. c/test_real_layer dumps that layer's staged outputs from the real shards
+ (attention -> router -> MoE), computed by the C engine.
+ 2. tools/verify_real_layer.py recomputes every stage in torch from the same
+ shards and compares, at a tolerance of 1.2e-7 * sqrt(width) * 50, which is
+ float32 rounding for a dot product of that accumulation width.
+ 3. The per-stage relative errors are recorded.
+
+ A layer counts as PASSED only if verify_real_layer.py exits 0. Its exit code is the
+ verdict; this script does not second-guess it.
+
+usage: conform_all.py <shard_dir> <c_dir> <python> [first] [last] [T] [cache_gb]
+"""
+from __future__ import annotations
+
+import json
+import os
+import re
+import subprocess
+import sys
+import time
+
+STAGE_RE = re.compile(r"^\s{2}(\S+)\s+max\|diff\|\s+(\S+)\s+rel\s+(\S+)\s+budget\s+(\S+)\s+(OK|MISMATCH)")
+
+
+def main():
+ if len(sys.argv) < 4:
+ print(__doc__)
+ return 2
+ shards, cdir, py = sys.argv[1], sys.argv[2], sys.argv[3]
+ first = int(sys.argv[4]) if len(sys.argv) > 4 else 0
+ last = int(sys.argv[5]) if len(sys.argv) > 5 else 92
+ T = sys.argv[6] if len(sys.argv) > 6 else "4"
+ cache = sys.argv[7] if len(sys.argv) > 7 else "2"
+
+ rows = []
+ t_start = time.time()
+ for L in range(first, last + 1):
+ t0 = time.time()
+ r = subprocess.run([os.path.join(cdir, "test_real_layer"), shards, str(L), T, cache],
+ cwd=cdir, capture_output=True, text=True, timeout=7200)
+ if r.returncode != 0:
+ rows.append({"layer": L, "kind": "?", "ok": False,
+ "why": "test_real_layer exit %d" % r.returncode,
+ "tail": r.stdout[-400:] + r.stderr[-400:], "stages": {}})
+ print("L%-3d DUMP FAILED (exit %d)" % (L, r.returncode), flush=True)
+ continue
+ kind = "MLA" if '"is_mla":1' in open(os.path.join(cdir, "real_layer.json")).read(4096) else "KDA"
+
+ v = subprocess.run([py, os.path.join(os.path.dirname(os.path.abspath(__file__)),
+ "verify_real_layer.py"),
+ shards, os.path.join(cdir, "real_layer.json")],
+ cwd=cdir, capture_output=True, text=True, timeout=7200)
+ stages = {}
+ for line in v.stdout.splitlines():
+ m = STAGE_RE.match(line)
+ if m:
+ stages[m.group(1)] = {"rel": float(m.group(3)), "budget": float(m.group(4)),
+ "ok": m.group(5) == "OK"}
+ ok = v.returncode == 0
+ worst = max((s["rel"] / s["budget"] for s in stages.values()), default=float("nan"))
+ rows.append({"layer": L, "kind": kind, "ok": ok, "stages": stages,
+ "worst_ratio": worst, "seconds": time.time() - t0,
+ "tail": "" if ok else (v.stdout[-1200:] + v.stderr[-600:])})
+ print("L%-3d %-3s %-4s %2d stages worst %.2fx budget %.0fs" %
+ (L, kind, "PASS" if ok else "FAIL", len(stages), worst, time.time() - t0),
+ flush=True)
+ if not ok:
+ for line in v.stdout.splitlines():
+ if "MISMATCH" in line or line.startswith("FAILED") or line.startswith(" "):
+ print(" " + line.strip(), flush=True)
+
+ npass = sum(1 for r in rows if r["ok"])
+ nfail = len(rows) - npass
+ kda = [r for r in rows if r["kind"] == "KDA"]
+ mla = [r for r in rows if r["kind"] == "MLA"]
+ print("\n" + "=" * 78)
+ print("LAYERS %d..%d %d passed, %d failed (%d KDA, %d MLA) %.0f s total"
+ % (first, last, npass, nfail, len(kda), len(mla), time.time() - t_start))
+ good = [r["worst_ratio"] for r in rows if r["ok"] and r["worst_ratio"] == r["worst_ratio"]]
+ if good:
+ print("worst stage across all passing layers: %.2fx of its rounding budget"
+ % max(good))
+ if nfail:
+ print("\nFAILING LAYERS:")
+ for r in rows:
+ if not r["ok"]:
+ print(" L%d (%s): %s" % (r["layer"], r["kind"], r.get("why", "stage mismatch")))
+ print("=" * 78)
+ print("VERDICT: %s" % ("ALL LAYERS CONFORM" if nfail == 0 else "%d LAYER(S) DISAGREE" % nfail))
+
+ with open(os.path.join(cdir, "conform_all.json"), "w") as f:
+ json.dump({"first": first, "last": last, "passed": npass, "failed": nfail,
+ "rows": rows}, f, indent=1)
+ return 0 if nfail == 0 else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/devbw.py b/tools/devbw.py
new file mode 100644
index 0000000..13964d7
--- /dev/null
+++ b/tools/devbw.py
@@ -0,0 +1,95 @@
+#!/usr/bin/env python
+"""
+devbw.py - measure a device the way the ENGINE actually reads it.
+
+WHY NOT dd
+ dd is one sequential stream at queue depth 1. The expert path is random 17.55 MB
+ O_DIRECT reads issued up to 16 at a time by the MoE block's batch prefetch. Those are
+ different workloads, and on network-backed storage they differ by a large factor, so
+ a dd number cannot tell you whether a device is the bottleneck for THIS engine.
+
+WHAT IT REPORTS
+ Achieved MB/s for expert-sized random O_DIRECT reads at queue depth 1 and at queue
+ depth 16, the depths the engine uses without and with the batch prefetch. The gap
+ between the two is the headroom the prefetch can convert into speed on this device;
+ if they are equal, the device does not reward depth and the prefetch buys nothing.
+
+usage: devbw.py <file> [<file> ...]
+"""
+from __future__ import annotations
+
+import ctypes
+import os
+import random
+import sys
+import threading
+import time
+
+SZ = 17547264 # one real Kimi K3 routed expert, to the byte
+ALIGN = 4096
+N = 40 # reads per measurement
+
+
+def aligned_buf(n: int):
+ """O_DIRECT needs the destination aligned too, not just offset and length."""
+ raw = ctypes.create_string_buffer(n + ALIGN)
+ addr = ctypes.addressof(raw)
+ off = (-addr) % ALIGN
+ return raw, (ctypes.c_char * n).from_buffer(raw, off)
+
+
+def measure(path: str, qd: int) -> float:
+ fsz = os.path.getsize(path)
+ span = max(1, (fsz - SZ) // ALIGN)
+ offs = [random.randrange(0, span) * ALIGN for _ in range(N)]
+ err = []
+
+ def worker(k: int):
+ try:
+ fd = os.open(path, os.O_RDONLY | getattr(os, "O_DIRECT", 0))
+ except OSError as e:
+ err.append(e); return
+ try:
+ _raw, buf = aligned_buf(SZ)
+ mv = memoryview(buf).cast("B")
+ for i in range(k, N, qd):
+ got, want = 0, SZ
+ while got < want:
+ r = os.preadv(fd, [mv[got:want]], offs[i] + got)
+ if r <= 0:
+ break
+ got += r
+ except Exception as e:
+ err.append(e)
+ finally:
+ os.close(fd)
+
+ t0 = time.time()
+ th = [threading.Thread(target=worker, args=(k,)) for k in range(qd)]
+ for x in th:
+ x.start()
+ for x in th:
+ x.join()
+ dt = time.time() - t0
+ if err:
+ raise err[0]
+ return N * SZ / dt / 1e6
+
+
+def main():
+ if len(sys.argv) < 2:
+ print(__doc__)
+ return 2
+ print("expert-sized (%d B) random O_DIRECT reads, %d per measurement\n" % (SZ, N))
+ for path in sys.argv[1:]:
+ for qd in (1, 4, 16):
+ try:
+ print(" %-46s QD%-3d %7.0f MB/s" % (path, qd, measure(path, qd)))
+ except Exception as e:
+ print(" %-46s QD%-3d FAILED: %s" % (path, qd, e))
+ print()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/pack_trunk.py b/tools/pack_trunk.py
new file mode 100644
index 0000000..0cf0a95
--- /dev/null
+++ b/tools/pack_trunk.py
@@ -0,0 +1,148 @@
+#!/usr/bin/env python
+"""
+pack_trunk.py - extract the resident trunk into one compact file on fast local storage.
+
+WHY
+ The engine holds all 110 GB of trunk in RAM because reading it per token from the
+ network volume (measured 772 MB/s) would cost 142 s/token. Local NVMe measures
+ 4.5 GB/s, which turns the same read into 24 s/token, and the trunk is walked in a
+ fixed order (layer 0..92, every token) so it prefetches perfectly and overlaps
+ compute. That makes streaming the trunk viable, and streaming is LOSSLESS, unlike
+ every quantisation route.
+
+ Kimi K3's own technical report is the reason lossless matters here. Section 4.1.4:
+ the MoE experts are MXFP4 with quantisation-aware training, "while all non-expert
+ components (attention projections, latent MoE projections, shared experts, and MoE
+ routers) remain in higher precision". That list is exactly this trunk. Moonshot
+ deliberately did not quantise it, and post-hoc 4-bit measures 12% output error on
+ real K3 weights against 0.54% for int8. So the trunk is copied here byte for byte.
+
+WHAT MAKES THIS CHEAP
+ Every layer's trunk tensors form ONE contiguous run inside its shard, verified for
+ every layer before copying. So packing is 93 sequential range copies, and loading a
+ layer later is a single pread from a known offset.
+
+Writes <out>/trunk.bin and <out>/trunk.json.
+"""
+from __future__ import annotations
+
+import json
+import os
+import struct
+import sys
+import time
+
+CHUNK = 64 << 20
+ALIGN = 4096 # O_DIRECT needs offset, length and buffer all aligned
+
+
+def shard_header(path):
+ with open(path, "rb") as f:
+ n = struct.unpack("<Q", f.read(8))[0]
+ hdr = json.loads(f.read(n).decode("utf-8"))
+ return hdr, 8 + n
+
+
+def main():
+ if len(sys.argv) < 3:
+ print("usage: pack_trunk.py <shard_dir> <out_dir> [n_layers]")
+ return 2
+ src, out = sys.argv[1], sys.argv[2]
+ nlayers = int(sys.argv[3]) if len(sys.argv) > 3 else 93
+ os.makedirs(out, exist_ok=True)
+
+ print("indexing %d shards..." % len(os.listdir(src)))
+ # name -> (shard_path, absolute_offset, nbytes, dtype, shape)
+ where = {}
+ for fn in sorted(os.listdir(src)):
+ if not fn.endswith(".safetensors"):
+ continue
+ p = os.path.join(src, fn)
+ hdr, base = shard_header(p)
+ for name, e in hdr.items():
+ if name == "__metadata__":
+ continue
+ a, b = e["data_offsets"]
+ where[name] = (p, base + a, b - a, e["dtype"], e["shape"])
+
+ manifest = {"n_layers": nlayers, "align": ALIGN, "layers": []}
+ total = 0
+ t0 = time.time()
+ outp = os.path.join(out, "trunk.bin")
+ with open(outp, "wb") as dst:
+ for L in range(nlayers):
+ pre = "language_model.model.layers.%d." % L
+ mine = {k: v for k, v in where.items()
+ if k.startswith(pre) and ".block_sparse_moe.experts." not in k}
+ if not mine:
+ print("layer %d: NO TENSORS FOUND" % L)
+ return 1
+ shards = {v[0] for v in mine.values()}
+ if len(shards) != 1:
+ print("layer %d spans %d shards, cannot pack as one run" % (L, len(shards)))
+ return 1
+ sp = shards.pop()
+ lo = min(v[1] for v in mine.values())
+ hi = max(v[1] + v[2] for v in mine.values())
+ own = sum(v[2] for v in mine.values())
+ if hi - lo != own:
+ # A gap would mean copying expert bytes too; refuse rather than bloat.
+ print("layer %d trunk is NOT contiguous (span %d, own %d)" % (L, hi - lo, own))
+ return 1
+
+ # Start every run on a 4096 boundary so the engine can read it with
+ # O_DIRECT. Under a tight cgroup the buffered path collapses (measured
+ # 1,878 MB/s against 6,553 MB/s unconstrained) because the page cache has no
+ # room and thrashes; O_DIRECT moves bytes straight into the engine's own
+ # aligned buffer with no double-buffering. It costs 93 x under 4 KB of
+ # padding in a 108 GB file.
+ pad = (-dst.tell()) % ALIGN
+ if pad:
+ dst.write(b"\0" * pad)
+ file_off = dst.tell()
+ assert file_off % ALIGN == 0
+ with open(sp, "rb") as f:
+ f.seek(lo)
+ left = own
+ while left:
+ b = f.read(min(CHUNK, left))
+ if not b:
+ print("layer %d: short read" % L)
+ return 1
+ dst.write(b)
+ left -= len(b)
+ # Pad the tail too: an O_DIRECT read is rounded up to ALIGN, so the last
+ # layer must not run off the end of the file.
+ pad = (-dst.tell()) % ALIGN
+ if pad:
+ dst.write(b"\0" * pad)
+
+ manifest["layers"].append({
+ "layer": L,
+ "shard": os.path.basename(sp),
+ "run_start": lo, # absolute offset in the shard
+ "nbytes": own,
+ "file_off": file_off, # offset in trunk.bin
+ "tensors": {k: {"off": v[1] - lo, "nbytes": v[2],
+ "dtype": v[3], "shape": v[4]}
+ for k, v in sorted(mine.items())},
+ })
+ total += own
+ if (L + 1) % 10 == 0 or L + 1 == nlayers:
+ el = time.time() - t0
+ print(" packed %d/%d layers, %.2f GB, %.0f s (%.0f MB/s)"
+ % (L + 1, nlayers, total / 1e9, el, total / 1e6 / max(el, 1e-9)))
+ sys.stdout.flush()
+
+ with open(os.path.join(out, "trunk.json"), "w", encoding="utf-8") as f:
+ json.dump(manifest, f)
+
+ big = max(x["nbytes"] for x in manifest["layers"])
+ print("\nwrote %s: %.2f GB across %d layers" % (outp, total / 1e9, nlayers))
+ print("largest layer run: %.3f GB <- the streaming slot size" % (big / 1e9))
+ print("wrote %s" % os.path.join(out, "trunk.json"))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/ref_forward.py b/tools/ref_forward.py
new file mode 100644
index 0000000..76f79bd
--- /dev/null
+++ b/tools/ref_forward.py
@@ -0,0 +1,313 @@
+#!/usr/bin/env python
+"""
+ref_forward.py - a full 93-layer reference forward pass over the REAL Kimi K3 checkpoint,
+in torch and numpy, producing GOLDEN LOGITS.
+
+WHY THIS IS THE TEST THAT MATTERS
+ Everything else in this project validates a piece:
+ - the op fixtures validate each kernel against torch, on tiny synthetic weights;
+ - the full-model oracle validates COMPOSITION end to end, but on a 13-layer toy;
+ - tools/conform_all.py validates every one of the 93 real layers against torch on
+ REAL weights, but each layer in ISOLATION, fed a fresh random input.
+
+ None of those proves the thing a user actually cares about: that stacking the real 93
+ layers produces the right logits. The residual stream, the AttnRes aggregator that
+ spans layers and resets every attn_res_block, the embedding, the final norm and the
+ lm_head are all untested at real scale, and an error in any of them is invisible to a
+ per-layer check because each layer is still individually correct.
+
+ This script closes that gap. It runs the whole model the way the reference defines it
+ (k3_ref.K3Model.forward, mirrored statement for statement below), from the same shard
+ bytes the C engine reads, and writes the final-position logits. Comparing those to the
+ C engine's logits ELEMENTWISE -- not argmax -- is the definitive conformance test.
+ Argmax alone is not sufficient: it hides near-ties, so two engines can agree on every
+ token while their logit vectors differ substantially. Elementwise comparison is what
+ turns "picks the same words" into "computes the same function".
+
+HOW IT FITS IN 64 GB
+ The always-active weights are 113.49 GB at bf16 and would be ~227 GB in fp32, so
+ nothing is held resident. Each layer's weights are loaded, used and freed before the
+ next layer starts, and the MoE
+ dequantises only the experts the router actually selected. Peak memory is one layer.
+
+usage: ref_forward.py <shard_dir> <ids> [out.json]
+ ids is a comma-separated list of token ids, e.g. 3,4,5,6,7
+"""
+from __future__ import annotations
+
+import json
+import os
+import sys
+import time
+
+import numpy as np
+import torch
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, HERE)
+
+from k3_ref import (K3Config, GatedMLA, KimiDeltaAttention, # noqa: E402
+ apply_attn_res, situ_glu)
+from verify_real_layer import Shards, dequant # noqa: E402
+
+PRE = "language_model.model."
+
+# ---------------------------------------------------------------- int8 simulation ----
+# Set by --int8. When on, every LARGE matrix is round-tripped through int8 with one fp32
+# scale per 32 elements along the contraction dimension, exactly the scheme a C kernel
+# would use, before it is multiplied. Nothing else changes, so the resulting logits show
+# what an int8 trunk would actually produce end to end.
+#
+# WHAT IS DELIBERATELY NOT QUANTISED, and why:
+# routers (gate.weight, e_score_correction_bias) - the router's output SELECTS experts.
+# A 0.5% perturbation near a top-16 boundary does not shift the answer slightly, it
+# swaps in a different expert, which is a discrete change of computation. Routers are
+# ~1.2 GB across 92 layers, so keeping them exact is nearly free.
+# every *norm* weight, A_log, dt_bias, conv1d, *_res_proj - all tiny vectors that are
+# read elementwise rather than through a dot product, so quantising them buys nothing
+# and costs precision where it is most visible.
+# embed and lm_head - left exact. They sit at the two ends of the network and perturb
+# the logits most directly, so quantising them would confound the very measurement
+# this flag exists to make.
+INT8 = False
+GROUP = 32
+
+
+def q8(w: np.ndarray) -> np.ndarray:
+ """Round-trip a matrix through int8 with one fp32 scale per GROUP elements along the
+ LAST axis, which is the contraction dimension for every matmul here."""
+ if not INT8 or w.ndim != 2 or w.shape[-1] < GROUP:
+ return w
+ r, c = w.shape
+ g = c // GROUP
+ body, tail = w[:, : g * GROUP], w[:, g * GROUP:]
+ b = body.reshape(r, g, GROUP).astype(np.float32)
+ scale = np.abs(b).max(axis=2, keepdims=True) / 127.0
+ scale[scale == 0] = 1.0
+ qb = np.rint(b / scale).clip(-127, 127)
+ out = (qb * scale).reshape(r, g * GROUP)
+ if tail.size:
+ out = np.concatenate([out, tail], axis=1)
+ return out.astype(np.float32)
+
+
+def rms(x: torch.Tensor, w: np.ndarray, eps: float) -> torch.Tensor:
+ wt = torch.from_numpy(w.astype(np.float32))
+ return x * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + eps) * wt
+
+
+def load_attention(sh: Shards, c: K3Config, L: int, is_mla: bool):
+ """Same tensor names and the same A_log truncation as tools/verify_real_layer.py."""
+ lp = PRE + "layers.%d." % L
+ sp = lp + "self_attn."
+ # Big projections go through q8. It is a no-op for anything that is not a 2-D matrix
+ # of at least GROUP columns, so the 1-D norms, A_log and dt_bias below pass through
+ # untouched without needing a special case.
+ g = lambda n: torch.from_numpy(q8(sh.get(sp + n).astype(np.float32))) # noqa: E731
+ if is_mla:
+ m = GatedMLA(c)
+ m.q_a_proj.weight.copy_(g("q_a_proj.weight"))
+ m.q_a_layernorm.weight.copy_(g("q_a_layernorm.weight"))
+ m.q_b_proj.weight.copy_(g("q_b_proj.weight"))
+ m.kv_a_proj_with_mqa.weight.copy_(g("kv_a_proj_with_mqa.weight"))
+ m.kv_a_layernorm.weight.copy_(g("kv_a_layernorm.weight"))
+ m.kv_b_proj.weight.copy_(g("kv_b_proj.weight"))
+ m.o_proj.weight.copy_(g("o_proj.weight"))
+ if m.g_proj is not None:
+ m.g_proj.weight.copy_(g("g_proj.weight"))
+ return m
+ m = KimiDeltaAttention(c)
+ for n in ("q_proj", "k_proj", "v_proj", "g_proj", "o_proj",
+ "f_a_proj", "f_b_proj", "b_proj"):
+ getattr(m, n).weight.copy_(g(n + ".weight"))
+ for nm, mod in (("q", m.q_conv1d), ("k", m.k_conv1d), ("v", m.v_conv1d)):
+ w = sh.get(sp + "%s_conv1d.weight" % nm).astype(np.float32)
+ mod.weight.copy_(torch.from_numpy(w).reshape(mod.weight.shape))
+ alog = sh.get(sp + "A_log").astype(np.float32) # ships 128, PER HEAD
+ m.A_log.copy_(torch.from_numpy(alog[: c.kda_num_heads]))
+ m.dt_bias.copy_(torch.from_numpy(sh.get(sp + "dt_bias").astype(np.float32)))
+ m.o_norm.weight.copy_(torch.from_numpy(sh.get(sp + "o_norm.weight").astype(np.float32)))
+ return m
+
+
+def mlp_forward(sh: Shards, c: K3Config, L: int, hn: torch.Tensor) -> torch.Tensor:
+ """Dense MLP for layer 0, latent MoE for the rest. Mirrors verify_real_layer.py."""
+ lp = PRE + "layers.%d." % L
+ x = hn.numpy().astype(np.float32) # [T, H]
+ T = x.shape[0]
+
+ if L < c.first_k_dense_replace:
+ dp = lp + "mlp."
+ dg = q8(sh.get(dp + "gate_proj.weight").astype(np.float32))
+ du = q8(sh.get(dp + "up_proj.weight").astype(np.float32))
+ dd = q8(sh.get(dp + "down_proj.weight").astype(np.float32))
+ a = situ_glu(torch.from_numpy(np.concatenate([x @ dg.T, x @ du.T], axis=1)),
+ c.situ_beta, c.situ_linear_beta).numpy()
+ return torch.from_numpy(a @ dd.T)
+
+ mp = lp + "block_sparse_moe."
+ gate_w = sh.get(mp + "gate.weight").astype(np.float32)
+ bias = sh.get(mp + "gate.e_score_correction_bias").astype(np.float32)
+ logits = x @ gate_w.T
+ scores = 1.0 / (1.0 + np.exp(-logits.astype(np.float64)))
+ biased = scores + bias # bias steers SELECTION only
+ idx = np.argsort(-biased, axis=1)[:, : c.num_experts_per_token]
+ w = np.take_along_axis(scores, idx, axis=1)
+ w = w / (w.sum(1, keepdims=True) + 1e-20)
+
+ down = q8(sh.get(mp + "routed_expert_down_proj.weight").astype(np.float32))
+ up = q8(sh.get(mp + "routed_expert_up_proj.weight").astype(np.float32))
+ lnorm = sh.get(mp + "routed_expert_norm.weight").astype(np.float32)
+ z = x @ down.T # [T, latent]
+
+ acc = np.zeros((T, c.routed_expert_hidden_size), dtype=np.float32)
+ for e in sorted({int(v) for row in idx for v in row}):
+ base = mp + "experts.%d." % e
+ w1, w3, w2 = dequant(sh, base + "w1"), dequant(sh, base + "w3"), dequant(sh, base + "w2")
+ for t in range(T):
+ hit = np.where(idx[t] == e)[0]
+ if hit.size == 0:
+ continue
+ a = situ_glu(torch.from_numpy(np.stack([z[t] @ w1.T, z[t] @ w3.T]).reshape(1, -1)),
+ c.situ_beta, c.situ_linear_beta).numpy().ravel()
+ acc[t] += float(w[t, hit[0]]) * (a @ w2.T)
+ del w1, w3, w2
+
+ # RMSNorm on the AGGREGATE, not per expert.
+ r = np.sqrt((acc.astype(np.float64) ** 2).mean(1, keepdims=True) + c.rms_norm_eps)
+ y = ((acc / r) * lnorm).astype(np.float32) @ up.T
+
+ s1 = q8(sh.get(mp + "shared_experts.gate_proj.weight").astype(np.float32))
+ s3 = q8(sh.get(mp + "shared_experts.up_proj.weight").astype(np.float32))
+ s2 = q8(sh.get(mp + "shared_experts.down_proj.weight").astype(np.float32))
+ sa = situ_glu(torch.from_numpy(np.concatenate([x @ s1.T, x @ s3.T], axis=1)),
+ c.situ_beta, c.situ_linear_beta).numpy()
+ return torch.from_numpy(y + sa @ s2.T) # shared added UNWEIGHTED
+
+
+def main():
+ if len(sys.argv) < 3:
+ print(__doc__)
+ return 2
+ global INT8
+ argv = [a for a in sys.argv if a != "--int8"]
+ INT8 = len(argv) != len(sys.argv)
+ shard_dir = argv[1]
+ ids = [int(v) for v in argv[2].split(",") if v != ""]
+ outp = argv[3] if len(argv) > 3 else "ref_logits.json"
+ if INT8:
+ print("INT8 SIMULATION: large matrices round-tripped through int8/g%d.\n"
+ " Routers, norms, biases, A_log, dt_bias, conv and res_proj stay exact.\n"
+ " embed and lm_head stay exact." % GROUP)
+
+ c = K3Config()
+ sh = Shards(shard_dir)
+ T, H, eps = len(ids), c.hidden_size, c.rms_norm_eps
+ print("reference forward: %d layers, %d prompt ids, hidden %d, vocab %d"
+ % (c.num_hidden_layers, T, H, c.vocab_size))
+
+ # ---- embedding: read only the referenced rows, not the full 2.35 GB table ----
+ p, dt, shape, off, _nb = sh.index[PRE + "embed_tokens.weight"]
+ itemsize = 2 if dt == "BF16" else 4
+ h = np.empty((T, H), dtype=np.float32)
+ with open(p, "rb") as f:
+ for i, tok in enumerate(ids):
+ f.seek(off + tok * H * itemsize)
+ raw = f.read(H * itemsize)
+ if dt == "BF16":
+ h[i] = (np.frombuffer(raw, dtype=np.uint16).astype(np.uint32) << 16).view(np.float32)
+ else:
+ h[i] = np.frombuffer(raw, dtype=np.float32)
+ h = torch.from_numpy(h).reshape(1, T, H)
+ print("embedded %d ids (%s)" % (T, dt))
+
+ # ---- 93 layers, mirroring k3_ref.DecoderLayer.forward statement for statement ----
+ block_residual = h.new_zeros(T, 0, H)
+ t_start = time.time()
+ for L in range(c.num_hidden_layers):
+ t0 = time.time()
+ lp = PRE + "layers.%d." % L
+ is_mla = c.is_mla(L)
+ prefix_sum = h
+
+ if block_residual.shape[1] > 0:
+ h = apply_attn_res(
+ prefix_sum.view(-1, H), block_residual,
+ torch.from_numpy(sh.get(lp + "self_attention_res_proj.weight")
+ .astype(np.float32)).squeeze(0),
+ torch.from_numpy(sh.get(lp + "self_attention_res_norm.weight")
+ .astype(np.float32)), eps).view(1, T, H)
+
+ if L % c.attn_res_block_size == 0:
+ block_residual = torch.cat(
+ [block_residual, prefix_sum.view(-1, H).unsqueeze(1)], dim=1)
+ prefix_sum = None # reset, k3_ref:998
+
+ hn = rms(h, sh.get(lp + "input_layernorm.weight"), eps)
+ attn = load_attention(sh, c, L, is_mla)
+ att, _ = attn(hn)
+ del attn
+ prefix_sum = att if prefix_sum is None else prefix_sum + att
+
+ h = apply_attn_res(
+ prefix_sum.view(-1, H), block_residual,
+ torch.from_numpy(sh.get(lp + "mlp_res_proj.weight").astype(np.float32)).squeeze(0),
+ torch.from_numpy(sh.get(lp + "mlp_res_norm.weight").astype(np.float32)),
+ eps).view(1, T, H)
+ hpn = rms(h, sh.get(lp + "post_attention_layernorm.weight"), eps)
+ mo = mlp_forward(sh, c, L, hpn.view(T, H)).view(1, T, H)
+ h = mo if prefix_sum is None else prefix_sum + mo
+
+ print(" L%-3d %-3s %-5s %6.1f s |h| max %.6f" %
+ (L, "MLA" if is_mla else "KDA",
+ "dense" if L < c.first_k_dense_replace else "MoE",
+ time.time() - t0, float(h.abs().max())), flush=True)
+ if not torch.isfinite(h).all():
+ print("NON-FINITE hidden state at layer %d -- aborting" % L)
+ return 1
+
+ # ---- model-level AttnRes, final norm, lm_head ----
+ h = apply_attn_res(
+ h.view(-1, H), block_residual,
+ torch.from_numpy(sh.get(PRE + "output_attn_res_proj.weight")
+ .astype(np.float32)).squeeze(0),
+ torch.from_numpy(sh.get(PRE + "output_attn_res_norm.weight")
+ .astype(np.float32)), eps).view(1, T, H)
+ h = rms(h, sh.get(PRE + "norm.weight"), eps)
+
+ last = h.view(T, H)[-1].numpy().astype(np.float32)
+ lm_name = "lm_head.weight" if sh.has("lm_head.weight") else PRE + "lm_head.weight"
+ if not sh.has(lm_name):
+ lm_name = "language_model.lm_head.weight"
+ p, dt, shape, off, _nb = sh.index[lm_name]
+ V = shape[0]
+ logits = np.empty(V, dtype=np.float32)
+ step = 4096
+ itemsize = 2 if dt == "BF16" else 4
+ with open(p, "rb") as f:
+ f.seek(off)
+ for s in range(0, V, step):
+ n = min(step, V - s)
+ raw = f.read(n * H * itemsize)
+ if dt == "BF16":
+ blk = (np.frombuffer(raw, dtype=np.uint16).astype(np.uint32) << 16).view(np.float32)
+ else:
+ blk = np.frombuffer(raw, dtype=np.float32)
+ logits[s:s + n] = blk.reshape(n, H) @ last
+
+ tok = int(np.argmax(logits))
+ print("\nfinal position: argmax token %d, logit %.6f, mean %.6f, max %.6f"
+ % (tok, float(logits[tok]), float(logits.mean()), float(logits.max())))
+ print("total %.1f s" % (time.time() - t_start))
+
+ with open(outp, "w") as f:
+ json.dump({"prompt_ids": ids, "argmax": tok, "vocab": int(V),
+ "logits_bits": np.asarray(logits, dtype=np.float32).view(np.uint32).tolist()},
+ f)
+ print("wrote %s" % outp)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/sim_cache.py b/tools/sim_cache.py
new file mode 100644
index 0000000..fc619ad
--- /dev/null
+++ b/tools/sim_cache.py
@@ -0,0 +1,182 @@
+#!/usr/bin/env python
+"""
+sim_cache.py - how much RAM does Kimi K3 actually need?
+
+THE IDEA
+ Hit rate versus cache size is the question the whole streaming design turns on, and
+ measuring it directly would mean re-running the model once per cache size on a
+ machine big enough to hold the whole expert pool. That is expensive and unnecessary:
+ routing does not depend on the cache, so ONE run produces the entire curve. k3_cache
+ records every (layer, expert) request in order, and this replays that trace at any
+ capacity under any policy.
+
+WHAT IT REPORTS
+ LRU what the engine actually implements.
+ Belady the optimal offline policy, which no real cache can beat. The gap between
+ the two is the most a cleverer replacement policy could ever be worth. If
+ the gap is small, effort belongs in prefetching or pinning, not in
+ replacement.
+ Pinned the hottest N experts held permanently, LRU for the rest. This is what the
+ usage histogram is for.
+
+usage: sim_cache.py expert_trace.bin [--expert-bytes 17547264] [--disk-mbs 1234]
+"""
+from __future__ import annotations
+
+import argparse
+import sys
+from collections import OrderedDict, Counter
+
+import numpy as np
+
+EXPERT_BYTES = 17_547_264 # measured, not assumed: see README
+TOTAL_EXPERTS = 92 * 896
+
+
+def lru(trace, cap):
+ """Returns hits. trace is a list of integer keys."""
+ seen = OrderedDict()
+ hits = 0
+ for k in trace:
+ if k in seen:
+ seen.move_to_end(k)
+ hits += 1
+ else:
+ if len(seen) >= cap:
+ seen.popitem(last=False)
+ seen[k] = 1
+ return hits
+
+
+def belady(trace, cap):
+ """Optimal: evict whatever is needed furthest in the future. Needs the whole trace,
+ which is exactly why no online cache can implement it."""
+ n = len(trace)
+ nxt = [n] * n
+ last = {}
+ for i in range(n - 1, -1, -1):
+ k = trace[i]
+ nxt[i] = last.get(k, n)
+ last[k] = i
+
+ resident = {} # key -> next use index
+ hits = 0
+ for i, k in enumerate(trace):
+ if k in resident:
+ hits += 1
+ resident[k] = nxt[i]
+ continue
+ if len(resident) >= cap:
+ victim = max(resident, key=resident.get)
+ if resident[victim] < nxt[i]:
+ # Everything resident is needed sooner than this one; skip caching it.
+ continue
+ del resident[victim]
+ resident[k] = nxt[i]
+ return hits
+
+
+def pinned_lru(trace, cap, npin):
+ """Hold the npin hottest experts permanently, LRU the remaining capacity.
+
+ Two honesty constraints:
+ - A pinned expert still has to be READ once. Counting its first touch as a hit
+ would make pinning look like it conjures weights out of nothing.
+ - The hot set here is chosen from this very trace, which is future knowledge. Real
+ pinning uses a profile from a previous workload, so this is an UPPER BOUND on
+ what histogram-driven pinning can deliver, not a prediction.
+ """
+ if npin >= cap:
+ npin = cap - 1
+ hot = {k for k, _ in Counter(trace).most_common(npin)}
+ loaded = set()
+ seen = OrderedDict()
+ room = max(cap - len(hot), 1)
+ hits = 0
+ for k in trace:
+ if k in hot:
+ if k in loaded:
+ hits += 1
+ else:
+ loaded.add(k) # compulsory miss, paid once
+ continue
+ if k in seen:
+ seen.move_to_end(k)
+ hits += 1
+ else:
+ if len(seen) >= room:
+ seen.popitem(last=False)
+ seen[k] = 1
+ return hits
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("trace")
+ ap.add_argument("--expert-bytes", type=int, default=EXPERT_BYTES)
+ ap.add_argument("--disk-mbs", type=float, default=1234.0,
+ help="measured random-cold read rate, for the time column")
+ a = ap.parse_args()
+
+ raw = np.fromfile(a.trace, dtype=np.int32)
+ if raw.size % 2:
+ sys.exit("trace is not an even number of int32")
+ pairs = raw.reshape(-1, 2)
+ layers, experts = pairs[:, 0], pairs[:, 1]
+ keys = (layers.astype(np.int64) << 20) | experts.astype(np.int64)
+ trace = keys.tolist()
+
+ n = len(trace)
+ uniq = len(set(trace))
+ per_tok = 1472 # top-16 x 92 MoE layers
+ ntok = max(n // per_tok, 1)
+ print("trace: %d requests, %d distinct experts, about %d token(s)" % (n, uniq, ntok))
+ print("distinct experts touched: %d of %d (%.2f%% of the pool)"
+ % (uniq, TOTAL_EXPERTS, 100.0 * uniq / TOTAL_EXPERTS))
+ print("if nothing were cached: %.2f GB per token\n"
+ % (per_tok * a.expert_bytes / 1e9))
+
+ c = Counter(trace)
+ top = c.most_common(10)
+ print("hottest experts: " + ", ".join("L%d/e%d x%d" % (k >> 20, k & 0xFFFFF, v)
+ for k, v in top[:6]))
+ reuse = sum(v - 1 for v in c.values())
+ print("total reuse: %d of %d requests are repeats (%.1f%%)\n"
+ % (reuse, n, 100.0 * reuse / n))
+
+ caps_gb = [8, 16, 32, 64, 128, 192, 256, 384, 512, 768, 1024, 1450]
+ print("%-9s %8s %9s %9s %9s %12s %11s" %
+ ("CACHE", "SLOTS", "LRU", "BELADY", "PIN+LRU", "GB READ/TOK", "SEC/TOK"))
+ print("-" * 76)
+ for gb in caps_gb:
+ cap = int(gb * 1e9 // a.expert_bytes)
+ if cap < 17:
+ continue
+ h = lru(trace, cap)
+ b = belady(trace, cap)
+ p = pinned_lru(trace, cap, cap // 2)
+ miss = n - h
+ gb_tok = miss * a.expert_bytes / 1e9 / ntok
+ sec = gb_tok * 1000.0 / a.disk_mbs
+ print("%-9s %8d %8.2f%% %8.2f%% %8.2f%% %12.2f %11.2f"
+ % ("%d GB" % gb, cap, 100.0 * h / n, 100.0 * b / n, 100.0 * p / n,
+ gb_tok, sec))
+ print("-" * 76)
+ print("SEC/TOK is expert I/O only, at the measured %.0f MB/s random-cold rate.\n"
+ "It excludes compute, which overlaps with it in a real serving loop."
+ % a.disk_mbs)
+ print("BELADY and PIN+LRU both use future knowledge, so they are ceilings rather\n"
+ "than achievable policies. LRU is what the engine actually does.")
+ comp = uniq
+ print("compulsory misses: %d (every expert must be read at least once), a ceiling of\n"
+ "%.2f%% hit rate for ANY policy at ANY size on this trace."
+ % (comp, 100.0 * (n - comp) / n))
+
+ full = uniq * a.expert_bytes / 1e9
+ print("\nholding every expert this trace touched needs %.2f GB." % full)
+ print("holding the whole pool needs %.2f GB." % (TOTAL_EXPERTS * a.expert_bytes / 1e9))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/tok.py b/tools/tok.py
new file mode 100644
index 0000000..c6bec0f
--- /dev/null
+++ b/tools/tok.py
@@ -0,0 +1,165 @@
+#!/usr/bin/env python
+"""
+tok.py - text to token ids and back, for driving the C engine.
+
+WHY THE TOKENIZER IS IN PYTHON AND THE ENGINE IS IN C
+ Kimi K3 uses a tiktoken BPE with 163,584 ranks plus 256 special tokens. Writing that
+ in C is a self-contained project of its own and would prove nothing about the
+ inference engine, which is what this work is about. So tokenisation happens here,
+ ids go to the engine, and ids come back here to be decoded. The boundary is explicit
+ rather than hidden.
+
+ The engine therefore does text in and text out only in the sense that this script
+ wraps it. That is stated plainly rather than glossed over.
+
+FORMAT
+ tiktoken.model is one "base64(token_bytes) rank" pair per line. The chat template
+ and special tokens come from tokenizer_config.json.
+
+usage:
+ tok.py encode "some text" -> prints comma separated ids
+ tok.py decode 1,2,3 -> prints the text
+ tok.py chat "some text" -> ids with the chat template applied
+"""
+from __future__ import annotations
+
+import base64
+import json
+import os
+import sys
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+ROOT = os.path.dirname(os.path.dirname(HERE))
+
+
+def find_files():
+ """Locate the released tokenizer files. Public: tok_parity.py calls this too.
+
+ A single hardcoded path works in a full checkout and nowhere else. On a machine where
+ only the tokenizer files were copied across, a hardcoded join raises FileNotFoundError
+ from inside the oracle, which surfaces as a tokenizer PARITY FAILURE rather than a
+ missing-path error -- the most misleading possible framing, since the tokenizer is
+ fine.
+
+ Order: explicit K3_TOK_FILES, the in-repo location, then conventional spots. On
+ failure every candidate is listed, so the fix is obvious rather than guessed at.
+ """
+ cands = []
+ env = os.environ.get("K3_TOK_FILES")
+ if env:
+ cands.append(env)
+ cands += [
+ os.path.join(ROOT, "kimi_k3_hf", "files"),
+ os.path.join(os.path.dirname(ROOT), "kimi_k3_hf", "files"),
+ os.path.expanduser("~/k3/hf"),
+ os.path.expanduser("~/k3model"),
+ ]
+ for c in cands:
+ if os.path.isfile(os.path.join(c, "tiktoken.model")):
+ return c
+ raise SystemExit(
+ "cannot find tiktoken.model; looked in:\n " + "\n ".join(cands) +
+ "\nset K3_TOK_FILES to the directory holding tiktoken.model")
+
+
+FILES = find_files()
+
+
+def split_pattern() -> str:
+ """Read TikTokenTokenizer.pat_str out of the released tokenizer.
+
+ It is written as a multi-line '|'.join([...]) of eight raw strings, so scraping it
+ with line matching is fragile and importing the module would drag in transformers,
+ tokenizers and a relative import. Parsing the source with ast gets the exact value
+ with no dependencies and no guessing: a tokenizer whose split pattern differs even
+ slightly produces different ids, and the engine would then be fed a prompt the model
+ never saw in that form.
+ """
+ import ast
+
+ src = open(os.path.join(FILES, "tokenization_kimi.py"), encoding="utf-8").read()
+ tree = ast.parse(src)
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Assign):
+ continue
+ if not any(isinstance(t, ast.Name) and t.id == "pat_str" for t in node.targets):
+ continue
+ v = node.value
+ # "sep".join([...]) of string literals
+ if (isinstance(v, ast.Call) and isinstance(v.func, ast.Attribute)
+ and v.func.attr == "join"):
+ sep = ast.literal_eval(v.func.value)
+ parts = ast.literal_eval(v.args[0])
+ return sep.join(parts)
+ return ast.literal_eval(v) # a plain string literal
+ raise SystemExit("pat_str not found in tokenization_kimi.py")
+
+
+def load():
+ import tiktoken
+
+ ranks = {}
+ with open(os.path.join(FILES, "tiktoken.model"), encoding="utf-8") as f:
+ for line in f:
+ tok, rank = line.split()
+ ranks[base64.b64decode(tok)] = int(rank)
+
+ cfg = json.load(open(os.path.join(FILES, "tokenizer_config.json"), encoding="utf-8"))
+ special = {}
+ for _id, entry in (cfg.get("added_tokens_decoder") or {}).items():
+ special[entry["content"]] = int(_id)
+
+ pat = split_pattern()
+
+ enc = tiktoken.Encoding(name="kimi_k3", pat_str=pat, mergeable_ranks=ranks,
+ special_tokens=special)
+ return enc, cfg, special
+
+
+def main():
+ if len(sys.argv) < 3:
+ print(__doc__)
+ return 2
+ mode, arg = sys.argv[1], sys.argv[2]
+ enc, cfg, special = load()
+
+ if mode == "encode":
+ ids = enc.encode(arg, allowed_special=set(special))
+ print(",".join(str(i) for i in ids))
+ elif mode == "chat":
+ # Apply the released chat template if there is one, so the model sees the format
+ # it was trained on. Without it a chat model answers as if mid-document.
+ tmpl = cfg.get("chat_template")
+ if tmpl:
+ from jinja2 import Template
+ text = Template(tmpl).render(
+ messages=[{"role": "user", "content": arg}],
+ add_generation_prompt=True, bos_token=cfg.get("bos_token", ""),
+ )
+ else:
+ text = arg
+ ids = enc.encode(text, allowed_special=set(special))
+ sys.stderr.write("templated prompt:\n%s\n---\n" % text)
+ print(",".join(str(i) for i in ids))
+ elif mode == "decode":
+ ids = [int(x) for x in arg.replace(" ", "").split(",") if x != ""]
+ rev = {v: k for k, v in special.items()}
+ out, buf = [], []
+ for i in ids:
+ if i in rev:
+ if buf:
+ out.append(enc.decode(buf)); buf = []
+ out.append(rev[i])
+ else:
+ buf.append(i)
+ if buf:
+ out.append(enc.decode(buf))
+ print("".join(out))
+ else:
+ print(__doc__)
+ return 2
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/tok_parity.py b/tools/tok_parity.py
new file mode 100644
index 0000000..4f127ea
--- /dev/null
+++ b/tools/tok_parity.py
@@ -0,0 +1,152 @@
+#!/usr/bin/env python
+"""tok_parity.py - prove the C tokenizer matches the Python oracle, case by case.
+
+WHY THIS EXISTS
+ k3_tok.h populates the Tok struct from tiktoken.model directly, so the whole
+ encode path (byte-level keying, rank-BPE merging, the Kimi \\p{Han} pre-tokenizer)
+ is new wiring around vendored machinery. "It produced ids" proves nothing -- a
+ mis-keyed vocab still produces ids, just one per byte. This compares against
+ tiktoken itself on the cases that actually separate a correct tokenizer from a
+ plausible one.
+
+ Divergence is reported per case with both id lists, because a single differing id
+ in the middle of a long prompt is invisible in aggregate counts.
+
+usage: tok_parity.py <path-to-test_tok.exe> [--verbose]
+"""
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+import tempfile
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+ROOT = os.path.dirname(os.path.dirname(HERE))
+
+
+sys.path.insert(0, HERE)
+import tok as oracle # noqa: E402 the reference Python tokenizer
+
+# The tokenizer files are located by tok.find_files(), not by a second copy of the same
+# search. Two copies of a path search drift, and when they drift this gate reports a
+# tokenizer DIVERGENCE for what is actually a path disagreement between the two halves
+# of the comparison, the most misleading failure this script can produce.
+FILES = oracle.find_files()
+
+# Each case names the property it probes, so a failure says what broke.
+CASES = [
+ ("ascii plain", "Hello world"),
+ ("ascii sentence", "The quick brown fox jumps over the lazy dog."),
+ ("leading space", " leading"),
+ ("trailing space", "trailing "),
+ ("double space", "two spaces"),
+ ("tab", "a\tb"),
+ ("newlines", "line1\nline2\n\nline4"),
+ ("crlf", "dos\r\nline"),
+ ("many spaces", "a" + " " * 17 + "b"),
+ ("digits run", "1234567890 42 007"),
+ ("mixed alnum", "abc123def456"),
+ ("punctuation", "!@#$%^&*()_+-=[]{}|;':\",./<>?"),
+ ("contractions", "don't can't it's I'm we'll they've he'd"),
+ ("caps run", "HTTP HTML JSON XML API"),
+ ("camelCase", "camelCaseIdentifierName"),
+ ("snake_case", "snake_case_identifier_name"),
+ # Han is the K3-specific pre-tokenizer rule: a leading Han run splits, and Han is
+ # excluded from the letter classes. This is the single most likely thing to break.
+ ("han only", "\u4f60\u597d\u4e16\u754c"),
+ ("han + ascii", "\u4f60\u597d world"),
+ ("ascii + han", "hello \u4f60\u597d"),
+ ("han sentence", "\u6211\u4eec\u5728\u6d4b\u8bd5\u5206\u8bcd\u5668\u3002"),
+ ("han + digits", "\u7b2c123\u9875"),
+ ("japanese", "\u3053\u3093\u306b\u3061\u306f\u4e16\u754c"),
+ ("korean", "\uc548\ub155\ud558\uc138\uc694"),
+ ("cyrillic", "\u041f\u0440\u0438\u0432\u0435\u0442 \u043c\u0438\u0440"),
+ ("arabic", "\u0645\u0631\u062d\u0628\u0627 \u0628\u0627\u0644\u0639\u0627\u0644\u0645"),
+ ("greek", "\u0393\u03b5\u03b9\u03b1 \u03c3\u03bf\u03c5"),
+ ("accents", "caf\u00e9 na\u00efve r\u00e9sum\u00e9 \u00fcber"),
+ ("emoji", "\U0001f600\U0001f680\U0001f9e0"),
+ ("emoji + text", "ship it \U0001f680 now"),
+ ("emoji zwj", "\U0001f469\u200d\U0001f4bb"),
+ ("code c", "int main(void){ return 0; }"),
+ ("code python", "def f(x):\n return x ** 2\n"),
+ ("json", '{"key": [1, 2, {"n": null}], "b": true}'),
+ ("url", "https://example.com/a/b?c=d&e=f#g"),
+ ("path windows", "C:\\Users\\dev\\project\\file.c"),
+ ("markdown", "# Title\n\n- item **bold** `code`\n"),
+ ("repeated char", "aaaaaaaaaaaaaaaaaaaa"),
+ ("long word", "supercalifragilisticexpialidocious"),
+ ("mixed script", "hello \u4f60\u597d \u041c\u0438\u0440 \U0001f600 123"),
+ ("empty-ish", " "),
+ ("single char", "x"),
+ ("high bytes", "\u00ff\u00fe\u00fd"),
+ ("math symbols", "\u2211 \u221e \u2260 \u2264 \u03c0 \u00d7 \u00f7"),
+ ("quotes typographic", "\u201cquoted\u201d and \u2018single\u2019"),
+ ("dashes", "em\u2014dash en\u2013dash hyphen-minus"),
+]
+
+
+def c_encode(exe: str, text: str) -> list[int]:
+ """Always go through a file.
+
+ argv is re-encoded at the process boundary (on Windows into the active code page),
+ so a non-ASCII case sent as an argument reaches the C side as different bytes than
+ the oracle saw. That produces confident, entirely bogus 'divergences'. Writing the
+ UTF-8 bytes to a file and having C read them verbatim compares the same input.
+ """
+ fd, tmp = tempfile.mkstemp(prefix="k3_parity_", suffix=".txt")
+ try:
+ with os.fdopen(fd, "wb") as f:
+ f.write(text.encode("utf-8"))
+ r = subprocess.run([exe, FILES, "encodefile", tmp],
+ capture_output=True, text=True, encoding="utf-8")
+ if r.returncode != 0:
+ raise RuntimeError(f"test_tok failed: {r.stderr.strip()}")
+ line = r.stdout.strip().splitlines()[-1] if r.stdout.strip() else ""
+ return [int(x) for x in line.split(",")] if line else []
+ finally:
+ if os.path.exists(tmp):
+ os.remove(tmp)
+
+
+def main() -> int:
+ if len(sys.argv) < 2:
+ print(__doc__)
+ return 2
+ exe = sys.argv[1]
+ verbose = "--verbose" in sys.argv
+
+ enc, _cfg, special = oracle.load()
+ allowed = set(special)
+ npass = nfail = 0
+ failures = []
+
+ for name, text in CASES:
+ want = enc.encode(text, allowed_special=allowed)
+ got = c_encode(exe, text)
+ if want == got:
+ npass += 1
+ if verbose:
+ print(f" PASS {name:22s} {len(got):3d} ids")
+ else:
+ nfail += 1
+ failures.append((name, text, want, got))
+ print(f" FAIL {name:22s} oracle={len(want)} c={len(got)}")
+ print(f" oracle: {want}")
+ print(f" c : {got}")
+
+ print()
+ print(f"tokenizer parity: {npass}/{npass + nfail} cases match")
+ if failures:
+ print("\nFAILING CASES (first divergent index shown):")
+ for name, text, want, got in failures:
+ i = 0
+ while i < min(len(want), len(got)) and want[i] == got[i]:
+ i += 1
+ print(f" {name}: diverges at id index {i} input={text!r}")
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tools/verify_expert.py b/tools/verify_expert.py
new file mode 100644
index 0000000..2488dfc
--- /dev/null
+++ b/tools/verify_expert.py
@@ -0,0 +1,125 @@
+#!/usr/bin/env python
+"""
+verify_expert.py - close the last link in the loading chain.
+
+THE CHAIN, AND THE LINK THIS CHECKS
+ tools/fetch_mxfp4.py pulled real bytes for
+ language_model.model.layers.1.block_sparse_moe.experts.0.w1
+ straight out of the released checkpoint over HTTP range reads, and wrote
+ fixtures/mxfp4.json. test_ops already proves k3_mxfp4_dequant reproduces that
+ fixture bit for bit.
+
+ But that proves the ARITHMETIC, not the READER. The fixture's bytes were located by
+ Python, using Python's parse of the header. Nothing yet proves the C code finds the
+ same bytes in a local shard file.
+
+ So this compares three things against the fixture, in increasing order of what a
+ failure would mean:
+ packed bytes - if these differ, k3_st computed a wrong file offset
+ scale bytes - if only these differ, the scale tensor offset is wrong, which is
+ the subtler bug: weights would be right and magnitudes wrong
+ float bits - the composed result, exact
+
+ Zero tolerance throughout. Both sides are reading identical bytes off identical
+ weights; there is nothing here that could legitimately differ.
+
+usage: verify_expert.py [expert_dump.json] [fixtures/mxfp4.json]
+"""
+from __future__ import annotations
+
+import json
+import os
+import sys
+
+import numpy as np
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from _paths import FIX_OPS
+
+DEF_FX = os.path.join(FIX_OPS, "mxfp4.json")
+
+
+def main():
+ dump_p = sys.argv[1] if len(sys.argv) > 1 else "expert_dump.json"
+ fx_p = sys.argv[2] if len(sys.argv) > 2 else DEF_FX
+ d = json.load(open(dump_p, encoding="utf-8"))
+ fx = json.load(open(fx_p, encoding="utf-8"))
+
+ print("C dump : layer %d expert 0 w1, %d rows x %d packed cols"
+ % (d["layer"], d["rows"], d["pcols"]))
+ print("fixture : %s" % fx["source"])
+ print(" %d rows, %d packed cols, logical width %d, group %d"
+ % (fx["rows"], fx["packed_cols"], fx["logical_width"], fx["group_size"]))
+
+ if not fx["source"].endswith("layers.%d.block_sparse_moe.experts.0.w1" % d["layer"]):
+ print("\nMISMATCHED SOURCES: the fixture is for %s but the dump is layer %d."
+ % (fx["source"], d["layer"]))
+ print("Re-run test_expert with the layer the fixture was built from.")
+ return 2
+
+ fails = []
+
+ # ---- 1. raw packed bytes: did the reader find the right place in the file? -------
+ cp = np.array(d["packed"], dtype=np.uint8)
+ fp = np.array(fx["packed"]["data"], dtype=np.uint8)[: cp.size]
+ nbad = int((cp != fp).sum())
+ if nbad:
+ i = int(np.argmax(cp != fp))
+ fails.append("packed bytes: %d/%d differ, first at [%d] C=%d fixture=%d"
+ % (nbad, cp.size, i, cp[i], fp[i]))
+ else:
+ print("\n packed bytes : %d/%d IDENTICAL -> k3_st found the right offset"
+ % (cp.size, cp.size))
+
+ # ---- 2. scale bytes -------------------------------------------------------------
+ cs = np.array(d["scales"], dtype=np.uint8)
+ fs = np.array(fx["scales"]["data"], dtype=np.uint8)[: cs.size]
+ nbad = int((cs != fs).sum())
+ if nbad:
+ i = int(np.argmax(cs != fs))
+ fails.append("scale bytes: %d/%d differ, first at [%d] C=%d fixture=%d"
+ % (nbad, cs.size, i, cs[i], fs[i]))
+ else:
+ print(" scale bytes : %d/%d IDENTICAL -> the scale tensor offset is right"
+ % (cs.size, cs.size))
+
+ # ---- 3. dequantised floats, compared as bit patterns ----------------------------
+ cb = np.array(d["bits"], dtype=np.uint32)
+ ref = np.array(fx["expected"]["data"], dtype=np.float32)[: cb.size]
+ rb = ref.view(np.uint32)
+ nbad = int((cb != rb).sum())
+ if nbad:
+ i = int(np.argmax(cb != rb))
+ cf = cb[i : i + 1].view(np.float32)[0]
+ fails.append("float bits: %d/%d differ, first at [%d] C=%.9g (0x%08x) "
+ "fixture=%.9g (0x%08x)" % (nbad, cb.size, i, cf, cb[i], ref[i], rb[i]))
+ else:
+ print(" float bits : %d/%d IDENTICAL -> dequantisation is exact end to end"
+ % (cb.size, cb.size))
+
+ # ---- the nibble-order trap, checked rather than assumed -------------------------
+ swapped = np.array(fx["expected_swapped_nibbles"]["first64"], dtype=np.float32)
+ mine = cb[:64].view(np.float32)
+ if np.array_equal(mine, swapped):
+ fails.append("the output matches the SWAPPED nibble order: every adjacent pair "
+ "of weights is transposed. Statistics look perfect and the model "
+ "is wrong.")
+ else:
+ agree = int((mine == swapped).sum())
+ print(" nibble order : differs from the swapped order in %d of the first 64 "
+ "(a coincidental match on %d)" % (64 - agree, agree))
+
+ print()
+ if fails:
+ print("FAILED:")
+ for f in fails:
+ print(" " + f)
+ return 1
+ print("VERIFIED END TO END: bytes read from the local shard by the C reader are "
+ "identical to bytes fetched independently from the released checkpoint, and "
+ "dequantise bit-exactly.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/verify_kda.py b/tools/verify_kda.py
new file mode 100644
index 0000000..2e21b6e
--- /dev/null
+++ b/tools/verify_kda.py
@@ -0,0 +1,151 @@
+#!/usr/bin/env python
+"""
+verify_kda.py - check the pure-torch KDA reference against the REAL released
+KimiDeltaAttention class.
+
+This is the most valuable single check in the project. KDA is 69 of the 93 layers, its
+recurrence is the most intricate part of the model, and it is where a silent ordering
+bug would do the most damage.
+
+REQUIREMENTS
+ A machine where `fla` imports, in practice, Linux. A GPU is not required, but it
+ changes what is being tested: with CUDA present fla dispatches to its Triton kernels,
+ and without it fla prints "Triton is not supported on current platform, roll back to
+ CPU" and runs a pure-torch fallback. Only the CUDA run exercises the kernels the
+ released model uses in production. See the device-selection comment in main().
+
+STRUCTURAL DIFFERENCE TO WATCH
+ The released forward ends with
+ g = g_proj(x); g = rearrange(g, '... (h d) -> ... h d'); o = o_norm(o, g)
+ where o_norm is fla's FusedRMSNormGated(head_v_dim, activation="sigmoid"), a FUSED
+ gated norm that takes the RAW gate and applies the sigmoid internally.
+
+ The reference implementation instead does RMSNorm(o) followed by an explicit
+ multiply by sigmoid(g_proj(x)). Those are the same function only if the fused kernel
+ is genuinely norm-then-sigmoid-gate in that order. This script proves it rather than
+ assuming it, because the plausible alternatives, gating before norming, or norming
+ the gate, both run cleanly and produce a different model.
+
+MODE SELECTION
+ modeling_kimi_linear.py:561 selects 'fused_recurrent' when use_cache and q_len == 1,
+ and otherwise self.mode, which is 'chunk' (:481). A single token therefore exercises
+ the recurrent kernel and a multi-token sequence the chunked one. Both are compared
+ here: the two released paths must agree with each other and with the reference.
+"""
+from __future__ import annotations
+
+import os
+import sys
+
+import torch
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+ROOT = os.path.dirname(os.path.dirname(HERE))
+HF = os.path.join(ROOT, "kimi_k3_hf", "files")
+if not os.path.isdir(HF):
+ HF = os.path.join(os.path.expanduser("~"), "k3c", "hf_files")
+
+sys.path.insert(0, HERE)
+from k3_ref import KimiDeltaAttention as RefKDA, tiny_config # noqa: E402
+
+
+def load_real():
+ for base in (os.path.dirname(HF), os.path.expanduser("~/k3c")):
+ if base not in sys.path:
+ sys.path.insert(0, base)
+ pkg = os.path.basename(HF)
+ mod = __import__("%s.modeling_kimi_linear" % pkg, fromlist=["KimiDeltaAttention"])
+ cfg = __import__("%s.configuration_kimi_k3" % pkg, fromlist=["KimiLinearConfig"])
+ return mod.KimiDeltaAttention, cfg.KimiLinearConfig
+
+
+def compare(tag, a, b, tol=2e-4):
+ d = (a - b).abs()
+ ok = bool(d.max() < tol)
+ print(" %-22s max abs %.3e mean %.3e %s"
+ % (tag, d.max(), d.mean(), "MATCH" if ok else "DIVERGED"))
+ if not ok:
+ i = int(d.argmax())
+ print(" worst element %d: reference %.7f released %.7f"
+ % (i, float(a.flatten()[i]), float(b.flatten()[i])))
+ return ok
+
+
+def main():
+ print("torch", torch.__version__)
+ try:
+ RealKDA, KimiLinearConfig = load_real()
+ except Exception as e:
+ print("cannot import released modeling code: %s: %s" % (type(e).__name__, e))
+ return 2
+
+ c = tiny_config()
+ torch.manual_seed(0)
+
+ real_cfg = KimiLinearConfig(
+ hidden_size=c.hidden_size,
+ num_hidden_layers=c.num_hidden_layers,
+ num_attention_heads=c.num_attention_heads,
+ vocab_size=c.vocab_size,
+ rms_norm_eps=c.rms_norm_eps,
+ attn_res_block_size=c.attn_res_block_size,
+ linear_attn_config={
+ "num_heads": c.kda_num_heads,
+ "head_dim": c.kda_head_dim,
+ "short_conv_kernel_size": c.short_conv_kernel_size,
+ "gate_lower_bound": c.gate_lower_bound,
+ "use_full_rank_gate": True,
+ "full_attn_layers": c.full_attn_layers,
+ "kda_layers": [i for i in range(1, c.num_hidden_layers + 1)
+ if i not in c.full_attn_layers],
+ },
+ )
+ # Device selection decides WHICH released kernel is under test, so it is not an
+ # implementation detail. With CUDA present, fla dispatches to its Triton kernels and
+ # this script validates those. Without it, fla falls back to a pure-torch CPU path
+ # and this script validates that instead. Both are worth checking; only the CUDA run
+ # tests the kernels the released model actually uses in production.
+ #
+ # The reference module is placed on the same device either way, so the comparison is
+ # like for like. Do not mix devices: a Triton kernel handed a CPU tensor fails with
+ # "Pointer argument cannot be accessed from Triton (cpu tensor?)".
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
+ print("device:", dev, torch.cuda.get_device_name(0) if dev == "cuda" else "")
+ real = RealKDA(real_cfg, layer_idx=1).to(torch.float32).to(dev).eval()
+ ref = RefKDA(c).to(torch.float32).to(dev).eval()
+
+ rm, om = dict(real.named_parameters()), dict(ref.named_parameters())
+ print("\nreal params %d, ref %d" % (len(rm), len(om)))
+ missing = []
+ with torch.no_grad():
+ for n, p in om.items():
+ if n in rm and rm[n].shape == p.shape:
+ p.copy_(rm[n])
+ else:
+ missing.append((n, tuple(p.shape), tuple(rm[n].shape) if n in rm else None))
+ if missing:
+ print("SHAPE/NAME MISMATCH, fix before trusting anything downstream:")
+ for n, o_s, r_s in missing:
+ print(" %-28s reference=%-16s released=%s" % (n, o_s, r_s))
+ print("\nreal-only names:", sorted(set(rm) - set(om)))
+ return 1
+ print("all %d parameters copied by name with matching shapes" % len(om))
+
+ ok = True
+ for T in (1, 4, 8, 16, 17):
+ x = torch.randn(1, T, c.hidden_size, device=dev)
+ with torch.no_grad():
+ y_ref, _ = ref(x)
+ out = real(x, attention_mask=None, cache_params=None, use_cache=False)
+ y_real = out[0] if isinstance(out, tuple) else out
+ ok &= compare("T=%-3d reference vs released" % T, y_ref.float().cpu(), y_real.float().cpu())
+
+ print("\nT=1 exercises the fused_recurrent kernel; T>1 exercises the chunked one")
+ print("(modeling_kimi_linear.py:561). Both must agree with the reference and with")
+ print("each other.")
+ print("\nVERDICT: %s" % ("KDA REFERENCE CONFIRMED" if ok else "DIVERGENCE PRESENT"))
+ return 0 if ok else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/verify_mla.py b/tools/verify_mla.py
new file mode 100644
index 0000000..f02bdb1
--- /dev/null
+++ b/tools/verify_mla.py
@@ -0,0 +1,153 @@
+#!/usr/bin/env python
+"""
+verify_mla.py - check the pure-torch MLA reference against the REAL released
+KimiMLAAttention class.
+
+WHY THIS IS POSSIBLE AT ALL
+ modeling_kimi_linear.py imports fla at module scope, and fla's KDA kernels are
+ Triton-backed, so the whole file fails to import on a machine without Triton. But
+ GatedMLA itself uses no fla, it is plain torch. So on a host where fla imports, the
+ real KimiMLAAttention class can be instantiated directly, loaded with the reference
+ implementation's weights, and compared output for output.
+
+ This closes the most important gap in the validation chain. Without it, the C engine
+ is checked against the pure-torch reference and the reference is checked only against
+ itself, so a shared misreading of the architecture would pass every test in the
+ project. This script checks the reference against the released code.
+
+TWO DIFFERENCES THAT ARE EXPECTED AND ARE NOT BUGS
+ 1. KV cache layout. KimiDynamicCache.update (modeling_kimi_linear.py:157-173)
+ stores the EXPANDED key and value states: 96 heads x (192 + 128) floats per token
+ per layer. The reference caches the COMPRESSED latent, 512 + 64 per token per
+ layer, and re-expands on use, 53x less memory, and what any serving engine does.
+ The two are mathematically identical, so outputs must still agree to tolerance.
+ 2. This script runs without a cache at all (one forward pass over the full
+ sequence), which removes difference 1 from the comparison entirely.
+
+USAGE
+ python verify_mla.py
+
+ Requires torch, fla, and the released modeling code on the import path.
+"""
+from __future__ import annotations
+
+import os
+import sys
+
+import torch
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+ROOT = os.path.dirname(os.path.dirname(HERE))
+HF = os.path.join(ROOT, "kimi_k3_hf", "files")
+if not os.path.isdir(HF):
+ HF = os.path.join(os.path.expanduser("~"), "k3c", "hf_files")
+
+sys.path.insert(0, HERE)
+sys.path.insert(0, HF)
+
+from k3_ref import GatedMLA, tiny_config # noqa: E402
+
+
+def main():
+ print("torch", torch.__version__)
+ # The released modeling file uses RELATIVE imports (from .configuration_kimi_k3
+ # import ...), so it must be loaded as a package, not as a top-level module. It
+ # also targets transformers 4.56.2 exactly: on 5.x, OutputRecorder has moved and
+ # the import fails. config.json records the version it was written against.
+ try:
+ import transformers
+ print("transformers", transformers.__version__)
+ for base in (os.path.dirname(HF), os.path.expanduser("~/k3c")):
+ if base not in sys.path:
+ sys.path.insert(0, base)
+ pkg = os.path.basename(HF)
+ mod = __import__("%s.modeling_kimi_linear" % pkg, fromlist=["KimiMLAAttention"])
+ cfgmod = __import__("%s.configuration_kimi_k3" % pkg, fromlist=["KimiLinearConfig"])
+ KimiMLAAttention = mod.KimiMLAAttention
+ KimiLinearConfig = cfgmod.KimiLinearConfig
+ except Exception as e:
+ print("cannot import the released modeling code: %s: %s" % (type(e).__name__, e))
+ print("Needs: transformers==4.56.2, flash-linear-attention, fla-core, triton,")
+ print("an __init__.py inside the modeling directory, and its PARENT on sys.path.")
+ return 2
+
+ c = tiny_config()
+ torch.manual_seed(0)
+
+ real_cfg = KimiLinearConfig(
+ hidden_size=c.hidden_size,
+ num_hidden_layers=c.num_hidden_layers,
+ num_attention_heads=c.num_attention_heads,
+ vocab_size=c.vocab_size,
+ q_lora_rank=c.q_lora_rank,
+ kv_lora_rank=c.kv_lora_rank,
+ qk_nope_head_dim=c.qk_nope_head_dim,
+ qk_rope_head_dim=c.qk_rope_head_dim,
+ v_head_dim=c.v_head_dim,
+ rms_norm_eps=c.rms_norm_eps,
+ mla_use_nope=True,
+ mla_use_output_gate=c.mla_use_output_gate,
+ attn_res_block_size=c.attn_res_block_size,
+ )
+ real_cfg._attn_implementation = "eager"
+
+ real = KimiMLAAttention(real_cfg, layer_idx=3).to(torch.float32).eval()
+ ref = GatedMLA(c).to(torch.float32).eval()
+
+ # Copy the released weights into the reference module by parameter name. A name that
+ rm = dict(real.named_parameters())
+ om = dict(ref.named_parameters())
+ print("\nreal parameters : %d" % len(rm))
+ print("reference parameters : %d" % len(om))
+ missing, copied = [], 0
+ with torch.no_grad():
+ for n, p in om.items():
+ if n in rm and rm[n].shape == p.shape:
+ p.copy_(rm[n]); copied += 1
+ else:
+ missing.append((n, tuple(p.shape),
+ tuple(rm[n].shape) if n in rm else None))
+ print("copied %d, mismatched/missing %d" % (copied, len(missing)))
+ for n, ref_shape, real_shape in missing:
+ print(" %-34s reference=%-18s released=%s" % (n, ref_shape, real_shape))
+ if missing:
+ print("\nSHAPE MISMATCH means the reference module is structurally different")
+ print("from the released one. Fix that before trusting anything downstream.")
+ return 1
+
+ # CAUSALITY IS THE CALLER'S JOB. eager_attention_forward (modeling_kimi_linear.py
+ # :325-326) only applies a mask "if attention_mask is not None", so passing None
+ # makes the real module run BIDIRECTIONAL attention. The causal mask is built by
+ # KimiLinearModel.forward via create_causal_mask and handed down. The reference
+ # masks internally, so without this the two cannot agree, and the mismatch would
+ # look like a model bug when it is purely a harness artefact.
+ Tq = 7
+ neg = torch.finfo(torch.float32).min
+ causal = torch.full((1, 1, Tq, Tq), neg)
+ causal = torch.triu(causal, diagonal=1) # 0 on/below the diagonal
+
+ x = torch.randn(1, Tq, c.hidden_size)
+ with torch.no_grad():
+ y_ref, _ = ref(x)
+ y_real = real(x, attention_mask=causal, position_ids=None, past_key_values=None)
+ if isinstance(y_real, tuple):
+ y_real = y_real[0]
+
+ d = (y_ref - y_real).abs()
+ rel = d / (y_real.abs() + 1e-6)
+ print("\n=== REFERENCE MLA vs THE RELEASED KimiMLAAttention ===")
+ print(" shapes : ref %s real %s" % (list(y_ref.shape), list(y_real.shape)))
+ print(" max abs diff: %.3e" % d.max())
+ print(" mean abs : %.3e" % d.mean())
+ print(" max rel diff: %.3e" % rel.max())
+ ok = bool(d.max() < 1e-4)
+ print(" VERDICT : %s" % ("MATCH" if ok else "DIVERGED"))
+ if not ok:
+ i = int(d.argmax())
+ print(" worst element %d: ref %.7f real %.7f" %
+ (i, float(y_ref.flatten()[i]), float(y_real.flatten()[i])))
+ return 0 if ok else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/verify_real_layer.py b/tools/verify_real_layer.py
new file mode 100644
index 0000000..52bcfb5
--- /dev/null
+++ b/tools/verify_real_layer.py
@@ -0,0 +1,350 @@
+#!/usr/bin/env python
+"""
+verify_real_layer.py - does the C engine compute a REAL Kimi K3 layer correctly?
+
+THE ONE THING THIS TESTS THAT NOTHING ELSE DOES
+ Every earlier test ran on weights this project generated. That validates the
+ arithmetic and says nothing about the BINDING: whether k3_bind attached
+ q_proj.weight to the q slot rather than the k slot, whether a matrix needed
+ transposing, whether A_log was taken per head or per channel. Those failures all
+ produce finite, plausible, wrong numbers, and no self-consistent test can see them.
+
+ So this reads the same shards independently, in Python, builds the reference module
+ from tools/k3_ref.py, and compares stage by stage. A disagreement localises to a
+ stage, and within a stage to a handful of tensors.
+
+STAGES
+ A KDA attention output 15 attention tensors, the recurrence, the decay
+ B router indices + weights gate.weight and e_score_correction_bias
+ C MoE output latent down/up, the aggregate norm, the shared expert,
+ and the streamed MXFP4 routed experts
+
+TOLERANCE
+ The C engine accumulates in double and torch in float32, so exact equality is not
+ expected and demanding it would be a false alarm. What matters is that the error
+ sits at float32 rounding for the width involved, not at the level a swapped tensor
+ would produce. A wrong binding does not miss by 1e-6; it misses by ~1.
+
+usage: verify_real_layer.py <shard_dir> [real_layer.json]
+"""
+from __future__ import annotations
+
+import json
+import os
+import struct
+import sys
+
+import numpy as np
+import torch
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, HERE)
+from k3_ref import (K3Config, GatedMLA, KimiDeltaAttention, RMSNorm, # noqa: E402
+ situ_glu)
+
+PRE = "language_model.model."
+E2M1 = np.array([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0,
+ -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0], dtype=np.float32)
+
+
+class Shards:
+ """A deliberately separate safetensors reader. Sharing code with the C side, or
+ even with tools/verify_st.py's parse, would weaken the independence."""
+
+ def __init__(self, d):
+ self.index = {}
+ self.files = {}
+ for fn in sorted(os.listdir(d)):
+ if not fn.endswith(".safetensors"):
+ continue
+ p = os.path.join(d, fn)
+ with open(p, "rb") as f:
+ n = struct.unpack("<Q", f.read(8))[0]
+ hdr = json.loads(f.read(n).decode("utf-8"))
+ base = 8 + n
+ for name, e in hdr.items():
+ if name == "__metadata__":
+ continue
+ a, b = e["data_offsets"]
+ self.index[name] = (p, e["dtype"], tuple(e["shape"]), base + a, b - a)
+
+ def raw(self, name):
+ p, dt, shape, off, nb = self.index[name]
+ with open(p, "rb") as f:
+ f.seek(off)
+ return f.read(nb), dt, shape
+
+ def get(self, name) -> np.ndarray:
+ buf, dt, shape = self.raw(name)
+ if dt == "F32":
+ a = np.frombuffer(buf, dtype=np.float32)
+ elif dt == "BF16":
+ a = (np.frombuffer(buf, dtype=np.uint16).astype(np.uint32) << 16).view(np.float32)
+ elif dt == "U8":
+ a = np.frombuffer(buf, dtype=np.uint8)
+ else:
+ raise ValueError(dt)
+ return a.reshape(shape)
+
+ def has(self, name):
+ return name in self.index
+
+
+def dequant(sh: Shards, base: str) -> np.ndarray:
+ """MXFP4 -> float32, done here with numpy so it does not share a line of code with
+ the C implementation being checked."""
+ p = sh.get(base + ".weight_packed")
+ s = sh.get(base + ".weight_scale")
+ R, C = p.shape
+ lo, hi = (p & 0x0F), (p >> 4)
+ out = np.empty((R, 2 * C), dtype=np.float32)
+ out[:, 0::2] = E2M1[lo] # low nibble is the EVEN element
+ out[:, 1::2] = E2M1[hi]
+ mult = np.where(s == 255, 0.0, np.exp2(s.astype(np.int32) - 127).astype(np.float32))
+ out *= np.repeat(mult, 32, axis=1)[:, : 2 * C]
+ return out
+
+
+def bits_to_f32(v):
+ return np.array(v, dtype=np.uint32).view(np.float32)
+
+
+def cmp(label, a, b, width, fails, note=""):
+ """Report agreement in units of float32 epsilon scaled by the accumulation width,
+ which is the right yardstick for a dot product of that length."""
+ a = np.asarray(a, dtype=np.float64).ravel()
+ b = np.asarray(b, dtype=np.float64).ravel()
+ if a.shape != b.shape:
+ fails.append("%s: shape %s vs %s" % (label, a.shape, b.shape))
+ return
+ diff = np.abs(a - b)
+ scale = max(float(np.abs(b).max()), 1e-30)
+ rel = float(diff.max()) / scale
+ # float32 has ~1.2e-7 resolution; a dot product of `width` terms accumulates error
+ # roughly with sqrt(width). Anything within ~50x that is rounding, not a bug.
+ budget = 1.2e-7 * np.sqrt(width) * 50
+ ok = rel <= budget
+ print(" %-28s max|diff| %.3e rel %.3e budget %.1e %s%s"
+ % (label, float(diff.max()), rel, budget, "OK" if ok else "MISMATCH", note))
+ if not ok:
+ i = int(np.argmax(diff))
+ fails.append("%s: rel %.3e exceeds %.1e; worst at [%d] C=%.9g torch=%.9g"
+ % (label, rel, budget, i, a[i], b[i]))
+
+
+def main():
+ if len(sys.argv) < 2:
+ print(__doc__)
+ return 2
+ d = sys.argv[1]
+ dump_p = sys.argv[2] if len(sys.argv) > 2 else "real_layer.json"
+
+ D = json.load(open(dump_p, encoding="utf-8"))
+ L, T, H, topk = D["layer"], D["T"], D["hidden"], D["topk"]
+ print("checking layer %d, T=%d, hidden=%d, top-%d\n" % (L, T, H, topk))
+
+ sh = Shards(d)
+ c = K3Config()
+ torch.set_grad_enabled(False)
+ fails = []
+
+ lp = PRE + "layers.%d." % L
+ x = bits_to_f32(D["x"]).reshape(1, T, H)
+ xn_c = bits_to_f32(D["x_norm"]).reshape(1, T, H)
+
+ # ---- the input norm, as a cheap first check that x itself round-tripped ---------
+ inw = torch.from_numpy(sh.get(lp + "input_layernorm.weight").astype(np.float32))
+ n = RMSNorm(H, c.rms_norm_eps)
+ n.weight.copy_(inw)
+ xn_t = n(torch.from_numpy(x))
+ print("stage A0 input RMSNorm")
+ cmp("x_norm", xn_c, xn_t.numpy(), H, fails)
+
+ # ---- stage A: attention ---------------------------------------------------------
+ if D.get("is_mla"):
+ print("\nstage A Gated MLA attention (8 tensors)")
+ mla = GatedMLA(c)
+ sp = lp + "self_attn."
+ mla.q_a_proj.weight.copy_(torch.from_numpy(sh.get(sp + "q_a_proj.weight").astype(np.float32)))
+ mla.q_a_layernorm.weight.copy_(
+ torch.from_numpy(sh.get(sp + "q_a_layernorm.weight").astype(np.float32)))
+ mla.q_b_proj.weight.copy_(torch.from_numpy(sh.get(sp + "q_b_proj.weight").astype(np.float32)))
+ mla.kv_a_proj_with_mqa.weight.copy_(
+ torch.from_numpy(sh.get(sp + "kv_a_proj_with_mqa.weight").astype(np.float32)))
+ mla.kv_a_layernorm.weight.copy_(
+ torch.from_numpy(sh.get(sp + "kv_a_layernorm.weight").astype(np.float32)))
+ mla.kv_b_proj.weight.copy_(torch.from_numpy(sh.get(sp + "kv_b_proj.weight").astype(np.float32)))
+ mla.o_proj.weight.copy_(torch.from_numpy(sh.get(sp + "o_proj.weight").astype(np.float32)))
+ if mla.g_proj is not None:
+ mla.g_proj.weight.copy_(torch.from_numpy(sh.get(sp + "g_proj.weight").astype(np.float32)))
+ print(" q_b [%d] = %d heads x (nope %d + rope %d); kv_b [%d] = %d x (nope %d + v %d)"
+ % (sh.index[sp + "q_b_proj.weight"][2][0], c.num_attention_heads,
+ c.qk_nope_head_dim, c.qk_rope_head_dim,
+ sh.index[sp + "kv_b_proj.weight"][2][0], c.num_attention_heads,
+ c.qk_nope_head_dim, c.v_head_dim))
+ print(" softmax scale = (nope+rope)^-0.5 = %d^-0.5; the rope dims are carried "
+ "but NEVER rotated" % (c.qk_nope_head_dim + c.qk_rope_head_dim))
+ out_t, _ = mla(torch.from_numpy(xn_c.reshape(1, T, H)))
+ att_c = bits_to_f32(D["attn_out"]).reshape(1, T, H)
+ cmp("attn_out", att_c, out_t.numpy(), H, fails)
+ # No early return: an MLA layer has a MoE block too, and stages B and C below
+ # check it exactly as they do for a KDA layer.
+ return stages_bc(D, sh, lp, c, T, H, topk, fails)
+
+ print("\nstage A KDA attention (15 tensors)")
+ att = KimiDeltaAttention(c)
+ att.q_proj.weight.copy_(torch.from_numpy(sh.get(lp + "self_attn.q_proj.weight").astype(np.float32)))
+ att.k_proj.weight.copy_(torch.from_numpy(sh.get(lp + "self_attn.k_proj.weight").astype(np.float32)))
+ att.v_proj.weight.copy_(torch.from_numpy(sh.get(lp + "self_attn.v_proj.weight").astype(np.float32)))
+ att.g_proj.weight.copy_(torch.from_numpy(sh.get(lp + "self_attn.g_proj.weight").astype(np.float32)))
+ att.o_proj.weight.copy_(torch.from_numpy(sh.get(lp + "self_attn.o_proj.weight").astype(np.float32)))
+ att.f_a_proj.weight.copy_(torch.from_numpy(sh.get(lp + "self_attn.f_a_proj.weight").astype(np.float32)))
+ att.f_b_proj.weight.copy_(torch.from_numpy(sh.get(lp + "self_attn.f_b_proj.weight").astype(np.float32)))
+ att.b_proj.weight.copy_(torch.from_numpy(sh.get(lp + "self_attn.b_proj.weight").astype(np.float32)))
+ for nm, mod in (("q", att.q_conv1d), ("k", att.k_conv1d), ("v", att.v_conv1d)):
+ # Ships rank 3 as [P][1][kernel]; the reference module may hold it as [P][kernel]
+ # or [P][1][kernel]. Same bytes in the same order either way, so reshape to
+ # whatever the module declares rather than assuming.
+ w = sh.get(lp + "self_attn.%s_conv1d.weight" % nm).astype(np.float32)
+ mod.weight.copy_(torch.from_numpy(w).reshape(mod.weight.shape))
+ # A_log ships [128] on a 96-head model; the tail is zero and it is PER HEAD.
+ alog = sh.get(lp + "self_attn.A_log").astype(np.float32)
+ print(" A_log shipped %d values, tail beyond %d heads all zero: %s"
+ % (alog.size, c.kda_num_heads, bool(np.all(alog[c.kda_num_heads:] == 0))))
+ att.A_log.copy_(torch.from_numpy(alog[: c.kda_num_heads]))
+ att.dt_bias.copy_(torch.from_numpy(sh.get(lp + "self_attn.dt_bias").astype(np.float32)))
+ att.o_norm.weight.copy_(torch.from_numpy(sh.get(lp + "self_attn.o_norm.weight").astype(np.float32)))
+
+ out_t, _ = att(torch.from_numpy(xn_c.reshape(1, T, H)))
+ att_c = bits_to_f32(D["attn_out"]).reshape(1, T, H)
+ cmp("attn_out", att_c, out_t.numpy(), H, fails)
+
+ return stages_bc(D, sh, lp, c, T, H, topk, fails)
+
+
+def stages_bc(D, sh, lp, c, T, H, topk, fails):
+ """Routing and MoE. Shared by both attention kinds: a KDA layer and an MLA layer
+ have identical MoE blocks, so verifying it twice with two copies of the code would
+ only create a way for the two to drift."""
+ moe_in = bits_to_f32(D["moe_in"]).reshape(T, H)
+
+ # ---- dense layer: no router, no experts -----------------------------------------
+ # Layer 0 is the only dense layer in Kimi K3. Its MLP is a single 33792-wide
+ # gate/up/SiTU-GLU/down, not a MoE block, so the checkpoint carries mlp.* rather than
+ # block_sparse_moe.*. It needs its own branch here: routing code applied to a dense
+ # layer dereferences a gate weight that does not exist.
+ if "dense_out" in D:
+ print("\nstage B (skipped: dense layer, no router)")
+ print("stage C dense MLP")
+ dp = lp + "mlp."
+ dg = sh.get(dp + "gate_proj.weight").astype(np.float32)
+ du = sh.get(dp + "up_proj.weight").astype(np.float32)
+ dd = sh.get(dp + "down_proj.weight").astype(np.float32)
+ print(" dense intermediate is %d (config dense_inter)" % dg.shape[0])
+ g = moe_in @ dg.T
+ u = moe_in @ du.T
+ a = situ_glu(torch.from_numpy(np.concatenate([g, u], axis=1)),
+ c.situ_beta, c.situ_linear_beta).numpy()
+ y = a @ dd.T
+ dense_c = bits_to_f32(D["dense_out"]).reshape(T, H)
+ cmp("dense_out", dense_c, y, H, fails)
+ print()
+ if fails:
+ print("FAILED: %d problem(s)" % len(fails))
+ for fl in fails:
+ print(" " + fl)
+ return 1
+ print("VERIFIED: the C engine reproduces the real Kimi K3 DENSE layer (layer %d) "
+ "from the real checkpoint, at float32 rounding, across attention and the "
+ "%d-wide MLP. The bindings are correct." % (D["layer"], dg.shape[0]))
+ return 0
+
+ # ---- stage B: routing -----------------------------------------------------------
+ print("\nstage B router")
+ mp = lp + "block_sparse_moe."
+ gate_w = sh.get(mp + "gate.weight").astype(np.float32)
+ bias = sh.get(mp + "gate.e_score_correction_bias").astype(np.float32)
+ logits = moe_in @ gate_w.T
+ scores = 1.0 / (1.0 + np.exp(-logits.astype(np.float64)))
+ biased = scores + bias
+ idx_t = np.argsort(-biased, axis=1)[:, :topk]
+ w_t = np.take_along_axis(scores, idx_t, axis=1)
+ w_t = w_t / (w_t.sum(1, keepdims=True) + 1e-20)
+
+ idx_c = np.array(D["route_idx"], dtype=np.int64).reshape(T, topk)
+ wt_c = bits_to_f32(D["route_wt"]).reshape(T, topk)
+ same_sets = all(set(idx_c[t].tolist()) == set(idx_t[t].tolist()) for t in range(T))
+ print(" selected expert SETS identical for all %d tokens: %s" % (T, same_sets))
+ if not same_sets:
+ for t in range(T):
+ a, b = set(idx_c[t].tolist()), set(idx_t[t].tolist())
+ if a != b:
+ fails.append("token %d: C picked %s, torch picked %s"
+ % (t, sorted(a - b), sorted(b - a)))
+ # Compare weights after sorting by expert id, since top-k order is unspecified.
+ oc = np.argsort(idx_c, axis=1)
+ ot = np.argsort(idx_t, axis=1)
+ cmp("route_wt (id-sorted)", np.take_along_axis(wt_c, oc, 1),
+ np.take_along_axis(w_t, ot, 1), H, fails)
+
+ # ---- stage C: MoE ---------------------------------------------------------------
+ print("\nstage C MoE, latent path + shared expert + streamed MXFP4 experts")
+ down = sh.get(mp + "routed_expert_down_proj.weight").astype(np.float32)
+ up = sh.get(mp + "routed_expert_up_proj.weight").astype(np.float32)
+ lnorm = sh.get(mp + "routed_expert_norm.weight").astype(np.float32)
+ z = moe_in @ down.T # [T, latent]
+
+ Lw = c.routed_expert_hidden_size
+ acc = np.zeros((T, Lw), dtype=np.float32)
+ needed = sorted({int(e) for row in idx_t for e in row})
+ print(" dequantising %d distinct experts with numpy" % len(needed))
+ for e in needed:
+ base = mp + "experts.%d." % e
+ w1 = dequant(sh, base + "w1")
+ w3 = dequant(sh, base + "w3")
+ w2 = dequant(sh, base + "w2")
+ for t in range(T):
+ hit = np.where(idx_t[t] == e)[0]
+ if hit.size == 0:
+ continue
+ g = z[t] @ w1.T
+ u = z[t] @ w3.T
+ a = situ_glu(torch.from_numpy(np.stack([g, u]).reshape(1, -1)),
+ c.situ_beta, c.situ_linear_beta).numpy().ravel()
+ acc[t] += float(w_t[t, hit[0]]) * (a @ w2.T)
+ del w1, w3, w2
+
+ # RMSNorm on the AGGREGATE, not per expert.
+ rms = np.sqrt((acc.astype(np.float64) ** 2).mean(1, keepdims=True) + c.rms_norm_eps)
+ accn = (acc / rms) * lnorm
+ y = accn.astype(np.float32) @ up.T
+
+ sh1 = sh.get(mp + "shared_experts.gate_proj.weight").astype(np.float32)
+ sh3 = sh.get(mp + "shared_experts.up_proj.weight").astype(np.float32)
+ sh2 = sh.get(mp + "shared_experts.down_proj.weight").astype(np.float32)
+ print(" shared expert intermediate is %d = num_shared_experts %d x moe_inter %d"
+ % (sh1.shape[0], c.num_shared_experts, c.moe_intermediate_size))
+ sg = moe_in @ sh1.T
+ su = moe_in @ sh3.T
+ sa = situ_glu(torch.from_numpy(np.concatenate([sg, su], axis=1)),
+ c.situ_beta, c.situ_linear_beta).numpy()
+ y = y + sa @ sh2.T # added UNWEIGHTED
+
+ moe_c = bits_to_f32(D["moe_out"]).reshape(T, H)
+ cmp("moe_out", moe_c, y, Lw, fails)
+
+ print()
+ if fails:
+ print("FAILED: %d problem(s)" % len(fails))
+ for f in fails:
+ print(" " + f)
+ return 1
+ print("VERIFIED: the C engine reproduces a real Kimi K3 %s layer from the real "
+ "checkpoint, at float32 rounding, across attention, routing and the "
+ "streamed-expert MoE. The bindings are correct."
+ % ("MLA" if D.get("is_mla") else "KDA"))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/verify_st.py b/tools/verify_st.py
new file mode 100644
index 0000000..b82587f
--- /dev/null
+++ b/tools/verify_st.py
@@ -0,0 +1,172 @@
+#!/usr/bin/env python
+"""
+verify_st.py - check the C safetensors reader against an independent Python parse.
+
+WHY THIS EXISTS
+ k3_st.c contains a hand-written JSON scanner. Hand-written parsers are the classic
+ place to hide an off-by-one that never crashes: a data_offsets base computed as
+ 8 + hlen - 1, a shape dimension dropped, a dtype mapped to the wrong width. Every
+ one of those still returns bytes, so the model still runs and is simply wrong.
+
+ This reparses the same files with Python's json (a different implementation, written
+ by different people) and compares, for EVERY tensor: dtype, shape, absolute byte
+ offset, byte count. Then, for any tensor the C side dumped values for, it re-reads
+ the raw bytes with numpy and compares the widened float32 BIT PATTERNS exactly.
+
+ Bit patterns rather than approximate equality, because widening bf16 or f16 to f32
+ is a lossless integer operation. There is no tolerance to negotiate. If a single bit
+ differs, the converter is wrong.
+
+usage: verify_st.py <shard_dir> [st_index.json] [st_values.json]
+"""
+from __future__ import annotations
+
+import json
+import os
+import struct
+import sys
+
+import numpy as np
+
+WIDTH = {"U8": 1, "BF16": 2, "F16": 2, "F32": 4}
+
+
+def parse_shard(path):
+ """Independent parse: read the length prefix, json.loads the header, return
+ name -> (dtype, shape, absolute_offset, nbytes)."""
+ with open(path, "rb") as f:
+ n = struct.unpack("<Q", f.read(8))[0]
+ hdr = json.loads(f.read(n).decode("utf-8"))
+ size = os.path.getsize(path)
+ base = 8 + n
+ out = {}
+ for name, e in hdr.items():
+ if name == "__metadata__":
+ continue
+ s, t = e["data_offsets"]
+ out[name] = (e["dtype"], tuple(e["shape"]), base + s, t - s)
+ return out, base, size
+
+
+def widen(raw: bytes, dtype: str) -> np.ndarray:
+ """The reference widening, done with numpy rather than by hand."""
+ if dtype == "F32":
+ return np.frombuffer(raw, dtype=np.float32)
+ if dtype == "F16":
+ return np.frombuffer(raw, dtype=np.float16).astype(np.float32)
+ if dtype == "U8":
+ return np.frombuffer(raw, dtype=np.uint8).astype(np.float32)
+ if dtype == "BF16":
+ # bf16 IS the top 16 bits of an f32, so widening is a shift. Building it this
+ # way rather than via any bfloat16 library keeps the reference independent of
+ # whatever the C code does.
+ u = np.frombuffer(raw, dtype=np.uint16).astype(np.uint32) << 16
+ return u.view(np.float32)
+ raise ValueError(dtype)
+
+
+def main():
+ if len(sys.argv) < 2:
+ print(__doc__)
+ return 2
+ d = sys.argv[1]
+ idx_path = sys.argv[2] if len(sys.argv) > 2 else "st_index.json"
+ val_path = sys.argv[3] if len(sys.argv) > 3 else "st_values.json"
+
+ shards = sorted(f for f in os.listdir(d) if f.endswith(".safetensors"))
+ print("verifying %d shard(s) in %s" % (len(shards), d))
+
+ truth = {}
+ for sh in shards:
+ t, base, size = parse_shard(os.path.join(d, sh))
+ print(" %-40s header ends at %-10d %d tensors %.2f GB"
+ % (sh, base, len(t), size / 1e9))
+ for k, v in t.items():
+ if k in truth:
+ print(" DUPLICATE across shards: %s" % k)
+ truth[k] = v + (sh,)
+
+ got = json.load(open(idx_path, encoding="utf-8"))["tensors"]
+ print("\npython sees %d tensors, C reported %d" % (len(truth), len(got)))
+
+ fails, checked = [], 0
+ for name, (dt, shape, off, nb, sh) in truth.items():
+ c = got.get(name)
+ if c is None:
+ fails.append("%s: MISSING from the C index" % name)
+ continue
+ checked += 1
+ if c["dtype"] != dt:
+ fails.append("%s: dtype C=%s python=%s" % (name, c["dtype"], dt))
+ if tuple(c["shape"]) != shape:
+ fails.append("%s: shape C=%s python=%s" % (name, tuple(c["shape"]), shape))
+ if c["off"] != off:
+ fails.append("%s: OFFSET C=%d python=%d (delta %d)"
+ % (name, c["off"], off, c["off"] - off))
+ if c["nbytes"] != nb:
+ fails.append("%s: nbytes C=%d python=%d" % (name, c["nbytes"], nb))
+ if c["shard"] != sh:
+ fails.append("%s: shard C=%s python=%s" % (name, c["shard"], sh))
+ # Independent cross-check of the size invariant itself.
+ want = int(np.prod(shape)) * WIDTH[dt] if shape else WIDTH[dt]
+ if nb != want:
+ fails.append("%s: header is self-inconsistent, %d bytes vs shape implying %d"
+ % (name, nb, want))
+ for name in got:
+ if name not in truth:
+ fails.append("%s: C invented a tensor python does not see" % name)
+
+ print("compared %d tensors on dtype, shape, absolute offset, nbytes and shard"
+ % checked)
+
+ # ---- values -------------------------------------------------------------------
+ nval = 0
+ if os.path.exists(val_path):
+ vals = json.load(open(val_path, encoding="utf-8"))
+ print("\nchecking %d dumped tensor(s), float32 bit patterns, zero tolerance"
+ % len(vals))
+ for name, v in vals.items():
+ dt, shape, off, nb, sh = truth[name]
+ with open(os.path.join(d, sh), "rb") as f:
+ f.seek(off)
+ raw = f.read(nb)
+ ref = widen(raw, dt)
+ if len(ref) != v["n"]:
+ fails.append("%s: element count C=%d python=%d" % (name, v["n"], len(ref)))
+ continue
+ rb = ref.view(np.uint32)
+ head = np.array(v["first_bits"], dtype=np.uint32)
+ tail = np.array(v["last_bits"], dtype=np.uint32)
+ ts = v["tail_start"]
+ nbad_h = int((rb[:len(head)] != head).sum())
+ nbad_t = int((rb[ts:ts + len(tail)] != tail).sum())
+ nval += 1
+ if nbad_h or nbad_t:
+ i = int(np.argmax(rb[:len(head)] != head)) if nbad_h else 0
+ fails.append("%s: %d/%d head and %d/%d tail bit mismatches; "
+ "first at [%d] C=0x%08x python=0x%08x (%g vs %g)"
+ % (name, nbad_h, len(head), nbad_t, len(tail), i,
+ head[i], rb[i],
+ head[i:i + 1].view(np.float32)[0],
+ ref[i]))
+ else:
+ print(" %-72s %-5s %8d elems EXACT (%d head + %d tail bits)"
+ % (name[:72], dt, len(ref), len(head), len(tail)))
+ else:
+ print("\n(no %s, skipping the value check)" % val_path)
+
+ print()
+ if fails:
+ print("FAILED: %d problem(s)" % len(fails))
+ for f in fails[:40]:
+ print(" " + f)
+ if len(fails) > 40:
+ print(" ... and %d more" % (len(fails) - 40))
+ return 1
+ print("VERIFIED: the C index matches an independent Python parse on all %d tensors, "
+ "and all %d dumped tensors are bit-exact." % (checked, nval))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())