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(qwen36): name a checkpoint by its geometry, and a converter that refuses what it cannot place

kreuzzelg54eddbed54de
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d4b5285e..c9af31a3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -446,6 +446,39 @@ jobs:
./qwen36 "$cap" 8 qwen36_tiny/ref_full.json
echo "::endgroup::"
done
+ - name: Qwen3.8-2.4T geometry, fused experts + mtp head (converter contract + token-exact)
+ run: |
+ cd c
+ # The 2.4T checkpoint declares the same model_type as the 35B and
+ # resolves to this engine (#1045). Its structural numbers at toy
+ # widths: 92 layers / interval 4 / 512 experts top-10 / 16:1 attention
+ # heads / 8:1 DeltaNet heads. The shard is rewritten into the layout
+ # the real checkpoints ship -- fused expert tensors and an mtp.* head
+ # -- so the converter is seen splitting the one and skipping the other
+ # ON PURPOSE (it must say so), not by never selecting them.
+ # --seed 3: the default seed collapses this geometry's reference to a
+ # single repeated token, which a shape error could still reproduce.
+ python3 tools/make_qwen36_tiny.py --geometry qwen38-2p4t --seed 3 \
+ --out qwen38_2p4t_tiny --ref-mode full \
+ --emit-ref qwen38_2p4t_tiny/ref_full.json
+ python3 tools/convert_qwen36.py --model qwen38_2p4t_tiny \
+ --out qwen38_2p4t_tiny_c --ebits 8 | tee convert_2p4t.log
+ grep -q "skipping 19 \`mtp.\*\` tensor" convert_2p4t.log
+ grep -q "tensor kinds: 1587 in 92 layers, 3 globals" convert_2p4t.log
+ # the container must not carry the head it skipped
+ python3 - <<'EOF'
+ import glob
+ from safetensors import safe_open
+ for path in glob.glob("qwen38_2p4t_tiny_c/*.safetensors"):
+ with safe_open(path, "pt") as f:
+ assert not [k for k in f.keys() if k.startswith("mtp.")], path
+ EOF
+ for cap in 1 2 512; do
+ echo "::group::2.4T geometry cap=$cap"
+ COLI_DENSE_I8=0 SNAP=qwen38_2p4t_tiny_c \
+ ./qwen36 "$cap" 8 qwen38_2p4t_tiny/ref_full.json
+ echo "::endgroup::"
+ done
- name: Same run under ASan + UBSan
run: |
cd c
@@ -465,13 +498,15 @@ jobs:
# diagnostic.
make clean >/dev/null 2>&1 || true
make qwen36 EXTRA_CFLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -g"
- ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=print_stacktrace=1 \
- COLI_DENSE_I8=0 SNAP=qwen36_tiny_c PILOT=1 WIDE=2 \
- ./qwen36 1 8 qwen36_tiny/ref_full.json > san.log 2>&1 || true
- if grep -qE "ERROR: AddressSanitizer|runtime error:" san.log; then
- echo "FAIL: sanitizer diagnostic under PILOT"; cat san.log; exit 1
- fi
- echo "sanitizers clean:"; grep -E "Matching tokens" san.log || true
+ for fx in qwen36_tiny qwen38_2p4t_tiny; do
+ ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=print_stacktrace=1 \
+ COLI_DENSE_I8=0 SNAP=${fx}_c PILOT=1 WIDE=2 \
+ ./qwen36 1 8 $fx/ref_full.json > san.log 2>&1 || true
+ if grep -qE "ERROR: AddressSanitizer|runtime error:" san.log; then
+ echo "FAIL: sanitizer diagnostic under PILOT ($fx)"; cat san.log; exit 1
+ fi
+ echo "sanitizers clean ($fx):"; grep -E "Matching tokens" san.log || true
+ done
- name: KV prefix reuse is token-identical (serve, several turns)
run: |
cd c
diff --git a/.gitignore b/.gitignore
index 2bacdacd..d1564447 100644
--- a/.gitignore
+++ b/.gitignore
@@ -125,6 +125,10 @@ c/olmoe_i4/
c/tiny_inkling/
c/qwen38_tiny/
c/dsv41_tiny/
+c/qwen36_tiny/
+c/qwen36_tiny_c/
+c/qwen38_2p4t_tiny/
+c/qwen38_2p4t_tiny_c/
# Claude Code working directory (agent worktrees, session scratch) — never a repo artifact
.claude/
diff --git a/c/coli b/c/coli
index 32030804..8912586e 100755
--- a/c/coli
+++ b/c/coli
@@ -69,7 +69,7 @@ except ModuleNotFoundError:
_version = "unknown"
from family_registry import (FamilyConfigError, UnknownFamilyError, all_families,
- family_by_id, family_for_config, resolve_model,
+ display_for, family_by_id, family_for_config, resolve_model,
tuning_replay_prompt)
_TUNE_ROTATION_PROMPT = (
@@ -190,9 +190,16 @@ def model_banner_line(model):
except (OSError, ValueError, TypeError):
return generic
kind = (cfg.get("model_type") or "").lower()
+ geometry = cfg
try:
- family = resolve_model(model).descriptor
- name, scale = family.display_name, family.display_scale
+ resolved = resolve_model(model)
+ family = resolved.descriptor
+ # Size-aware: a family's model_type can span checkpoints an order of
+ # magnitude apart (Qwen3.6-35B and Qwen3.8-2.4T both resolve to
+ # qwen36). display_for names the geometry actually on disk, and
+ # falls back to the model_type when it recognises none.
+ name, scale = display_for(resolved)
+ geometry = resolved.family_config
# display_scale e' la taglia del checkpoint di riferimento. Un REAP ha
# lo stesso model_type e meno esperti: "284B" su un 150B e' #1367
# di nuovo. Quando la geometria non e' quella del riferimento si
@@ -206,10 +213,11 @@ def model_banner_line(model):
scale = ""
bits = [name]
+ experts = geometry.get("n_routed_experts") or geometry.get("num_experts")
if scale:
- bits.append(f"{scale} MoE" if cfg.get("n_routed_experts") else scale)
+ bits.append(f"{scale} MoE" if experts else scale)
else:
- layers, experts = cfg.get("num_hidden_layers"), cfg.get("n_routed_experts")
+ layers = geometry.get("num_hidden_layers")
if layers and experts:
bits.append(f"{layers}L x {experts}E MoE")
elif layers:
diff --git a/c/family_registry.py b/c/family_registry.py
index 27593dc0..7b3c2e36 100644
--- a/c/family_registry.py
+++ b/c/family_registry.py
@@ -44,6 +44,23 @@ class FamilyLimits:
context_env: str
+@dataclass(frozen=True, slots=True)
+class DisplayVariant:
+ """One checkpoint geometry a family serves, and what to call it.
+
+ A family is keyed by model_type, and one model_type can cover checkpoints
+ of very different size: Qwen3.6-35B-A3B and Qwen3.8-2.4T-A95B both say
+ ``qwen3_5_moe_text``. A single display_name would announce the 2.4T as a
+ 35B, which is the kind of banner that costs someone a day (#1045). The
+ ``geometry`` pairs are config keys the family config must match exactly;
+ the first matching variant names the model. No match: the model keeps its
+ own model_type as its name rather than borrowing a sibling's.
+ """
+ geometry: tuple
+ display_name: str
+ display_scale: str
+
+
@dataclass(frozen=True, slots=True)
class PlannerGeometry:
context_state_bytes: int
@@ -84,6 +101,9 @@ class FamilyDescriptor:
has_cli_adapter: bool = False
tune_prompt_template: str = "{prompt}"
supports_accelerator: bool = True
+ # Size-keyed names for families whose model_type spans several checkpoint
+ # sizes. Empty: display_name/display_scale name every checkpoint.
+ display_variants: tuple = ()
# Optional model-owned allocations that are neither dense resident
# tensors nor per-expert cache entries. Qwen3.8 uses this for the
# normalized FP8 scale bank shared by every cache slot. Keeping this
@@ -1267,6 +1287,17 @@ FAMILIES = (
model_types=("qwen3_5_moe", "qwen3_5_moe_text"),
display_name="Qwen3.6-35B-A3B",
display_scale="35B",
+ # Both checkpoints declare qwen3_5_moe_text. Keyed on the three
+ # numbers that differ by an order of magnitude, so a config with
+ # any of them off names itself rather than one of these.
+ display_variants=(
+ DisplayVariant((("num_hidden_layers", 40), ("num_experts", 256),
+ ("hidden_size", 2048)),
+ "Qwen3.6-35B-A3B", "35B"),
+ DisplayVariant((("num_hidden_layers", 92), ("num_experts", 512),
+ ("hidden_size", 8192)),
+ "Qwen3.8-2.4T-A95B", "2.4T"),
+ ),
engine_artifact="qwen36",
engine_aliases=(),
engine_group="qwen36",
@@ -1432,6 +1463,21 @@ def _build_registry(families):
family.tune_prompt_template.format(prompt="test", prompt_len=4)
except (AttributeError, IndexError, KeyError, TypeError, ValueError) as error:
raise RegistryError(f"invalid tune prompt template: {family.id}") from error
+ for variant in family.display_variants:
+ if (not isinstance(variant, DisplayVariant) or not variant.geometry or
+ not isinstance(variant.display_name, str) or not variant.display_name or
+ not isinstance(variant.display_scale, str) or
+ any(not isinstance(key, str) or not key or isinstance(value, bool) or
+ not isinstance(value, int) or value < 1
+ for key, value in variant.geometry)):
+ raise RegistryError(f"invalid display variant: {family.id}")
+ # The static display_name is what the READMEs are held to mention, so
+ # it must be a name some checkpoint actually shows -- a family whose
+ # variants all say something else would document a name no banner
+ # prints.
+ if family.display_variants and family.display_name not in {
+ variant.display_name for variant in family.display_variants}:
+ raise RegistryError(f"display_name is not one of its variants: {family.id}")
identity = (family.engine_artifact, family.internal_arch)
if identity in identities:
raise RegistryError(f"duplicate engine identity: {identity}")
@@ -1512,6 +1558,25 @@ def resolve_model(model_dir):
config, family_config, str(model))
+def display_for(resolved):
+ """(display_name, display_scale) for what was actually loaded.
+
+ Families without variants keep their static name. With variants, the
+ first whose geometry keys all match the family config wins; a config that
+ matches none is named by its own model_type with an empty scale, so the
+ banner prints the measured geometry instead of a sibling's parameter
+ count.
+ """
+ family = resolved.descriptor
+ if not family.display_variants:
+ return family.display_name, family.display_scale
+ config = resolved.family_config
+ for variant in family.display_variants:
+ if all(config.get(key) == value for key, value in variant.geometry):
+ return variant.display_name, variant.display_scale
+ return resolved.model_type, ""
+
+
def planner_geometry(resolved, context):
if isinstance(context, bool) or not isinstance(context, int) or context < 1:
raise ValueError("context must be a positive integer")
@@ -1599,6 +1664,11 @@ def public_metadata(family):
"model_types": list(family.model_types),
"display_name": family.display_name,
"display_scale": family.display_scale,
+ "display_variants": [
+ {"geometry": dict(variant.geometry),
+ "display_name": variant.display_name,
+ "display_scale": variant.display_scale}
+ for variant in family.display_variants],
"engine_artifact": family.engine_artifact,
"engine_aliases": list(family.engine_aliases),
"engine_group": family.engine_group,
diff --git a/c/tests/test_cli_output.py b/c/tests/test_cli_output.py
index adcc44d1..82f04522 100644
--- a/c/tests/test_cli_output.py
+++ b/c/tests/test_cli_output.py
@@ -266,6 +266,29 @@ class BannerModelLineTest(unittest.TestCase):
line = self.line({"model_type": model_type, "n_routed_experts": 8})
self.assertTrue(line.startswith(expected), line)
+ def test_qwen_checkpoints_are_named_by_geometry(self):
+ """One model_type, two sizes: the banner must not call a 2.4T a 35B (#1045)."""
+ thirty_five = {"model_type": "qwen3_5_moe_text", "num_hidden_layers": 40,
+ "num_experts": 256, "hidden_size": 2048}
+ two_point_four = {"model_type": "qwen3_5_moe_text", "num_hidden_layers": 92,
+ "num_experts": 512, "hidden_size": 8192}
+ self.assertTrue(self.line(thirty_five).startswith("Qwen3.6-35B-A3B · 35B MoE"),
+ self.line(thirty_five))
+ line = self.line(two_point_four)
+ self.assertTrue(line.startswith("Qwen3.8-2.4T-A95B · 2.4T MoE"), line)
+ self.assertNotIn("35B", line)
+ # the HF repo nests the text config under text_config; the family
+ # config, not the root, is what carries the geometry
+ wrapped = {"model_type": "qwen3_5_moe", "text_config": two_point_four}
+ self.assertTrue(self.line(wrapped).startswith("Qwen3.8-2.4T-A95B"), self.line(wrapped))
+ # a geometry the registry does not recognise names itself, with its
+ # own numbers -- a tiny fixture is not "Qwen3.6-35B-A3B"
+ tiny = {"model_type": "qwen3_5_moe_text", "num_hidden_layers": 8,
+ "num_experts": 8, "hidden_size": 64}
+ line = self.line(tiny)
+ self.assertTrue(line.startswith("qwen3_5_moe_text · 8L x 8E MoE"), line)
+ self.assertNotIn("35B", line)
+
def test_deepseek_v4_is_not_read_as_glm(self):
"""The regression this exists for: a non-GLM checkpoint said GLM-5.2."""
line = self.line({"model_type": "deepseek_v4", "n_routed_experts": 256})
diff --git a/c/tests/test_family_registry.py b/c/tests/test_family_registry.py
index 52501f2b..4a3e95e2 100644
--- a/c/tests/test_family_registry.py
+++ b/c/tests/test_family_registry.py
@@ -9,6 +9,7 @@ from unittest import mock
from family_registry import (
FAMILIES,
+ DisplayVariant,
FamilyCapabilities,
FamilyConfigError,
FamilyDescriptor,
@@ -18,6 +19,7 @@ from family_registry import (
UnknownFamilyError,
PlannerUnsupportedError,
_build_registry,
+ display_for,
expert_contributions,
fixed_resident_contribution,
family_for_config,
@@ -1473,5 +1475,156 @@ class GlmFamilyNamesBothModelsTest(unittest.TestCase):
"name of the other")
+
+# Planning keys of Qwen/Qwen3.8-2.4T-A95B, config.json (fetched 2026-09-03).
+# Same model_type as the 35B container, an order of magnitude apart on every
+# size that matters -- the case #1045 is about.
+QWEN38_2P4T_CONFIG = {
+ "model_type": "qwen3_5_moe_text",
+ "num_hidden_layers": 92,
+ "num_experts": 512,
+ "num_experts_per_tok": 10,
+ "hidden_size": 8192,
+ "moe_intermediate_size": 2048,
+ "full_attention_interval": 4,
+ "layer_types": ["full_attention" if i % 4 == 3 else "linear_attention"
+ for i in range(92)],
+ "num_attention_heads": 64,
+ "num_key_value_heads": 4,
+ "head_dim": 256,
+ "linear_num_key_heads": 16,
+ "linear_key_head_dim": 128,
+ "linear_num_value_heads": 128,
+ "linear_value_head_dim": 128,
+ "linear_conv_kernel_dim": 4,
+ "vocab_size": 248320,
+ "max_position_embeddings": 262144,
+ "mtp_num_hidden_layers": 1,
+}
+
+# The 35B container's flattened text config (what the converter writes).
+QWEN36_35B_CONFIG = {
+ "model_type": "qwen3_5_moe_text",
+ "num_hidden_layers": 40,
+ "num_experts": 256,
+ "num_experts_per_tok": 8,
+ "hidden_size": 2048,
+ "layer_types": ["full_attention" if i % 4 == 3 else "linear_attention"
+ for i in range(40)],
+ "num_key_value_heads": 2,
+ "head_dim": 256,
+ "linear_num_key_heads": 16,
+ "linear_key_head_dim": 128,
+ "linear_num_value_heads": 32,
+ "linear_value_head_dim": 128,
+ "linear_conv_kernel_dim": 4,
+}
+
+
+class DisplayVariantTest(unittest.TestCase):
+ """One model_type, two checkpoint sizes: the banner must name what is on disk."""
+
+ def _resolve(self, config):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ (root / "config.json").write_text(json.dumps(config), encoding="utf-8")
+ return resolve_model(root)
+
+ def test_35b_container_keeps_its_name(self):
+ self.assertEqual(display_for(self._resolve(QWEN36_35B_CONFIG)),
+ ("Qwen3.6-35B-A3B", "35B"))
+
+ def test_2p4t_checkpoint_is_not_announced_as_35b(self):
+ resolved = self._resolve(QWEN38_2P4T_CONFIG)
+ self.assertEqual(resolved.descriptor.id, "qwen36")
+ self.assertEqual(display_for(resolved), ("Qwen3.8-2.4T-A95B", "2.4T"))
+
+ def test_35b_vl_checkpoint_resolves_through_text_config(self):
+ # the HF repo nests the text config; the container flattens it
+ wrapped = {"model_type": "qwen3_5_moe", "architectures": ["Qwen3_5MoeForConditionalGeneration"],
+ "text_config": QWEN36_35B_CONFIG}
+ self.assertEqual(display_for(self._resolve(wrapped)), ("Qwen3.6-35B-A3B", "35B"))
+
+ def test_unrecognised_geometry_names_itself(self):
+ # a tiny fixture, or a third sibling: no borrowed parameter count
+ tiny = dict(QWEN36_35B_CONFIG, num_hidden_layers=8, num_experts=8, hidden_size=64)
+ self.assertEqual(display_for(self._resolve(tiny)), ("qwen3_5_moe_text", ""))
+ # every key must match, one off is not "close enough"
+ off = dict(QWEN38_2P4T_CONFIG, hidden_size=4096)
+ self.assertEqual(display_for(self._resolve(off)), ("qwen3_5_moe_text", ""))
+
+ def test_families_without_variants_are_unchanged(self):
+ for family in FAMILIES:
+ if family.display_variants:
+ continue
+ resolved = self._resolve({"model_type": family.model_types[0]})
+ self.assertEqual(display_for(resolved), (family.display_name, family.display_scale))
+
+ def test_variants_are_public(self):
+ meta = public_metadata(next(f for f in FAMILIES if f.id == "qwen36"))
+ self.assertEqual([v["display_name"] for v in meta["display_variants"]],
+ ["Qwen3.6-35B-A3B", "Qwen3.8-2.4T-A95B"])
+ self.assertEqual(meta["display_variants"][1]["geometry"],
+ {"num_hidden_layers": 92, "num_experts": 512, "hidden_size": 8192})
+ for family in FAMILIES:
+ json.dumps(public_metadata(family))
+
+ def test_registry_refuses_malformed_variants(self):
+ good = DisplayVariant((("num_hidden_layers", 8),), "Qwen3.6", "")
+ for bad in (
+ DisplayVariant((), "Qwen3.6", ""), # matches everything
+ DisplayVariant((("num_hidden_layers", 0),), "Qwen3.6", ""),
+ DisplayVariant((("num_hidden_layers", True),), "Qwen3.6", ""),
+ DisplayVariant((("", 8),), "Qwen3.6", ""),
+ DisplayVariant((("num_hidden_layers", 8),), "", ""),
+ "not a variant",
+ ):
+ with self.subTest(bad=bad):
+ with self.assertRaises(RegistryError):
+ _build_registry((replace(QWEN36_FIXTURE, display_variants=(good, bad)),))
+ # display_name must be one of the variants' names (README contract)
+ with self.assertRaises(RegistryError):
+ _build_registry((replace(QWEN36_FIXTURE, display_variants=(
+ DisplayVariant((("num_hidden_layers", 8),), "Something-Else", ""),)),))
+ _build_registry((replace(QWEN36_FIXTURE, display_variants=(good,)),))
+
+
+class Qwen38_2p4tGeometryTest(unittest.TestCase):
+ """The registered qwen36 planner on the 2.4T config: every guard holds,
+ and the numbers are the ones quoted in #1045."""
+
+ def _resolve(self, config):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ (root / "config.json").write_text(json.dumps(config), encoding="utf-8")
+ return resolve_model(root)
+
+ def test_planner_geometry_at_8k_and_256k(self):
+ resolved = self._resolve(QWEN38_2P4T_CONFIG)
+ g8 = planner_geometry(resolved, 8192)
+ # 23 attention layers x 8192 x 4 kv heads x 256 x (K+V) x f32 = 1.44 GiB
+ self.assertEqual(g8.context_state_bytes, 23 * 8192 * 4 * 256 * 2 * 4)
+ self.assertAlmostEqual(g8.context_state_bytes / 2**30, 1.4375, places=4)
+ self.assertEqual(g8.configured_experts, 512)
+ # DeltaNet state is context-free: 0.55 GiB at any length
+ g256 = planner_geometry(resolved, 262144)
+ self.assertEqual(g256.fixed_state_bytes, g8.fixed_state_bytes)
+ self.assertAlmostEqual(g256.context_state_bytes / 2**30, 46.0, places=1)
+ self.assertAlmostEqual(g8.fixed_state_bytes / 2**30, 0.55, places=2)
+
+ def test_context_beyond_the_registered_maximum_is_refused(self):
+ resolved = self._resolve(QWEN38_2P4T_CONFIG)
+ with self.assertRaises(ValueError):
+ planner_geometry(resolved, 262144 + 1)
+
+ def test_expert_inventory_sees_the_container_layout(self):
+ # the container stores experts one tensor each; the 2.4T layer/expert
+ # indices are within what the descriptor claims
+ resolved = self._resolve(QWEN38_2P4T_CONFIG)
+ self.assertEqual(expert_contributions(
+ resolved, "model.layers.91.mlp.experts.511.merged_weight", 1234),
+ ((91, 511, 1234),))
+ self.assertEqual(expert_contributions(resolved, "mtp.layers.0.mlp.experts.0.x", 1), ())
+
if __name__ == "__main__":
unittest.main()
diff --git a/c/tests/test_qwen36_tensor_kinds.py b/c/tests/test_qwen36_tensor_kinds.py
new file mode 100644
index 00000000..65b98c68
--- /dev/null
+++ b/c/tests/test_qwen36_tensor_kinds.py
@@ -0,0 +1,164 @@
+"""The converter's tensor-name contract, pinned to the real checkpoints.
+
+Torch-free: it imports only tools/qwen36_tensor_kinds.py. The name lists are
+the safetensors indexes of the two shipped checkpoints with the layer/expert
+indices collapsed, so a checkpoint that adds a tensor kind fails here before
+anyone spends a terabyte finding out in the converter.
+"""
+import sys
+import unittest
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools"))
+from qwen36_tensor_kinds import ( # noqa: E402
+ GLOBAL_KINDS, LAYER_KINDS, UnknownTensor, classify, resolve_prefix, skip_reason)
+
+# Qwen/Qwen3.8-2.4T-A95B, model.safetensors.index.json (1609 tensors, 213
+# shards, fetched 2026-09-03). "N" stands for a layer index; 92 layers, of
+# which 23 (i % 4 == 3) carry self_attn and 69 linear_attn.
+QWEN38_2P4T = (
+ "lm_head.weight",
+ "model.embed_tokens.weight",
+ "model.norm.weight",
+ "model.layers.N.input_layernorm.weight",
+ "model.layers.N.post_attention_layernorm.weight",
+ "model.layers.N.linear_attn.A_log",
+ "model.layers.N.linear_attn.conv1d.weight",
+ "model.layers.N.linear_attn.dt_bias",
+ "model.layers.N.linear_attn.in_proj_a.weight",
+ "model.layers.N.linear_attn.in_proj_b.weight",
+ "model.layers.N.linear_attn.in_proj_qkv.weight",
+ "model.layers.N.linear_attn.in_proj_z.weight",
+ "model.layers.N.linear_attn.norm.weight",
+ "model.layers.N.linear_attn.out_proj.weight",
+ "model.layers.N.mlp.experts.down_proj",
+ "model.layers.N.mlp.experts.gate_up_proj",
+ "model.layers.N.mlp.gate.weight",
+ "model.layers.N.mlp.shared_expert.down_proj.weight",
+ "model.layers.N.mlp.shared_expert.gate_proj.weight",
+ "model.layers.N.mlp.shared_expert.up_proj.weight",
+ "model.layers.N.mlp.shared_expert_gate.weight",
+ "model.layers.N.self_attn.k_norm.weight",
+ "model.layers.N.self_attn.k_proj.weight",
+ "model.layers.N.self_attn.o_proj.weight",
+ "model.layers.N.self_attn.q_norm.weight",
+ "model.layers.N.self_attn.q_proj.weight",
+ "model.layers.N.self_attn.v_proj.weight",
+ # mtp_num_hidden_layers: 1 -- one head shaped like an attention layer
+ "mtp.fc.weight",
+ "mtp.norm.weight",
+ "mtp.pre_fc_norm_embedding.weight",
+ "mtp.pre_fc_norm_hidden.weight",
+ "mtp.layers.N.input_layernorm.weight",
+ "mtp.layers.N.post_attention_layernorm.weight",
+ "mtp.layers.N.mlp.experts.down_proj",
+ "mtp.layers.N.mlp.experts.gate_up_proj",
+ "mtp.layers.N.mlp.gate.weight",
+ "mtp.layers.N.mlp.shared_expert.down_proj.weight",
+ "mtp.layers.N.mlp.shared_expert.gate_proj.weight",
+ "mtp.layers.N.mlp.shared_expert.up_proj.weight",
+ "mtp.layers.N.mlp.shared_expert_gate.weight",
+ "mtp.layers.N.self_attn.k_norm.weight",
+ "mtp.layers.N.self_attn.k_proj.weight",
+ "mtp.layers.N.self_attn.o_proj.weight",
+ "mtp.layers.N.self_attn.q_norm.weight",
+ "mtp.layers.N.self_attn.q_proj.weight",
+ "mtp.layers.N.self_attn.v_proj.weight",
+)
+
+# Qwen/Qwen3.6-35B-A3B (1045 tensors): a vision-language checkpoint. Same
+# text tensors under model.language_model., plus the same mtp head and a
+# visual tower (333 tensors, three shown; the prefix is what matters).
+QWEN36_35B = tuple(
+ n.replace("model.", "model.language_model.", 1) if n.startswith("model.") else n
+ for n in QWEN38_2P4T
+) + (
+ "model.visual.patch_embed.proj.weight",
+ "model.visual.blocks.N.attn.qkv.weight",
+ "model.visual.merger.linear_fc1.weight",
+)
+
+# transformers save_pretrained on the text model (the tiny fixture): experts
+# one tensor each, no mtp, no visual.
+TINY_FIXTURE = tuple(
+ n for n in QWEN38_2P4T
+ if not n.startswith("mtp.") and ".mlp.experts." not in n
+) + (
+ "model.layers.N.mlp.experts.N.gate_proj.weight",
+ "model.layers.N.mlp.experts.N.up_proj.weight",
+ "model.layers.N.mlp.experts.N.down_proj.weight",
+)
+
+
+def _concrete(names):
+ return [n.replace("N", "7") for n in names]
+
+
+class TensorKindsTest(unittest.TestCase):
+ def _classify_all(self, names):
+ prefix = resolve_prefix(names)
+ return prefix, [classify(n, prefix) for n in names]
+
+ def test_every_2p4t_tensor_is_placed(self):
+ prefix, placed = self._classify_all(_concrete(QWEN38_2P4T))
+ self.assertEqual(prefix, "model.")
+ kinds = {p[0] for p in placed}
+ self.assertEqual(kinds, {"global", "layer", "skip"})
+ self.assertEqual({p[1] for p in placed if p[0] == "skip"}, {"mtp"})
+ self.assertEqual({p[1] for p in placed if p[0] == "global"}, set(GLOBAL_KINDS))
+ self.assertEqual({p[2] for p in placed if p[0] == "layer"},
+ set(LAYER_KINDS) - set())
+
+ def test_every_35b_tensor_is_placed(self):
+ prefix, placed = self._classify_all(_concrete(QWEN36_35B))
+ self.assertEqual(prefix, "model.language_model.")
+ self.assertEqual({p[1] for p in placed if p[0] == "skip"}, {"mtp", "visual"})
+ self.assertEqual(sum(p[0] == "layer" for p in placed),
+ sum(p[0] == "layer" for p in self._classify_all(
+ _concrete(QWEN38_2P4T))[1]))
+
+ def test_tiny_fixture_per_expert_layout(self):
+ prefix, placed = self._classify_all(_concrete(TINY_FIXTURE))
+ self.assertEqual(prefix, "model.")
+ self.assertNotIn("skip", {p[0] for p in placed})
+ experts = [p for p in placed if p[0] == "layer" and p[2].startswith("mlp.experts.7.")]
+ self.assertEqual(len(experts), 3)
+
+ def test_layer_index_is_read(self):
+ self.assertEqual(classify("model.layers.91.mlp.experts.down_proj", "model."),
+ ("layer", 91, "mlp.experts.down_proj"))
+ self.assertEqual(classify("model.language_model.layers.3.self_attn.q_proj.weight",
+ "model.language_model."),
+ ("layer", 3, "self_attn.q_proj.weight"))
+
+ def test_unknown_names_stop_the_converter(self):
+ for name in (
+ "model.layers.0.mlp.experts.gate_up_proj.weight_scale_inv", # FP8 sidecar
+ "model.layers.0.linear_attn.in_proj_qkvz.weight", # Qwen3-Next naming
+ "model.layers.0.self_attn.q_proj.bias", # attention_bias
+ "model.layers.0.mlp.experts.0.gate_proj.weight_scale_inv",
+ "model.layers.0.mlp.experts.gate_up_proj_extra",
+ "model.language_model.layers.0.mlp.gate.weight", # wrong prefix for this call
+ "audio.encoder.weight",
+ "model.mtp.fc.weight",
+ ):
+ with self.subTest(name=name):
+ with self.assertRaises(UnknownTensor):
+ classify(name, "model.")
+
+ def test_skip_groups_have_a_stated_reason(self):
+ for group in ("mtp", "visual"):
+ self.assertTrue(skip_reason(group))
+ self.assertEqual(skip_reason("nope"), "")
+
+ def test_layer_kinds_are_exact_suffixes(self):
+ # fragments would let "norm.weight" swallow "linear_attn.norm.weight"
+ # AND "mlp.experts.0.norm.weight"; exact strings keep a new kind loud
+ for kind in LAYER_KINDS:
+ self.assertFalse(kind.startswith("."))
+ self.assertFalse(kind.endswith("."))
+ self.assertNotIn("N", kind)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/c/tools/convert_qwen36.py b/c/tools/convert_qwen36.py
index a694080d..7ec413f9 100644
--- a/c/tools/convert_qwen36.py
+++ b/c/tools/convert_qwen36.py
@@ -22,6 +22,11 @@ Design notes (must stay in sync with c/qwen36.c):
and weight keys are prefixed `model.language_model.`. Both are handled transparently.
* The fused expert tensors `mlp.experts.gate_up_proj` / `down_proj` are split per expert
into the merged_weight layout (gate_up = [gate; up] along dim 0).
+ * Every tensor name is classified against tools/qwen36_tensor_kinds.py before the first
+ shard is read. The `mtp.*` head and the `visual.*` tower are skipped ON PURPOSE and
+ reported with a count; a name the contract does not know stops the conversion. A
+ converter that silently drops what it does not recognise produces a container that
+ loads and is quietly missing a tensor (GLM-5.3 precedent, #1045).
* Head dims are derived from the actual weight shapes (authoritative), not from config
heuristics, because Qwen3.6's qk split (q_head_dim=512, k/v_head_dim=256, rope over
256 dims) does not match naive head_dim=hidden/n_heads.
@@ -188,19 +193,11 @@ def _selftest():
sys.exit(0 if ok else 1)
-def resolve_prefix(keys):
- """Return the layer-weight prefix so that `prefix + "layers.{i}."` matches the
- actual weight keys. Handles the common layouts:
- * 'model.' for `model.layers.0...` (standard HF Qwen3 MoE)
- * 'model.language_model.' for `model.language_model.layers.0...` (some VL checkpoints)
- """
- for k in keys:
- if k.startswith("model.language_model.layers."):
- return "model.language_model."
- for k in keys:
- if k.startswith("model.layers."):
- return "model."
- return ""
+# Tensor-name contract: classify() places every name or raises. Kept torch-free
+# in its own module so the test that pins it to the real checkpoint indexes
+# runs wherever the registry tests run.
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from qwen36_tensor_kinds import classify, resolve_prefix, skip_reason, UnknownTensor # noqa: E402
def main():
@@ -302,13 +299,46 @@ def main():
for k in f.keys():
wm[k] = sh.name
- # ---- detect prefix + layer count from weights ----
- sample_layer_keys = [k for k in wm if ".layers.0." in k or ".layers.0." in k]
- prefix = resolve_prefix(wm.keys())
- # find max layer index present
+ # ---- classify every tensor name before touching a shard ----
+ # 5 KB of index settles whether the next hundreds of GB make sense: an
+ # unknown name stops here, a skipped subtree is counted and named.
import re
- layer_ids = set(int(m) for m in re.findall(r"\." + re.escape(prefix) + r"layers\.(\d+)\.", " ".join(wm.keys())))
+ prefix = resolve_prefix(wm.keys())
+ layer_map = {} # layer index -> [keys]
+ global_map = {} # kind -> key
+ skipped = {} # group -> count
+ unknown = []
+ for k in wm:
+ try:
+ placed = classify(k, prefix)
+ except UnknownTensor:
+ unknown.append(k)
+ continue
+ if placed[0] == "layer":
+ layer_map.setdefault(placed[1], []).append(k)
+ elif placed[0] == "global":
+ global_map[placed[1]] = k
+ else:
+ skipped[placed[1]] = skipped.get(placed[1], 0) + 1
+ if unknown:
+ shown = "\n ".join(unknown[:12])
+ more = f"\n ... and {len(unknown) - 12} more" if len(unknown) > 12 else ""
+ sys.exit(f"ERROR: {len(unknown)} tensor name(s) this converter cannot place "
+ f"(tools/qwen36_tensor_kinds.py):\n {shown}{more}\n"
+ "Refusing to convert: a container missing or blindly carrying a tensor "
+ "loads and answers wrongly. Extend the contract if the name is legitimate.")
+ for group, count in sorted(skipped.items()):
+ declared = ""
+ if group == "mtp":
+ declared = f", config mtp_num_hidden_layers={mcfg.get('mtp_num_hidden_layers')!r}"
+ print(f"skipping {count} `{group}.*` tensor(s): {skip_reason(group)}{declared}")
+ if mcfg.get("mtp_num_hidden_layers") and "mtp" not in skipped:
+ print(f"note: config declares mtp_num_hidden_layers={mcfg['mtp_num_hidden_layers']} "
+ "but the checkpoint carries no mtp.* tensors")
+ layer_ids = set(layer_map)
n_layers_weight = (max(layer_ids) + 1) if layer_ids else mcfg.get("num_hidden_layers", 0)
+ 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}")
layer_types = mcfg.get("layer_types")
if layer_types is None:
@@ -327,16 +357,18 @@ def main():
shard_layers = {} # shard name -> set of layer ids needing it (-1 = globals)
def layer_keys(i):
- p = f"{prefix}layers.{i}."
- return [k for k in wm if k.startswith(p)]
-
+ return layer_map.get(i, [])
for i in all_idx:
for k in layer_keys(i):
shard_layers.setdefault(wm[k], set()).add(i)
- globals_keys = [k for k in (f"{prefix}embed_tokens.weight",
- "lm_head.weight", f"{prefix}lm_head.weight",
- f"{prefix}norm.weight")
- if k in wm]
+ missing_layers = [i for i in all_idx if i not in layer_map]
+ if missing_layers:
+ sys.exit(f"ERROR: config declares {len(all_idx)} layers but the checkpoint has no "
+ f"tensors for layer(s) {missing_layers[:8]}")
+ globals_keys = [global_map[kind] for kind in ("embed_tokens.weight", "lm_head.weight",
+ "norm.weight") if kind in global_map]
+ if len(globals_keys) != 3:
+ sys.exit(f"ERROR: expected embed_tokens, lm_head and final norm, found {sorted(global_map)}")
for k in globals_keys:
shard_layers.setdefault(wm[k], set()).add(-1)
@@ -439,7 +471,8 @@ def main():
# ---- MoE experts: handle BOTH layouts the source may use ----
# (a) FUSED: model.layers.i.mlp.experts.gate_up_proj [E,2*inter,H]
# + model.layers.i.mlp.experts.down_proj [E,H,inter]
- # (b) SEPARATE (standard HF Qwen3 MoE, incl. the real 35B):
+ # (b) SEPARATE (transformers save_pretrained on the text model, e.g. the tiny fixture;
+ # the real 35B and 2.4T checkpoints both ship the FUSED layout):
# model.layers.i.mlp.experts.{e}.gate_proj [inter,H]
# model.layers.i.mlp.experts.{e}.up_proj [inter,H]
# model.layers.i.mlp.experts.{e}.down_proj [H,inter]
diff --git a/c/tools/make_qwen36_tiny.py b/c/tools/make_qwen36_tiny.py
index 54240ee7..23e22d65 100644
--- a/c/tools/make_qwen36_tiny.py
+++ b/c/tools/make_qwen36_tiny.py
@@ -18,6 +18,17 @@ matching what qwen36.c Phase 1 computes. No tokenizer needed.
Usage:
python tools/make_qwen36_tiny.py --out ./qwen36_tiny
python tools/make_qwen36_tiny.py --out ./qwen36_tiny --emit-ref ref_qwen36.json
+
+Geometry presets (--geometry): the structural numbers of a real checkpoint at
+toy widths, so the config-shape guards, the layer pattern, the routing and the
+converter's tensor contract are exercised without a single real weight:
+ qwen36-35b 8 layers (2 attention), 8 experts top-2, GQA 2:1 (default)
+ qwen38-2p4t 92 layers (23 attention), 512 experts top-10, GQA 16:1,
+ DeltaNet value:key heads 8:1, FUSED expert tensors and an
+ mtp.* head, exactly as Qwen/Qwen3.8-2.4T-A95B ships them
+--fused-experts rewrites the saved shard into the per-layer gate_up_proj /
+down_proj layout the real checkpoints use (transformers saves per-expert);
+--mtp adds a one-layer multi-token-prediction head the engine must skip.
"""
import argparse, json, sys
from pathlib import Path
@@ -68,10 +79,82 @@ class Zero(nn.Module):
return hidden_states
+GEOMETRIES = {
+ # the shipped fixture: what CI has gated since #712
+ "qwen36-35b": dict(hidden=64, n_layers=8, q_heads=4, kv_heads=2, head_dim=16,
+ rope_dim=8, n_experts=8, topk=2, inter=32,
+ dn_key_heads=4, dn_value_heads=8,
+ fused_experts=False, mtp=False),
+ # Qwen/Qwen3.8-2.4T-A95B, config.json: 92 layers / full_attention_interval 4
+ # / 512 experts top-10 / 64:4 attention heads / 128:16 DeltaNet heads /
+ # mtp_num_hidden_layers 1 / fused experts. Widths shrunk, ratios kept.
+ "qwen38-2p4t": dict(hidden=32, n_layers=92, q_heads=16, kv_heads=1, head_dim=16,
+ rope_dim=8, n_experts=512, topk=10, inter=16,
+ dn_key_heads=2, dn_value_heads=16,
+ fused_experts=True, mtp=True),
+}
+
+
+def _rewrite_shard(out: Path, n_layers, fused_experts, mtp, hidden, seed):
+ """Post-process the transformers shard into the real checkpoints' layout.
+
+ transformers saves routed experts one tensor per expert and never writes an
+ mtp head. The real 35B and 2.4T checkpoints do the opposite on both counts,
+ and those are the two paths the converter's tensor contract has to be seen
+ handling: splitting the fused tensor, and skipping mtp.* on purpose.
+ """
+ from safetensors.torch import load_file, save_file
+ path = out / "model.safetensors"
+ tens = load_file(str(path))
+ if fused_experts:
+ for i in range(n_layers):
+ pre = f"model.layers.{i}.mlp.experts."
+ gate, up, down = [], [], []
+ e = 0
+ while f"{pre}{e}.gate_proj.weight" in tens:
+ gate.append(tens.pop(f"{pre}{e}.gate_proj.weight"))
+ up.append(tens.pop(f"{pre}{e}.up_proj.weight"))
+ down.append(tens.pop(f"{pre}{e}.down_proj.weight"))
+ e += 1
+ if e == 0:
+ sys.exit(f"layer {i}: no per-expert tensors to fuse")
+ # [E, 2*inter, H] with gate rows first, then up -- the split the
+ # converter performs is gu[:, :inter] / gu[:, inter:]
+ tens[f"{pre}gate_up_proj"] = torch.stack(
+ [torch.cat([g, u], dim=0) for g, u in zip(gate, up)]).contiguous()
+ tens[f"{pre}down_proj"] = torch.stack(down).contiguous() # [E, H, inter]
+ if mtp:
+ # One MTP layer shaped like the last transformer layer (an attention
+ # layer, since (n_layers-1) % 4 == 3 for every geometry here), plus the
+ # four glue tensors the real checkpoints carry. Random, never read.
+ g = torch.Generator().manual_seed(seed + 1)
+ src = f"model.layers.{n_layers - 1}."
+ for k in list(tens):
+ if k.startswith(src):
+ tens["mtp.layers.0." + k[len(src):]] = torch.randn(
+ tens[k].shape, generator=g, dtype=torch.float32).to(tens[k].dtype) * 0.02
+ tens["mtp.fc.weight"] = torch.randn((hidden, 2 * hidden), generator=g) * 0.02
+ for k in ("mtp.norm.weight", "mtp.pre_fc_norm_embedding.weight",
+ "mtp.pre_fc_norm_hidden.weight"):
+ tens[k] = torch.ones(hidden)
+ cfg_path = out / "config.json"
+ cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
+ cfg["mtp_num_hidden_layers"] = 1
+ cfg_path.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
+ save_file(tens, str(path), metadata={"format": "pt"})
+ print(f"shard rewritten: fused_experts={fused_experts} mtp={mtp} ({len(tens)} tensors)")
+
+
def build(out: Path, hidden=64, n_layers=8, q_heads=4, kv_heads=2,
head_dim=16, rope_dim=8, n_experts=8, topk=2, inter=32,
vocab=320, max_new=16, prompt_ids=None, emit_ref=None,
- ref_mode="attention_only", seed=20260817):
+ ref_mode="attention_only", seed=20260817,
+ dn_key_heads=None, dn_value_heads=None,
+ fused_experts=False, mtp=False):
+ if dn_key_heads is None:
+ dn_key_heads = q_heads
+ if dn_value_heads is None:
+ dn_value_heads = q_heads * 2
# Fixed by default: an unseeded draw makes the gate flaky. Measured --
# 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.
@@ -88,7 +171,7 @@ def build(out: Path, hidden=64, n_layers=8, q_heads=4, kv_heads=2,
rms_norm_eps=1e-6, rope_theta=10000.0, tie_word_embeddings=False,
head_dim=head_dim, linear_conv_kernel_dim=4,
linear_key_head_dim=8, linear_value_head_dim=8,
- linear_num_key_heads=q_heads, linear_num_value_heads=q_heads * 2,
+ linear_num_key_heads=dn_key_heads, linear_num_value_heads=dn_value_heads,
layer_types=layer_types, hidden_act="silu",
attention_bias=False, attention_dropout=0.0, use_cache=True,
rope_parameters={"rope_type": "default", "rope_theta": 10000.0},
@@ -151,6 +234,10 @@ def build(out: Path, hidden=64, n_layers=8, q_heads=4, kv_heads=2,
print(f"ref.json -> {emit_ref}")
print(f" prompt_ids={prompt_ids}")
print(f" full_ids ={full}")
+ if fused_experts or mtp:
+ # after the reference: generate() ran on the in-memory model, the
+ # rewrite only changes what is on disk
+ _rewrite_shard(out, n_layers, fused_experts, mtp, hidden, seed)
def main():
@@ -166,22 +253,39 @@ def main():
help="full keeps both layer kinds (Phase-2 engine); "
"attention_only replaces DeltaNet with identity (Phase 1)")
ap.add_argument("--max-new", type=int, default=16)
- ap.add_argument("--hidden", type=int, default=64, help="hidden size (default 64)")
- ap.add_argument("--inter", type=int, default=32,
- help="routed/shared expert width (default 32). The shared "
- "expert kernel (expert_ffn.h) needs hidden and inter "
- "multiples of 64: --inter 64 exercises it.")
ap.add_argument("--prompt-ids", default=None,
help="Comma-separated token ids for the prompt (default 1,2,3,4,5)")
+ ap.add_argument("--geometry", choices=sorted(GEOMETRIES), default="qwen36-35b",
+ help="structural numbers of a real checkpoint at toy widths")
+ # --hidden/--inter override the preset's toy widths (qwen36-35b: 64/32). The
+ # shared expert kernel (expert_ffn.h) needs hidden and inter multiples of
+ # 64: --inter 64 exercises it (the CI's A/B step does exactly that).
+ for name in ("layers", "experts", "topk", "q-heads", "kv-heads", "hidden", "inter",
+ "dn-key-heads", "dn-value-heads"):
+ ap.add_argument(f"--{name}", type=int, default=None,
+ help=f"override the preset's {name.replace('-', '_')}")
+ ap.add_argument("--fused-experts", action="store_true", default=None,
+ help="save experts as per-layer gate_up_proj/down_proj (real layout)")
+ ap.add_argument("--mtp", action="store_true", default=None,
+ help="add a one-layer mtp.* head and mtp_num_hidden_layers=1")
args = ap.parse_args()
+ geo = dict(GEOMETRIES[args.geometry])
+ for arg, key in (("layers", "n_layers"), ("experts", "n_experts"), ("topk", "topk"),
+ ("q_heads", "q_heads"), ("kv_heads", "kv_heads"), ("hidden", "hidden"),
+ ("inter", "inter"), ("dn_key_heads", "dn_key_heads"),
+ ("dn_value_heads", "dn_value_heads"), ("fused_experts", "fused_experts"),
+ ("mtp", "mtp")):
+ if getattr(args, arg) is not None:
+ geo[key] = getattr(args, arg)
+ print(f"geometry {args.geometry}: " + ", ".join(f"{k}={v}" for k, v in geo.items()))
prompt_ids = None
if args.prompt_ids:
prompt_ids = [int(x) for x in args.prompt_ids.split(",") if x.strip() != ""]
emit = args.emit_ref if args.emit_ref else None
- build(Path(args.out), hidden=args.hidden, inter=args.inter, max_new=args.max_new, prompt_ids=prompt_ids, emit_ref=emit,
- ref_mode=args.ref_mode, seed=args.seed)
+ build(Path(args.out), max_new=args.max_new, prompt_ids=prompt_ids, emit_ref=emit,
+ ref_mode=args.ref_mode, seed=args.seed, **geo)
if __name__ == "__main__":
diff --git a/c/tools/qwen36_tensor_kinds.py b/c/tools/qwen36_tensor_kinds.py
new file mode 100644
index 00000000..f926982d
--- /dev/null
+++ b/c/tools/qwen36_tensor_kinds.py
@@ -0,0 +1,116 @@
+"""Every tensor name a Qwen3.6/3.8 MoE checkpoint can carry, classified.
+
+The converter used to select what it understood (``<prefix>layers.<i>.`` and
+four globals) and let everything else fall through unmentioned. That skipped
+the ``mtp.*`` head and the ``visual.*`` tower by accident, and it would have
+copied an unfamiliar tensor inside a layer as f16 without a word. Both are
+the failure GLM-5.3's converter was built to refuse: a container that loads
+and is quietly missing, or quietly carrying, a tensor (#1045).
+
+This module is the contract. ``classify`` names every tensor or raises; the
+converter stops on the first name it cannot place. Torch-free on purpose so
+the test can run wherever the registry tests run.
+
+Derived from the safetensors indexes of Qwen/Qwen3.6-35B-A3B (1045 tensors,
+prefix ``model.language_model.``, plus ``visual.*``) and
+Qwen/Qwen3.8-2.4T-A95B (1609 tensors, prefix ``model.``), and from the
+transformers-saved tiny fixture (per-expert layout). The test pins all three.
+"""
+import re
+
+# Suffixes after "<prefix>layers.<i>." -- exact, no fragments, so a new
+# tensor kind fails here instead of matching a substring of an old one.
+LAYER_KINDS = frozenset((
+ "input_layernorm.weight",
+ "post_attention_layernorm.weight",
+ # Gated DeltaNet (linear_attention layers)
+ "linear_attn.A_log",
+ "linear_attn.conv1d.weight",
+ "linear_attn.dt_bias",
+ "linear_attn.in_proj_a.weight",
+ "linear_attn.in_proj_b.weight",
+ "linear_attn.in_proj_qkv.weight",
+ "linear_attn.in_proj_z.weight",
+ "linear_attn.norm.weight",
+ "linear_attn.out_proj.weight",
+ # Gated Attention (full_attention layers)
+ "self_attn.q_proj.weight",
+ "self_attn.k_proj.weight",
+ "self_attn.v_proj.weight",
+ "self_attn.o_proj.weight",
+ "self_attn.q_norm.weight",
+ "self_attn.k_norm.weight",
+ # MoE block: router, shared expert, its gate
+ "mlp.gate.weight",
+ "mlp.shared_expert.gate_proj.weight",
+ "mlp.shared_expert.up_proj.weight",
+ "mlp.shared_expert.down_proj.weight",
+ "mlp.shared_expert_gate.weight",
+ # routed experts, fused layout (real checkpoints): one tensor per layer
+ "mlp.experts.gate_up_proj",
+ "mlp.experts.down_proj",
+))
+
+# routed experts, per-expert layout (transformers save_pretrained on the
+# text model, i.e. the tiny fixture): mlp.experts.<e>.<proj>.weight
+_EXPERT_SEPARATE = re.compile(r"^mlp\.experts\.(\d+)\.(gate_proj|up_proj|down_proj)\.weight$")
+
+GLOBAL_KINDS = frozenset(("embed_tokens.weight", "norm.weight", "lm_head.weight"))
+
+# Whole subtrees the text engine does not implement. Skipped deliberately,
+# counted, and reported -- never silently.
+SKIP_PREFIXES = (
+ ("mtp.", "mtp", "multi-token-prediction head (mtp_num_hidden_layers); "
+ "the engine predicts one token per step and never reads it"),
+ ("model.visual.", "visual", "vision tower; the engine is text-only"),
+ ("visual.", "visual", "vision tower; the engine is text-only"),
+)
+
+_LAYER = re.compile(r"^layers\.(\d+)\.(.+)$")
+
+
+class UnknownTensor(KeyError):
+ """A name the contract does not place. The converter must stop on it."""
+
+
+def resolve_prefix(keys):
+ """'model.language_model.' for VL checkpoints, else 'model.'."""
+ for k in keys:
+ if k.startswith("model.language_model.layers."):
+ return "model.language_model."
+ return "model."
+
+
+def classify(name, prefix):
+ """Return one of
+ ("global", kind) embed / final norm / lm_head
+ ("layer", index, kind) a tensor of transformer layer <index>
+ ("skip", group) mtp / visual, deliberately not converted
+ or raise UnknownTensor.
+
+ ``kind`` for a layer is the suffix after ``layers.<i>.``; for the
+ per-expert layout it is normalised to ``mlp.experts.<e>.<proj>.weight``
+ so the converter can key on it.
+ """
+ for skip_prefix, group, _why in SKIP_PREFIXES:
+ if name.startswith(skip_prefix):
+ return ("skip", group)
+ if name == "lm_head.weight" or name == prefix + "lm_head.weight":
+ return ("global", "lm_head.weight")
+ if name.startswith(prefix):
+ rest = name[len(prefix):]
+ if rest in GLOBAL_KINDS:
+ return ("global", rest)
+ m = _LAYER.match(rest)
+ if m:
+ kind = m.group(2)
+ if kind in LAYER_KINDS or _EXPERT_SEPARATE.match(kind):
+ return ("layer", int(m.group(1)), kind)
+ raise UnknownTensor(name)
+
+
+def skip_reason(group):
+ for _prefix, g, why in SKIP_PREFIXES:
+ if g == group:
+ return why
+ return ""
diff --git a/docs/qwen36.md b/docs/qwen36.md
index 968ba476..32cfcdd4 100644
--- a/docs/qwen36.md
+++ b/docs/qwen36.md
@@ -114,6 +114,66 @@ per-row quantization error concentrates the same way. The gs64 container costs
~1.7 GB more on disk and a few percent on cold-start; warm decode speed is the
same or slightly better.
+## Which checkpoints, and what the banner calls them
+
+Two Qwen checkpoints declare `model_type: qwen3_5_moe_text` and resolve to
+this engine:
+
+| checkpoint | layers | experts | hidden | banner |
+|---|---|---|---|---|
+| Qwen/Qwen3.6-35B-A3B | 40 (10 attention) | 256, top-8 | 2048 | `Qwen3.6-35B-A3B · 35B MoE` |
+| Qwen/Qwen3.8-2.4T-A95B | 92 (23 attention) | 512, top-10 | 8192 | `Qwen3.8-2.4T-A95B · 2.4T MoE` |
+
+The registry names a checkpoint by its geometry (`display_variants` on the
+`qwen36` descriptor), so the banner says what is on disk. A config that
+matches neither, a tiny fixture for instance, is named by its own
+`model_type` and measured geometry rather than by a sibling's parameter
+count (#1045).
+
+The 2.4T checkpoint is **architecture-identical** to the 35B: same layer
+pattern, every engine guard holds, and the registry's planner puts its KV
+cache at 1.44 GiB for 8k context and 46 GiB at the 256k maximum, with a
+context-free DeltaNet state of 0.55 GiB. What this engine cannot do for it
+is hold the experts: the warmstart keeps every expert in RAM by design (see
+`--ram` below), which is ~1.4 TB of int4 for 2.4T. Serving it needs the
+disk-streaming design, not this one. The conversion and the geometry checks
+are in place so that work starts from a verified shape, not from a guess.
+
+### The converter's tensor contract
+
+Both checkpoints ship experts **fused** per layer (`mlp.experts.gate_up_proj`,
+`mlp.experts.down_proj`), a one-layer multi-token-prediction head (`mtp.*`,
+`mtp_num_hidden_layers: 1`), and the 35B additionally a vision tower
+(`visual.*`). `tools/qwen36_tensor_kinds.py` classifies every tensor name
+before the first shard is read: layer tensors are converted, `mtp.*` and
+`visual.*` are skipped **on purpose** and reported with a count, and a name
+the contract does not know stops the conversion. A converter that silently
+drops what it does not recognise produces a container that loads and is
+quietly missing a tensor; this one refuses instead (the GLM-5.3 precedent).
+`tests/test_qwen36_tensor_kinds.py` pins the contract to both real indexes.
+
+### Validating the 2.4T shape without a single weight
+
+`tools/make_qwen36_tiny.py --geometry qwen38-2p4t` builds a fixture with the
+2.4T's structural numbers at toy widths -- 92 layers, interval 4, 512 experts
+top-10, 16:1 attention heads, 8:1 DeltaNet heads -- and rewrites the shard
+into the real layout: fused experts plus an `mtp.*` head. The converter must
+split the one and skip the other, and the engine must match the transformers
+reference token for token. CI runs it at cache capacities 1, 2 and 512, and
+under ASan/UBSan. Locally:
+
+```sh
+cd c && make qwen36
+python3 tools/make_qwen36_tiny.py --geometry qwen38-2p4t --seed 3 \
+ --out q24 --ref-mode full --emit-ref q24/ref_full.json
+python3 tools/convert_qwen36.py --model q24 --out q24_c --ebits 8
+COLI_DENSE_I8=0 SNAP=q24_c ./qwen36 512 8 q24/ref_full.json
+```
+
+(`--seed 3`: the default seed collapses this geometry's reference to one
+repeated token, which a shape error could still reproduce; seed 3 yields
+twelve distinct tokens over sixteen.)
+
## `--ram` is not honoured by this engine
The engine reads no `RAM_GB`: `grep -c RAM_GB c/qwen36.c` returns 0, and passing