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 standard dense models (llama, qwen3) straight from a plain GGUF: metadata config, tensor map, ForeignLinear projections

YanissAmz73a1eb15de72
diff --git a/exllamav3/architecture/architectures.py b/exllamav3/architecture/architectures.py
index ff746c3..fee5c85 100644
--- a/exllamav3/architecture/architectures.py
+++ b/exllamav3/architecture/architectures.py
@@ -53,6 +53,7 @@ from .phi3 import Phi3Model
from .qwen2 import Qwen2Model
from .qwen2_5_vl import Qwen2_5VLModel
from .qwen3 import Qwen3Model
+from .gguf_dense import GGUFDenseModel
from .qwen3_5 import Qwen3_5Model, Qwen3_5MoeModel, Qwen3_5VLModel, Qwen3_5VLMoeModel
from .qwen4_exp import Qwen4ExpModel
from .qwen3_moe import Qwen3MoeModel
@@ -129,6 +130,7 @@ ARCHITECTURES = {
Qwen2Model,
Qwen2_5VLModel,
Qwen3Model,
+ GGUFDenseModel,
Qwen3_5Model,
Qwen3_5MoeModel,
Qwen3_5VLModel,
diff --git a/exllamav3/architecture/gguf_dense.py b/exllamav3/architecture/gguf_dense.py
new file mode 100644
index 0000000..5389f11
--- /dev/null
+++ b/exllamav3/architecture/gguf_dense.py
@@ -0,0 +1,139 @@
+"""Standard dense models (llama, qwen3) served straight from a plain GGUF.
+
+No requant: every projection is a ForeignLinear over the raw GGUF payload (Q4_0 ... IQ4_XS, MXFP4, NVFP4).
+Config, tensor names and tokenizer all come from the GGUF (loader/gguf_config.py). Build the config directory with
+write_config_dir(gguf, dir), then Config.from_directory(dir) as for any other model.
+
+llama.cpp stores llama-arch Q/K rows permuted for interleaved (adjacent-pair) rotary, so llama uses RopeStyle.GPTJ;
+qwen3 is stored in HF order (NEOX).
+"""
+from __future__ import annotations
+from typing_extensions import override
+import os
+
+import numpy as np
+import torch
+
+from ..loader.gguf_collection import GGUFCollection
+from ..loader.gguf_config import GGML_FMT, name_map
+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
+from ..modules.foreign_linear import ForeignLinear
+from ..modules.attn import prepare_for_attn
+
+
+def _fl(config, eng_key: str, in_features: int, out_features: int, out_dtype=None):
+ gname = config.gguf.name_map[eng_key + ".weight"]
+ fmt = config.gguf_formats[gname]
+ assert fmt != "fp" and not fmt.startswith("unk"), f"{eng_key}: unsupported ggml type {fmt}"
+ return ForeignLinear(config, eng_key, in_features, out_features, fmt, out_dtype=out_dtype)
+
+
+def _mlp(config, L, H, I):
+ mlp = GatedMLP(
+ config=config, key=f"{L}.mlp", hidden_size=H, intermediate_size=I,
+ qmap="block.mlp", 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)])
+ # the prebuilt-projection branch of GatedMLP does not register them for loading
+ for m in mlp.gates + mlp.ups + mlp.downs:
+ mlp.register_submodule(m)
+ return mlp
+
+
+class GGUFDenseConfig(Config):
+ arch_string = "GGUFDenseForCausalLM"
+
+ def __init__(self, directory: str, **kwargs):
+ super().__init__(directory, {"text": GGUFDenseModel}, **kwargs)
+ self.gguf_arch = self.read_cfg(str, "gguf_arch", no_default)
+ self.head_dim = self.read_cfg(int, "head_dim", None)
+ self.hidden_size = self.read_cfg(int, "hidden_size", no_default)
+ self.num_q_heads = self.read_cfg(int, "num_attention_heads", no_default)
+ self.num_kv_heads = self.read_cfg(int, "num_key_value_heads", self.num_q_heads)
+ self.intermediate_size = self.read_cfg(int, "intermediate_size", no_default)
+ self.rms_norm_eps = self.read_cfg(float, "rms_norm_eps", no_default)
+ self.num_hidden_layers = self.read_cfg(int, "num_hidden_layers", no_default)
+ self.tie_word_embeddings = self.read_cfg(bool, "tie_word_embeddings", False)
+ style = RopeStyle.GPTJ if self.gguf_arch == "llama" else RopeStyle.NEOX
+ self.rope_settings = self.read_rope_settings_default(style)
+
+ self.gguf = GGUFCollection(os.path.join(directory, "model.gguf"))
+ self.gguf.name_map = name_map(self.config_dict)
+ self.stc = self.gguf
+ self.gguf_formats = {g: GGML_FMT.get(ty, f"unk{ty}") for g, (ty, _, _) in self.gguf.infos.items()}
+ self.has_qk_norm = "blk.0.attn_q_norm.weight" in self.gguf.infos
+ self._embedding_override()
+
+ def _embedding_override(self):
+ # token_embd dequantized to fp16 once and served as an in-memory tensor (rows are gathered, never matmul'd)
+ gname = "token_embd.weight"
+ ty, (K, N), _ = self.gguf.infos[gname]
+ fmt = GGML_FMT.get(ty, f"unk{ty}")
+ if fmt == "fp":
+ return
+ fl = ForeignLinear(self, "model.embed_tokens", K, N, fmt)
+ fl.load(torch.device("cpu"))
+ w = torch.cat([fl._dequant_rows(i, min(4096, N - i)) for i in range(0, N, 4096)])
+ self.gguf.new_tensors = {"model.embed_tokens.weight": w}
+
+ def get_tensor_name_fixes(self):
+ return {}
+
+
+class GGUFDenseModel(Model):
+ config_class = GGUFDenseConfig
+
+ def __init__(self, config: GGUFDenseConfig, key_prefix: str = "model", **kwargs):
+ super().__init__(config, **kwargs)
+ H, hd = config.hidden_size, config.head_dim
+ nq, nkv, I = config.num_q_heads, config.num_kv_heads, config.intermediate_size
+ P = key_prefix
+ self.modules += [Embedding(config=config, key=f"{P}.embed_tokens",
+ vocab_size=config.vocab_size, hidden_size=H)]
+ self.first_block_idx = len(self.modules)
+ for idx in range(config.num_hidden_layers):
+ L = f"{P}.layers.{idx}"
+ norms = {}
+ if config.has_qk_norm:
+ norms = dict(
+ q_norm=RMSNorm(config=config, key=f"{L}.self_attn.q_norm", rms_norm_eps=config.rms_norm_eps),
+ k_norm=RMSNorm(config=config, key=f"{L}.self_attn.k_norm", rms_norm_eps=config.rms_norm_eps))
+ 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,
+ num_q_heads=nq, num_kv_heads=nkv, rope_settings=config.rope_settings, sm_scale=None,
+ qmap="block.attn", out_dtype=torch.float,
+ q_proj=_fl(config, f"{L}.self_attn.q_proj", H, nq * hd),
+ k_proj=_fl(config, f"{L}.self_attn.k_proj", H, nkv * hd),
+ v_proj=_fl(config, f"{L}.self_attn.v_proj", H, nkv * hd),
+ o_proj=_fl(config, f"{L}.self_attn.o_proj", nq * hd, H, out_dtype=torch.float),
+ **norms),
+ mlp_norm=RMSNorm(config=config, key=f"{L}.post_attention_layernorm", rms_norm_eps=config.rms_norm_eps),
+ mlp=_mlp(config, L, H, I))]
+ 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:
+ # tied head: the quantized embedding payload doubles as the output projection
+ config.gguf.name_map["lm_head.weight"] = "token_embd.weight"
+ self.modules += [_fl(config, "lm_head", H, config.vocab_size)]
+ self.modules[-1].caps["logits_output"] = True
+ self.logit_layer_idx = len(self.modules) - 1
+
+ @override
+ def prepare_inputs(self, input_ids: torch.Tensor, params: dict) -> torch.Tensor:
+ return prepare_for_attn(input_ids, params)
+
+ @override
+ def default_chat_prompt(self, prompt: str, system_prompt: str = None) -> str:
+ p = ""
+ if system_prompt:
+ p += f"<|im_start|>system\n{system_prompt}<|im_end|>\n"
+ p += f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
+ return p
diff --git a/exllamav3/loader/gguf_collection.py b/exllamav3/loader/gguf_collection.py
index e4ff6a2..a785e57 100644
--- a/exllamav3/loader/gguf_collection.py
+++ b/exllamav3/loader/gguf_collection.py
@@ -69,26 +69,28 @@ class GGUFCollection:
def rs():
n = struct.unpack("<Q", f.read(8))[0]
- return f.read(n).decode()
-
- def sv():
- t = struct.unpack("<I", f.read(4))[0]
- if t in _META_SZ:
- f.read(_META_SZ[t])
- elif t == 8:
- f.read(struct.unpack("<Q", f.read(8))[0])
- elif t == 9:
+ return f.read(n).decode(errors="replace")
+
+ _SC = {0: "<B", 1: "<b", 2: "<H", 3: "<h", 4: "<I", 5: "<i", 6: "<f", 7: "<?", 10: "<Q", 11: "<q", 12: "<d"}
+
+ def sv(t=None):
+ if t is None:
+ t = struct.unpack("<I", f.read(4))[0]
+ if t in _SC:
+ return struct.unpack(_SC[t], f.read(struct.calcsize(_SC[t])))[0]
+ if t == 8:
+ return rs()
+ if t == 9:
at = struct.unpack("<I", f.read(4))[0]
n = struct.unpack("<Q", f.read(8))[0]
- if at == 8:
- for _ in range(n):
- f.read(struct.unpack("<Q", f.read(8))[0])
- else:
- f.read(n * _META_SZ[at])
+ return [sv(at) for _ in range(n)]
+ raise ValueError(f"gguf metadata type {t}")
+ # Metadata kept (config + tokenizer are derived from it, see loader/gguf_config.py)
+ self.meta = {}
for _ in range(nm):
- rs()
- sv()
+ k = rs()
+ self.meta[k] = sv()
self.infos = {}
for _ in range(nt):
name = rs()
diff --git a/exllamav3/loader/gguf_config.py b/exllamav3/loader/gguf_config.py
new file mode 100644
index 0000000..4555cdb
--- /dev/null
+++ b/exllamav3/loader/gguf_config.py
@@ -0,0 +1,92 @@
+"""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"),
+}
+
+# ggml type id -> ForeignLinear format
+GGML_FMT = {
+ 2: "q4_0", 6: "q5_0", 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", 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 + "."
+ 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 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."""
+ g = GGUFCollection(gguf_path)
+ try:
+ cfg = hf_config(g)
+ finally:
+ g.close()
+ os.makedirs(outdir, exist_ok=True)
+ 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 outdir
diff --git a/tests/gguf_dense_synthetic_gpu_check.py b/tests/gguf_dense_synthetic_gpu_check.py
new file mode 100644
index 0000000..b3bc5f8
--- /dev/null
+++ b/tests/gguf_dense_synthetic_gpu_check.py
@@ -0,0 +1,72 @@
+"""GPU: a tiny qwen3-arch GGUF (random weights, Q4_0/Q8_0 via gguf-py) served by GGUFDenseModel must match a torch
+reference forward over the dequantized weights. Needs the built extension and the gguf package.
+Usage: python tests/gguf_dense_synthetic_gpu_check.py <scratch_dir> [fmt]"""
+import os, sys, tempfile
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+import numpy as np, torch, gguf
+from gguf import GGMLQuantizationType as T
+
+out = sys.argv[1]; FMT = sys.argv[2] if len(sys.argv) > 2 else "Q4_0"
+os.makedirs(out, exist_ok=True)
+H, nq, nkv, hd, I, V, NL = 256, 4, 2, 64, 512, 512, 2
+rng = np.random.default_rng(0)
+path = os.path.join(out, "tiny.gguf")
+w = gguf.GGUFWriter(path, "qwen3")
+w.add_block_count(NL); w.add_context_length(512); w.add_embedding_length(H); w.add_feed_forward_length(I)
+w.add_head_count(nq); w.add_head_count_kv(nkv); w.add_key_length(hd); w.add_value_length(hd)
+w.add_layer_norm_rms_eps(1e-6); w.add_rope_freq_base(10000.0)
+ref = {}
+qt = getattr(T, FMT)
+def mat(name, n, k, quant=True):
+ a = (rng.standard_normal((n, k)) * 0.05).astype(np.float32)
+ if quant:
+ q = gguf.quants.quantize(a, qt); ref[name] = torch.from_numpy(gguf.quants.dequantize(q, qt))
+ w.add_tensor(name, q, raw_dtype=qt)
+ else:
+ ref[name] = torch.from_numpy(a); w.add_tensor(name, a)
+def vec(name, n):
+ a = (1 + 0.1 * rng.standard_normal(n)).astype(np.float32); ref[name] = torch.from_numpy(a); w.add_tensor(name, a)
+mat("token_embd.weight", V, H)
+vec("output_norm.weight", H)
+for i in range(NL):
+ g = f"blk.{i}"
+ vec(f"{g}.attn_norm.weight", H); vec(f"{g}.ffn_norm.weight", H)
+ mat(f"{g}.attn_q.weight", nq * hd, H); mat(f"{g}.attn_k.weight", nkv * hd, H); mat(f"{g}.attn_v.weight", nkv * hd, H)
+ mat(f"{g}.attn_output.weight", H, nq * hd)
+ vec(f"{g}.attn_q_norm.weight", hd); vec(f"{g}.attn_k_norm.weight", hd)
+ mat(f"{g}.ffn_gate.weight", I, H); mat(f"{g}.ffn_up.weight", I, H); mat(f"{g}.ffn_down.weight", H, I)
+w.write_header_to_file(); w.write_kv_data_to_file(); w.write_tensors_to_file(); w.close()
+
+def rms(x, wt): return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-6) * wt
+def rope(x, pos): # NEOX, x [S, h, hd]
+ half = hd // 2
+ f = 1.0 / (10000.0 ** (torch.arange(half, dtype=torch.float32) / half))
+ ang = pos[:, None] * f[None]; c, s = ang.cos()[:, None], ang.sin()[:, None]
+ x1, x2 = x[..., :half], x[..., half:]
+ return torch.cat([x1 * c - x2 * s, x1 * s + x2 * c], -1)
+ids = torch.tensor([3, 17, 99, 250, 5, 71, 400, 12])
+S = len(ids); pos = torch.arange(S, dtype=torch.float32)
+x = ref["token_embd.weight"][ids]
+for i in range(NL):
+ g = f"blk.{i}"
+ h = rms(x, ref[f"{g}.attn_norm.weight"])
+ q = (h @ ref[f"{g}.attn_q.weight"].T).view(S, nq, hd); k = (h @ ref[f"{g}.attn_k.weight"].T).view(S, nkv, hd)
+ v = (h @ ref[f"{g}.attn_v.weight"].T).view(S, nkv, hd)
+ q = rope(rms(q, ref[f"{g}.attn_q_norm.weight"]), pos); k = rope(rms(k, ref[f"{g}.attn_k_norm.weight"]), pos)
+ k = k.repeat_interleave(nq // nkv, 1); v = v.repeat_interleave(nq // nkv, 1)
+ att = torch.einsum("qhd,khd->hqk", q, k) / hd ** 0.5
+ att = att.masked_fill(torch.triu(torch.ones(S, S, dtype=torch.bool), 1), float("-inf")).softmax(-1)
+ x = x + torch.einsum("hqk,khd->qhd", att, v).reshape(S, -1) @ ref[f"{g}.attn_output.weight"].T
+ h = rms(x, ref[f"{g}.ffn_norm.weight"])
+ x = x + (torch.nn.functional.silu(h @ ref[f"{g}.ffn_gate.weight"].T) * (h @ ref[f"{g}.ffn_up.weight"].T)) @ ref[f"{g}.ffn_down.weight"].T
+ref_logits = rms(x, ref["output_norm.weight"]) @ ref["token_embd.weight"].T
+
+from exllamav3.loader.gguf_config import write_config_dir
+from exllamav3.model.config import Config
+from exllamav3.model.model import Model
+d = write_config_dir(path, os.path.join(out, "cfg"))
+config = Config.from_directory(d); model = Model.from_config(config); model.load()
+got = model.forward(ids[None].cuda(), params={"attn_mode": "flash_attn_nc"})[0].float().cpu()
+err = ((got - ref_logits).norm() / ref_logits.norm()).item()
+print(FMT, "rel err", err, "argmax match", (got.argmax(-1) == ref_logits.argmax(-1)).float().mean().item())
+assert err < 2e-2