Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

GGUF block registry: the generic loader composes registered blocks

YanissAmz3ebeb42801ae
diff --git a/exllamav3/architecture/gguf_generic.py b/exllamav3/architecture/gguf_generic.py
index e41f577..c5fc506 100644
--- a/exllamav3/architecture/gguf_generic.py
+++ b/exllamav3/architecture/gguf_generic.py
@@ -1,4 +1,4 @@
-"""Generic GGUF loader (first cut): llama-family attention + dense gated MLP or standard top-k MoE, no per-model class.
+"""Generic GGUF loader: the composition of the block registry (loader/gguf_registry.py, loader/gguf_blocks/), no per-model class.
Off by default: only active with EXL3_GGUF_GENERIC=1, and only for a GGUF whose general.architecture has no entry in
loader/gguf_config.GGUF_ARCHS. Everything is derived from the GGUF header:
@@ -18,297 +18,84 @@ from ..loader.gguf_collection import GGUFCollection
from ..model.config import Config, no_default
from ..model.model import Model
from ..util.rope import RopeStyle
-from ..modules import RMSNorm, Embedding, TransformerBlock, Attention, GatedMLP, BlockSparseMLP
+from ..loader.gguf_registry import ARCH_FEATS, GenericUnsupported, REGISTRY, CONFIG_ONLY, build_plan, req
+from ..loader.gguf_blocks.attn import gqa_global
+from ..loader.gguf_blocks.transformer import residual_global
+from ..loader.gguf_blocks.mlp import moe_global, moe_layers
from ..modules.attn import prepare_for_attn
ARCH_STRING = "GGUFGenericForCausalLM"
+_ARCH_FEATS = ARCH_FEATS # per-arch residue: loader/gguf_registry.ARCH_FEATS (only what llama.cpp hard-codes with no key)
def enabled() -> bool:
return os.environ.get("EXL3_GGUF_GENERIC", "0") == "1"
-class GenericUnsupported(ValueError):
- """The GGUF needs a piece the generic builder does not have (the message names it)."""
-
-
-# llama.cpp permutes Q/K rows (adjacent-pair rotary) only for these converters; every other arch is stored in HF/NEOX order.
-_ROPE_PERMUTED = {"llama"}
-# routing weights renormalised over the picked experts (llama.cpp hparams.expert_weights_norm) when the GGUF lacks the key
-# gpt-oss: softmax over the top-k logits == softmax over all, renormalised over the picked experts
-_NORM_TOPK_DEFAULT = {"qwen3moe": True, "mixtral": True, "olmoe": False, "gpt-oss": True}
-
-# arch default for <arch>.attention.sliding_window_pattern when the GGUF lacks it (llama.cpp set_swa_pattern); 0/absent = all layers sliding
-_SWA_DEFAULT_PATTERN = {"gpt-oss": 2}
-# yarn without truncation of the correction range (HF gpt-oss rope_scaling.truncate = false)
-_YARN_NO_TRUNCATE = {"gpt-oss"}
-
-# activation + clamp per arch: llama.cpp hard-codes swiglu_oai alpha 1.702 / limit 7.0 for gpt-oss (llama-graph.cpp build_moe_ffn, no GGUF key);
-# the engine's "swiglu_oai" has the same alpha and the +1 on up. <arch>.swiglu_limit overrides when a GGUF carries it.
-_MOE_ACT = {"gpt-oss": ("swiglu_oai", 7.0)}
-
-_KNOWN = {
- "attn_q.bias", "attn_k.bias", "attn_v.bias", "attn_output.bias", "attn_sinks.weight",
- "post_attention_norm.weight", "post_ffw_norm.weight", "layer_output_scale.weight",
- "attn_norm.weight", "attn_q.weight", "attn_k.weight", "attn_v.weight", "attn_output.weight",
- "attn_q_norm.weight", "attn_k_norm.weight", "ffn_norm.weight",
- "ffn_gate.weight", "ffn_up.weight", "ffn_down.weight",
- "ffn_gate_shexp.weight", "ffn_up_shexp.weight", "ffn_down_shexp.weight", "ffn_gate_inp_shexp.weight",
- "ffn_gate_inp.weight", "ffn_gate_exps.weight", "ffn_up_exps.weight", "ffn_down_exps.weight",
- "ffn_gate_inp.bias", "ffn_gate_exps.bias", "ffn_up_exps.bias", "ffn_down_exps.bias",
-}
-_KNOWN_GLOBAL = {"token_embd.weight", "output_norm.weight", "output.weight", "rope_freqs.weight"}
-
-# arch features llama.cpp hard-codes per arch (no GGUF key): gemma4 = src/models/gemma4.cpp (see GEMMA4_UNCHECKED.md)
-# act: dense FFN activation (LLM_FFN_GELU = tanh approx); embed_scale: inp = tok_embd * sqrt(n_embd) (build_inp_embd(.., sqrtf(n_embd)));
-# v_norm: unweighted rms_norm on V of every layer (K=V layers: V = raw k_proj output); sm_scale: hparams.f_attention_scale = 1.0
-_ARCH_FEATS = {"gemma4": {"act": "gelu", "embed_scale": True, "v_norm": True, "sm_scale": 1.0}}
-
-
def _req(m: dict, key: str):
- if key not in m:
- raise GenericUnsupported(f"missing GGUF metadata key {key!r}")
- return m[key]
+ return req(m, key)
def hf_config_generic(g: GGUFCollection) -> dict:
- """GGUF header -> HF-style config dict for GGUFGenericForCausalLM; unmapped pieces go to cfg['gaps']."""
- m, infos = g.meta, g.infos
+ """GGUF header -> HF-style config dict for GGUFGenericForCausalLM, composed from the block plan; unmapped pieces go to cfg['gaps']."""
+ m = g.meta
arch = _req(m, "general.architecture")
p = arch + "."
- ne, nq = _req(m, p + "embedding_length"), _req(m, p + "attention.head_count")
+ _req(m, p + "embedding_length"), _req(m, p + "attention.head_count")
nl = _req(m, p + "block_count")
- hd = m.get(p + "attention.key_length", ne // nq)
- gaps, unmapped = [], []
- # per-layer kv heads (gemma4: array)
- kvr = m.get(p + "attention.head_count_kv", nq)
- n_kv_l = list(kvr) if isinstance(kvr, list) else [kvr] * nl
- if len(n_kv_l) != nl:
- gaps.append(f"head_count_kv array has {len(n_kv_l)} entries for {nl} layers")
- n_kv_l = (n_kv_l * nl)[:nl]
- # tensor-name audit: every tensor must be one the builder knows
- layers: dict[int, set] = {}
- for name in infos:
- mt = re.match(r"blk\.(\d+)\.(.+)$", name)
- if mt:
- layers.setdefault(int(mt.group(1)), set()).add(mt.group(2))
- if mt.group(2) not in _KNOWN:
- unmapped.append(name if int(mt.group(1)) == 0 else re.sub(r"blk\.\d+", "blk.N", name))
- elif name not in _KNOWN_GLOBAL:
- unmapped.append(name)
- unmapped = sorted(set(unmapped))
- if unmapped:
- gaps.append(f"no builder for tensors: {', '.join(unmapped[:12])}")
- if sorted(layers) != list(range(nl)):
- gaps.append(f"blk indices {sorted(layers)[:3]}.. do not cover block_count={nl} (nextn/MTP or non-uniform stack)")
- moe_layers = [i for i in range(nl) if "ffn_gate_exps.weight" in layers.get(i, ())]
+ plan = build_plan(g)
+ ctx = plan.ctx
+ a = gqa_global(ctx)
+ gaps = ctx.gaps
+ if sorted(ctx.layers) != list(range(nl)):
+ gaps.append(f"blk indices {sorted(ctx.layers)[:3]}.. do not cover block_count={nl} (nextn/MTP or non-uniform stack)")
if p + "ssm.state_size" in m:
gaps.append(f"metadata {p}ssm.state_size (ssm / mamba layers) has no module wiring")
if m.get(p + "attention.shared_kv_layers", 0):
gaps.append(f"shared_kv_layers={m[p + 'attention.shared_kv_layers']} (KV sharing across layers) not wired")
- if m.get(p + "embedding_length_per_layer_input", 0):
+ if m.get(p + "embedding_length_per_layer_input", 0) and not any(lp["pre"] == "engram" for lp in plan.layers):
gaps.append("per-layer input embeddings (PLE) not wired")
- # (1) sandwich norms: llama.cpp names the pre-FFN norm ffn_norm; gpt-oss has no ffn_norm and uses post_attention_norm there
- def has_all(sfx):
- return all(sfx in layers.get(i, ()) for i in range(nl))
- def has_any(sfx):
- return any(sfx in layers.get(i, ()) for i in range(nl))
- for sfx in ("post_attention_norm.weight", "post_ffw_norm.weight", "layer_output_scale.weight", "ffn_norm.weight"):
- if has_any(sfx) and not has_all(sfx):
- gaps.append(f"{sfx} present on only some layers")
- sandwich = has_all("post_attention_norm.weight") and has_all("post_ffw_norm.weight")
- pre_ffn_from_post = (not has_any("ffn_norm.weight")) and has_all("post_attention_norm.weight") and not has_any("post_ffw_norm.weight")
- if not has_any("ffn_norm.weight") and not pre_ffn_from_post:
- gaps.append("no pre-FFN norm tensor (ffn_norm / post_attention_norm)")
- layer_scalar = has_all("layer_output_scale.weight")
- # (2) sliding window, per-layer pattern, per-layer head dim / rope base
- win = m.get(p + "attention.sliding_window", 0) or 0
- swa = [False] * nl
- if win:
- pat = m.get(p + "attention.sliding_window_pattern", _SWA_DEFAULT_PATTERN.get(arch, 0))
- if isinstance(pat, list):
- if len(pat) != nl:
- gaps.append(f"sliding_window_pattern has {len(pat)} entries for {nl} layers")
- swa = [bool(pat[i % len(pat)]) for i in range(nl)]
- elif pat:
- swa = [i % pat < pat - 1 for i in range(nl)]
- else:
- swa = [True] * nl
- hd_swa = m.get(p + "attention.key_length_swa", hd)
- hd_l = [hd_swa if swa[i] else hd for i in range(nl)]
- bad_q = [i for i in range(nl) if f"blk.{i}.attn_q.weight" in infos and infos[f"blk.{i}.attn_q.weight"][1][1] != nq * hd_l[i]]
- if bad_q:
- gaps.append(f"attn_q width != n_heads*head_dim on layers {bad_q[:4]} (gated q / unknown per-layer head dim)")
- fb, fbs = m.get(p + "rope.freq_base", 10000.0), m.get(p + "rope.freq_base_swa")
- theta_l = [fbs if (swa[i] and fbs) else fb for i in range(nl)]
- rd, rds = m.get(p + "rope.dimension_count"), m.get(p + "rope.dimension_count_swa")
- rdim_l = [(rds if (swa[i] and rds) else rd) or hd_l[i] for i in range(nl)]
- kv_eq_v = [i for i in range(nl) if "attn_k.weight" in layers.get(i, ()) and "attn_v.weight" not in layers.get(i, ())]
- feats = _ARCH_FEATS.get(arch, {})
- if kv_eq_v and not feats.get("v_norm"): # K=V is only wired together with the unweighted v_norm of that arch family
- gaps.append(f"K=V layers without attn_v (use_k_as_v + unweighted v_norm) on {len(kv_eq_v)} layers, first {kv_eq_v[:3]}")
- if arch.startswith("gemma") and arch not in _ARCH_FEATS:
- gaps.append(f"gemma family arch {arch!r}: GELU-tanh MLP act, embedding * sqrt(hidden), unweighted v_norm, sm_scale 1.0 not mapped")
- # rope_freqs.weight (llama.cpp: freq_factors on the non-SWA layers, theta_i / ff_i): ff = 1 on the rotated angles, huge on the rest
- # == engine "proportional" rope (partial_rotary_factor = rotated angles * 2 / head_dim)
- rope_prop, rope_pf, rope_pending = [], None, False
- if "rope_freqs.weight" in infos:
- rope_prop = [i for i in range(nl) if not swa[i]]
- nff = infos["rope_freqs.weight"][1][0]
- hd_g = {hd_l[i] for i in rope_prop}
- if infos["rope_freqs.weight"][0] != 0 or not rope_prop or hd_g != {2 * nff}:
- gaps.append(f"rope_freqs.weight (type {infos['rope_freqs.weight'][0]}, n={nff}) does not match head_dim {sorted(hd_g)} of the non-SWA layers")
- else:
- try:
- ff = g._pread(infos["rope_freqs.weight"][2], 4 * nff).view("<f4")
- except (IOError, OSError, ValueError):
- ff, rope_pending = None, True # header-only cut: no tensor data; GGUFGenericConfig re-reads it on the full file
- if ff is not None:
- rot = int((ff == 1.0).sum())
- if rot == 0 or not (ff[:rot] == 1.0).all() or not (ff[rot:] >= 1e9).all():
- gaps.append(f"rope_freqs.weight is not (1.0 x k, then >=1e9): not a proportional rope ({rot} ones)")
- else:
- rope_pf = 2.0 * rot / hd_l[rope_prop[0]]
- # (4) attention biases + sinks
- attn_bias = ["".join(c for c, t in (("q", "attn_q"), ("k", "attn_k"), ("v", "attn_v"), ("o", "attn_output"))
- if f"{t}.bias" in layers.get(i, ())) for i in range(nl)]
- sinks_layers = [i for i in range(nl) if "attn_sinks.weight" in layers.get(i, ())]
- if p + "attention.layer_norm_rms_epsilon" not in m:
- gaps.append("no rms epsilon (LayerNorm-style arch)")
- # (6) rope scaling: yarn + linear mapped; llama3 / longrope / rope_freqs factors stay gaps
- rs = m.get(p + "rope.scaling.type", "none")
- rope_scaling = None
- if rs in ("yarn", "linear"):
- rope_scaling = {"rope_type": rs, "factor": float(m.get(p + "rope.scaling.factor", 1.0))}
- if rs == "yarn":
- rope_scaling["original_max_position_embeddings"] = int(m.get(p + "rope.scaling.original_context_length", m.get(p + "context_length", 4096)))
- for k_gguf, k_hf in (("yarn_beta_fast", "beta_fast"), ("yarn_beta_slow", "beta_slow"), ("attn_factor", "attention_factor")):
- if p + "rope.scaling." + k_gguf in m:
- rope_scaling[k_hf] = float(m[p + "rope.scaling." + k_gguf])
- if arch in _YARN_NO_TRUNCATE:
- rope_scaling["truncate"] = False
- elif rs != "none":
- gaps.append(f"rope.scaling.type={rs!r} not mapped (llama3/longrope factors)")
- if any(rdim_l[i] != hd_l[i] for i in range(nl)):
- gaps.append(f"partial rotary: rope.dimension_count={sorted(set(rdim_l))} != head_dim={sorted(set(hd_l))}")
- # qk norm: per head (width head_dim, qwen3) or spanning all heads (width nq*hd, olmoe)
- qn = infos.get("blk.0.attn_q_norm.weight")
- qk_norm = "none" if qn is None else ("head" if qn[1][0] == hd_l[0] else "span" if qn[1][0] == nq * hd_l[0] else "?")
- if qk_norm == "?":
- gaps.append(f"attn_q_norm width {qn[1][0]} is neither head_dim nor n_heads*head_dim")
- cfg = {
- "architectures": [ARCH_STRING], "model_type": "gguf_generic", "gguf_arch": arch,
- "hidden_size": ne, "num_attention_heads": nq, "num_key_value_heads": n_kv_l[0],
- "num_hidden_layers": nl, "head_dim": hd,
- "rms_norm_eps": m.get(p + "attention.layer_norm_rms_epsilon", 1e-6),
- "max_position_embeddings": m.get(p + "context_length", 4096),
- "rope_theta": fb, "hidden_act": feats.get("act", "silu"),
- "embed_scale": float(ne) ** 0.5 if feats.get("embed_scale") else 1.0, "v_norm": bool(feats.get("v_norm")),
- "sm_scale": feats.get("sm_scale"), "rope_prop_layers": rope_prop, "rope_partial_factor": rope_pf, "rope_freqs_pending": rope_pending,
- "n_kv_layers": n_kv_l, "head_dim_layers": hd_l, "rope_theta_layers": theta_l, "rotary_dim_layers": rdim_l,
- "sliding_window": win, "swa_layers": swa, "rope_scaling": rope_scaling,
- "sandwich_norms": sandwich, "pre_ffn_from_post": pre_ffn_from_post, "layer_scalar": layer_scalar,
- "attn_bias": attn_bias, "sinks_layers": sinks_layers, "kv_eq_v_layers": kv_eq_v,
- "final_logit_softcapping": float(m.get(p + "final_logit_softcapping", 0.0)),
- "attn_logit_softcapping": float(m.get(p + "attn_logit_softcapping", 0.0)),
- "logit_scale": float(m.get(p + "logit_scale", 1.0)),
- "vocab_size": infos["token_embd.weight"][1][1],
- "tie_word_embeddings": "output.weight" not in infos,
- "qk_norm": qk_norm, "moe_layers": moe_layers, "gaps": gaps,
- "intermediate_size": m.get(p + "feed_forward_length", 0),
- }
- if moe_layers:
- gd = infos[f"blk.{moe_layers[0]}.ffn_gate_exps.weight"][1] # gguf dims (H, I, E)
- cfg.update(num_experts=gd[2], moe_intermediate_size=gd[1],
- num_experts_per_tok=_req(m, p + "expert_used_count"))
- if m.get(p + "expert_count", gd[2]) != gd[2]:
- gaps.append("expert_count metadata disagrees with ffn_gate_exps shape")
- # (5) shared experts: GatedMLP beside the routed experts, optional sigmoid gate (ffn_gate_inp_shexp)
- sh = [i for i in moe_layers if "ffn_gate_shexp.weight" in layers.get(i, ())]
- if sh and len(sh) != len(moe_layers):
- gaps.append("shared experts present on only some MoE layers")
- elif sh:
- cfg["shared_intermediate_size"] = infos[f"blk.{sh[0]}.ffn_gate_shexp.weight"][1][1]
- cfg["shared_gate"] = "ffn_gate_inp_shexp.weight" in layers.get(sh[0], ())
- elif m.get(p + "expert_shared_count", 0):
- gaps.append("expert_shared_count > 0 but no ffn_*_shexp tensors")
- # (7) router logit bias + stacked per-expert biases (gpt-oss): all MoE layers or none
- for sfx, nmk in (("ffn_gate_inp.bias", "router_bias"), ("ffn_gate_exps.bias", "expert_bias_gate"),
- ("ffn_up_exps.bias", "expert_bias_up"), ("ffn_down_exps.bias", "expert_bias_down")):
- have = [i for i in moe_layers if sfx in layers.get(i, ())]
- if have and len(have) != len(moe_layers):
- gaps.append(f"{sfx} present on only some MoE layers")
- cfg[nmk] = bool(have) and len(have) == len(moe_layers)
- if cfg["router_bias"]:
- bd = infos[f"blk.{moe_layers[0]}.ffn_gate_inp.bias"][1]
- if tuple(bd) != (gd[2],):
- gaps.append(f"ffn_gate_inp.bias dims {tuple(bd)} != (num_experts,)")
- for pj, nmk, shp in (("gate", "expert_bias_gate", (gd[1], gd[2])), ("up", "expert_bias_up", (gd[1], gd[2])),
- ("down", "expert_bias_down", (gd[0], gd[2]))):
- if cfg[nmk] and tuple(infos[f"blk.{moe_layers[0]}.ffn_{pj}_exps.bias"][1]) != shp:
- gaps.append(f"ffn_{pj}_exps.bias dims {tuple(infos[f'blk.{moe_layers[0]}.ffn_{pj}_exps.bias'][1])} != {shp}")
- act, lim = _MOE_ACT.get(arch, ("silu", 0.0))
- cfg["moe_activation"], cfg["moe_act_limit"] = act, float(m.get(p + "swiglu_limit", lim))
- norm = m.get(p + "expert_weights_norm", _NORM_TOPK_DEFAULT.get(arch))
- if norm is None:
- gaps.append(f"unknown expert_weights_norm for arch {arch!r}")
- if m.get(p + "expert_gating_func", 1) not in (0, 1):
- gaps.append("router gating func is not softmax")
- cfg["norm_topk_prob"] = bool(norm)
- if len(moe_layers) not in (0, nl):
- cfg["dense_layers"] = [i for i in range(nl) if i not in moe_layers]
+ res = residual_global(ctx)
+ emb = plan.configs.get(("token_embd", None)) or REGISTRY["token_embd"].config(ctx, None)
+ head = plan.configs.get(("lm_head", None)) or REGISTRY["lm_head"].config(ctx, None)
+ ml = moe_layers(ctx)
+ moe = moe_global(ctx)
+ cfg = {"architectures": [ARCH_STRING], "model_type": "gguf_generic", "gguf_arch": arch, **a,
+ "hidden_act": ctx.feats.get("act", "silu"), "embed_scale": emb["embed_scale"], **res, **head,
+ "vocab_size": emb["vocab_size"], "moe_layers": ml, "intermediate_size": m.get(p + "feed_forward_length", 0), **moe}
+ if len(ml) not in (0, nl):
+ cfg["dense_layers"] = [i for i in range(nl) if i not in ml]
+ cfg["gaps"] = plan.gaps
return cfg
-def name_map_generic(cfg: dict) -> dict:
- """engine key -> gguf tensor name; routed experts use per-expert slice keys (.eN) like the minicpm builder."""
- nm = {"model.norm.weight": "output_norm.weight", "model.embed_tokens.weight": "token_embd.weight"}
- if not cfg["tie_word_embeddings"]:
- nm["lm_head.weight"] = "output.weight"
+def name_map_generic(cfg: dict, plan=None) -> dict:
+ """engine key -> gguf tensor name, the union of the selected blocks' name maps; routed experts use per-expert slice keys (.eN)."""
+ nm = {}
+ if plan is None: # config-only callers (tests): the plan of the stack the config describes
+ return _name_map_fixed(cfg)
+ for slot in ("embed", "head"):
+ b = REGISTRY[plan.glob[slot]]
+ nm.update(b.names(cfg, None, None, None))
+ for i in range(cfg["num_hidden_layers"]):
+ L, G = f"model.layers.{i}", f"blk.{i}"
+ for bn in plan.blocks_at(i):
+ b = REGISTRY[bn]
+ if b.names is not None:
+ nm.update(b.names(cfg, i, L, G))
+ return nm
+
+
+def _name_map_fixed(cfg: dict) -> dict:
+ """the plain residual / gqa / dense-or-moe stack the generic config dict describes (no header at hand)"""
+ from ..loader.gguf_blocks import transformer as T, attn as A, mlp as MM
+ nm = {**T._head_names(cfg, None, None, None), "model.embed_tokens.weight": "token_embd.weight"}
moe = set(cfg["moe_layers"])
for i in range(cfg["num_hidden_layers"]):
L, G = f"model.layers.{i}", f"blk.{i}"
- pre_ffn = "post_attention_norm" if cfg.get("pre_ffn_from_post") else "ffn_norm"
- nm.update({
- f"{L}.input_layernorm.weight": f"{G}.attn_norm.weight",
- f"{L}.post_attention_layernorm.weight": f"{G}.{pre_ffn}.weight",
- f"{L}.self_attn.q_proj.weight": f"{G}.attn_q.weight", f"{L}.self_attn.k_proj.weight": f"{G}.attn_k.weight",
- f"{L}.self_attn.v_proj.weight": f"{G}.attn_v.weight", f"{L}.self_attn.o_proj.weight": f"{G}.attn_output.weight",
- })
- if cfg.get("qk_norm", "none") != "none":
- nm.update({f"{L}.self_attn.q_norm.weight": f"{G}.attn_q_norm.weight", f"{L}.self_attn.k_norm.weight": f"{G}.attn_k_norm.weight"})
- if cfg.get("sandwich_norms"):
- nm[f"{L}.attn_post_norm.weight"] = f"{G}.post_attention_norm.weight"
- nm[f"{L}.mlp_post_norm.weight"] = f"{G}.post_ffw_norm.weight"
- if cfg.get("layer_scalar"):
- nm[f"{L}.layer_scalar"] = f"{G}.layer_output_scale.weight"
- if i in cfg.get("sinks_layers", ()):
- nm[f"{L}.self_attn.sinks"] = f"{G}.attn_sinks.weight"
- for c, pj, t in (("q", "q_proj", "attn_q"), ("k", "k_proj", "attn_k"), ("v", "v_proj", "attn_v"), ("o", "o_proj", "attn_output")):
- if c in cfg.get("attn_bias", [""] * (i + 1))[i]:
- nm[f"{L}.self_attn.{pj}.bias"] = f"{G}.{t}.bias"
- if i in cfg.get("kv_eq_v_layers", ()): # no V projection: the attention reads K (use_k_as_v) when the arch has v_norm, else dry-run alias (gap flagged)
- if cfg.get("v_norm"):
- nm.pop(f"{L}.self_attn.v_proj.weight", None)
- else:
- nm[f"{L}.self_attn.v_proj.weight"] = f"{G}.attn_k.weight"
- if i in moe:
- nm[f"{L}.mlp.gate.weight"] = f"{G}.ffn_gate_inp.weight"
- if cfg.get("router_bias"):
- nm[f"{L}.mlp.gate.bias"] = f"{G}.ffn_gate_inp.bias"
- if cfg.get("shared_intermediate_size"):
- for proj in ("gate", "up", "down"):
- nm[f"{L}.mlp.shared_experts.{proj}_proj.weight"] = f"{G}.ffn_{proj}_shexp.weight"
- if cfg.get("shared_gate"):
- nm[f"{L}.mlp.shared_expert_gate.weight"] = f"{G}.ffn_gate_inp_shexp.weight"
- for e in range(cfg["num_experts"]):
- for proj, gp in (("gate_proj", "ffn_gate_exps"), ("up_proj", "ffn_up_exps"), ("down_proj", "ffn_down_exps")):
- nm[f"{L}.mlp.experts.{e}.{proj}.weight"] = f"{G}.{gp}.e{e}.weight"
- if cfg.get("expert_bias_" + proj[:-5]):
- nm[f"{L}.mlp.experts.{e}.{proj}.bias"] = f"{G}.{gp}.e{e}.bias"
- else:
- nm.update({f"{L}.mlp.gate_proj.weight": f"{G}.ffn_gate.weight", f"{L}.mlp.up_proj.weight": f"{G}.ffn_up.weight",
- f"{L}.mlp.down_proj.weight": f"{G}.ffn_down.weight"})
+ nm.update(T._residual_names(cfg, i, L, G))
+ nm.update(A._names(cfg, i, L, G))
+ nm.update(MM._moe_names(cfg, i, L, G) if i in moe else MM._dense_names(cfg, i, L, G))
return nm
@@ -368,7 +155,7 @@ class GGUFGenericConfig(Config):
self.sandwich_norms, self.layer_scalar = cd["sandwich_norms"], cd["layer_scalar"]
self.sinks_layers = set(cd["sinks_layers"])
self.final_softcap, self.attn_softcap, self.logit_scale = cd["final_logit_softcapping"], cd["attn_logit_softcapping"], cd["logit_scale"]
- style = RopeStyle.GPTJ if self.gguf_arch in _ROPE_PERMUTED else RopeStyle.NEOX
+ style = RopeStyle.GPTJ if ARCH_FEATS.get(self.gguf_arch, {}).get("rope_gptj") else RopeStyle.NEOX
self.layer_rope = []
rope_prop, rope_pf = set(cd["rope_prop_layers"]), cd["rope_partial_factor"]
if cd["rope_freqs_pending"]: # header-only cut at config build time: read the factors now, or refuse on a real run
@@ -396,7 +183,8 @@ class GGUFGenericConfig(Config):
self.layer_rope.append(self.read_rope_settings_default(style, config_dict=rcd, override_head_dim=self.head_dim_l[i]))
self.rope_settings = self.layer_rope[0]
self.gguf = GGUFCollection(os.path.join(directory, "model.gguf"))
- self.gguf.name_map = name_map_generic(self.config_dict)
+ self.gguf_plan = build_plan(self.gguf)
+ self.gguf.name_map = name_map_generic(self.config_dict, self.gguf_plan)
self.stc = self.gguf
self.gguf_formats = {n: GGML_FMT.get(ty, f"unk{ty}") for n, (ty, _, _) in self.gguf.infos.items()}
# Quantized token_embd: dequantize once on the GPU and serve it from memory (as gguf_dense does).
@@ -422,98 +210,35 @@ class GGUFGenericConfig(Config):
return {}
+def _built(name):
+ """the registry block, refusing a block that is still a predicate only (its build step is named)"""
+ b = REGISTRY.get(name) if name else None
+ if b is None or b.build is None:
+ raise GenericUnsupported(f"no built block for {name!r}" + (f" ({b.step})" if b else ""))
+ return b
+
+
class GGUFGenericModel(Model):
config_class = GGUFGenericConfig
def __init__(self, config: GGUFGenericConfig, key_prefix: str = "model", **kwargs):
super().__init__(config, **kwargs)
- H, nq = config.hidden_size, config.num_q_heads
- P = key_prefix
- self.modules += [Embedding(config=config, key=f"{P}.embed_tokens", vocab_size=config.vocab_size, hidden_size=H,
- multiplier=config.embed_scale)]
+ P, plan = key_prefix, config.gguf_plan
+ self.modules += [_built(plan.glob["embed"]).build(config, P)]
+ for bn in plan.glob["embed_mod"] + plan.glob["head_mod"]:
+ _built(bn)
self.first_block_idx = len(self.modules)
- span = config.qk_norm == "span"
for idx in range(config.num_hidden_layers):
- L = f"{P}.layers.{idx}"
- hd_i, nkv_i = config.head_dim_l[idx], config.n_kv_l[idx]
- norms = {}
- if config.qk_norm != "none":
- norms = {n: RMSNorm(config=config, key=f"{L}.self_attn.{n}", rms_norm_eps=config.rms_norm_eps, span_heads=span)
- for n in ("q_norm", "k_norm")}
- if config.v_norm:
- norms["v_norm"] = RMSNorm(config=config, key=f"{L}.self_attn.v_norm", rms_norm_eps=config.rms_norm_eps, unweighted=True)
- post = {}
- if config.sandwich_norms:
- post = dict(attn_post_norm=RMSNorm(config=config, key=f"{L}.attn_post_norm", rms_norm_eps=config.rms_norm_eps, out_dtype=torch.float),
- mlp_post_norm=RMSNorm(config=config, key=f"{L}.mlp_post_norm", rms_norm_eps=config.rms_norm_eps, out_dtype=torch.float))
- if config.layer_scalar:
- post["key_layer_scalar"] = "layer_scalar"
- self.modules += [TransformerBlock(
- config=config, key=L, layer_idx=idx,
- attn_norm=RMSNorm(config=config, key=f"{L}.input_layernorm", rms_norm_eps=config.rms_norm_eps),
- attn=Attention(
- config=config, key=f"{L}.self_attn", layer_idx=idx, hidden_size=H, head_dim=hd_i,
- num_q_heads=nq, num_kv_heads=nkv_i, rope_settings=config.layer_rope[idx], sm_scale=config.sm_scale,
- use_k_as_v=idx in config.kv_eq_v,
- qmap="block.attn", out_dtype=torch.float,
- sliding_window=config.swa_l[idx], logit_softcapping=config.attn_softcap,
- key_sinks="sinks" if idx in config.sinks_layers else None,
- q_proj=_fl(config, f"{L}.self_attn.q_proj", H, nq * hd_i, bias="q" in config.attn_bias[idx]),
- k_proj=_fl(config, f"{L}.self_attn.k_proj", H, nkv_i * hd_i, bias="k" in config.attn_bias[idx]),
- v_proj=None if idx in config.kv_eq_v else _fl(config, f"{L}.self_attn.v_proj", H, nkv_i * hd_i, bias="v" in config.attn_bias[idx]),
- o_proj=_fl(config, f"{L}.self_attn.o_proj", nq * hd_i, H, out_dtype=torch.float, bias="o" in config.attn_bias[idx]), **norms),
- mlp_norm=RMSNorm(config=config, key=f"{L}.post_attention_layernorm", rms_norm_eps=config.rms_norm_eps),
- **post,
- mlp=self._moe(config, L, H) if idx in config.moe_layers else self._dense(config, L, H))]
+ L, lp = f"{P}.layers.{idx}", plan.layers[idx]
+ for bn in ([lp["pre"]] if lp["pre"] else []) + lp["attn_mod"] + lp["ffn_mod"] + lp["layer_mod"]:
+ _built(bn)
+ attn = _built(lp["attn"]).build(config, plan, idx, L)
+ mlp = _built(lp["ffn"]).build(config, plan, idx, L)
+ self.modules += [_built(lp["stream"]).build(config, plan, idx, L, attn, mlp)]
self.last_kv_module_idx = len(self.modules) - 1
- self.modules += [RMSNorm(config=config, key=f"{P}.norm", rms_norm_eps=config.rms_norm_eps, out_dtype=torch.half)]
- if config.tie_word_embeddings:
- config.gguf.name_map["lm_head.weight"] = "token_embd.weight"
- self.modules += [_fl(config, "lm_head", H, config.vocab_size, post_scale=config.logit_scale, softcap=config.final_softcap)]
- self.modules[-1].caps["logits_output"] = True
+ self.modules += _built(plan.glob["head"]).build(config, P)
self.logit_layer_idx = len(self.modules) - 1
- @staticmethod
- def _dense(config, L, H):
- I = config.intermediate_size
- mlp = GatedMLP(config=config, key=f"{L}.mlp", hidden_size=H, intermediate_size=I, qmap="block.mlp", activation_fn=config.hidden_act,
- interm_dtype=torch.half, out_dtype=torch.float,
- gates=[_fl(config, f"{L}.mlp.gate_proj", H, I)], ups=[_fl(config, f"{L}.mlp.up_proj", H, I)],
- downs=[_fl(config, f"{L}.mlp.down_proj", I, H, out_dtype=torch.float)])
- for m in mlp.gates + mlp.ups + mlp.downs:
- mlp.register_submodule(m)
- return mlp
-
- @staticmethod
- def _moe(config, L, H):
- I, E = config.moe_intermediate_size, config.num_experts
- eb = config.expert_bias
- gates = [_fl(config, f"{L}.mlp.experts.{e}.gate_proj", H, I, bias=eb["gate"]) for e in range(E)]
- ups = [_fl(config, f"{L}.mlp.experts.{e}.up_proj", H, I, bias=eb["up"]) for e in range(E)]
- downs = [_fl(config, f"{L}.mlp.experts.{e}.down_proj", I, H, out_dtype=torch.float, bias=eb["down"]) for e in range(E)]
- moe_kw = {}
- if config.router_bias: # logit bias before top-k, softmax over the picked biased logits (engine gpt-oss: routing_std_bias, no e_score bias)
- moe_kw.update(router_type="std_bias", key_e_score_bias=None)
- if config.moe_activation != "silu":
- moe_kw.update(activation_fn=config.moe_activation, act_limit=config.moe_act_limit)
- shared = None
- if config.shared_intermediate:
- SI, SK = config.shared_intermediate, f"{L}.mlp.shared_experts"
- shared = GatedMLP(config=config, key=SK, hidden_size=H, intermediate_size=SI, qmap="block.mlp",
- interm_dtype=torch.half, out_dtype=torch.float,
- gates=[_fl(config, f"{SK}.gate_proj", H, SI)], ups=[_fl(config, f"{SK}.up_proj", H, SI)],
- downs=[_fl(config, f"{SK}.down_proj", SI, H, out_dtype=torch.float)])
- for m in shared.gates + shared.ups + shared.downs:
- shared.register_submodule(m)
- mlp = BlockSparseMLP(config=config, key=f"{L}.mlp", hidden_size=H, intermediate_size=I, num_experts=E,
- shared_experts=shared, key_shared_gate="shared_expert_gate" if config.shared_gate else None,
- num_experts_per_tok=config.num_experts_per_tok, norm_topk=bool(config.norm_topk_prob), key_up=None, key_gate=None, key_down=None,
- key_routing_gate="gate", qmap="block.mlp", interm_dtype=torch.half, out_dtype=torch.float,
- gates=gates, ups=ups, downs=downs, **moe_kw)
- for m in gates + ups + downs:
- mlp.register_submodule(m)
- return mlp
-
@override
def prepare_inputs(self, input_ids: torch.Tensor, params: dict) -> torch.Tensor:
return prepare_for_attn(input_ids, params)
diff --git a/exllamav3/loader/gguf_blocks/__init__.py b/exllamav3/loader/gguf_blocks/__init__.py
new file mode 100644
index 0000000..b2ae752
--- /dev/null
+++ b/exllamav3/loader/gguf_blocks/__init__.py
@@ -0,0 +1 @@
+"""GGUF registry blocks, one file per engine module family (see loader/gguf_registry.py)."""
diff --git a/exllamav3/loader/gguf_blocks/attn.py b/exllamav3/loader/gguf_blocks/attn.py
new file mode 100644
index 0000000..6d99c7e
--- /dev/null
+++ b/exllamav3/loader/gguf_blocks/attn.py
@@ -0,0 +1,158 @@
+"""Blocks around modules/attn.py: GQA / MHA attention (q/k/v/o, qk-norm, biases, sinks, sliding window, rope variants)."""
+from __future__ import annotations
+from ..gguf_registry import Block, register, req
+
+_CLAIMS = frozenset({"attn_q.weight", "attn_k.weight", "attn_v.weight", "attn_output.weight", "attn_q.bias", "attn_k.bias",
+ "attn_v.bias", "attn_output.bias", "attn_q_norm.weight", "attn_k_norm.weight", "attn_sinks.weight"})
+
+
+def gqa_global(ctx):
+ """header -> attention config over all layers (lists indexed by layer); gaps go to ctx.gaps"""
+ def f(ctx):
+ m, infos, p, arch, nl, gaps, feats = ctx.meta, ctx.infos, ctx.p, ctx.arch, ctx.nl, ctx.gaps, ctx.feats
+ ne, nq = req(m, p + "embedding_length"), req(m, p + "attention.head_count")
+ nq = nq[0] if isinstance(nq, list) else nq
+ hd = m.get(p + "attention.key_length", ne // nq)
+ kvr = m.get(p + "attention.head_count_kv", nq)
+ n_kv_l = list(kvr) if isinstance(kvr, list) else [kvr] * nl
+ if len(n_kv_l) != nl:
+ gaps.append(f"head_count_kv array has {len(n_kv_l)} entries for {nl} layers")
+ n_kv_l = (n_kv_l * nl)[:nl]
+ win = m.get(p + "attention.sliding_window", 0) or 0
+ swa = [False] * nl
+ if win:
+ pat = m.get(p + "attention.sliding_window_pattern", feats.get("swa_pattern", 0))
+ if isinstance(pat, list):
+ if len(pat) != nl:
+ gaps.append(f"sliding_window_pattern has {len(pat)} entries for {nl} layers")
+ swa = [bool(pat[i % len(pat)]) for i in range(nl)]
+ elif pat:
+ swa = [i % pat < pat - 1 for i in range(nl)]
+ else:
+ swa = [True] * nl
+ hd_swa = m.get(p + "attention.key_length_swa", hd)
+ hd_l = [hd_swa if swa[i] else hd for i in range(nl)]
+ bad_q = [i for i in range(nl) if f"blk.{i}.attn_q.weight" in infos and infos[f"blk.{i}.attn_q.weight"][1][1] != nq * hd_l[i]]
+ if bad_q:
+ gaps.append(f"attn_q width != n_heads*head_dim on layers {bad_q[:4]} (gated q / unknown per-layer head dim)")
+ fb, fbs = m.get(p + "rope.freq_base", 10000.0), m.get(p + "rope.freq_base_swa")
+ theta_l = [fbs if (swa[i] and fbs) else fb for i in range(nl)]
+ rd, rds = m.get(p + "rope.dimension_count"), m.get(p + "rope.dimension_count_swa")
+ rdim_l = [(rds if (swa[i] and rds) else rd) or hd_l[i] for i in range(nl)]
+ kv_eq_v = [i for i in range(nl) if ctx.has(i, "attn_k.weight") and not ctx.has(i, "attn_v.weight")]
+ if kv_eq_v and not feats.get("v_norm"): # K=V is only wired together with the unweighted v_norm of that arch family
+ gaps.append(f"K=V layers without attn_v (use_k_as_v + unweighted v_norm) on {len(kv_eq_v)} layers, first {kv_eq_v[:3]}")
+ if arch.startswith("gemma") and not feats:
+ gaps.append(f"gemma family arch {arch!r}: GELU-tanh MLP act, embedding * sqrt(hidden), unweighted v_norm, sm_scale 1.0 not mapped")
+ # rope_freqs.weight: ff = 1 on the rotated angles, huge on the rest == engine "proportional" rope
+ rope_prop, rope_pf, rope_pending = [], None, False
+ if "rope_freqs.weight" in infos:
+ rope_prop = [i for i in range(nl) if not swa[i]]
+ nff = infos["rope_freqs.weight"][1][0]
+ hd_g = {hd_l[i] for i in rope_prop}
+ if infos["rope_freqs.weight"][0] != 0 or not rope_prop or hd_g != {2 * nff}:
+ gaps.append(f"rope_freqs.weight (type {infos['rope_freqs.weight'][0]}, n={nff}) does not match head_dim {sorted(hd_g)} of the non-SWA layers")
+ else:
+ try:
+ ff = ctx.g._pread(infos["rope_freqs.weight"][2], 4 * nff).view("<f4")
+ except (IOError, OSError, ValueError):
+ ff, rope_pending = None, True # header-only cut: GGUFGenericConfig re-reads it on the full file
+ if ff is not None:
+ rot = int((ff == 1.0).sum())
+ if rot == 0 or not (ff[:rot] == 1.0).all() or not (ff[rot:] >= 1e9).all():
+ gaps.append(f"rope_freqs.weight is not (1.0 x k, then >=1e9): not a proportional rope ({rot} ones)")
+ else:
+ rope_pf = 2.0 * rot / hd_l[rope_prop[0]]
+ attn_bias = ["".join(c for c, t in (("q", "attn_q"), ("k", "attn_k"), ("v", "attn_v"), ("o", "attn_output"))
+ if ctx.has(i, f"{t}.bias")) for i in range(nl)]
+ sinks_layers = [i for i in range(nl) if ctx.has(i, "attn_sinks.weight")]
+ if p + "attention.layer_norm_rms_epsilon" not in m:
+ gaps.append("no rms epsilon (LayerNorm-style arch)")
+ rs = m.get(p + "rope.scaling.type", "none")
+ rope_scaling = None
+ if rs in ("yarn", "linear"):
+ rope_scaling = {"rope_type": rs, "factor": float(m.get(p + "rope.scaling.factor", 1.0))}
+ if rs == "yarn":
+ rope_scaling["original_max_position_embeddings"] = int(m.get(p + "rope.scaling.original_context_length", m.get(p + "context_length", 4096)))
+ for k_gguf, k_hf in (("yarn_beta_fast", "beta_fast"), ("yarn_beta_slow", "beta_slow"), ("attn_factor", "attention_factor")):
+ if p + "rope.scaling." + k_gguf in m:
+ rope_scaling[k_hf] = float(m[p + "rope.scaling." + k_gguf])
+ if feats.get("yarn_no_truncate"):
+ rope_scaling["truncate"] = False
+ elif rs != "none":
+ gaps.append(f"rope.scaling.type={rs!r} not mapped (llama3/longrope factors)")
+ if any(rdim_l[i] != hd_l[i] for i in range(nl)):
+ gaps.append(f"partial rotary: rope.dimension_count={sorted(set(rdim_l))} != head_dim={sorted(set(hd_l))}")
+ qn = infos.get("blk.0.attn_q_norm.weight")
+ qk_norm = "none" if qn is None else ("head" if qn[1][0] == hd_l[0] else "span" if qn[1][0] == nq * hd_l[0] else "?")
+ if qk_norm == "?":
+ gaps.append(f"attn_q_norm width {qn[1][0]} is neither head_dim nor n_heads*head_dim")
+ return {
+ "hidden_size": ne, "num_attention_heads": nq, "num_key_value_heads": n_kv_l[0], "num_hidden_layers": nl, "head_dim": hd,
+ "rms_norm_eps": m.get(p + "attention.layer_norm_rms_epsilon", 1e-6), "max_position_embeddings": m.get(p + "context_length", 4096),
+ "rope_theta": fb, "v_norm": bool(feats.get("v_norm")), "sm_scale": feats.get("sm_scale"),
+ "rope_prop_layers": rope_prop, "rope_partial_factor": rope_pf, "rope_freqs_pending": rope_pending,
+ "n_kv_layers": n_kv_l, "head_dim_layers": hd_l, "rope_theta_layers": theta_l, "rotary_dim_layers": rdim_l,
+ "sliding_window": win, "swa_layers": swa, "rope_scaling": rope_scaling,
+ "attn_bias": attn_bias, "sinks_layers": sinks_layers, "kv_eq_v_layers": kv_eq_v,
+ "attn_logit_softcapping": float(m.get(p + "attn_logit_softcapping", 0.0)), "qk_norm": qk_norm,
+ }
+ return ctx.once("gqa", f)
+
+
+def gqa_layer(ctx, i):
+ a = gqa_global(ctx)
+ return {"head_dim": a["head_dim_layers"][i], "n_q": a["num_attention_heads"], "n_kv": a["n_kv_layers"][i],
+ "swa": a["swa_layers"][i], "window": a["sliding_window"], "rope_theta": a["rope_theta_layers"][i],
+ "rotary_dim": a["rotary_dim_layers"][i], "rope_prop": i in a["rope_prop_layers"], "bias": a["attn_bias"][i],
+ "sinks": i in a["sinks_layers"], "kv_eq_v": i in a["kv_eq_v_layers"], "qk_norm": a["qk_norm"]}
+
+
+def _names(cfg, i, L, G):
+ nm = {f"{L}.self_attn.q_proj.weight": f"{G}.attn_q.weight", f"{L}.self_attn.k_proj.weight": f"{G}.attn_k.weight",
+ f"{L}.self_attn.v_proj.weight": f"{G}.attn_v.weight", f"{L}.self_attn.o_proj.weight": f"{G}.attn_output.weight"}
+ if cfg.get("qk_norm", "none") != "none":
+ nm.update({f"{L}.self_attn.q_norm.weight": f"{G}.attn_q_norm.weight", f"{L}.self_attn.k_norm.weight": f"{G}.attn_k_norm.weight"})
+ if i in cfg.get("sinks_layers", ()):
+ nm[f"{L}.self_attn.sinks"] = f"{G}.attn_sinks.weight"
+ for c, pj, t in (("q", "q_proj", "attn_q"), ("k", "k_proj", "attn_k"), ("v", "v_proj", "attn_v"), ("o", "o_proj", "attn_output")):
+ if c in cfg.get("attn_bias", [""] * (i + 1))[i]:
+ nm[f"{L}.self_attn.{pj}.bias"] = f"{G}.{t}.bias"
+ if i in cfg.get("kv_eq_v_layers", ()): # no V projection: the attention reads K (use_k_as_v) when the arch has v_norm, else dry-run alias
+ if cfg.get("v_norm"):
+ nm.pop(f"{L}.self_attn.v_proj.weight", None)
+ else:
+ nm[f"{L}.self_attn.v_proj.weight"] = f"{G}.attn_k.weight"
+ return nm
+
+
+def _build(config, plan, idx, L):
+ import torch
+ from ...modules import RMSNorm, Attention
+ from ...architecture.gguf_generic import _fl
+ H, nq = config.hidden_size, config.num_q_heads
+ hd_i, nkv_i = config.head_dim_l[idx], config.n_kv_l[idx]
+ norms = {}
+ if config.qk_norm != "none":
+ norms = {n: RMSNorm(config=config, key=f"{L}.self_attn.{n}", rms_norm_eps=config.rms_norm_eps, span_heads=config.qk_norm == "span")
+ for n in ("q_norm", "k_norm")}
+ if config.v_norm:
+ norms["v_norm"] = RMSNorm(config=config, key=f"{L}.self_attn.v_norm", rms_norm_eps=config.rms_norm_eps, unweighted=True)
+ return Attention(
+ config=config, key=f"{L}.self_attn", layer_idx=idx, hidden_size=H, head_dim=hd_i,
+ num_q_heads=nq, num_kv_heads=nkv_i, rope_settings=config.layer_rope[idx], sm_scale=config.sm_scale,
+ use_k_as_v=idx in config.kv_eq_v, qmap="block.attn", out_dtype=torch.float,
+ sliding_window=config.swa_l[idx], logit_softcapping=config.attn_softcap,
+ key_sinks="sinks" if idx in config.sinks_layers else None,
+ q_proj=_fl(config, f"{L}.self_attn.q_proj", H, nq * hd_i, bias="q" in config.attn_bias[idx]),
+ k_proj=_fl(config, f"{L}.self_attn.k_proj", H, nkv_i * hd_i, bias="k" in config.attn_bias[idx]),
+ v_proj=None if idx in config.kv_eq_v else _fl(config, f"{L}.self_attn.v_proj", H, nkv_i * hd_i, bias="v" in config.attn_bias[idx]),
+ o_proj=_fl(config, f"{L}.self_attn.o_proj", nq * hd_i, H, out_dtype=torch.float, bias="o" in config.attn_bias[idx]), **norms)
+
+
+def _select(ctx, i):
+ ls = ctx.layers.get(i, ())
+ return "attn_q.weight" in ls and "attn_kv_a_mqa.weight" not in ls and not any(s.startswith("ssm_") for s in ls)
+
+
+register(Block("gqa", "attn", select=_select, config=gqa_layer, claims=_CLAIMS, build=_build, names=_names))
diff --git a/exllamav3/loader/gguf_blocks/mlp.py b/exllamav3/loader/gguf_blocks/mlp.py
new file mode 100644
index 0000000..e009ad4
--- /dev/null
+++ b/exllamav3/loader/gguf_blocks/mlp.py
@@ -0,0 +1,144 @@
+"""Blocks around modules/mlp.py and block_sparse_mlp.py: dense gated MLP, standard top-k MoE (+shared, +biases)."""
+from __future__ import annotations
+from ..gguf_registry import Block, register, req
+
+_EXPS = ("ffn_gate_exps", "ffn_up_exps", "ffn_down_exps")
+_MOE_CLAIMS = frozenset({"ffn_gate_inp.weight", "ffn_gate_inp.bias", *(f"{e}.weight" for e in _EXPS), *(f"{e}.bias" for e in _EXPS),
+ "ffn_gate_shexp.weight", "ffn_up_shexp.weight", "ffn_down_shexp.weight", "ffn_gate_inp_shexp.weight"})
+
+
+def moe_layers(ctx):
+ return ctx.once("moe_layers", lambda c: [i for i in range(c.nl) if c.has(i, "ffn_gate_exps.weight")])
+
+
+def moe_global(ctx):
+ """standard MoE config (first MoE layer's shapes); empty when the header has no routed experts"""
+ def f(ctx):
+ m, infos, p, arch, gaps, ml = ctx.meta, ctx.infos, ctx.p, ctx.arch, ctx.gaps, moe_layers(ctx)
+ if not ml:
+ return {}
+ gd = infos[f"blk.{ml[0]}.ffn_gate_exps.weight"][1] # gguf dims (H, I, E)
+ cfg = {"num_experts": gd[2], "moe_intermediate_size": gd[1], "num_experts_per_tok": req(m, p + "expert_used_count")}
+ if m.get(p + "expert_count", gd[2]) != gd[2]:
+ gaps.append("expert_count metadata disagrees with ffn_gate_exps shape")
+ sh = [i for i in ml if ctx.has(i, "ffn_gate_shexp.weight")]
+ if sh and len(sh) != len(ml):
+ gaps.append("shared experts present on only some MoE layers")
+ elif sh:
+ cfg["shared_intermediate_size"] = infos[f"blk.{sh[0]}.ffn_gate_shexp.weight"][1][1]
+ cfg["shared_gate"] = ctx.has(sh[0], "ffn_gate_inp_shexp.weight")
+ elif m.get(p + "expert_shared_count", 0):
+ gaps.append("expert_shared_count > 0 but no ffn_*_shexp tensors")
+ for sfx, nmk in (("ffn_gate_inp.bias", "router_bias"), ("ffn_gate_exps.bias", "expert_bias_gate"),
+ ("ffn_up_exps.bias", "expert_bias_up"), ("ffn_down_exps.bias", "expert_bias_down")):
+ have = [i for i in ml if ctx.has(i, sfx)]
+ if have and len(have) != len(ml):
+ gaps.append(f"{sfx} present on only some MoE layers")
+ cfg[nmk] = bool(have) and len(have) == len(ml)
+ if cfg["router_bias"]:
+ bd = infos[f"blk.{ml[0]}.ffn_gate_inp.bias"][1]
+ if tuple(bd) != (gd[2],):
+ gaps.append(f"ffn_gate_inp.bias dims {tuple(bd)} != (num_experts,)")
+ for pj, nmk, shp in (("gate", "expert_bias_gate", (gd[1], gd[2])), ("up", "expert_bias_up", (gd[1], gd[2])),
+ ("down", "expert_bias_down", (gd[0], gd[2]))):
+ if cfg[nmk] and tuple(infos[f"blk.{ml[0]}.ffn_{pj}_exps.bias"][1]) != shp:
+ gaps.append(f"ffn_{pj}_exps.bias dims {tuple(infos[f'blk.{ml[0]}.ffn_{pj}_exps.bias'][1])} != {shp}")
+ act, lim = ctx.feats.get("moe_act", ("silu", 0.0))
+ cfg["moe_activation"], cfg["moe_act_limit"] = act, float(m.get(p + "swiglu_limit", lim))
+ norm = m.get(p + "expert_weights_norm", ctx.feats.get("norm_topk"))
+ if norm is None:
+ gaps.append(f"unknown expert_weights_norm for arch {arch!r}")
+ if m.get(p + "expert_gating_func", 1) not in (0, 1):
+ gaps.append("router gating func is not softmax")
+ cfg["norm_topk_prob"] = bool(norm)
+ return cfg
+ return ctx.once("moe", f)
+
+
+def _dense_names(cfg, i, L, G):
+ return {f"{L}.mlp.gate_proj.weight": f"{G}.ffn_gate.weight", f"{L}.mlp.up_proj.weight": f"{G}.ffn_up.weight",
+ f"{L}.mlp.down_proj.weight": f"{G}.ffn_down.weight"}
+
+
+def _dense_build(config, plan, idx, L):
+ import torch
+ from ...modules import GatedMLP
+ from ...architecture.gguf_generic import _fl
+ H, I = config.hidden_size, config.intermediate_size
+ mlp = GatedMLP(config=config, key=f"{L}.mlp", hidden_size=H, intermediate_size=I, qmap="block.mlp", activation_fn=config.hidden_act,
+ interm_dtype=torch.half, out_dtype=torch.float,
+ gates=[_fl(config, f"{L}.mlp.gate_proj", H, I)], ups=[_fl(config, f"{L}.mlp.up_proj", H, I)],
+ downs=[_fl(config, f"{L}.mlp.down_proj", I, H, out_dtype=torch.float)])
+ for m in mlp.gates + mlp.ups + mlp.downs:
+ mlp.register_submodule(m)
+ return mlp
+
+
+register(Block(
+ "dense_ffn", "ffn",
+ select=lambda ctx, i: not ctx.has(i, "ffn_gate_exps.weight"),
+ config=lambda ctx, i: {"intermediate_size": ctx.key("feed_forward_length", 0), "act": ctx.feats.get("act", "silu")},
+ claims=frozenset({"ffn_gate.weight", "ffn_up.weight", "ffn_down.weight"}), build=_dense_build, names=_dense_names))
+
+
+def _moe_names(cfg, i, L, G):
+ nm = {f"{L}.mlp.gate.weight": f"{G}.ffn_gate_inp.weight"}
+ if cfg.get("router_bias"):
+ nm[f"{L}.mlp.gate.bias"] = f"{G}.ffn_gate_inp.bias"
+ if cfg.get("shared_intermediate_size"):
+ for proj in ("gate", "up", "down"):
+ nm[f"{L}.mlp.shared_experts.{proj}_proj.weight"] = f"{G}.ffn_{proj}_shexp.weight"
+ if cfg.get("shared_gate"):
+ nm[f"{L}.mlp.shared_expert_gate.weight"] = f"{G}.ffn_gate_inp_shexp.weight"
+ for e in range(cfg["num_experts"]):
+ for proj, gp in (("gate_proj", "ffn_gate_exps"), ("up_proj", "ffn_up_exps"), ("down_proj", "ffn_down_exps")):
+ nm[f"{L}.mlp.experts.{e}.{proj}.weight"] = f"{G}.{gp}.e{e}.weight"
+ if cfg.get("expert_bias_" + proj[:-5]):
+ nm[f"{L}.mlp.experts.{e}.{proj}.bias"] = f"{G}.{gp}.e{e}.bias"
+ return nm
+
+
+def _moe_build(config, plan, idx, L):
+ import torch
+ from ...modules import GatedMLP, BlockSparseMLP
+ from ...architecture.gguf_generic import _fl
+ H, I, E = config.hidden_size, config.moe_intermediate_size, config.num_experts
+ eb = config.expert_bias
+ gates = [_fl(config, f"{L}.mlp.experts.{e}.gate_proj", H, I, bias=eb["gate"]) for e in range(E)]
+ ups = [_fl(config, f"{L}.mlp.experts.{e}.up_proj", H, I, bias=eb["up"]) for e in range(E)]
+ downs = [_fl(config, f"{L}.mlp.experts.{e}.down_proj", I, H, out_dtype=torch.float, bias=eb["down"]) for e in range(E)]
+ moe_kw = {}
+ if config.router_bias: # logit bias before top-k, softmax over the picked biased logits (engine gpt-oss: routing_std_bias)
+ moe_kw.update(router_type="std_bias", key_e_score_bias=None)
+ if config.moe_activation != "silu":
+ moe_kw.update(activation_fn=config.moe_activation, act_limit=config.moe_act_limit)
+ shared = None
+ if config.shared_intermediate:
+ SI, SK = config.shared_intermediate, f"{L}.mlp.shared_experts"
+ shared = GatedMLP(config=config, key=SK, hidden_size=H, intermediate_size=SI, qmap="block.mlp",
+ interm_dtype=torch.half, out_dtype=torch.float,
+ gates=[_fl(config, f"{SK}.gate_proj", H, SI)], ups=[_fl(config, f"{SK}.up_proj", H, SI)],
+ downs=[_fl(config, f"{SK}.down_proj", SI, H, out_dtype=torch.float)])
+ for m in shared.gates + shared.ups + shared.downs:
+ shared.register_submodule(m)
+ mlp = BlockSparseMLP(config=config, key=f"{L}.mlp", hidden_size=H, intermediate_size=I, num_experts=E,
+ shared_experts=shared, key_shared_gate="shared_expert_gate" if config.shared_gate else None,
+ num_experts_per_tok=config.num_experts_per_tok, norm_topk=bool(config.norm_topk_prob), key_up=None, key_gate=None,
+ key_down=None, key_routing_gate="gate", qmap="block.mlp", interm_dtype=torch.half, out_dtype=torch.float,
+ gates=gates, ups=ups, downs=downs, **moe_kw)
+ for m in gates + ups + downs:
+ mlp.register_submodule(m)
+ return mlp
+
+
+def _moe_layer(ctx, i):
+ g = moe_global(ctx)
+ keys = ("num_experts", "moe_intermediate_size", "num_experts_per_tok", "shared_intermediate_size", "shared_gate", "router_bias",
+ "expert_bias_gate", "expert_bias_up", "expert_bias_down", "moe_activation", "moe_act_limit", "norm_topk_prob")
+ return {k: g.get(k) for k in keys}
+
+
+register(Block(
+ "moe_ffn", "ffn",
+ select=lambda ctx, i: ctx.has(i, "ffn_gate_exps.weight") and not ctx.has(i, "ffn_routed_down.weight"),
+ config=_moe_layer, claims=_MOE_CLAIMS, build=_moe_build, names=_moe_names))
diff --git a/exllamav3/loader/gguf_blocks/transformer.py b/exllamav3/loader/gguf_blocks/transformer.py
new file mode 100644
index 0000000..d65377a
--- /dev/null
+++ b/exllamav3/loader/gguf_blocks/transformer.py
@@ -0,0 +1,104 @@
+"""Blocks around modules/transformer.py, embedding.py, rmsnorm.py: token embedding, LM head, plain residual stream."""
+from __future__ import annotations
+from ..gguf_registry import Block, register, CONFIG_ONLY
+
+_NORMS = ("post_attention_norm.weight", "post_ffw_norm.weight", "layer_output_scale.weight", "ffn_norm.weight")
+
+
+def residual_global(ctx):
+ """sandwich norms: llama.cpp names the pre-FFN norm ffn_norm; gpt-oss has no ffn_norm and uses post_attention_norm there"""
+ def f(ctx):
+ for sfx in _NORMS:
+ if ctx.has_any(sfx) and not ctx.has_all(sfx):
+ ctx.gaps.append(f"{sfx} present on only some layers")
+ sandwich = ctx.has_all("post_attention_norm.weight") and ctx.has_all("post_ffw_norm.weight")
+ pre_ffn_from_post = (not ctx.has_any("ffn_norm.weight")) and ctx.has_all("post_attention_norm.weight") \
+ and not ctx.has_any("post_ffw_norm.weight")
+ if not ctx.has_any("ffn_norm.weight") and not pre_ffn_from_post:
+ ctx.gaps.append("no pre-FFN norm tensor (ffn_norm / post_attention_norm)")
+ return {"sandwich_norms": sandwich, "pre_ffn_from_post": pre_ffn_from_post, "layer_scalar": ctx.has_all("layer_output_scale.weight")}
+ return ctx.once("residual", f)
+
+
+def _residual_names(cfg, i, L, G):
+ pre_ffn = "post_attention_norm" if cfg.get("pre_ffn_from_post") else "ffn_norm"
+ nm = {f"{L}.input_layernorm.weight": f"{G}.attn_norm.weight", f"{L}.post_attention_layernorm.weight": f"{G}.{pre_ffn}.weight"}
+ if cfg.get("sandwich_norms"):
+ nm[f"{L}.attn_post_norm.weight"] = f"{G}.post_attention_norm.weight"
+ nm[f"{L}.mlp_post_norm.weight"] = f"{G}.post_ffw_norm.weight"
+ if cfg.get("layer_scalar"):
+ nm[f"{L}.layer_scalar"] = f"{G}.layer_output_scale.weight"
+ return nm
+
+
+def _residual_build(config, plan, idx, L, attn, mlp):
+ import torch
+ from ...modules import RMSNorm, TransformerBlock
+ post = {}
+ if config.sandwich_norms:
+ post = dict(attn_post_norm=RMSNorm(config=config, key=f"{L}.attn_post_norm", rms_norm_eps=config.rms_norm_eps, out_dtype=torch.float),
+ mlp_post_norm=RMSNorm(config=config, key=f"{L}.mlp_post_norm", rms_norm_eps=config.rms_norm_eps, out_dtype=torch.float))
+ if config.layer_scalar:
+ post["key_layer_scalar"] = "layer_scalar"
+ return TransformerBlock(config=config, key=L, layer_idx=idx,
+ attn_norm=RMSNorm(config=config, key=f"{L}.input_layernorm", rms_norm_eps=config.rms_norm_eps),
+ attn=attn,
+ mlp_norm=RMSNorm(config=config, key=f"{L}.post_attention_layernorm", rms_norm_eps=config.rms_norm_eps),
+ **post, mlp=mlp)
+
+
+register(Block(
+ "residual", "stream",
+ select=lambda ctx, i: not ctx.has(i, "hc_attn_fn.weight"),
+ config=lambda ctx, i: residual_global(ctx),
+ claims=frozenset({"attn_norm.weight", *_NORMS}),
+ build=_residual_build, names=_residual_names))
+
+
+def _embed_build(config, P):
+ from ...modules import Embedding
+ return Embedding(config=config, key=f"{P}.embed_tokens", vocab_size=config.vocab_size, hidden_size=config.hidden_size,
+ multiplier=config.embed_scale)
+
+
+register(Block(
+ "token_embd", "embed",
+ select=lambda ctx, i: "token_embd.weight" in ctx.glob,
+ config=lambda ctx, i: {"vocab_size": ctx.dims("token_embd.weight")[1],
+ "embed_scale": float(ctx.key("embedding_length")) ** 0.5 if ctx.feats.get("embed_scale") else 1.0},
+ claims=frozenset({"token_embd.weight"}), build=_embed_build,
+ names=lambda cfg, i, L, G: {"model.embed_tokens.weight": "token_embd.weight"}))
+
+
+def _head_build(config, P):
+ import torch
+ from ...modules import RMSNorm
+ from ...architecture.gguf_generic import _fl
+ norm = RMSNorm(config=config, key=f"{P}.norm", rms_norm_eps=config.rms_norm_eps, out_dtype=torch.half)
+ if config.tie_word_embeddings:
+ config.gguf.name_map["lm_head.weight"] = "token_embd.weight"
+ head = _fl(config, "lm_head", config.hidden_size, config.vocab_size, post_scale=config.logit_scale, softcap=config.final_softcap)
+ head.caps["logits_output"] = True
+ return [norm, head]
+
+
+def _head_names(cfg, i, L, G):
+ nm = {"model.norm.weight": "output_norm.weight"}
+ if not cfg["tie_word_embeddings"]:
+ nm["lm_head.weight"] = "output.weight"
+ return nm
+
+
+register(Block(
+ "lm_head", "head",
+ select=lambda ctx, i: "output_norm.weight" in ctx.glob,
+ config=lambda ctx, i: {"tie_word_embeddings": "output.weight" not in ctx.infos,
+ "final_logit_softcapping": float(ctx.key("final_logit_softcapping", 0.0)),
+ "logit_scale": float(ctx.key("logit_scale", 1.0))},
+ claims=frozenset({"output_norm.weight", "output.weight"}), build=_head_build, names=_head_names))
+
+# rope_freqs.weight: llama.cpp freq_factors on the non-SWA layers; read by the attention config (attn.py gqa_global)
+register(Block(
+ "rope_freqs", "embed_mod",
+ select=lambda ctx, i: "rope_freqs.weight" in ctx.glob,
+ config=None, claims=frozenset({"rope_freqs.weight"}), build=CONFIG_ONLY))
diff --git a/exllamav3/loader/gguf_config.py b/exllamav3/loader/gguf_config.py
index 047db27..f2d0d29 100644
--- a/exllamav3/loader/gguf_config.py
+++ b/exllamav3/loader/gguf_config.py
@@ -8,6 +8,7 @@ import json
import os
from .gguf_collection import GGUFCollection
+from .gguf_registry import Block, register, class_block
# gguf general.architecture -> (HF architectures entry, HF model_type)
GGUF_ARCHS = {
@@ -30,18 +31,23 @@ GGML_FMT = {
def hf_config(g: GGUFCollection) -> dict:
+ """GGUF header -> HF-style config, resolved through the block registry: a dedicated-class arch is one 'model' block
+ (class:<arch>), any other arch goes to the generic composer when EXL3_GGUF_GENERIC=1."""
m = g.meta
arch = m["general.architecture"]
- if arch not in GGUF_ARCHS and os.environ.get("EXL3_GGUF_GENERIC", "0") == "1":
+ blk = class_block(arch)
+ if blk is None and os.environ.get("EXL3_GGUF_GENERIC", "0") == "1":
from ..architecture.gguf_generic import hf_config_generic # generic fallback: only when no specific mapping exists
return hf_config_generic(g)
- if arch not in GGUF_ARCHS:
+ if blk is None:
raise ValueError(f"GGUF architecture {arch!r} has no standard-class mapping (have: {sorted(GGUF_ARCHS)})")
+ return blk.config(g, None)
+
+
+def _hf_config_dense(g: GGUFCollection) -> dict:
+ m = g.meta
+ arch = m["general.architecture"]
p = arch + "."
- if arch in ("qwen35moe", "qwen35"):
- return _hf_config_qwen35moe(g, m, arch)
- if arch == "qwen4exp":
- return _hf_config_qwen4exp(g, m)
ne = m[p + "embedding_length"]
nq = m[p + "attention.head_count"]
cfg = {
@@ -246,3 +252,23 @@ def write_config_dir(gguf_path: str, outdir: str) -> str:
os.remove(link)
os.symlink(os.path.abspath(gguf_path), link)
return outdir
+
+
+def _name_map_qwen35(cfg: dict) -> dict:
+ """the MiniCPM-V-4.7 text class's GGUF name map (architecture/minicpm_v47.py: _map_layer + norm / head)"""
+ from ..architecture.minicpm_v47 import _map_layer
+ nm: dict = {}
+ for i in range(cfg["text_config"]["num_hidden_layers"]):
+ _map_layer(nm, i)
+ nm["model.language_model.norm.weight"] = "output_norm.weight"
+ nm["lm_head.weight"] = "output.weight"
+ return nm
+
+
+# Dedicated-class archs as registry 'model' blocks: config = their mapping function (unchanged), names = their name map.
+for _arch, _cfg, _nm in (("llama", lambda g, i: _hf_config_dense(g), name_map), ("qwen3", lambda g, i: _hf_config_dense(g), name_map),
+ ("qwen35moe", lambda g, i: _hf_config_qwen35moe(g, g.meta, "qwen35moe"), _name_map_qwen35),
+ ("qwen35", lambda g, i: _hf_config_qwen35moe(g, g.meta, "qwen35"), _name_map_qwen35),
+ ("qwen4exp", lambda g, i: _hf_config_qwen4exp(g, g.meta), name_map_qwen4exp)):
+ register(Block("class:" + _arch, "model", select=lambda ctx, i, a=_arch: ctx.arch == a, config=_cfg, claims=frozenset(),
+ build=GGUF_ARCHS[_arch][0], names=lambda cfg, i, L, G, f=_nm: f(cfg)))
diff --git a/exllamav3/loader/gguf_registry.py b/exllamav3/loader/gguf_registry.py
new file mode 100644
index 0000000..a5680e3
--- /dev/null
+++ b/exllamav3/loader/gguf_registry.py
@@ -0,0 +1,236 @@
+"""GGUF block registry: the generic loader is the composition of these blocks (no per-model class).
+
+A Block is (name, slot, select, config, claims, build):
+ select(ctx, i) -> bool ctx = the GGUF header (metadata + tensor suffixes per layer); i = layer index, None for global slots
+ config(ctx, i) -> dict the per-layer (or global) module config
+ claims tensor suffixes the block owns (blk.N.<suffix>, or full names for global slots)
+ build(config, plan, i, key) -> Module, or None while the block exists only as a predicate (its step is named)
+Blocks live in loader/gguf_blocks/<module>.py, one file per engine module family; their builds import the modules lazily
+so the registry itself imports without torch or the extension (CPU header tests).
+
+Composition (architecture/gguf_generic.py): per layer pre -> stream(attn [+ attn_mod], ffn [+ ffn_mod]); global embed
+[+ embed_mod], head [+ head_mod]. In each base slot the first selected block (priority order) wins; *_mod slots take every
+selected block. Coverage audit: the union of the selected blocks' claims must cover every tensor of the header, else the
+'no builder for tensors' gap fires (an unknown arch still fails loudly). Tensors owned by a selected block that has no
+build yet are reported per block ('block X not built').
+
+Per-arch residue: ARCH_FEATS holds only what llama.cpp hard-codes for an arch with no GGUF key (each entry names its source).
+"""
+from __future__ import annotations
+import importlib
+import re
+from dataclasses import dataclass
+from typing import Callable
+
+BASE_SLOTS = ("pre", "stream", "attn", "ffn")
+MOD_SLOTS = ("attn_mod", "ffn_mod", "layer_mod")
+GLOBAL_SLOTS = ("embed", "embed_mod", "head", "head_mod")
+CONFIG_ONLY = "config-only" # build marker: the block feeds module configs, no module of its own
+BLOCK_MODULES = ("transformer", "attn", "mlp")
+
+# Per-arch features llama.cpp hard-codes with no GGUF key. Every entry names the llama.cpp source it mirrors
+# (M = the model patch published with the model, else the llama.cpp file).
+ARCH_FEATS = {
+ # llama.cpp convert_hf_to_gguf.py LlamaModel.permute: Q/K rows permuted to adjacent-pair rotary (only this converter)
+ "llama": {"rope_gptj": True},
+ # llama.cpp llama-model.cpp load_hparams: expert_weights_norm default when the key is absent
+ "qwen3moe": {"norm_topk": True},
+ "mixtral": {"norm_topk": True},
+ "olmoe": {"norm_topk": False},
+ "gpt-oss": {
+ "norm_topk": True, # softmax over the top-k logits == softmax over all, renormalised over the picked experts
+ "swa_pattern": 2, # llama-model.cpp LLM_ARCH_OPENAI_MOE: hparams.set_swa_pattern(2)
+ "yarn_no_truncate": True, # HF gpt-oss rope_scaling.truncate = false (llama.cpp yarn has no truncation)
+ "moe_act": ("swiglu_oai", 7.0), # llama-graph.cpp build_moe_ffn: swiglu_oai alpha 1.702 / limit 7.0 (no key; <arch>.swiglu_limit overrides)
+ },
+ # src/models/gemma4.cpp (see GEMMA4_UNCHECKED.md): LLM_FFN_GELU (tanh) dense act; build_inp_embd(.., sqrtf(n_embd));
+ # unweighted rms_norm on V of every layer (K=V layers: V = raw k_proj output); hparams.f_attention_scale = 1.0
+ "gemma4": {"act": "gelu", "embed_scale": True, "v_norm": True, "sm_scale": 1.0},
+}
+
+
+class GenericUnsupported(ValueError):
+ """The GGUF needs a piece the generic builder does not have (the message names it)."""
+
+
+def req(m: dict, key: str):
+ if key not in m:
+ raise GenericUnsupported(f"missing GGUF metadata key {key!r}")
+ return m[key]
+
+
+@dataclass(frozen=True)
+class Block:
+ name: str
+ slot: str
+ select: Callable
+ config: Callable | None
+ claims: frozenset
+ build: Callable | None = None
+ names: Callable | None = None # (cfg, i, L, G) -> {engine key: gguf name}: the block's part of the name map
+ step: str = "" # design §8 build step, for blocks that are predicates only
+ priority: int = 0
+
+
+REGISTRY: dict[str, Block] = {}
+
+
+def register(b: Block) -> Block:
+ assert b.slot in BASE_SLOTS + MOD_SLOTS + GLOBAL_SLOTS + ("model",), b.slot
+ REGISTRY[b.name] = b
+ return b
+
+
+def _load_blocks():
+ for mod in BLOCK_MODULES:
+ importlib.import_module(f"{__package__}.gguf_blocks.{mod}")
+
+
+class Ctx:
+ """GGUF header view shared by every block predicate / config (cached derived values in .memo)."""
+
+ def __init__(self, g):
+ self.g, self.meta, self.infos = g, g.meta, g.infos
+ self.arch = self.meta.get("general.architecture")
+ self.p = (self.arch or "") + "."
+ self.nl = self.meta.get(self.p + "block_count", 0)
+ self.feats = ARCH_FEATS.get(self.arch, {})
+ self.layers: dict[int, set] = {}
+ self.glob: set = set()
+ for name in self.infos:
+ mt = re.match(r"blk\.(\d+)\.(.+)$", name)
+ if mt:
+ self.layers.setdefault(int(mt.group(1)), set()).add(mt.group(2))
+ else:
+ self.glob.add(name)
+ self.memo: dict = {}
+ self.gaps: list = []
+
+ def key(self, k, default=None):
+ return self.meta.get(self.p + k, default)
+
+ def has(self, i, sfx) -> bool:
+ return sfx in self.layers.get(i, ())
+
+ def has_all(self, sfx) -> bool:
+ return all(sfx in self.layers.get(i, ()) for i in range(self.nl))
+
+ def has_any(self, sfx) -> bool:
+ return any(sfx in self.layers.get(i, ()) for i in range(self.nl))
+
+ def dims(self, name):
+ return self.infos[name][1] if name in self.infos else None
+
+ def once(self, name, fn):
+ if name not in self.memo:
+ self.memo[name] = fn(self)
+ return self.memo[name]
+
+ def per_layer(self, k, default=None):
+ """<arch>.<k> as a per-layer list (scalar keys repeated)."""
+ v = self.key(k, default)
+ return list(v) if isinstance(v, list) else [v] * self.nl
+
+
+@dataclass
+class Plan:
+ arch: str
+ layers: list # per layer: {slot: block name} for base slots, {slot: [names]} for mod slots
+ glob: dict # {slot: block name / [names]}
+ configs: dict # (block name, i or None) -> config dict
+ claimed: dict # tensor name -> block name
+ unclaimed: list
+ unbuilt: dict # block name -> sorted tensor patterns (blk.N.<sfx> with the layer list)
+ cov_gaps: list
+ ctx: object = None
+
+ @property
+ def gaps(self):
+ """block-config gaps (ctx.gaps grows while the composer reads global configs) + coverage / unbuilt gaps"""
+ return list(self.ctx.gaps) + list(self.cov_gaps)
+
+ def blocks_at(self, i):
+ lp = self.layers[i]
+ return [lp[s] for s in BASE_SLOTS if lp.get(s)] + [b for s in MOD_SLOTS for b in lp.get(s, [])]
+
+ def block(self, i, slot):
+ return REGISTRY[self.layers[i][slot]] if self.layers[i].get(slot) else None
+
+
+def _pick(ctx, slot, i):
+ cands = sorted((b for b in REGISTRY.values() if b.slot == slot), key=lambda b: -b.priority)
+ sel = [b for b in cands if b.select(ctx, i)]
+ return sel if slot in MOD_SLOTS or slot.endswith("_mod") else sel[:1]
+
+
+def _compress(pats: dict) -> list:
+ out = []
+ for sfx, ls in sorted(pats.items()):
+ ls = sorted(ls)
+ if ls == [None]:
+ out.append(sfx)
+ continue
+ rng, s = [], ls[0]
+ for a, b in zip(ls, ls[1:] + [None]):
+ if b != a + 1:
+ rng.append(f"{s}" if s == a else f"{s}-{a}")
+ s = b
+ out.append(f"blk.[{','.join(rng)}].{sfx}")
+ return out
+
+
+def build_plan(g) -> Plan:
+ """GGUF header -> block plan (selection, configs, claims, coverage audit)."""
+ _load_blocks()
+ ctx = Ctx(g)
+ layers, configs, claimed = [], {}, {}
+
+ def take(b, i):
+ if b.config is not None:
+ configs[(b.name, i)] = b.config(ctx, i)
+ names = (ctx.glob if i is None else ctx.layers.get(i, ()))
+ for sfx in b.claims:
+ if sfx in names:
+ claimed.setdefault(sfx if i is None else f"blk.{i}.{sfx}", b.name)
+
+ glob = {}
+ for slot in GLOBAL_SLOTS:
+ sel = _pick(ctx, slot, None)
+ for b in sel:
+ take(b, None)
+ glob[slot] = [b.name for b in sel] if slot.endswith("_mod") else (sel[0].name if sel else None)
+ for i in range(ctx.nl):
+ lp = {}
+ for slot in BASE_SLOTS + MOD_SLOTS:
+ sel = _pick(ctx, slot, i)
+ for b in sel:
+ take(b, i)
+ lp[slot] = [b.name for b in sel] if slot in MOD_SLOTS else (sel[0].name if sel else None)
+ layers.append(lp)
+ unclaimed = []
+ for name in ctx.infos:
+ if name not in claimed:
+ unclaimed.append(name if not name.startswith("blk.") or name.startswith("blk.0.") else re.sub(r"blk\.\d+", "blk.N", name))
+ unclaimed = sorted(set(unclaimed))
+ gaps = []
+ if unclaimed:
+ gaps.append(f"no builder for tensors: {', '.join(unclaimed[:12])}")
+ unbuilt: dict = {}
+ for name, bn in claimed.items():
+ if REGISTRY[bn].build is None:
+ mt = re.match(r"blk\.(\d+)\.(.+)$", name)
+ unbuilt.setdefault(bn, {}).setdefault(mt.group(2) if mt else name, []).append(int(mt.group(1)) if mt else None)
+ selected = {bn for lp in layers for v in lp.values() for bn in ([v] if isinstance(v, str) else (v or []))}
+ selected |= {bn for v in glob.values() for bn in ([v] if isinstance(v, str) else (v or []))}
+ for bn in sorted(selected):
+ if REGISTRY[bn].build is None and bn not in unbuilt:
+ unbuilt[bn] = {"(no tensor: key-selected)": [None]}
+ unbuilt = {bn: _compress(p) for bn, p in unbuilt.items()}
+ for bn, pats in sorted(unbuilt.items()):
+ gaps.append(f"block {bn} not built ({REGISTRY[bn].step}): {', '.join(pats)}")
+ return Plan(ctx.arch, layers, glob, configs, claimed, unclaimed, unbuilt, gaps, ctx)
+
+
+def class_block(arch: str) -> Block | None:
+ """Dedicated-class archs (loader/gguf_config.GGUF_ARCHS) are one 'model' block each: config = their mapping function."""
+ return REGISTRY.get("class:" + arch)