Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
convert_qwen36: Qwen3-Coder containers, with a tiny oracle in CI
JustVugg33d34665b63f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 5c33075c..56b3996a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -506,6 +506,28 @@ jobs:./qwen36 "$cap" 8 qwen38_2p4t_tiny/ref_full.jsonecho "::endgroup::"done+ - name: "Qwen3-Coder geometry: qwen3_moe, every layer attention, no shared expert"+ run: |+ cd c+ # Qwen/Qwen3-Coder-30B-A3B-Instruct is Qwen3MoeForCausalLM: no DeltaNet, no+ # attention output gate, no shared expert, full rotary and plain RMSNorm+ # weights. The fixture draws its norms around 1 so a container that applied+ # them zero-centered could not pass, and the converter has to say so in the+ # meta; the engine runs it token for token against transformers.+ python3 tools/make_qwen36_tiny.py --geometry qwen3-coder-30b \+ --out qwen3_coder_tiny --ref-mode full \+ --emit-ref qwen3_coder_tiny/ref_full.json+ python3 tools/convert_qwen36.py --model qwen3_coder_tiny \+ --out qwen3_coder_tiny_c --ebits 8+ python3 -c "import json; m = json.load(open('qwen3_coder_tiny_c/qwen36_meta.json')); \+ assert (m['shared_inter'], m['zero_centered_norms'], m['partial_rotary_factor'], \+ set(m['layer_types'])) == (0, False, 1.0, {'full_attention'}), m"+ for cap in 1 8; do+ echo "::group::Qwen3-Coder geometry cap=$cap"+ COLI_DENSE_I8=0 SNAP=qwen3_coder_tiny_c \+ ./qwen36 "$cap" 8 qwen3_coder_tiny/ref_full.json+ echo "::endgroup::"+ done- name: "Qwen3.8-27B geometry: a dense checkpoint of the same architecture (#1757)"run: |cd cdiff --git a/c/tools/convert_qwen36.py b/c/tools/convert_qwen36.pyindex bc06b8fa..984881b3 100644--- a/c/tools/convert_qwen36.py+++ b/c/tools/convert_qwen36.py@@ -306,6 +306,10 @@ def main():cfg_full = json.load(open(cfg_path, encoding="utf-8"))# VL checkpoints nest dims under text_configmcfg = cfg_full.get("text_config", cfg_full)+ # transformers 5 writes qwen3_moe's expert count as num_local_experts; the released+ # checkpoints (written by 4.x) say num_experts. Read either.+ if "num_experts" not in mcfg and "num_local_experts" in mcfg:+ mcfg = dict(mcfg, num_experts=mcfg["num_local_experts"])out = Path(args.out)out.mkdir(parents=True, exist_ok=True)import shutil@@ -401,11 +405,18 @@ def main():print(f"tensor kinds: {sum(len(v) for v in layer_map.values())} in {len(layer_ids)} layers, "f"{len(global_map)} globals, prefix {prefix!r}")+ # Qwen3 MoE (qwen3_moe, e.g. Qwen3-Coder-30B-A3B): every layer is plain attention,+ # full rotary, ordinary RMSNorm weights and no shared expert. Qwen3.5/3.6 differ on+ # each of those, so the defaults below branch on it.+ plain_qwen3 = cfg_full.get("model_type") == "qwen3_moe"layer_types = mcfg.get("layer_types")if layer_types is None:- # infer: every 4th layer is full_attention (Qwen3.5/3.6 convention)n = mcfg.get("num_hidden_layers", n_layers_weight)- layer_types = ["full_attention" if i % 4 == 3 else "linear_attention" for i in range(n)]+ if plain_qwen3:+ layer_types = ["full_attention"] * n+ else:+ # infer: every 4th layer is full_attention (Qwen3.5/3.6 convention)+ layer_types = ["full_attention" if i % 4 == 3 else "linear_attention" for i in range(n)]full_idx = [i for i, lt in enumerate(layer_types) if lt == "full_attention"]all_idx = list(range(len(layer_types)))print(f"layers: {len(layer_types)} total, {len(full_idx)} full_attention (Phase 2: all {len(all_idx)} stored)")@@ -610,7 +621,8 @@ def main():"topk": int(mcfg.get("num_experts_per_tok", 0)) if mcfg.get("num_experts") else 0,"moe_inter": (int(mcfg.get("moe_intermediate_size", mcfg.get("intermediate_size", 0) // 2))if mcfg.get("num_experts") else 0),- "shared_inter": (int(mcfg.get("shared_expert_intermediate_size", mcfg.get("moe_intermediate_size", 0)))+ "shared_inter": (0 if plain_qwen3 else+ int(mcfg.get("shared_expert_intermediate_size", mcfg.get("moe_intermediate_size", 0)))if mcfg.get("num_experts") else int(mcfg["intermediate_size"])),"rms_eps": float(mcfg.get("rms_norm_eps", 1e-6)),"ebits": args.ebits,@@ -619,10 +631,13 @@ def main():"topk_group": int(mcfg.get("topk_group", 1)),"norm_topk_prob": bool(mcfg.get("norm_topk_prob", False)),"attn_output_gate": bool(mcfg.get("attn_output_gate", False)),- "rope_theta": float((mcfg.get("rope_parameters") or {}).get("rope_theta", 10000000.0)),+ "rope_theta": float((mcfg.get("rope_parameters") or {}).get(+ "rope_theta", mcfg.get("rope_theta", 10000000.0))),"mrope_section": (mcfg.get("rope_parameters") or {}).get("mrope_section", [16, 16, 16]),- "partial_rotary_factor": float(mcfg.get("partial_rotary_factor", 0.25)),+ "partial_rotary_factor": float(mcfg.get("partial_rotary_factor", 1.0 if plain_qwen3 else 0.25)),}+ if plain_qwen3:+ meta["zero_centered_norms"] = False# derive head dims from first full-attention layer weights (authoritative).# Read from SOURCE (not local output) so this works even when layer 0 was# skipped during a resume and its local shard was already stream-deleted.@@ -659,6 +674,11 @@ def main():meta["expert_down_gs"] = args.down_gsmeta["head_dim"] = meta.get("k_head_dim", meta.get("q_head_dim", 256))meta["rope_dim"] = meta.get("qk_rope_head_dim", meta["head_dim"] // 4)+ if plain_qwen3:+ # One position per token, so M-RoPE over sections that cover the whole+ # rotary half is ordinary 1D RoPE; the engine needs the sections to add up.+ half = int(meta["rope_dim"] * meta["partial_rotary_factor"]) // 2+ meta["mrope_section"] = [half - 2 * (half // 3), half // 3, half // 3]# ---- DeltaNet (linear_attention) dims. From config (authoritative for dn; unlike the# attention qk split, dn dims are explicit in config and never evicted shards). ----meta["dn_vheads"] = int(mcfg.get("linear_num_value_heads", mcfg.get("num_value_heads", 0)))diff --git a/c/tools/make_qwen36_tiny.py b/c/tools/make_qwen36_tiny.pyindex 3508d42a..234efdd2 100644--- a/c/tools/make_qwen36_tiny.py+++ b/c/tools/make_qwen36_tiny.py@@ -100,6 +100,12 @@ GEOMETRIES = {rope_dim=8, n_experts=0, topk=0, inter=128,dn_key_heads=2, dn_value_heads=6,fused_experts=False, mtp=False, dense=True),+ # Qwen/Qwen3-Coder-30B-A3B-Instruct, config.json: Qwen3MoeForCausalLM (qwen3_moe),+ # 48 attention layers (no DeltaNet), 32:4 heads of 128, 128 experts top-8,+ # norm_topk_prob, no shared expert, full rotary, rope_theta 1e7, plain RMSNorm.+ "qwen3-coder-30b": dict(hidden=64, n_layers=6, q_heads=8, kv_heads=1, head_dim=16,+ rope_dim=16, n_experts=16, topk=4, inter=32,+ fused_experts=False, mtp=False, plain_qwen3=True),}@@ -158,7 +164,7 @@ def build(out: Path, hidden=64, n_layers=8, q_heads=4, kv_heads=2,vocab=320, max_new=16, prompt_ids=None, emit_ref=None,ref_mode="attention_only", seed=20260817,dn_key_heads=None, dn_value_heads=None,- fused_experts=False, mtp=False, dense=False):+ fused_experts=False, mtp=False, dense=False, plain_qwen3=False):if dn_key_heads is None:dn_key_heads = q_headsif dn_value_heads is None:@@ -167,6 +173,11 @@ def build(out: Path, hidden=64, n_layers=8, q_heads=4, kv_heads=2,# three local draws passed, one CI draw failed at 11/16, with identical# code. A gate that reddens at random gets muted within a week.torch.manual_seed(seed)+ if plain_qwen3:+ model = _plain_qwen3(hidden, n_layers, q_heads, kv_heads, head_dim, n_experts,+ topk, inter, vocab)+ return _save_and_reference(model, out, n_layers, max_new, prompt_ids, emit_ref,+ "full", fused_experts, mtp, hidden, seed, "qwen3_moe_tiny")ModelCls, ConfigCls = get_classes(dense)layer_types = ["full_attention" if i % 4 == 3 else "linear_attention"for i in range(n_layers)]@@ -209,6 +220,46 @@ def build(out: Path, hidden=64, n_layers=8, q_heads=4, kv_heads=2,passmodel = ModelCls(cfg)+ return _save_and_reference(model, out, n_layers, max_new, prompt_ids, emit_ref,+ ref_mode, fused_experts, mtp, hidden, seed, "qwen36_tiny")+++def _plain_qwen3(hidden, n_layers, q_heads, kv_heads, head_dim, n_experts, topk, inter,+ vocab):+ """Qwen3-MoE as transformers ships it (Qwen3MoeForCausalLM). The RMSNorm weights+ are drawn around 1 instead of left at 1, so a container that applied them as+ zero-centered (1 + w), the Qwen3.5/3.6 convention, could not pass."""+ import transformers+ ModelCls = getattr(transformers, "Qwen3MoeForCausalLM", None)+ if ModelCls is None:+ sys.exit("this transformers build has no Qwen3MoeForCausalLM")+ ConfigCls = ModelCls.config_class+ base = dict(+ vocab_size=vocab, hidden_size=hidden, intermediate_size=hidden * 2,+ num_hidden_layers=n_layers, num_attention_heads=q_heads,+ num_key_value_heads=kv_heads, head_dim=head_dim, num_experts=n_experts,+ num_experts_per_tok=topk, moe_intermediate_size=inter, norm_topk_prob=True,+ decoder_sparse_step=1, mlp_only_layers=[], max_position_embeddings=512,+ rms_norm_eps=1e-6, rope_theta=10000000.0, tie_word_embeddings=False,+ attention_bias=False, use_sliding_window=False, hidden_act="silu",+ rope_parameters={"rope_type": "default", "rope_theta": 10000000.0},+ pad_token_id=0, bos_token_id=1, eos_token_id=vocab - 1)+ try:+ cfg = ConfigCls(**base)+ except TypeError:+ import inspect+ allowed = set(inspect.signature(ConfigCls.__init__).parameters) - {"self"}+ cfg = ConfigCls(**{k: v for k, v in base.items() if k in allowed})+ model = ModelCls(cfg)+ with torch.no_grad():+ for name, param in model.named_parameters():+ if name.endswith("norm.weight"):+ param.copy_(1.0 + 0.2 * torch.randn_like(param))+ return model+++def _save_and_reference(model, out, n_layers, max_new, prompt_ids, emit_ref, ref_mode,+ fused_experts, mtp, hidden, seed, label):model.eval()out.mkdir(parents=True, exist_ok=True)model.save_pretrained(str(out))@@ -225,7 +276,7 @@ def build(out: Path, hidden=64, n_layers=8, q_heads=4, kv_heads=2,# script encodes a text prompt through AutoTokenizer.from_pretrained(),# and this fixture is synthetic: it has weights and no tokenizer. The# oracle script stays the tool for real checkpoints.- if ref_mode == "attention_only":+ if ref_mode == "attention_only" and label == "qwen36_tiny":replaced = 0for i in range(n_layers):if i % 4 != 3:@@ -243,7 +294,7 @@ def build(out: Path, hidden=64, n_layers=8, q_heads=4, kv_heads=2,use_cache=True)full = out_ids[0].tolist()payload = {"prompt_ids": prompt_ids, "full_ids": full,- "mode": ref_mode, "model": "qwen36_tiny"}+ "mode": ref_mode, "model": label}Path(emit_ref).write_text(json.dumps(payload, indent=2))print(f"ref.json -> {emit_ref}")print(f" prompt_ids={prompt_ids}")