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

feat(planner): the partial chain's layouts for qwen36 and olmoe

JustVuggefd91e5b8fb3
diff --git a/c/resource_plan.py b/c/resource_plan.py
index 440984f0..ff3e9991 100644
--- a/c/resource_plan.py
+++ b/c/resource_plan.py
@@ -582,6 +582,174 @@ def _v4_chain_layout(info, env, vulkan):
_VK_CHAIN_LAYOUT["deepseek_v4"] = _v4_chain_layout
+# ---- qwen36 (Qwen3.6, Qwen3-Coder, Qwen3.8-27B, Clef's backbone) and olmoe ------------
+def _vk_chain_rows(env, default=256):
+ """vkc_fit_rows: COLI_VK_CHAIN_ROWS when it is a number, else the engine's block."""
+ value = (env.get("COLI_VK_CHAIN_ROWS") or "").strip()
+ match = re.match(r"\s*([+-]?\d+)", value)
+ if not value or value == "auto" or not match:
+ return default
+ return min(max(int(match[1]), 1), 65535)
+
+
+def _vk_kv_block(env):
+ match = re.match(r"\s*([+-]?\d+)", env.get("COLI_VK_KV_BLOCK") or "")
+ return max(int(match[1]) if match else 64, 1)
+
+
+def _q36_dense_fmt(env, tag, columns):
+ """The format qwen36.c puts a dense matrix on the device in (load_tq, vk_qw_fmt): f32
+ with COLI_DENSE_I8=0, f16 with COLI_DENSE_BITS=16, int4 in groups of 64 with
+ COLI_DENSE_BITS=4 where COLI_DENSE_INT4 (unset: every tag) names its tag and the
+ columns divide by 64, else int8 rows."""
+ if (env.get("COLI_DENSE_I8") or "").strip() == "0":
+ return 10
+ match = re.match(r"\s*([+-]?\d+)", env.get("COLI_DENSE_BITS") or "")
+ bits = int(match[1]) if match else 8
+ if bits == 16:
+ return 14
+ if bits == 4 and columns % 64 == 0:
+ tags = (env.get("COLI_DENSE_INT4") or "").strip()
+ if not tags or tag in re.split(r"[ ,]+", tags):
+ return 4
+ return 1
+
+
+# the matrices qwen36's chain multiplies by, and load_tq's tag for each (a dense model's
+# MLP loads as the shared expert)
+_Q36_CHAIN_TAGS = {"self_attn.q_proj": "attn", "self_attn.k_proj": "attn", "self_attn.v_proj": "attn",
+ "self_attn.o_proj": "attn", "linear_attn.in_proj_qkv": "dnproj",
+ "linear_attn.in_proj_z": "dnproj", "linear_attn.out_proj": "dnout", "mlp.gate": "router",
+ "mlp.shared_expert.gate_proj": "shexp", "mlp.shared_expert.up_proj": "shexp",
+ "mlp.shared_expert.down_proj": "shexp", "mlp.gate_proj": "shexp", "mlp.up_proj": "shexp",
+ "mlp.down_proj": "shexp"}
+
+
+def _q36_chain_layout(info, env, vulkan):
+ """qwen36_chain.h: q36c_fit_layer, q36c_start's fixed bytes and lm_head as the tail,
+ from the scanned matrices' shapes and the scalars of qwen36_meta.json (what the engine
+ reads; config.json's when the checkpoint has none)."""
+ try:
+ meta = json.loads((Path(info["path"]) / "qwen36_meta.json").read_text(encoding="utf-8"))
+ except (KeyError, OSError, ValueError):
+ meta = {}
+ c = info.get("config") or {}
+ c = c.get("text_config", c)
+ try:
+ L = int(meta.get("n_layers") or c["num_hidden_layers"])
+ D = int(meta.get("hidden") or c["hidden_size"])
+ hd = int(meta.get("head_dim") or c["head_dim"])
+ kdim = int(meta.get("dn_kdim") or c.get("linear_key_head_dim") or 0)
+ convk = int(meta.get("dn_convk") or c.get("linear_conv_kernel_dim") or 0)
+ except (KeyError, TypeError, ValueError):
+ return None
+ types = meta.get("layer_types") or c.get("layer_types")
+ if not isinstance(types, list):
+ interval = int(c.get("full_attention_interval") or 4)
+ types = ["full_attention" if i % interval == interval - 1 else "linear_attention" for i in range(L)]
+ if L < 1 or len(types) < L:
+ return None
+ attn = [t == "full_attention" for t in types[:L]]
+ rot = int(meta.get("rotary_dim") or 0)
+ if rot <= 0:
+ factor = float(meta.get("partial_rotary_factor") or c.get("partial_rotary_factor") or 0)
+ rot = int(hd * factor + 0.5) if factor > 0 else hd
+ rot = min(max(rot + rot % 2, 2), hd)
+ # the shapes the engine loads, from the checkpoint
+ rows_of, layers, norms = {}, [0] * L, [0] * L
+ matrices = []
+ for tensor in info.get("dense_tensors", []):
+ name, shape = _text_weight_name(tensor["name"]), tensor.get("shape")
+ layer, part = _vk_layer_index(name), _layer_component(name)
+ if layer is not None and layer < L and part in ("self_attn.q_norm", "self_attn.k_norm"):
+ norms[layer] += hd
+ continue
+ if not isinstance(shape, list) or len(shape) != 2:
+ continue
+ if name == "lm_head.weight" or (layer is not None and layer < L and (part in _Q36_CHAIN_TAGS or part in (
+ "linear_attn.in_proj_b", "mlp.shared_expert_gate"))):
+ rows_of.setdefault(name if layer is None else part, shape)
+ matrices.append((layer, part if layer is not None else name, shape))
+ def rows(part, default=0):
+ return rows_of[part][0] if part in rows_of else default
+ E = rows("mlp.gate")
+ SI = rows("mlp.shared_expert.gate_proj") or rows("mlp.gate_proj")
+ vh = rows("linear_attn.in_proj_b")
+ conv, vd = rows("linear_attn.in_proj_qkv"), rows("linear_attn.in_proj_z")
+ qo, kvo = rows("self_attn.q_proj"), rows("self_attn.k_proj")
+ o_in = rows_of["self_attn.o_proj"][1] if "self_attn.o_proj" in rows_of else 0
+ vocab = rows("lm_head.weight", int(c.get("vocab_size") or 0))
+ vdim = vd // vh if vh else 0
+ # COLI_VK_IMPORT (qwen36.c main, vk_qw_tensor): int8 and f16 rows read in place, only
+ # their scales on the device; by default for a model without routed experts on a device
+ # sharing the CPU's RAM, never while host copies are dropped off a non-integrated one
+ kind = (vulkan or {}).get("type")
+ flag = _vk_flag(env, "COLI_VK_IMPORT")
+ imports = flag != 0 if flag is not None else E == 0 and kind in ("integrated", "cpu")
+ if imports and kind != "integrated" and _vk_flag(env, "COLI_VK_DENSE_HOST") == 0:
+ imports = False
+
+ def placed(tag, shape):
+ out, columns = shape
+ fmt = _q36_dense_fmt(env, tag, columns)
+ if imports and fmt in (1, 14):
+ return _vk_up(4 * (out if fmt == 1 else 1))
+ return vk_tensor_bytes(fmt, columns, out, 64 if fmt == 4 else 0)
+ head = 0
+ for layer, part, shape in matrices:
+ if layer is None:
+ head = placed("lmhead", shape)
+ elif part in _Q36_CHAIN_TAGS:
+ layers[layer] += placed(_Q36_CHAIN_TAGS[part], shape)
+ elif part == "mlp.shared_expert_gate" and E and SI:
+ layers[layer] += vk_tensor_bytes(10, D, 1) # the gate row, f32
+ for i in range(L):
+ floats = 2 * D
+ if attn[i]:
+ floats += norms[i]
+ layers[i] += 2 * vk_buf_bytes(kvo * 3 * _vk_kv_block(env) * 4) # the K/V mirror at the split's floor
+ else:
+ floats += conv * convk + 2 * vh + vdim
+ layers[i] += vk_tensor_bytes(10, D, 2 * vh) # the b|a rows, f32
+ layers[i] += vk_buf_bytes(vh * kdim * vdim * 4) + vk_buf_bytes(conv * (convk - 1) * 4)
+ layers[i] += 4 * floats # its share of the parameters
+ # q36c_bufs for the fit's rows, their read-back, the arena's final norm
+ r, n_attn = _vk_chain_rows(env), sum(attn)
+ counts = [r * D, r * D, r * D, r * qo, r * kvo, r * kvo, r * o_in, r * conv, r * vd, r * 2 * vh, r * conv,
+ r * vd, r * D, r * max(E, 1), r * max(SI, 1), r * max(SI, 1), r * max(SI, 1), r * D, r, D, r * D,
+ r * max(E, 1), max(n_attn, 1) * 2 * r * kvo, vocab, r * D, r * max(rot, 2), r * D]
+ fixed = sum(vk_buf_bytes(4 * max(n, 1)) for n in counts) + vk_buf_bytes(4 * D) + vk_buf_bytes(4)
+ return VkChainLayout(layers, fixed, head)
+
+
+_VK_CHAIN_LAYOUT["qwen36"] = _q36_chain_layout
+
+
+def _olmoe_chain_layout(info, env, vulkan):
+ """olmoe_chain.h olc_fit_start: q, k, v, o and the router as f32 tensors, the K/V
+ mirror at the split's floor, the parameters; one chunk's scratch; lm_head the tail."""
+ c = info.get("config") or {}
+ try:
+ L, D, H = int(c["num_hidden_layers"]), int(c["hidden_size"]), int(c["num_attention_heads"])
+ E, vocab = int(c["num_experts"]), int(c["vocab_size"])
+ except (KeyError, TypeError, ValueError):
+ return None
+ if L < 1 or H < 1 or D % H:
+ return None
+ hd = D // H
+ layer = (4 * vk_tensor_bytes(10, D, D) + vk_tensor_bytes(10, D, E) +
+ 2 * vk_buf_bytes(H * 3 * _vk_kv_block(env) * hd * 4) + 4 * 4 * D)
+ r = _vk_chain_rows(env)
+ counts = [r * D] * 8 + [r * E, D, r * D, r * E, 2 * r * D, vocab, r * D, r * hd, r * D]
+ if (env.get("PILOT") or "").strip() not in ("", "0"):
+ counts.append(r * D) # PILOT's rows after attention
+ fixed = sum(vk_buf_bytes(4 * max(n, 1)) for n in counts) + vk_buf_bytes(4 * D) + vk_buf_bytes(4)
+ return VkChainLayout([layer] * L, fixed, vk_tensor_bytes(10, D, vocab))
+
+
+_VK_CHAIN_LAYOUT["olmoe"] = _olmoe_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.py
index 7c73b39a..0962351e 100644
--- a/c/tests/test_resource_plan.py
+++ b/c/tests/test_resource_plan.py
@@ -1770,6 +1770,170 @@ class VulkanPartialChainTest(unittest.TestCase):
self.assertLess(two["shared_device_dense_bytes"], every["shared_device_dense_bytes"])
+class VulkanPartialChainQwenOlmoeTest(unittest.TestCase):
+ """The partial chain's layouts of qwen36 and olmoe (_VK_CHAIN_LAYOUT): each layer's
+ device bytes, the fixed bytes and the head as their engines' fit lines printed them
+ for the tiny fixtures on Lavapipe, and the plan's credit for the first N layers."""
+
+ LAYERS = ["linear_attention"] * 3 + ["full_attention"] + ["linear_attention"] * 3 + ["full_attention"]
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.model = Path(self.tmp.name)
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def write_qwen36(self, inter=32):
+ """tools/make_qwen36_tiny.py's default geometry as tools/convert_qwen36.py writes
+ it (--inter sets the routed and shared experts' width): 8 layers, attention at 3
+ and 7, 8 experts, a shared expert with its gate, f16 dense tensors."""
+ c = {"architectures": ["Qwen3_5MoeForCausalLM"], "model_type": "qwen3_5_moe_text", "head_dim": 16,
+ "hidden_size": 64, "intermediate_size": 128, "layer_types": self.LAYERS, "linear_conv_kernel_dim": 4,
+ "linear_key_head_dim": 8, "linear_num_key_heads": 4, "linear_num_value_heads": 8,
+ "linear_value_head_dim": 8, "moe_intermediate_size": inter, "num_attention_heads": 4, "num_experts": 8,
+ "num_experts_per_tok": 2, "num_hidden_layers": 8, "num_key_value_heads": 2,
+ "partial_rotary_factor": 0.25, "shared_expert_intermediate_size": inter, "vocab_size": 320}
+ meta = {"hidden": 64, "n_layers": 8, "layer_types": self.LAYERS, "num_experts": 8, "topk": 2,
+ "moe_inter": inter, "shared_inter": inter, "partial_rotary_factor": 0.25, "q_heads": 4,
+ "kv_heads": 2, "q_head_dim": 32, "k_head_dim": 16, "v_head_dim": 16, "o_in": 64, "head_dim": 16,
+ "dn_vheads": 8, "dn_kheads": 4, "dn_kdim": 8, "dn_vdim": 8, "dn_convk": 4, "dn_conv_dim": 128}
+ (self.model / "config.json").write_text(json.dumps(c))
+ (self.model / "qwen36_meta.json").write_text(json.dumps(meta))
+ tensors = []
+
+ def add(name, dtype, *shape):
+ count = 1
+ for n in shape:
+ count *= n
+ tensors.append((name, count * {"F16": 2, "F32": 4, "I8": 1}[dtype], dtype, list(shape)))
+ add("model.embed_tokens.weight", "F16", 320, 64)
+ add("lm_head.weight", "F16", 320, 64)
+ add("model.norm.weight", "F16", 64)
+ for i, kind in enumerate(self.LAYERS):
+ p = f"model.layers.{i}."
+ add(p + "input_layernorm.weight", "F16", 64)
+ add(p + "post_attention_layernorm.weight", "F16", 64)
+ if kind == "full_attention":
+ for name, rows in (("q_proj", 128), ("k_proj", 32), ("v_proj", 32)):
+ add(p + f"self_attn.{name}.weight", "F16", rows, 64)
+ add(p + "self_attn.o_proj.weight", "F16", 64, 64)
+ add(p + "self_attn.q_norm.weight", "F16", 16)
+ add(p + "self_attn.k_norm.weight", "F16", 16)
+ else:
+ add(p + "linear_attn.A_log", "F16", 8)
+ add(p + "linear_attn.dt_bias", "F16", 8)
+ add(p + "linear_attn.conv1d.weight", "F16", 128, 1, 4)
+ add(p + "linear_attn.in_proj_a.weight", "F16", 8, 64)
+ add(p + "linear_attn.in_proj_b.weight", "F16", 8, 64)
+ add(p + "linear_attn.in_proj_qkv.weight", "F16", 128, 64)
+ add(p + "linear_attn.in_proj_z.weight", "F16", 64, 64)
+ add(p + "linear_attn.norm.weight", "F16", 8)
+ add(p + "linear_attn.out_proj.weight", "F16", 64, 64)
+ add(p + "mlp.gate.weight", "F16", 8, 64)
+ add(p + "mlp.shared_expert.gate_proj.weight", "F16", inter, 64)
+ add(p + "mlp.shared_expert.up_proj.weight", "F16", inter, 64)
+ add(p + "mlp.shared_expert.down_proj.weight", "F16", 64, inter)
+ add(p + "mlp.shared_expert_gate.weight", "F16", 1, 64)
+ for e in range(8):
+ add(p + f"mlp.experts.{e}.merged_weight", "I8", 3 * inter * 64)
+ add(p + f"mlp.experts.{e}.qs", "F32", 2 * inter + 64)
+ write_shard(self.model / "model.safetensors", tensors)
+ return analyze_model(self.model)
+
+ def write_olmoe(self):
+ """tools/make_olmoe_tiny.py's geometry as tools/convert_olmoe_merged.py writes it."""
+ c = {"architectures": ["OlmoeForCausalLM"], "model_type": "olmoe", "hidden_size": 64,
+ "intermediate_size": 32, "num_attention_heads": 4, "num_key_value_heads": 4, "num_experts": 8,
+ "num_experts_per_tok": 2, "num_hidden_layers": 4, "vocab_size": 128, "norm_topk_prob": True}
+ (self.model / "config.json").write_text(json.dumps(c))
+ tensors = [("model.embed_tokens.weight", 128 * 64 * 4, "F32", [128, 64]),
+ ("lm_head.weight", 128 * 64 * 4, "F32", [128, 64]), ("model.norm.weight", 256, "F32", [64])]
+ for i in range(4):
+ p = f"model.layers.{i}."
+ for name in ("q_proj", "k_proj", "v_proj", "o_proj"):
+ tensors.append((p + f"self_attn.{name}.weight", 64 * 64 * 4, "F32", [64, 64]))
+ for name in ("q_norm", "k_norm"):
+ tensors.append((p + f"self_attn.{name}.weight", 256, "F32", [64]))
+ for name in ("input_layernorm", "post_attention_layernorm"):
+ tensors.append((p + f"{name}.weight", 256, "F32", [64]))
+ tensors.append((p + "mlp.gate.weight", 8 * 64 * 4, "F32", [8, 64]))
+ for e in range(8):
+ tensors.append((p + f"mlp.experts.{e}.merged_weight", 3 * 32 * 64, "I8", [3 * 32 * 64]))
+ tensors.append((p + f"mlp.experts.{e}.qs", (2 * 32 + 64) * 4, "F32", [2 * 32 + 64]))
+ write_shard(self.model / "model.safetensors", tensors)
+ return analyze_model(self.model)
+
+ def test_layouts_are_the_engines(self):
+ # "[VK] qwen36 chain fit: ... fixed X B (the engine's E B, ...), tail T B, layers ..." and
+ # olmoe's, printed on Lavapipe for the tiny fixtures in each dense format
+ from resource_plan import _VK_CHAIN_LAYOUT
+ cpu = {"type": "cpu", "budget_bytes": 64 * GB}
+ on = {"COLI_VULKAN": "1", "COLI_VK_CHAIN": "1"}
+ attn = [3, 7]
+ def q36(lin, full):
+ return [full if i in attn else lin for i in range(8)]
+ info = self.write_qwen36()
+ for env, fixed, tail, layers in (({"COLI_DENSE_I8": "0"}, 1448960, 82176, q36(105056, 144512)),
+ ({}, 1448960, 21760, q36(36192, 75648)),
+ ({"COLI_DENSE_BITS": "16"}, 1448960, 41216, q36(58976, 98432)),
+ ({"COLI_DENSE_I8": "0", "COLI_VK_CHAIN_ROWS": "3"}, 20480, 82176, q36(105056, 144512))):
+ with self.subTest(engine="qwen36", env=env):
+ got = _VK_CHAIN_LAYOUT["qwen36"](info, dict(on, **env), cpu)
+ self.assertEqual((got.layers, got.fixed, got.tail), (layers, fixed, tail))
+ # COLI_DENSE_BITS=4 on the --inter 64 fixture: int4 in groups of 64
+ self.tmp.cleanup(); self.tmp = tempfile.TemporaryDirectory(); self.model = Path(self.tmp.name)
+ got = _VK_CHAIN_LAYOUT["qwen36"](self.write_qwen36(inter=64), dict(on, COLI_DENSE_BITS="4"), cpu)
+ self.assertEqual((got.layers, got.fixed, got.tail), (q36(27744, 67200), 1547264, 11520))
+ self.tmp.cleanup(); self.tmp = tempfile.TemporaryDirectory(); self.model = Path(self.tmp.name)
+ info = self.write_olmoe()
+ for env, fixed in (({}, 886016), ({"PILOT": "1", "COLI_VK_CHAIN_ROWS": "3"}, 12800)):
+ with self.subTest(engine="olmoe", env=env):
+ got = _VK_CHAIN_LAYOUT["olmoe"](info, dict(on, **env), cpu)
+ self.assertEqual((got.layers, got.fixed, got.tail), ([168192] * 4, fixed, 33024))
+
+ def test_device_only_credits_the_layers_on_the_device(self):
+ from resource_plan import vk_chain_fit, vk_fit_pools
+ kwargs = dict(context=64, ram_gb=4, available_memory=16 * GB, available_disk=16 * GB, gpus=[])
+ for engine, write, L in (("qwen36", self.write_qwen36, 8), ("olmoe", self.write_olmoe, 4)):
+ with self.subTest(engine=engine):
+ self.tmp.cleanup(); self.tmp = tempfile.TemporaryDirectory(); self.model = Path(self.tmp.name)
+ info = write()
+ on = {"COLI_VULKAN": "1", "COLI_VK_CHAIN": "1", "COLI_VK_DENSE_HOST": "0",
+ "COLI_VK_TIER_RESERVE_GB": "0", "COLI_DENSE_I8": "0"}
+ fit = vk_chain_fit(info, engine, on, {"type": "discrete", "budget_bytes": 64 * GB})
+ self.assertEqual(fit["n"], L)
+ # what each engine drops: the chain's matrices of the first k layers (not the
+ # DeltaNet's a/b rows, the shared expert's gate, norms or the head)
+ def released(k):
+ plan = build_plan(self.model, env=dict(on, COLI_VK_CHAIN_LAYERS=str(k)),
+ vulkan={"type": "discrete", "budget_bytes": 64 * GB}, **kwargs)
+ return plan["tiers"]["ram"]["dense_on_device_bytes"]
+ per = released(1)
+ self.assertGreater(per, 0)
+ self.assertEqual(released(0), 0)
+ for k in range(1, L):
+ 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"], released(k))
+ self.assertIn(f"the first {k} of {L} layers", format_plan(plan))
+ # every layer but no room for the head: the layers' copies alone; with room
+ # for it (or every layer forced) the head's copy goes too
+ from resource_plan import _VK_CHAIN_LAYOUT
+ tail = _VK_CHAIN_LAYOUT[engine](info, on, {"type": "discrete"}).tail
+ free = fit["fixed"] + sum(fit["layers"]) + tail // 2
+ no_head = build_plan(self.model, env=on, vulkan={"type": "discrete", "budget_bytes": free}, **kwargs)
+ full = build_plan(self.model, env=on, vulkan={"type": "discrete", "budget_bytes": 64 * GB}, **kwargs)
+ self.assertEqual((no_head["tiers"]["ram"]["vk_chain_layers"]["on_device"],
+ no_head["tiers"]["ram"]["vk_chain_layers"]["tail"]), (L, False))
+ self.assertEqual(full["tiers"]["ram"]["vk_chain_layers"]["tail"], True)
+ self.assertLess(no_head["tiers"]["ram"]["dense_on_device_bytes"],
+ full["tiers"]["ram"]["dense_on_device_bytes"])
+ self.assertEqual(full["tiers"]["ram"]["dense_on_device_bytes"], released(L))
+
+
class PhysicalCpuCountTest(unittest.TestCase):
"""Regression for #325: --auto-tier pinned decode to one core because
physical_cpu_count() silently returned 1.