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.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
tests: CPU tests for the generic GGUF loader hooks (flag off == origin/main mapping)
YanissAmz890d096f9114
diff --git a/tests/fixtures/gguf_config_main.py b/tests/fixtures/gguf_config_main.pynew file mode 100644index 0000000..3a04824--- /dev/null+++ b/tests/fixtures/gguf_config_main.py@@ -0,0 +1,244 @@+"""Plain GGUF -> HF-style config for the standard dense architectures (llama, qwen3).++The GGUF metadata is the source of truth: write_config_dir() emits the config.json that the engine Config classes read,+next to a symlink to the GGUF itself (so transformers can build the tokenizer from it with gguf_file=).+"""+from __future__ import annotations+import json+import os++from .gguf_collection import GGUFCollection++# gguf general.architecture -> (HF architectures entry, HF model_type)+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"),+ # dense sibling (Qwen3.6-27B class): same GDN + attention blocks, plain gated MLP per layer+ "qwen35": ("MiniCPMV4_7ForConditionalGeneration", "qwen3_5"),+ # Qwen3.8-Flash-Next family: GDN + QSA attention, gated-residual hyper-connections, PLE n-gram layer, 512-expert MoE+ "qwen4exp": ("Qwen4ExpForConditionalGeneration", "qwen4_exp"),+}++# ggml type id -> ForeignLinear format+GGML_FMT = {+ 2: "q4_0", 6: "q5_0", 7: "q5_1", 8: "q8_0", 12: "q4_k", 13: "q5_k", 14: "q6_k", 18: "iq3_xxs", 16: "iq2_xxs",+ 20: "iq4_nl", 21: "iq3_s", 23: "iq4_xs", 11: "q3_k", 10: "q2_k", 17: "iq2_xs", 22: "iq2_s", 39: "mxfp4", 40: "nvfp4_gguf", 0: "fp", 1: "fp",+}+++def hf_config(g: GGUFCollection) -> dict:+ m = g.meta+ arch = m["general.architecture"]+ 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 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 = {+ "architectures": [GGUF_ARCHS[arch][0]],+ "model_type": GGUF_ARCHS[arch][1],+ "gguf_arch": arch,+ "hidden_size": ne,+ "num_attention_heads": nq,+ "num_key_value_heads": m.get(p + "attention.head_count_kv", nq),+ "num_hidden_layers": m[p + "block_count"],+ "intermediate_size": m[p + "feed_forward_length"],+ "rms_norm_eps": m[p + "attention.layer_norm_rms_epsilon"],+ "max_position_embeddings": m[p + "context_length"],+ "rope_theta": m.get(p + "rope.freq_base", 10000.0),+ "hidden_act": "silu",+ "head_dim": m.get(p + "attention.key_length", ne // nq),+ "vocab_size": g.infos["token_embd.weight"][1][1],+ "tie_word_embeddings": "output.weight" not in g.infos,+ }+ if p + "rope.scaling.type" in m and m[p + "rope.scaling.type"] != "none":+ raise ValueError(f"GGUF rope scaling {m[p + 'rope.scaling.type']!r} is not mapped yet")+ return cfg+++def _hf_config_qwen35moe(g: GGUFCollection, m: dict, arch: str = "qwen35moe") -> dict:+ p = arch + "."+ dense = arch == "qwen35"+ 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",+ **({"intermediate_size": m[p + "feed_forward_length"]} if dense else {+ "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": arch, "tie_word_embeddings": "output.weight" not in g.infos, "text_config": tc}+++def _hf_config_qwen4exp(g: GGUFCollection, m: dict) -> dict:+ p = "qwen4exp."+ L = m[p + "block_count"]+ fai = m[p + "full_attention_interval"]+ nh_ssm, ng_ssm = m[p + "ssm.time_step_rank"], m[p + "ssm.group_count"]+ hd = m[p + "attention.key_length"]+ heads_ple = len(m[p + "ple.head_offsets"])+ cr = [int(c) for c in m.get(p + "attention.compress_ratios", [4])]+ tc = {+ "model_type": "qwen4_exp_text",+ "hidden_size": m[p + "embedding_length"],+ "num_hidden_layers": L,+ "num_attention_heads": m[p + "attention.head_count"],+ "num_key_value_heads": m[p + "attention.head_count_kv"],+ "head_dim": hd,+ "full_attention_interval": fai,+ "layer_types": ["full_attention" if (i + 1) % fai == 0 else "linear_attention" for i in range(L)],+ "linear_conv_kernel_dim": m[p + "ssm.conv_kernel"],+ "linear_num_key_heads": ng_ssm,+ "linear_num_value_heads": nh_ssm,+ "linear_key_head_dim": m[p + "ssm.state_size"],+ "linear_value_head_dim": m[p + "ssm.inner_size"] // nh_ssm,+ "num_experts": m[p + "expert_count"],+ "num_experts_per_tok": m[p + "expert_used_count"],+ "moe_intermediate_size": m[p + "expert_feed_forward_length"],+ "shared_expert_intermediate_size": m[p + "expert_shared_feed_forward_length"],+ "hidden_act": "silu",+ "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_parameters": {"rope_type": "default", "rope_theta": m[p + "rope.freq_base"],+ "partial_rotary_factor": m[p + "rope.dimension_count"] / hd,+ "mrope_section": [int(v) for v in m[p + "rope.dimension_sections"]][:3], "mrope_interleaved": True},+ "partial_rotary_factor": m[p + "rope.dimension_count"] / hd,+ "hc_count": m[p + "hyper_connection.count"],+ "hc_lowrank": m[p + "hyper_connection.low_rank"],+ "indexer_n_heads": m[p + "attention.indexer.head_count"],+ "indexer_kv_heads": 1,+ "indexer_head_dim": m[p + "attention.indexer.key_length"],+ "indexer_budget": m[p + "attention.indexer.top_k"],+ "indexer_compress_ratio": max(cr) if cr else 4,+ "output_gate_type": "sigmoid",+ "ple_layer_ids": [int(v) + 1 for v in m[p + "ple.layers"]], # GGUF 0-based, engine 1-based+ "ple_embed_dim": m[p + "embedding_length_per_layer_input"] * heads_ple,+ "ple_conv_kernel_size": m[p + "ple.conv_kernel"],+ "ngram_size": m[p + "ple.ngram_size"],+ "heads_per_ngram": m[p + "ple.heads_per_ngram"],+ "eos_token_id": m[p + "ple.eos_token_id"],+ "bos_token_id": m.get("tokenizer.ggml.bos_token_id", m[p + "ple.eos_token_id"]),+ "mtp_num_hidden_layers": 0,+ "tie_word_embeddings": "output.weight" not in g.infos,+ }+ return {"architectures": ["Qwen4ExpForConditionalGeneration"], "model_type": "qwen4_exp", "gguf_arch": "qwen4exp",+ "image_token_id": m.get(p + "ple.image_token_id"), "language_model_only": True,+ "tie_word_embeddings": tc["tie_word_embeddings"], "text_config": tc}+++def name_map_qwen4exp(cfg: dict) -> dict:+ """engine key -> gguf tensor name for qwen4exp (tensor keys incl. .weight; experts as '<gguf 3d>.e<idx>.weight' slices)."""+ tc = cfg["text_config"]+ P = "model.language_model"+ nm = {"lm_head.weight": "output.weight", f"{P}.embed_tokens.weight": "token_embd.weight",+ f"{P}.hyper_connection_mixer.input_mix_weight_down.weight": "output_hc_down.weight",+ f"{P}.hyper_connection_mixer.input_mix_weight_up.weight": "output_hc_up.weight",+ f"{P}.hyper_connection_mixer.hc_norm.weight": "output_hc_norm.weight"}+ for i, lt in enumerate(tc["layer_types"]):+ L, G = f"{P}.layers.{i}", f"blk.{i}"+ for site, gs in (("attn_hyper_connection", "hc_attn"), ("mlp_hyper_connection", "hc_ffn")):+ nm.update({f"{L}.{site}.input_mix_weight_down.weight": f"{G}.{gs}_down.weight",+ f"{L}.{site}.input_mix_weight_up.weight": f"{G}.{gs}_up.weight",+ f"{L}.{site}.block_inject_weight.weight": f"{G}.{gs}_inject.weight",+ f"{L}.{site}.hc_norm.weight": f"{G}.{gs}_norm.weight"})+ if lt == "linear_attention":+ A = f"{L}.linear_attn"+ nm.update({f"{A}.in_proj_qkv.weight": f"{G}.attn_qkv.weight", f"{A}.in_proj_z.weight": f"{G}.attn_gate.weight",+ f"{A}.in_proj_b.weight": f"{G}.ssm_beta.weight", f"{A}.in_proj_a.weight": f"{G}.ssm_alpha.weight",+ f"{A}.out_proj.weight": f"{G}.ssm_out.weight", f"{A}.conv1d.weight": f"{G}.ssm_conv1d.weight",+ f"{A}.A_log": f"{G}.ssm_a", f"{A}.dt_bias": f"{G}.ssm_dt.bias", f"{A}.norm.weight": f"{G}.ssm_norm.weight"})+ else:+ A = f"{L}.self_attn"+ nm.update({f"{A}.q_proj.weight": f"{G}.attn_q.weight", f"{A}.k_proj.weight": f"{G}.attn_k.weight",+ f"{A}.v_proj.weight": f"{G}.attn_v.weight", f"{A}.o_proj.weight": f"{G}.attn_output.weight",+ f"{A}.q_norm.weight": f"{G}.attn_q_norm.weight", f"{A}.k_norm.weight": f"{G}.attn_k_norm.weight",+ f"{A}.indexer.q_layernorm.weight": f"{G}.indexer.q_norm.weight",+ f"{A}.indexer.k_layernorm.weight": f"{G}.indexer.k_norm.weight"})+ M = f"{L}.mlp"+ nm.update({f"{M}.gate.weight": f"{G}.ffn_gate_inp.weight", f"{M}.shared_expert_gate.weight": f"{G}.ffn_gate_inp_shexp.weight",+ f"{M}.shared_expert.gate_proj.weight": f"{G}.ffn_gate_shexp.weight",+ f"{M}.shared_expert.up_proj.weight": f"{G}.ffn_up_shexp.weight",+ f"{M}.shared_expert.down_proj.weight": f"{G}.ffn_down_shexp.weight"})+ for e in range(tc["num_experts"]):+ for proj, gp in (("gate_proj", "ffn_gate_exps"), ("up_proj", "ffn_up_exps"), ("down_proj", "ffn_down_exps")):+ nm[f"{M}.experts.{e}.{proj}.weight"] = f"{G}.{gp}.e{e}.weight"+ if (i + 1) in tc["ple_layer_ids"]:+ Q = f"{L}.ple"+ nm.update({f"{Q}.key_proj.weight": f"{G}.ple_key.weight", f"{Q}.value_proj.weight": f"{G}.ple_value.weight",+ f"{Q}.conv1d.weight": f"{G}.ple_conv1d.weight", f"{Q}.norm_conv.weight": f"{G}.ple_norm_conv.weight",+ f"{Q}.norm_key.weight": f"{G}.ple_norm_key.weight", f"{Q}.norm_query.weight": f"{G}.ple_norm_query.weight",+ f"{Q}.ple_embedding.ngram_embedding.weight": "per_layer_token_embd.weight"})+ return nm+++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"}+ if not cfg["tie_word_embeddings"]:+ nm["lm_head.weight"] = "output.weight"+ for i in range(cfg["num_hidden_layers"]):+ L, G = f"model.layers.{i}", f"blk.{i}"+ nm.update({+ f"{L}.input_layernorm.weight": f"{G}.attn_norm.weight",+ f"{L}.post_attention_layernorm.weight": f"{G}.ffn_norm.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",+ 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",+ 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",+ })+ return nm+++def write_config_dir(gguf_path: str, outdir: str) -> str:+ """Create outdir/{config.json, model.gguf -> gguf_path}; return outdir."""+ from .gguf_tokenizer import write_tokenizer_files+ g = GGUFCollection(gguf_path)+ os.makedirs(outdir, exist_ok=True)+ try:+ cfg = hf_config(g)+ write_tokenizer_files(g, outdir)+ # servers expect the chat template as its own file (the GGUF carries it in tokenizer.chat_template)+ if g.meta.get("tokenizer.chat_template"):+ with open(os.path.join(outdir, "chat_template.jinja"), "w", encoding="utf8") as f:+ f.write(g.meta["tokenizer.chat_template"])+ finally:+ g.close()+ with open(os.path.join(outdir, "config.json"), "w", encoding="utf8") as f:+ json.dump(cfg, f, indent=1)+ link = os.path.join(outdir, "model.gguf")+ if os.path.lexists(link):+ os.remove(link)+ os.symlink(os.path.abspath(gguf_path), link)+ return outdirdiff --git a/tests/test_gguf_generic_cpu.py b/tests/test_gguf_generic_cpu.pynew file mode 100644index 0000000..df63718--- /dev/null+++ b/tests/test_gguf_generic_cpu.py@@ -0,0 +1,249 @@+"""CPU tests for the generic GGUF loader hooks (EXL3_GGUF_GENERIC, default off). No GPU, no extension at import:+the modules under test are loaded by path under a stub `exllamav3` package.+ flag off: gguf_config.hf_config == origin/main's (tests/fixtures/gguf_config_main.py, `git show origin/main:exllamav3/loader/gguf_config.py`)+ for llama / qwen3 / qwen35moe / qwen35 / qwen4exp, unknown archs raise main's ValueError (same message)+ flag on : unknown archs dispatch to hf_config_generic; olmoe / gpt-oss resolve to the generic architecture+ .bias expert slicing of a fake stacked F32 tensor; norm_topk on / off numeric check."""+import ast, importlib.util, os, sys, types, struct+import numpy as np+import pytest+import torch++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+FLAG = "EXL3_GGUF_GENERIC"+++def _stub_pkgs():+ for name, sub in (("exllamav3", ""), ("exllamav3.loader", "loader")):+ if name not in sys.modules:+ m = types.ModuleType(name)+ m.__path__ = [os.path.join(ROOT, "exllamav3", sub)]+ sys.modules[name] = m+++def _load(modname, path, pkg="exllamav3.loader"):+ _stub_pkgs()+ if modname in sys.modules:+ return sys.modules[modname]+ spec = importlib.util.spec_from_file_location(modname, path)+ mod = importlib.util.module_from_spec(spec)+ mod.__package__ = pkg+ sys.modules[modname] = mod+ spec.loader.exec_module(mod)+ return mod+++def cfg_new():+ return _load("exllamav3.loader.gguf_config", os.path.join(ROOT, "exllamav3/loader/gguf_config.py"))++def cfg_main():+ return _load("exllamav3.loader.gguf_config_main", os.path.join(ROOT, "tests/fixtures/gguf_config_main.py"))++def coll():+ return _load("exllamav3.loader.gguf_collection", os.path.join(ROOT, "exllamav3/loader/gguf_collection.py"))+++class Meta(dict):+ """every missing key reads as 4 (dict.get still returns its default): enough for the mapping functions"""+ def __missing__(self, k):+ return 4+++class FakeG:+ def __init__(self, arch, extra=None):+ self.meta = Meta({"general.architecture": arch, arch + ".attention.layer_norm_rms_epsilon": 1e-6,+ arch + ".rope.freq_base": 1e6})+ self.meta.update({"qwen4exp.ple.head_offsets": [0, 1], "qwen4exp.rope.dimension_sections": [2, 2, 2, 2], "qwen4exp.ple.layers": [1, 3]} if arch == "qwen4exp" else {})+ self.meta.update(extra or {})+ self.infos = {"token_embd.weight": (0, (64, 1000), 0), "output.weight": (0, (64, 1000), 0)}+ self.name_map = {}+++def run(mod, g):+ try:+ return ("ok", mod.hf_config(g))+ except Exception as e: # noqa: BLE001 - compare class + message+ return ("err", type(e).__name__, str(e))+++def env(monkeypatch):+ monkeypatch.delenv(FLAG, raising=False)+ return monkeypatch++[email protected]("arch", ["llama", "qwen3", "qwen35moe", "qwen35", "qwen4exp"])+def test_flag_off_same_as_main(env, arch):+ new, main = cfg_new(), cfg_main()+ assert set(new.GGUF_ARCHS) == set(main.GGUF_ARCHS)+ r_new, r_main = run(new, FakeG(arch)), run(main, FakeG(arch))+ print(arch, r_main[0], str(r_main[1:])[:100])+ assert r_new == r_main+ env.setenv(FLAG, "0")+ assert run(new, FakeG(arch)) == r_main+ # nextn layers: the hard-coded qwen35 mappings only subtract them with the flag on+ if arch in ("qwen35moe", "qwen35") and r_main[0] == "ok":+ g = FakeG(arch, {arch + ".nextn_predict_layers": 1})+ assert run(new, g) == run(main, g)+ env.setenv(FLAG, "1")+ a, b = run(new, g), run(main, g)+ assert a[0] == "ok" and a[1]["text_config"]["num_hidden_layers"] == b[1]["text_config"]["num_hidden_layers"] - 1++[email protected]("arch", ["gpt-oss", "foo", "olmoe"])+def test_flag_off_unknown_raises_main_error(env, arch):+ new, main = cfg_new(), cfg_main()+ r_new, r_main = run(new, FakeG(arch)), run(main, FakeG(arch))+ assert r_main[0] == "err" and r_main[1] == "ValueError" and "has no standard-class mapping" in r_main[2]+ assert r_new == r_main+ env.setenv(FLAG, "0")+ assert run(new, FakeG(arch)) == r_main++[email protected]("arch", ["gpt-oss", "foo", "olmoe"])+def test_flag_on_dispatches_to_generic(env, arch):+ new = cfg_new()+ env.setenv(FLAG, "1")+ stub = types.ModuleType("exllamav3.architecture.gguf_generic")+ stub.hf_config_generic = lambda g: {"generic": g.meta["general.architecture"]}+ pkg = types.ModuleType("exllamav3.architecture"); pkg.__path__ = []+ env.setitem(sys.modules, "exllamav3.architecture", pkg)+ env.setitem(sys.modules, "exllamav3.architecture.gguf_generic", stub)+ assert new.hf_config(FakeG(arch)) == {"generic": arch}+ # a hard-coded arch never reaches the generic path, flag on or off+ assert run(new, FakeG("llama")) == run(cfg_main(), FakeG("llama"))+++def test_flag_on_architecture_resolves_generic():+ """real package in a subprocess (the other tests install stub packages in this one); skipped when the extension is not built"""+ import subprocess+ code = ("import os\nimport exllamav3.architecture.architectures as A\n"+ "os.environ.pop('EXL3_GGUF_GENERIC', None)\n"+ "assert 'GGUFGenericForCausalLM' not in A.get_architectures()\n"+ "os.environ['EXL3_GGUF_GENERIC'] = '0'\nassert 'GGUFGenericForCausalLM' not in A.get_architectures()\n"+ "os.environ['EXL3_GGUF_GENERIC'] = '1'\n"+ "a = A.get_architectures()['GGUFGenericForCausalLM']\n"+ "import exllamav3.architecture.gguf_generic as G\n"+ "assert a['model_class'] is G.GGUFGenericModel and a['config_class'].arch_string == 'GGUFGenericForCausalLM'\n"+ "from exllamav3.loader import gguf_config as C\n"+ "assert C.hf_config.__module__\n"+ "print('RESOLVED')")+ env = dict(os.environ, CUDA_VISIBLE_DEVICES="", HIP_VISIBLE_DEVICES="", PYTHONPATH=ROOT)+ env.pop(FLAG, None)+ r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, env=env, cwd=ROOT, timeout=200)+ if r.returncode != 0 and ("exllamav3_ext" in r.stderr or "ModuleNotFoundError" in r.stderr):+ pytest.skip("extension not built: " + r.stderr.strip().splitlines()[-1][:100])+ assert r.returncode == 0 and "RESOLVED" in r.stdout, r.stderr[-800:]+++def test_generic_resolves_gpt_oss_olmoe_config():+ """flag on, real hf_config_generic (needs the built package, subprocess): gpt-oss and olmoe headers -> GGUFGenericForCausalLM config"""+ import subprocess+ code = r"""+import os, types+os.environ['EXL3_GGUF_GENERIC'] = '1'+from exllamav3.loader import gguf_config as C+class M(dict): pass+def fake(arch, moe_dims, extra):+ nl, ne, nq, E = 2, 64, 4, 4+ m = M({'general.architecture': arch, arch+'.embedding_length': ne, arch+'.attention.head_count': nq, arch+'.attention.head_count_kv': 2,+ arch+'.block_count': nl, arch+'.attention.key_length': 16, arch+'.attention.layer_norm_rms_epsilon': 1e-5,+ arch+'.context_length': 128, arch+'.expert_count': E, arch+'.expert_used_count': 2, arch+'.expert_feed_forward_length': 32})+ m.update(extra)+ inf = {'token_embd.weight': (0, (ne, 100), 0), 'output.weight': (0, (ne, 100), 0), 'output_norm.weight': (0, (ne,), 0)}+ for i in range(nl):+ b = f'blk.{i}.'+ inf.update({b+'attn_norm.weight': (0,(ne,),0), b+'ffn_norm.weight': (0,(ne,),0), b+'attn_q.weight': (0,(ne, nq*16),0),+ b+'attn_k.weight': (0,(ne, 32),0), b+'attn_v.weight': (0,(ne, 32),0), b+'attn_output.weight': (0,(nq*16, ne),0),+ b+'ffn_gate_inp.weight': (0,(ne, E),0), b+'ffn_gate_exps.weight': (8,(ne, 32, E),0),+ b+'ffn_up_exps.weight': (8,(ne, 32, E),0), b+'ffn_down_exps.weight': (8,(32, ne, E),0)})+ return types.SimpleNamespace(meta=m, infos=inf, name_map={})+for arch in ('olmoe', 'gpt-oss'):+ cfg = C.hf_config(fake(arch, None, {}))+ assert cfg['architectures'] == ['GGUFGenericForCausalLM'], cfg+ print(arch, 'norm_topk_prob', cfg.get('norm_topk_prob'), 'gaps', cfg.get('gaps'))+print('RESOLVED')+"""+ env = dict(os.environ, CUDA_VISIBLE_DEVICES="", HIP_VISIBLE_DEVICES="", PYTHONPATH=ROOT)+ r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, env=env, cwd=ROOT, timeout=200)+ if r.returncode != 0 and ("exllamav3_ext" in r.stderr or "ModuleNotFoundError" in r.stderr):+ pytest.skip("extension not built")+ assert r.returncode == 0 and "RESOLVED" in r.stdout, r.stderr[-800:]+ print(r.stdout)+++def _fake_collection(tmp_path, E=4, R=5):+ c = coll()+ stacked = (np.arange(E * R, dtype=np.float32) * 0.5 + 1) # ggml dims (R, E): row e = values [e*R:(e+1)*R]+ f = tmp_path / "bias.bin"; f.write_bytes(b"\0" * 8 + stacked.tobytes())+ g = object.__new__(c.GGUFCollection)+ g.__dict__.update(infos={"blk.0.ffn_up_exps.bias": (0, (R, E), 8), "blk.0.ffn_up_exps.weight": (2, (32, 3, E), 0),+ "blk.0.ffn_gate_inp.bias": (0, (E,), 8)},+ name_map={"eng.e2": "blk.0.ffn_up_exps.e2.bias", "eng.e9": "blk.0.ffn_up_exps.e9.bias",+ "eng.w": "blk.0.ffn_up_exps.e1.weight"},+ new_tensors=None, aux=None, path="fake")+ g._pread = lambda off, n: np.frombuffer(f.read_bytes()[off:off + n], dtype=np.uint8)+ return g, stacked+++def test_bias_slice(tmp_path):+ g, st = _fake_collection(tmp_path)+ assert g._exps_slice("blk.0.ffn_up_exps.e3.bias") == ("blk.0.ffn_up_exps.bias", 3)+ assert g._exps_slice("blk.0.ffn_up_exps.e3.weight") == ("blk.0.ffn_up_exps.weight", 3)+ assert g._exps_slice("blk.0.ffn_up_exps.e3") == ("blk.0.ffn_up_exps.weight", 3)+ assert g._exps_slice("blk.0.ffn_up_exps.bias") is None and g._exps_slice("blk.0.ffn_down_exps.e3.bias") is None+ assert g._exps_slice("blk.0.ffn_up_exps.eX.bias") is None+ assert g.has_tensor("eng.e2") is True+ for e in range(4):+ g.name_map["k"] = f"blk.0.ffn_up_exps.e{e}.bias"+ t = g.get_tensor("k")+ assert t.dtype == torch.float32 and t.shape == (5,) and np.array_equal(t.numpy(), st[e * 5:(e + 1) * 5])+ with pytest.raises(AssertionError):+ g.get_tensor("eng.e9") # expert 9 of 4+ # quant weight slices still use the old protocol (name resolution only; the payload read is not faked here)+ assert g._exps_slice("blk.0.ffn_up_exps.e1.weight") == ("blk.0.ffn_up_exps.weight", 1)+++def test_f32_weight_slice_still_refused(tmp_path):+ g, _ = _fake_collection(tmp_path)+ g.infos["blk.1.ffn_up_exps.weight"] = (0, (5, 4), 8)+ g.name_map["k"] = "blk.1.ffn_up_exps.e1.weight"+ with pytest.raises(ValueError, match="per-expert slice of a F32 stacked tensor is not supported: blk.1.ffn_up_exps.weight \\(expert 1\\)"):+ g.get_tensor("k")+++def _routing_ns():+ """_router_logits / _routing_std_nonorm / routing_std source taken from the file (the module imports the extension)."""+ path = os.path.join(ROOT, "exllamav3/modules/block_sparse_mlp_routing.py")+ src = open(path).read()+ tree = ast.parse(src)+ keep = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in ("_router_logits", "_routing_std_nonorm")]+ ns = {"torch": torch, "os": os, "_pad_rows": lambda y: y}+ exec(compile(ast.Module(keep, []), path, "exec"), ns)+ return ns, src+++def test_norm_topk():+ ns, src = _routing_ns()+ assert "if not cfg.norm_topk:\n return _routing_std_nonorm(cfg, y, params)" in src+ assert "norm_topk: bool = True" in src # RoutingCFG default = today's renormalised routing+ torch.manual_seed(0)+ H, E, K, B = 16, 8, 3, 6+ cfg = types.SimpleNamespace(gate_tensor=torch.randn(H, E).half(), num_experts=E, num_experts_per_tok=K, per_expert_scale=None)+ y = torch.randn(B, H).half()+ sel, w = ns["_routing_std_nonorm"](cfg, y, {})+ logits = (y @ cfg.gate_tensor).float()+ probs = torch.softmax(logits, -1)+ ref_sel = torch.sort(logits, dim=-1, descending=True, stable=True)[1][:, :K]+ assert torch.equal(sel, ref_sel)+ assert torch.allclose(w.float(), torch.gather(probs, 1, ref_sel).half().float())+ assert (w.float().sum(-1) < 1.001).all() and (w.float().sum(-1) < 0.99).any() # off: NOT renormalised+ renorm = torch.softmax(torch.gather(logits, 1, ref_sel), -1) # on (main's routing_std): top-k softmax, sums to 1+ assert torch.allclose(renorm.sum(-1), torch.ones(B))+ assert not torch.allclose(renorm, w.float(), atol=1e-3)+ s = torch.rand(E).half() # per-expert scale applies in both+ cfg.per_expert_scale = s+ _, w2 = ns["_routing_std_nonorm"](cfg, y, {})+ assert torch.allclose(w2.float(), (torch.gather(probs, 1, ref_sel) * s.float()[ref_sel]).half().float())+ _, wa = ns["_routing_std_nonorm"](cfg, y, {"activate_all_experts": True})+ assert wa.shape == (B, E)