Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
feat(planner): glm53's partial chain layout
JustVugg90227711058c
diff --git a/c/resource_plan.py b/c/resource_plan.pyindex 6881ccea..f14631cd 100644--- a/c/resource_plan.py+++ b/c/resource_plan.py@@ -885,6 +885,97 @@ def _q38_chain_rows(env):_VK_CHAIN_LAYOUT["qwen38"] = _q38_chain_layout+def _glm53_chain_layout(info, env, vulkan):+ """glm53_chain.h g53c_fit_plan: each layer's device bytes (the mHC mixes in f32, its+ matrices at GLM53_BITS as quantize_loaded leaves them, an int4 container's as it is,+ the absorbed kv_b halves, its share of the parameter arena, a KDA layer's state and+ window, an MLA layer's caches at their first 256 positions), the scratch of one prompt+ chunk at GLM53_MAXT and the head."""+ config = info.get("config") or {}+ c = config.get("text_config") if isinstance(config.get("text_config"), dict) else config+ try:+ L, D, V = int(c["num_hidden_layers"]), int(c["hidden_size"]), int(c["vocab_size"])+ H = int(c.get("hc_mult") or 1)+ linear = c["linear_attn_config"]+ kh, kd, ck = int(linear["num_heads"]), int(linear["head_dim"]), int(linear["short_conv_kernel_size"])+ nh, ql, kvl = int(c["num_attention_heads"]), int(c["q_lora_rank"]), int(c["kv_lora_rank"])+ qn, qr, vh = int(c["qk_nope_head_dim"]), int(c.get("qk_rope_head_dim") or 0), int(c["v_head_dim"])+ di, mi, ns = int(c["intermediate_size"]), int(c["moe_intermediate_size"]), int(c.get("n_shared_experts") or 1)+ kinds = list(c["layer_types"])[:L]+ except (KeyError, TypeError, ValueError):+ return None+ if len(kinds) < L or L < 1:+ return None+ IH, ID = int(c.get("index_n_heads") or 0), int(c.get("index_head_dim") or 0)+ pool, topk = int(c.get("index_kpool") or 1), int(c.get("index_topk") or 0)+ full = ["linear" not in str(k) for k in kinds]+ if c.get("first_k_dense_replace") is not None:+ first_dense = int(c["first_k_dense_replace"])+ else:+ mlp = c.get("mlp_layer_types") or []+ first_dense = next((i for i, k in enumerate(mlp) if "sparse" in str(k)), len(mlp))+ setting = re.match(r"\s*([+-]?\d+)", env.get("GLM53_BITS", "4"))+ bits = int(setting[1]) if setting else 4+ packed = {_text_weight_name(t["name"]) for t in info.get("dense_tensors", []) if t.get("dtype") in ("U8", "I8")}+ P, nm, HD = kh * kd, (2 + H) * H, H * D++ def mat(rows, columns, name=None):+ if name is not None and name in packed:+ return vk_tensor_bytes(4, columns, rows, 64)+ if bits == 32:+ return vk_tensor_bytes(10, columns, rows)+ if bits == 4 and columns % 64 == 0:+ return vk_tensor_bytes(4, columns, rows, 64)+ return vk_tensor_bytes(1, columns, rows)+ layers = []+ for i in range(L):+ p = f"model.layers.{i}."+ size = 2 * vk_tensor_bytes(10, HD, nm)+ if full[i]:+ a = p + "self_attn."+ size += (mat(ql, D, a + "q_a_proj.weight") + mat(nh * (qn + qr), ql, a + "q_b_proj.weight") ++ mat(kvl + qr, D, a + "kv_a_proj_with_mqa.weight") + mat(nh * kvl, qn) + mat(nh * vh, kvl) ++ mat(D, nh * vh, a + "o_proj.weight") + mat(IH * ID, ql, a + "indexer.wq_b.weight") ++ mat(ID, D, a + "indexer.wk.weight") + mat(IH, D, a + "indexer.weights_proj.weight") ++ mat(ID, D, a + "indexer.index_kpool_compress_gate"))+ floats = 2 * D + 2 * (3 + nm) + ql + kvl + 2 * ID + pool * ID+ size += (vk_buf_bytes(256 * kvl * 4) + 2 * vk_buf_bytes(256 * ID * 4) ++ vk_buf_bytes((256 // pool + 1) * ID * 4))+ else:+ a = p + "self_attn."+ size += (mat(P, D, a + "q_proj.weight") + mat(P, D, a + "k_proj.weight") + mat(P, D, a + "v_proj.weight") ++ mat(D, P, a + "o_proj.weight") + mat(kd, D, a + "g_a_proj.weight") + mat(P, kd, a + "g_b_proj.weight") ++ mat(kd, D, a + "f_a_proj.weight") + mat(P, kd, a + "f_b_proj.weight") + mat(kh, D, a + "b_proj.weight"))+ floats = 2 * D + 2 * (3 + nm) + 3 * P * ck + kh + P + kd+ size += vk_buf_bytes(3 * P * ck * 4) + vk_buf_bytes(kh * kd * kd * 4)+ m = p + ("mlp." if i < first_dense else "mlp.shared_experts.")+ inner = di if i < first_dense else mi * ns+ size += mat(inner, D, m + "gate_proj.weight") + mat(inner, D, m + "up_proj.weight") + mat(D, inner, m + "down_proj.weight")+ layers.append(size + 4 * floats)+ # g53c_scratch's counting pass for one chunk (every layer's new rows down) and the MLA+ # scratch, at vkc_fit_rows(128) rows and a serve slot's context+ value = (env.get("COLI_VK_CHAIN_ROWS") or "").strip()+ match = re.match(r"([+-]?\d+)", value) if value and value != "auto" else None+ r = min(max(int(match[1]), 1), 65535) if match else 128+ match = re.match(r"\s*([+-]?\d+)", env.get("GLM53_MAXT") or "")+ ctx = max(int(match[1]) if match else 8192, 64)+ wide = max(di, mi)+ width = topk + pool - 1 if c.get("index_kpool_always_select_tail") else topk+ counts = [r * HD, r * HD, r * D, r * D, r * D, r * nm, r * (2 * H + H * H), r * wide, r * wide, r * wide, r * D,+ r * D, L * r * (kvl + 2 * ID), r * HD, r * D]+ if P > 0:+ counts += [3 * r * P, 3 * r * P, r * P, r * kh, r * P, r * kd, r * P]+ if any(full):+ counts += [r * ID, r * IH * ID, r * IH, r * ID, r * (ctx // pool + 1), r * (1 + width)]+ counts += [r * ql, r * nh * qn, r * kvl, r * nh * kvl, r * nh * kvl, r * nh * vh]+ fixed = sum(vk_buf_bytes(4 * (n if n else 1)) for n in counts) + vk_buf_bytes(4)+ tail = 0 if c.get("tie_word_embeddings") else mat(V, D, "lm_head.weight")+ return VkChainLayout(layers, fixed, tail)+++_VK_CHAIN_LAYOUT["glm53"] = _glm53_chain_layout++def _analysis_signature(shards, config_path):parts = [f"v{_ANALYSIS_CACHE_VERSION}"]st = config_path.stat()diff --git a/c/tests/test_resource_plan.py b/c/tests/test_resource_plan.pyindex a2eca22e..3bf7f49b 100644--- a/c/tests/test_resource_plan.py+++ b/c/tests/test_resource_plan.py@@ -2114,6 +2114,141 @@ class Qwen38PartialChainTest(unittest.TestCase):self.assertEqual(off["tiers"]["ram"]["dense_on_device_bytes"], 0)+class VulkanPartialChainGlm53Test(unittest.TestCase):+ """glm53's partial chain in the plan: _glm53_chain_layout is g53c_fit_plan+ (glm53_chain.h), and the device-only credit is the N layers' matrices alone."""++ # tests/vulkan_partial_glm.sh's six-layer GLM-5.3: KDA and MLA layers alternating,+ # the first MLP dense+ TEXT = {+ "vocab_size": 128, "hidden_size": 128, "intermediate_size": 256, "moe_intermediate_size": 128,+ "num_hidden_layers": 6, "num_attention_heads": 4, "num_key_value_heads": 4, "n_shared_experts": 1,+ "n_routed_experts": 4, "num_experts_per_tok": 2, "kv_lora_rank": 64, "q_lora_rank": 128,+ "qk_rope_head_dim": 0, "qk_nope_head_dim": 32, "v_head_dim": 32, "max_position_embeddings": 128,+ "layer_types": ["linear_attention", "deepseek_sparse_attention"] * 3,+ "mlp_layer_types": ["dense"] + ["sparse"] * 5, "indexer_types": ["full"] * 6,+ "index_topk": 4, "index_kpool": 2, "index_head_dim": 32, "index_n_heads": 2,+ "hc_mult": 2, "hc_sinkhorn_iters": 3, "hc_eps": 1e-06, "rms_norm_eps": 1e-05,+ "routed_scaling_factor": 2.5, "swiglu_limit": 10.0, "tie_word_embeddings": False,+ "model_type": "glm5_next_text", "num_nextn_predict_layers": 0,+ "linear_attn_config": {"num_heads": 4, "head_dim": 32, "short_conv_kernel_size": 4,+ "gate_lower_bound": -5.0, "kda_layers": [0, 2, 4]},+ }++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.model = Path(self.tmp.name)+ (self.model / "config.json").write_text(json.dumps({+ "architectures": ["Glm5NextForConditionalGeneration"], "model_type": "glm5_next",+ "text_config": self.TEXT}))+ tensors = []++ def add(name, *shape, dtype="F32"):+ count = 1+ for n in shape:+ count *= n+ tensors.append((name, count * (1 if dtype == "U8" else 4), dtype, list(shape)))+ P = "model.language_model."+ add("lm_head.weight", 128, 128)+ add(P + "embed_tokens.weight", 128, 128)+ add(P + "norm.weight", 128)+ for i, kind in enumerate(self.TEXT["layer_types"]):+ p = f"{P}layers.{i}."+ for site in ("attn", "ffn"):+ add(p + f"hc_{site}_base", 8)+ add(p + f"hc_{site}_fn", 8, 256)+ add(p + f"hc_{site}_scale", 3)+ add(p + "input_layernorm.weight", 128)+ add(p + "post_attention_layernorm.weight", 128)+ a = p + "self_attn."+ if kind == "linear_attention":+ for name in ("q", "k", "v", "o"):+ add(a + f"{name}_proj.weight", 128, 128)+ for name in ("q", "k", "v"):+ add(a + f"{name}_conv1d.weight", 128, 1, 4)+ add(a + "A_log", 4); add(a + "dt_bias", 128); add(a + "o_norm.weight", 32)+ add(a + "b_proj.weight", 4, 128)+ for name in ("f", "g"):+ add(a + f"{name}_a_proj.weight", 32, 128)+ add(a + f"{name}_b_proj.weight", 128, 32)+ else:+ add(a + "q_a_proj.weight", 128, 128); add(a + "q_a_layernorm.weight", 128)+ add(a + "q_b_proj.weight", 128, 128)+ add(a + "kv_a_proj_with_mqa.weight", 64, 128); add(a + "kv_a_layernorm.weight", 64)+ add(a + "kv_b_proj.weight", 256, 64)+ add(a + "o_proj.weight", 128, 128)+ ix = a + "indexer."+ add(ix + "wq_b.weight", 64, 128); add(ix + "wk.weight", 32, 128)+ add(ix + "weights_proj.weight", 2, 128); add(ix + "index_kpool_compress_gate", 32, 128)+ add(ix + "index_kpool_compress_ape", 2, 32)+ add(ix + "k_norm.weight", 32); add(ix + "k_norm.bias", 32)+ if i == 0:+ add(p + "mlp.gate_proj.weight", 256, 128); add(p + "mlp.up_proj.weight", 256, 128)+ add(p + "mlp.down_proj.weight", 128, 256)+ continue+ add(p + "mlp.gate.weight", 4, 128); add(p + "mlp.gate.e_score_correction_bias", 4)+ for name in ("gate", "up", "down"):+ add(p + f"mlp.shared_experts.{name}_proj.weight", *((128, 128)))+ for e in range(4):+ for name in ("gate", "up", "down"):+ add(p + f"mlp.experts.{e}.{name}_proj.weight", 8192, dtype="U8")+ add(p + f"mlp.experts.{e}.{name}_proj.weight.qs", 256)+ write_shard(self.model / "model.safetensors", tensors)+ self.info = analyze_model(self.model)++ def tearDown(self):+ self.tmp.cleanup()++ def test_layout_is_the_engines(self):+ # The numbers glm53 printed for the fixture on Lavapipe ("[VK] glm53 chain fit: ...+ # the engine's 4847872 B ..., tail 65792 B, layers 773352 728408 ... B"), at each+ # GLM53_BITS, and with a chunk of 7 rows and a 300-position slot (155904 B)+ from resource_plan import vk_chain_fit, vk_fit_pools+ device = {"type": "cpu", "budget_bytes": 64 * GB}+ want = {"32": ([773352, 728408, 576744, 728408, 576744, 728408], 65792),+ "8": ([234472, 312408, 184296, 312408, 184296, 312408], 16896),+ "4": ([153832, 250456, 126184, 250456, 126184, 250456], 9216)}+ for bits, (layers, tail) in want.items():+ with self.subTest(bits=bits):+ env = {"COLI_VULKAN": "1", "COLI_VK_CHAIN": "1", "GLM53_BITS": bits}+ fit = vk_chain_fit(self.info, "glm53", env, device)+ self.assertEqual(fit["layers"], layers)+ self.assertEqual(fit["fixed"] - vk_fit_pools(0), 4847872)+ self.assertEqual((fit["n"], fit["tail"]), (6, True))+ small = vk_chain_fit(self.info, "glm53", {"COLI_VULKAN": "1", "COLI_VK_CHAIN": "1", "GLM53_BITS": "4",+ "COLI_VK_CHAIN_ROWS": "7", "GLM53_MAXT": "300"}, device)+ self.assertEqual(small["fixed"] - vk_fit_pools(0), 155904)+ self.assertEqual(small["layers"], want["4"][0])++ def test_device_only_credits_the_layers_on_the_device(self):+ from resource_plan import _glm53_dense_tensors, _vk_layer_index, _vk_released_tensor_bytes, vk_chain_fit+ kwargs = dict(context=64, ram_gb=4, available_memory=16 * GB, available_disk=16 * GB, gpus=[])+ on = {"COLI_VULKAN": "1", "COLI_VK_CHAIN": "1", "COLI_VK_DENSE_HOST": "0", "COLI_VK_TIER_RESERVE_GB": "0",+ "GLM53_BITS": "32"}+ big = {"type": "discrete", "budget_bytes": 64 * GB}+ fit = vk_chain_fit(self.info, "glm53", on, big)++ tensors = _glm53_dense_tensors(self.info, on)["dense_tensors"] # resident at GLM53_BITS=32++ def droppable(k): # the matrices g53_dho_layer drops, of layers 0..k-1+ return sum(_vk_released_tensor_bytes(t, "glm53", on) for t in tensors+ if _vk_layer_index(t["name"]) is not None and _vk_layer_index(t["name"]) < k)+ for k in (1, 3, 5):+ with self.subTest(k=k):+ free = fit["fixed"] + sum(fit["layers"][:k]) + fit["layers"][k] // 2+ plan = build_plan(self.model, env=on, vulkan={"type": "discrete", "budget_bytes": free}, **kwargs)+ ram = plan["tiers"]["ram"]+ self.assertEqual(ram["vk_chain_layers"]["on_device"], k)+ self.assertEqual(ram["dense_on_device_bytes"], droppable(k))+ self.assertIn(f"the first {k} of 6 layers", format_plan(plan))+ forced = build_plan(self.model, env=dict(on, COLI_VK_CHAIN_LAYERS=str(k)), vulkan=big, **kwargs)+ self.assertEqual(forced["tiers"]["ram"]["dense_on_device_bytes"], droppable(k))+ self.assertGreater(droppable(3), droppable(1))+ none = build_plan(self.model, env=on, vulkan={"type": "discrete", "budget_bytes": 1 << 20}, **kwargs)+ self.assertEqual(none["tiers"]["ram"]["dense_on_device_bytes"], 0)+ self.assertEqual(none["tiers"]["ram"]["vk_chain_layers"]["on_device"], 0)++class PhysicalCpuCountTest(unittest.TestCase):"""Regression for #325: --auto-tier pinned decode to one core becausephysical_cpu_count() silently returned 1.