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.

Serve plain qwen35moe GGUF (unsloth UD) through the GGUF-backed hybrid MoE class: config from metadata, Q8_0 embedding/projections, F32 gate tensors

YanissAmzaeb790c09d6d
diff --git a/exllamav3/architecture/minicpm_v47.py b/exllamav3/architecture/minicpm_v47.py
index c1b483a..4717955 100644
--- a/exllamav3/architecture/minicpm_v47.py
+++ b/exllamav3/architecture/minicpm_v47.py
@@ -39,12 +39,15 @@ MCPM_ARCH = "MiniCPMV4_7ForConditionalGeneration"
MCPM_GGUF_ENV = "MCPM_GGUF"
MCPM_FOREIGN = os.environ.get("MCPM_FOREIGN", "1") != "0"
-_GGML_FMT = {12: "q4_k", 13: "q5_k", 14: "q6_k", 23: "iq4_xs", 0: "fp", 1: "fp"}
+_GGML_FMT = {12: "q4_k", 13: "q5_k", 14: "q6_k", 23: "iq4_xs", 8: "q8_0", 0: "fp", 1: "fp"}
P = "model.language_model"
-def _gguf_path() -> str:
+def _gguf_path(directory: str | None = None) -> str:
+ # plain-GGUF config dirs (loader/gguf_config.write_config_dir) carry model.gguf next to config.json
+ if directory and os.path.exists(os.path.join(directory, "model.gguf")):
+ return os.path.join(directory, "model.gguf")
p = os.environ.get(MCPM_GGUF_ENV)
assert p, f"{MCPM_GGUF_ENV} must point at the MiniCPM GGUF file"
return p
@@ -132,7 +135,7 @@ class MiniCPMV47Config(Config):
self.model_classes.pop("vision", None)
# GGUF backing store + engine->gguf name map
- self.gguf = GGUFCollection(_gguf_path())
+ self.gguf = GGUFCollection(_gguf_path(directory))
nm: dict[str, str] = {}
for i in range(self.num_hidden_layers):
_map_layer(nm, i)
@@ -153,10 +156,17 @@ class MiniCPMV47Config(Config):
# per-block Python). Format-generic (IQ4_XS / Q4_K).
from ..foreign_quant.k_quants import dequant_iq4_xs_bulk, dequant_q4_K_bulk
ty, dims, off = self.gguf.infos["token_embd.weight"]
- bbs = {23: 136, 12: 144}
+ bbs = {23: 136, 12: 144, 8: 34}
assert ty in bbs, f"token_embd type {ty}"
bb = bbs[ty]
K, N = dims[0], dims[1]
+ if ty == 8:
+ from ..foreign_quant.q8_0 import dequant_q8_0
+ raw = self.gguf._pread(off, N * (K // 32) * bb).reshape(N * (K // 32), bb)
+ w = dequant_q8_0(raw).reshape(N, K).astype(np.float16)
+ self.gguf.new_tensors = {
+ f"{P}.embed_tokens.weight": torch.from_numpy(np.ascontiguousarray(w))}
+ return
assert K % 256 == 0
raw = self.gguf._pread(off, N * (K // 256) * bb).reshape(N, (K // 256) * bb)
nb = N * (K // 256)
@@ -175,6 +185,15 @@ def _fp_override(config, eng_weight_key: str, gguf_name: str):
For the tiny GDN b/a projs the fused kernels require fp16."""
from ..foreign_quant.k_quants import dequant_row
ty, dims, off = config.gguf.infos[gguf_name]
+ if ty in (0, 1): # F32 / F16 stored as is: [N, K] rows -> [K, N] = [in, out]
+ K, N = dims[0], dims[1]
+ dt = np.float32 if ty == 0 else np.float16
+ raw = config.gguf._pread(off, N * K * np.dtype(dt).itemsize)
+ w = np.frombuffer(raw, dtype=dt).reshape(N, K).T
+ if config.gguf.new_tensors is None:
+ config.gguf.new_tensors = {}
+ config.gguf.new_tensors[eng_weight_key] = torch.from_numpy(np.ascontiguousarray(w))
+ return
bbs = {12: 144, 13: 176, 14: 210, 23: 136}
fmts = {12: "q4_k", 13: "q5_k", 14: "q6_k", 23: "iq4_xs"}
assert ty in bbs, f"{gguf_name}: type {ty}"
diff --git a/exllamav3/loader/gguf_config.py b/exllamav3/loader/gguf_config.py
index da13670..7b8a2d9 100644
--- a/exllamav3/loader/gguf_config.py
+++ b/exllamav3/loader/gguf_config.py
@@ -13,6 +13,9 @@ from .gguf_collection import GGUFCollection
GGUF_ARCHS = {
"llama": ("GGUFDenseForCausalLM", "llama"),
"qwen3": ("GGUFDenseForCausalLM", "qwen3"),
+ # unsloth / llama.cpp Qwen3.5-style hybrid MoE (GDN + attention, 256 experts + shared expert), served by the
+ # MiniCPM-V-4.7 text class (same block family, GGUF-backed)
+ "qwen35moe": ("MiniCPMV4_7ForConditionalGeneration", "qwen3_5_moe"),
}
# ggml type id -> ForeignLinear format
@@ -28,6 +31,8 @@ def hf_config(g: GGUFCollection) -> dict:
if arch not in GGUF_ARCHS:
raise ValueError(f"GGUF architecture {arch!r} has no standard-class mapping (have: {sorted(GGUF_ARCHS)})")
p = arch + "."
+ if arch == "qwen35moe":
+ return _hf_config_qwen35moe(g, m)
ne = m[p + "embedding_length"]
nq = m[p + "attention.head_count"]
cfg = {
@@ -52,6 +57,37 @@ def hf_config(g: GGUFCollection) -> dict:
return cfg
+def _hf_config_qwen35moe(g: GGUFCollection, m: dict) -> dict:
+ p = "qwen35moe."
+ ssm_heads, ssm_groups, ssm_dim = m[p + "ssm.time_step_rank"], m[p + "ssm.group_count"], m[p + "ssm.state_size"]
+ tc = {
+ "model_type": "qwen3_5_moe_text",
+ "hidden_size": m[p + "embedding_length"],
+ "num_attention_heads": m[p + "attention.head_count"],
+ "num_key_value_heads": m[p + "attention.head_count_kv"],
+ "head_dim": m[p + "attention.key_length"],
+ "num_hidden_layers": m[p + "block_count"],
+ "full_attention_interval": m[p + "full_attention_interval"],
+ "linear_conv_kernel_dim": m[p + "ssm.conv_kernel"],
+ "linear_num_key_heads": ssm_groups,
+ "linear_num_value_heads": ssm_heads,
+ "linear_key_head_dim": ssm_dim,
+ "linear_value_head_dim": m[p + "ssm.inner_size"] // ssm_heads,
+ "hidden_act": "silu",
+ "moe_intermediate_size": m[p + "expert_feed_forward_length"],
+ "num_experts": m[p + "expert_count"],
+ "num_experts_per_tok": m[p + "expert_used_count"],
+ "shared_expert_intermediate_size": m[p + "expert_shared_feed_forward_length"],
+ "rms_norm_eps": m[p + "attention.layer_norm_rms_epsilon"],
+ "vocab_size": g.infos["token_embd.weight"][1][1],
+ "max_position_embeddings": m[p + "context_length"],
+ "rope_theta": m[p + "rope.freq_base"],
+ "partial_rotary_factor": m[p + "rope.dimension_count"] / m[p + "attention.key_length"],
+ }
+ return {"architectures": ["MiniCPMV4_7ForConditionalGeneration"], "model_type": "qwen3_5_moe",
+ "gguf_arch": "qwen35moe", "tie_word_embeddings": "output.weight" not in g.infos, "text_config": tc}
+
+
def name_map(cfg: dict) -> dict:
"""engine key -> gguf tensor name (tensor keys, with .weight)."""
nm = {"model.norm.weight": "output_norm.weight", "model.embed_tokens.weight": "token_embd.weight"}
diff --git a/tests/test_gguf_qwen35moe_load.py b/tests/test_gguf_qwen35moe_load.py
new file mode 100644
index 0000000..658a376
--- /dev/null
+++ b/tests/test_gguf_qwen35moe_load.py
@@ -0,0 +1,37 @@
+"""Load a plain qwen35moe GGUF (unsloth UD) as stored bytes and run one forward; grouped MoE path vs per-expert path.
+
+ FMOE_GGUF=<file.gguf> python tests/test_gguf_qwen35moe_load.py
+"""
+import json, os, sys
+import torch
+
+ENGINE = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
+sys.path.insert(0, ENGINE)
+from exllamav3.loader.gguf_collection import GGUFCollection
+from exllamav3.loader.gguf_config import hf_config
+from exllamav3.model.config import Config
+from exllamav3.model.model import Model
+
+src = os.environ["FMOE_GGUF"]
+d = os.path.join(os.environ.get("FMOE_CFG", "/tmp"), "qwen35moe_cfg")
+os.makedirs(d, exist_ok=True)
+g = GGUFCollection(src)
+json.dump(hf_config(g), open(os.path.join(d, "config.json"), "w"), indent=1)
+link = os.path.join(d, "model.gguf")
+if os.path.lexists(link):
+ os.remove(link)
+os.symlink(os.path.abspath(src), link)
+
+config = Config.from_directory(d)
+model = Model.from_config(config)
+model.load()
+print("loaded, GPU MiB", torch.cuda.memory_allocated() >> 20)
+ids = torch.randint(0, 1000, (1, 32)).cuda()
+out = {}
+for grouped in ("1", "0"):
+ os.environ["MCPM_FQ_MOE_GROUPED"] = grouped
+ out[grouped] = model.forward(ids, params={"attn_mode": "flash_attn_nc"})[0].float().cpu()
+ print("grouped" if grouped == "1" else "per-expert", "finite", bool(torch.isfinite(out[grouped]).all()),
+ "absmax", float(out[grouped].abs().max()))
+print("prefill path equal (grouped is decode-only, expect identical):", torch.equal(out["1"], out["0"]))
+print("PASS")