Skip to content

Run frontier MoE models on hardware you already own β€” pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

fix(k3-repack): rebuild cumulative index on resume

Mario Gutierrez49994a294308
diff --git a/c/tests/test_k3_repack.py b/c/tests/test_k3_repack.py
new file mode 100644
index 00000000..959b1218
--- /dev/null
+++ b/c/tests/test_k3_repack.py
@@ -0,0 +1,191 @@
+"""Kimi K3 repack resume and cumulative-index regressions."""
+import importlib
+import importlib.util
+import io
+import json
+import os
+import struct
+import sys
+import tempfile
+import types
+import unittest
+from contextlib import redirect_stdout
+from pathlib import Path
+from unittest import mock
+
+
+TOOLS = Path(__file__).resolve().parent.parent / "tools"
+
+
+def load_tool():
+ """The index path is stdlib-only; stub numpy when optional tooling is absent."""
+ try:
+ importlib.import_module("numpy")
+ stubbed = False
+ except ImportError:
+ stubbed = True
+ if stubbed:
+ sys.modules["numpy"] = types.ModuleType("numpy")
+ try:
+ spec = importlib.util.spec_from_file_location("k3_repack_under_test", TOOLS / "k3_repack.py")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+ finally:
+ if stubbed:
+ sys.modules.pop("numpy", None)
+
+
+k3_repack = load_tool()
+
+
+def write_shard(path, tensors):
+ offset = 0
+ header = {}
+ payload = b""
+ for name, data in tensors:
+ header[name] = {"dtype": "U8", "shape": [len(data)],
+ "data_offsets": [offset, offset + len(data)]}
+ payload += data
+ offset += len(data)
+ raw = json.dumps(header, separators=(",", ":")).encode()
+ path.write_bytes(struct.pack("<Q", len(raw)) + raw + payload)
+
+
+class K3RepackIndexTest(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.dst = Path(self.tmp.name)
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def shard(self, number, tensors):
+ path = self.dst / f"model-{number:05d}-of-000094.safetensors"
+ write_shard(path, tensors)
+ return path
+
+ def index(self):
+ return json.loads((self.dst / "model.safetensors.index.json").read_text())
+
+ def test_rebuild_combines_disjoint_partial_runs_and_counts_existing_payloads(self):
+ first = self.shard(1, [("layer.1.weight", b"1234")])
+ self.assertEqual(k3_repack.rebuild_index(self.dst), (1, 4))
+ self.assertEqual(self.index(), {
+ "metadata": {"total_size": 4},
+ "weight_map": {"layer.1.weight": first.name},
+ })
+
+ second = self.shard(2, [("layer.2.weight", b"abcdef")])
+ self.assertEqual(k3_repack.rebuild_index(self.dst), (2, 10))
+ self.assertEqual(self.index(), {
+ "metadata": {"total_size": 10},
+ "weight_map": {
+ "layer.1.weight": first.name,
+ "layer.2.weight": second.name,
+ },
+ })
+
+ before = (self.dst / "model.safetensors.index.json").read_bytes()
+ self.assertEqual(k3_repack.rebuild_index(self.dst), (2, 10))
+ self.assertEqual((self.dst / "model.safetensors.index.json").read_bytes(), before)
+
+ def test_duplicate_tensor_aborts_without_replacing_the_previous_index(self):
+ self.shard(1, [("duplicate.weight", b"1234")])
+ k3_repack.rebuild_index(self.dst)
+ index_path = self.dst / "model.safetensors.index.json"
+ previous = index_path.read_bytes()
+ self.shard(2, [("duplicate.weight", b"5678")])
+
+ with self.assertRaisesRegex(ValueError, "duplicate tensor.*model-00001.*model-00002"):
+ k3_repack.rebuild_index(self.dst)
+
+ self.assertEqual(index_path.read_bytes(), previous)
+ self.assertFalse((self.dst / "model.safetensors.index.json.tmp").exists())
+
+ def test_rebuilt_index_passes_doctor_container_validation(self):
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+ try:
+ from doctor import deep_container_report
+ finally:
+ sys.path.pop(0)
+ tensors = [
+ ("model.embed_tokens.weight", b"e"),
+ ("model.norm.weight", b"n"),
+ ]
+ self.shard(1, tensors)
+ self.shard(2, [("lm_head.weight", b"head")])
+ k3_repack.rebuild_index(self.dst)
+
+ report = deep_container_report(self.dst)
+
+ self.assertEqual(report["index"]["status"], "pass")
+ self.assertEqual(report["required"]["status"], "pass")
+
+ def test_index_is_flushed_before_atomic_replace(self):
+ self.shard(1, [("layer.weight", b"1234")])
+ calls = []
+ real_replace = os.replace
+
+ def replace(src, dst):
+ calls.append((Path(src), Path(dst)))
+ real_replace(src, dst)
+
+ with mock.patch.object(k3_repack.os, "fsync") as fsync, \
+ mock.patch.object(k3_repack.os, "replace", side_effect=replace):
+ k3_repack.rebuild_index(self.dst)
+
+ self.assertEqual(fsync.call_count, 1)
+ self.assertEqual(calls, [(
+ self.dst / "model.safetensors.index.json.tmp",
+ self.dst / "model.safetensors.index.json",
+ )])
+
+
+class K3RepackResumeIntegrationTest(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.root = Path(self.tmp.name)
+ self.src = self.root / "src"
+ self.dst = self.root / "dst"
+ self.src.mkdir()
+ (self.src / "config.json").write_text(json.dumps({
+ "text_config": {"linear_attn_config": {"kda_layers": [1]}},
+ }))
+ for number in (1, 2):
+ write_shard(
+ self.src / f"model-{number:05d}-of-000096.safetensors",
+ [(f"model.layers.{number}.input_layernorm.weight", bytes([number]) * number)],
+ )
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def run_main(self, shard):
+ argv = ["k3_repack.py", str(self.src), str(self.dst), "--shards", str(shard)]
+ with mock.patch.object(sys, "argv", argv), redirect_stdout(io.StringIO()):
+ k3_repack.main()
+
+ def test_disjoint_shard_passes_publish_one_cumulative_index(self):
+ self.run_main(1)
+ self.run_main(2)
+ index_path = self.dst / "model.safetensors.index.json"
+ document = json.loads(index_path.read_text())
+
+ self.assertEqual(document, {
+ "metadata": {"total_size": 3},
+ "weight_map": {
+ "model.layers.1.input_layernorm.weight":
+ "model-00001-of-000094.safetensors",
+ "model.layers.2.input_layernorm.weight":
+ "model-00002-of-000094.safetensors",
+ },
+ })
+
+ before = index_path.read_bytes()
+ self.run_main(1)
+ self.assertEqual(index_path.read_bytes(), before)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/c/tools/k3_repack.py b/c/tools/k3_repack.py
index 00a91803..0d5d9456 100644
--- a/c/tools/k3_repack.py
+++ b/c/tools/k3_repack.py
@@ -30,6 +30,7 @@ Classification needs the layer type (o_proj/g_proj exist on BOTH KDA and MLA
layers) β€” read from config.json linear_attn_config.
"""
import argparse
+import glob
import json
import os
import shutil
@@ -81,7 +82,8 @@ def quant_int4_g64(rows):
class Classifier:
def __init__(self, src):
- cfg = json.load(open(os.path.join(src, "config.json")))
+ with open(os.path.join(src, "config.json"), encoding="utf-8") as f:
+ cfg = json.load(f)
tc = cfg.get("text_config", cfg)
self.kda = set(x - 1 for x in tc["linear_attn_config"]["kda_layers"])
@@ -220,6 +222,52 @@ def repack_shard(src_path, dst_path, cls, bits_map, verify_full):
return oh, written
+def rebuild_index(dst):
+ """Publish an index covering every completed output shard in dst."""
+ dst = os.fspath(dst)
+ index = {}
+ total = 0
+ shards = sorted(glob.glob(os.path.join(dst, "model-*-of-000094.safetensors")))
+ for path in shards:
+ header, data_start = read_header(path)
+ name = os.path.basename(path)
+ payload_size = os.path.getsize(path) - data_start
+ if payload_size < 0:
+ raise ValueError(f"{name}: header exceeds file size")
+ for tensor, meta in header.items():
+ previous = index.get(tensor)
+ if previous is not None:
+ raise ValueError(f"duplicate tensor {tensor!r} in {previous} and {name}")
+ try:
+ start, end = meta["data_offsets"]
+ except (KeyError, TypeError, ValueError):
+ raise ValueError(f"{name}: tensor {tensor!r} has invalid data offsets") from None
+ if (isinstance(start, bool) or isinstance(end, bool) or
+ not isinstance(start, int) or not isinstance(end, int) or
+ start < 0 or end < start or end > payload_size):
+ raise ValueError(f"{name}: tensor {tensor!r} has invalid data offsets")
+ index[tensor] = name
+ total += end - start
+
+ if not shards:
+ return 0, 0
+ index_path = os.path.join(dst, "model.safetensors.index.json")
+ tmp = index_path + ".tmp"
+ try:
+ with open(tmp, "w", encoding="utf-8") as f:
+ json.dump({"metadata": {"total_size": total}, "weight_map": index}, f)
+ f.flush()
+ os.fsync(f.fileno())
+ os.replace(tmp, index_path)
+ except BaseException:
+ try:
+ os.unlink(tmp)
+ except FileNotFoundError:
+ pass
+ raise
+ return len(shards), total
+
+
def main():
ap = argparse.ArgumentParser()
ap.add_argument("src")
@@ -238,10 +286,8 @@ def main():
cls = Classifier(a.src)
shard_nums = ([int(x) for x in a.shards.split(",")] if a.shards
else list(range(1, 95)))
- index = {}
t0 = time.time()
- total = 0
- done_any = False
+ written_total = 0
for i, num in enumerate(shard_nums):
sp = os.path.join(a.src, f"model-{num:05d}-of-000096.safetensors")
dname = f"model-{num:05d}-of-000094.safetensors"
@@ -250,29 +296,24 @@ def main():
print(f"[{num:2d}] SOURCE MISSING β€” skipped (rerun when downloaded)", flush=True)
continue
if os.path.exists(dp):
- oh, _ = read_header(dp)
- for name in oh:
- index[name] = dname
print(f"[{num:2d}] exists β€” skipped (resume)", flush=True)
continue
- oh, written = repack_shard(sp, dp, cls, bits_map, a.verify_full)
- for name in oh:
- index[name] = dname
- total += written
- done_any = True
+ _header, written = repack_shard(sp, dp, cls, bits_map, a.verify_full)
+ written_total += written
el = time.time() - t0
print(f"[{num:2d}] {os.path.getsize(dp)/1e9:6.2f} GB out "
- f"({total/1e9:7.1f} GB total, {total/1e9/max(el,1e-9):5.2f} GB/s, {el:6.0f}s)",
+ f"({written_total/1e9:7.1f} GB written, "
+ f"{written_total/1e9/max(el,1e-9):5.2f} GB/s, {el:6.0f}s)",
flush=True)
- if done_any or index:
- with open(os.path.join(a.dst, "model.safetensors.index.json"), "w") as f:
- json.dump({"metadata": {"total_size": total}, "weight_map": index}, f)
+ indexed_shards, indexed_total = rebuild_index(a.dst)
for extra in ("config.json", "generation_config.json", "tokenizer.json",
"tokenizer_config.json"):
s = os.path.join(a.src, extra)
if os.path.exists(s):
shutil.copy2(s, os.path.join(a.dst, extra))
- print(f"done: {total/1e9:.1f} GB written in {time.time()-t0:.0f}s -> {a.dst}")
+ print(f"done: {written_total/1e9:.1f} GB written this run; "
+ f"index covers {indexed_total/1e9:.1f} GB in {indexed_shards} shard(s); "
+ f"{time.time()-t0:.0f}s -> {a.dst}")
if __name__ == "__main__":
diff --git a/docs/kimi_k3.md b/docs/kimi_k3.md
index eb34b416..5653c67d 100644
--- a/docs/kimi_k3.md
+++ b/docs/kimi_k3.md
@@ -94,7 +94,11 @@ load-time algorithm and stored as `U8` + `<name>.qs` f32 scales, the small /
sensitive tensors (norms, router, conv taps, `dt_bias`, `A_log`, `f_a/f_b`,
`b_proj`, embeddings) pass through, vision is dropped. Output is spec-valid
safetensors (`model-XXXXX-of-000094.safetensors`) plus a regenerated index;
-interrupted runs resume per shard. `--verify-full` re-reads every expert byte
+interrupted runs resume per shard. On every run, including disjoint `--shards`
+passes, the index is rebuilt atomically from all completed output shards in the
+destination; its `total_size` therefore includes both new and previously
+converted data. Duplicate tensor names abort the index update instead of
+publishing an ambiguous artifact. `--verify-full` re-reads every expert byte
and compares against the source.
The engine auto-detects container tensors (dtype U8 + `.qs` sidecar) and skips