Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
fix(mirror): recognize Kimi K3 expert shards
Mario Gutierrezd1653ca8dbcd
diff --git a/c/tests/test_mirror_plan.py b/c/tests/test_mirror_plan.pyindex 6f5638f9..6fc21cbd 100644--- a/c/tests/test_mirror_plan.py+++ b/c/tests/test_mirror_plan.py@@ -67,6 +67,49 @@ class MirrorPlannerTest(unittest.TestCase):self.assertEqual(selected[0]["activated_experts"], 1)self.assertEqual(selected[1]["activated_experts"], 0)+ def test_plan_recognizes_k3_expert_tensors_and_packed_w1_anchor(self):+ prefix = "language_model.model.layers.1.block_sparse_moe.experts.7"+ anchor = self.write_shard(self.model, "k3-w1.safetensors", [+ (f"{prefix}.w1.weight_packed", 11),+ ])+ companion = self.write_shard(self.model, "k3-rest.safetensors", [+ (f"{prefix}.w1.weight_scale", 2),+ (f"{prefix}.w2.weight_packed", 13),+ (f"{prefix}.w2.weight_scale", 3),+ (f"{prefix}.w3.weight_packed", 17),+ (f"{prefix}.w3.weight_scale", 5),+ ])+ self.usage.write_text("1 7 99\n", encoding="utf-8")+ budget = anchor.stat().st_size + companion.stat().st_size++ plan, selected = create_plan(self.model, self.mirror, [], self.usage, budget, 0)++ self.assertTrue(plan["admitted"])+ self.assertEqual([item["name"] for item in selected],+ ["k3-w1.safetensors", "k3-rest.safetensors"])+ self.assertEqual(selected[0]["weighted_expert_bytes"], 99 * 11)+ self.assertEqual(selected[1]["weighted_expert_bytes"], 99 * 40)+ self.assertEqual([item["activated_experts"] for item in selected], [1, 0])++ def test_k3_names_accept_engine_prefixes_and_reject_near_matches(self):+ accepted = [+ ("model.layers.2.block_sparse_moe.experts.8.w1.weight_packed", 7),+ ("language_model.model.layers.3.block_sparse_moe.experts.9."+ "w1.weight_packed", 11),+ ]+ rejected = [+ ("model.layers.2.block_sparse_moe.shared_experts.w1.weight_packed", 13),+ ("model.layers.2.block_sparse_moe.experts.8.w4.weight_packed", 17),+ ("model.layers.2.block_sparse_moe.experts.8.w1.weight_scale_inv", 19),+ ("foo.model.layers.2.block_sparse_moe.experts.8.w1.weight_packed", 23),+ ]+ self.write_shard(self.model, "k3-names.safetensors", accepted + rejected)++ _directories, candidates = discover_shards(self.model, [])++ self.assertEqual(candidates[0]["expert_bytes"], {(2, 8): 7, (3, 9): 11})+ self.assertEqual(candidates[0]["anchor_experts"], {(2, 8), (3, 9)})+def test_plan_requires_learned_usage_instead_of_guessing(self):shard = self.write_shard(self.model, "model.safetensors", [("model.layers.0.mlp.experts.0.gate_proj.weight", 8),diff --git a/c/tools/mirror_plan.py b/c/tools/mirror_plan.pyindex 0e488979..96a1fde2 100644--- a/c/tools/mirror_plan.py+++ b/c/tools/mirror_plan.py@@ -21,10 +21,14 @@ RECEIPT = ".colibri-mirror.json"GIB = 1024 ** 3MAX_HEADER = 256 * 1024 * 1024COPY_CHUNK = 16 * 1024 * 1024-EXPERT_KEY = re.compile(+GLM_EXPERT_KEY = re.compile(r"(?:^|\.)layers\.(\d+)\.mlp\.experts\.(\d+)\."r"(gate_proj|up_proj|down_proj)\.weight(?:\.qs)?$")+K3_EXPERT_KEY = re.compile(+ r"(?:language_model\.)?model\.layers\.(\d+)\.block_sparse_moe\."+ r"experts\.(\d+)\.(w1|w2|w3)\.weight_(packed|scale)$"+)SHA256_HEX = re.compile(r"^[0-9a-f]{64}$")@@ -72,6 +76,18 @@ def usage_counts(path):return counts+def expert_tensor(name):+ match = GLM_EXPERT_KEY.search(name)+ if match is not None:+ return ((int(match.group(1)), int(match.group(2))),+ match.group(3) == "gate_proj" and name.endswith(".weight"))+ match = K3_EXPERT_KEY.fullmatch(name)+ if match is not None:+ return ((int(match.group(1)), int(match.group(2))),+ match.group(3) == "w1" and match.group(4) == "packed")+ return None++def shard_metadata(path):size = path.stat().st_sizeif size < 8:@@ -89,24 +105,24 @@ def shard_metadata(path):raise MirrorError(f"Safetensors header is not an object: {path}")expert_bytes = {}- gate_experts = set()+ anchor_experts = set()for name, metadata in header.items():if name == "__metadata__" or not isinstance(name, str) or not isinstance(metadata, dict):continue- match = EXPERT_KEY.search(name)+ tensor = expert_tensor(name)offsets = metadata.get("data_offsets")- if match is None or not isinstance(offsets, list) or len(offsets) != 2:+ if tensor is None or not isinstance(offsets, list) or len(offsets) != 2:continuestart, end = offsetsif (isinstance(start, bool) or isinstance(end, bool) ornot isinstance(start, int) or not isinstance(end, int) orstart < 0 or end < start or end > size - 8 - header_size):raise MirrorError(f"Invalid tensor offsets for {name} in {path}")- expert = (int(match.group(1)), int(match.group(2)))+ expert, is_anchor = tensorexpert_bytes[expert] = expert_bytes.get(expert, 0) + end - start- if match.group(3) == "gate_proj" and name.endswith(".weight"):- gate_experts.add(expert)- return size, expert_bytes, gate_experts+ if is_anchor:+ anchor_experts.add(expert)+ return size, expert_bytes, anchor_expertsdef discover_shards(model, source_dirs):@@ -124,13 +140,13 @@ def discover_shards(model, source_dirs):if path.name in seen or not path.is_file():continueseen.add(path.name)- size, expert_bytes, gate_experts = shard_metadata(path)+ size, expert_bytes, anchor_experts = shard_metadata(path)candidates.append({"name": path.name,"size": size,"source": path,"expert_bytes": expert_bytes,- "gate_experts": gate_experts,+ "anchor_experts": anchor_experts,})if not candidates:raise MirrorError("No safetensors shards were found in the model source directories")@@ -138,9 +154,8 @@ def discover_shards(model, source_dirs):def select_shards(candidates, counts, budget):- # The engine decides an expert's replica from its gate_proj shard. A shard- # containing only up/down weights cannot serve that expert from the mirror- # until its gate shard is present, so score companions only after activation.+ # The engine decides an expert's replica from its first tensor (gate_proj for+ # GLM, packed w1 for K3), so score companions only after that anchor is present.# The byte-weighted usage score estimates I/O moved off the primary drive.selected = []activated = set()@@ -151,7 +166,7 @@ def select_shards(candidates, counts, budget):for item in remaining:if used + item["size"] > budget:continue- eligible = activated | item["gate_experts"]+ eligible = activated | item["anchor_experts"]benefit = sum(counts.get(expert, 0) * byte_countfor expert, byte_count in item["expert_bytes"].items()if expert in eligible)@@ -168,10 +183,10 @@ def select_shards(candidates, counts, budget):choice[0]["name"],),)- newly_activated = item["gate_experts"] - activated+ newly_activated = item["anchor_experts"] - activatedselected.append({**item, "weighted_expert_bytes": benefit,"activated_experts": len(newly_activated)})- activated.update(item["gate_experts"])+ activated.update(item["anchor_experts"])remaining.remove(item)used += item["size"]return selected