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
GGUF body: MTP draft head from a safetensors sidecar (#223)
Yaniss Amazouz4dd6fef3b98a
diff --git a/exllamav3/architecture/minicpm_v47.py b/exllamav3/architecture/minicpm_v47.pyindex 2206f62..cdfe79c 100644--- a/exllamav3/architecture/minicpm_v47.py+++ b/exllamav3/architecture/minicpm_v47.py@@ -138,9 +138,11 @@ class MiniCPMV47Config(Config):# MTP head and vision tower are separate concerns (draft file)self.model_classes.pop("mtp", None)self.model_classes.pop("vision", None)+ self.mtp_num_hidden_layers = 0# GGUF backing store + engine->gguf name mapself.gguf = GGUFCollection(_gguf_path(directory))+ self._attach_mtp_head(directory)nm: dict[str, str] = {}for i in range(self.num_hidden_layers):_map_layer(nm, i)@@ -155,6 +157,19 @@ class MiniCPMV47Config(Config):# as an in-memory override (vectorized numpy, no per-block Python).self._load_embedding_override()+ def _attach_mtp_head(self, directory):+ """MTP head (any Qwen3.5-family HF model that ships mtp.* tensors) beside the GGUF body. KYO_GGUF_MTP (or <model dir>/mtp) = a directory with the head's mtp.*+ tensors as safetensors (tools/qwen/gguf_mtp_fetch.py). It is served by the same config.stc, the head runs on the body's+ last hidden state and the body's embedding / lm_head (qwen3_5_mtp.py attach_to). Off (no head) without it."""+ d = os.environ.get("KYO_GGUF_MTP") or os.path.join(directory or "", "mtp")+ if not os.path.isdir(d) or not any(f.endswith(".safetensors") for f in os.listdir(d)):+ return+ from ..loader.safetensors import SafetensorsCollection+ from .qwen3_5_mtp import Qwen3_5MoeMTPModel, Qwen3_5MTPModel+ self.gguf.aux = SafetensorsCollection(d)+ self.mtp_num_hidden_layers = 1+ self.model_classes["mtp"] = Qwen3_5MTPModel if self.num_experts is None else Qwen3_5MoeMTPModel+def _load_embedding_override(self):# token_embd dequantized to fp16 once (~1 GB) and served as an# in-memory override under the engine key (vectorized numpy, nodiff --git a/exllamav3/architecture/qwen3_5_mtp.py b/exllamav3/architecture/qwen3_5_mtp.pyindex 46893eb..2530d98 100644--- a/exllamav3/architecture/qwen3_5_mtp.py+++ b/exllamav3/architecture/qwen3_5_mtp.py@@ -31,6 +31,32 @@ def exl3_block_subhead(inner, blocks):mul1 = inner.mul1_tensor, out_dtype = inner.out_dtype)+_GGUF_EXPERT_FMT = {144: "q4_k", 176: "q5_k", 210: "q6_k", 136: "iq4_xs"} # bytes per 256 weights+++def _expert_kwargs(config, idx):+ """BlockSparseMLP expert arguments of the MTP head. Default: the checkpoint's experts (bf16 / fp8 safetensors). GGUF body whose+ sidecar holds the experts as GGUF blocks (uint8 [N, K/256*bytes], tools/qwen/gguf_mtp_fetch.py --experts-gguf): ForeignLinear experts+ on the body's grouped K-quant MoE kernels."""+ base = dict(key_up = "experts.{expert_idx}.up_proj", key_gate = "experts.{expert_idx}.gate_proj", key_down = "experts.{expert_idx}.down_proj",+ key_gate_up_split = "experts.gate_up_proj", key_down_split = "experts.down_proj", transpose_fused_weights = False)+ stc = getattr(config, "stc", None)+ k0 = f"mtp.layers.{idx}.mlp.experts.0.gate_proj.weight"+ if getattr(config, "gguf", None) is None or stc is None or not stc.has_tensor(k0):+ return base+ meta = stc.get_tensor_meta(k0)[k0]+ if "uint8" not in meta["dtype"]:+ return base+ from ..modules.foreign_linear import ForeignLinear+ H, I, E = config.hidden_size, config.moe_intermediate_size, config.num_experts+ fmt = _GGUF_EXPERT_FMT[meta["n_bytes"] // I // (H // 256)]+ L = f"mtp.layers.{idx}.mlp.experts"+ gates = [ForeignLinear(config, f"{L}.{e}.gate_proj", H, I, fmt) for e in range(E)]+ ups = [ForeignLinear(config, f"{L}.{e}.up_proj", H, I, fmt) for e in range(E)]+ downs = [ForeignLinear(config, f"{L}.{e}.down_proj", I, H, fmt, out_dtype = torch.float) for e in range(E)]+ return dict(key_up = None, key_gate = None, key_down = None, gates = gates, ups = ups, downs = downs)++class Qwen3_5MTPModel(Model):def __init__(@@ -121,14 +147,9 @@ class Qwen3_5MTPModel(Model):intermediate_size = config.moe_intermediate_size,num_experts = config.num_experts,num_experts_per_tok = config.num_experts_per_tok,- key_up = "experts.{expert_idx}.up_proj",- key_gate = "experts.{expert_idx}.gate_proj",- key_down = "experts.{expert_idx}.down_proj",- key_gate_up_split = "experts.gate_up_proj",- key_down_split = "experts.down_proj",+ **_expert_kwargs(config, idx),key_routing_gate = "gate",key_shared_gate = "shared_expert_gate",- transpose_fused_weights = False,qmap = "block.mlp",interm_dtype = torch.half,out_dtype = torch.float,@@ -165,6 +186,12 @@ class Qwen3_5MTPModel(Model):))+ for blk in self.modules[self.first_block_idx:]:+ m = getattr(blk, "mlp", None)+ for l in (*getattr(m, "gates", ()), *getattr(m, "ups", ()), *getattr(m, "downs", ())):+ if l.__class__.__name__ == "ForeignLinear": # prebuilt experts bypass the builders, which are the register_submodule sites+ m.register_submodule(l)+self.last_kv_module_idx = len(self.modules) - 1# Final norm@@ -223,7 +250,8 @@ class Qwen3_5MTPModel(Model):self.target_embed = weakref.ref(target_embed)# lm_head is the last module- assert isinstance(target.modules[-1], Linear), "Expected Linear lm_head as last target module"+ from ..modules.foreign_linear import ForeignLinear # GGUF body: the head is a ForeignLinear+ assert isinstance(target.modules[-1], (Linear, ForeignLinear)), "Expected Linear lm_head as last target module"self.target_lm_head = weakref.ref(target.modules[-1])target_norm = target.modules[target.logit_layer_idx - 1]diff --git a/exllamav3/loader/gguf_collection.py b/exllamav3/loader/gguf_collection.pyindex 847e674..c95c313 100644--- a/exllamav3/loader/gguf_collection.py+++ b/exllamav3/loader/gguf_collection.py@@ -86,6 +86,18 @@ class GGUFCollection:self.name_map: dict[str, str | tuple] = {}# In-memory overrides (e.g. dequantized embedding), served first.self.new_tensors: dict[str, torch.Tensor] | None = None+ # Side collection (SafetensorsCollection) that serves the "mtp.*" keys (the Qwen3.5/3.6 MTP head kept beside a GGUF body)+ self.aux = None++ def __getattr__(self, name):+ # only reached for attributes this class lacks: the MTP head's loaders use the safetensors-collection API+ aux = self.__dict__.get("aux")+ if aux is not None and not name.startswith("__"):+ return getattr(aux, name)+ raise AttributeError(name)++ def _is_aux(self, key) -> bool:+ return self.aux is not None and isinstance(key, str) and key.startswith("mtp.")@staticmethoddef _read_header(p: str):@@ -135,6 +147,8 @@ class GGUFCollection:return mapped[0] if isinstance(mapped, tuple) else mappeddef has_tensor(self, key: str) -> bool:+ if self._is_aux(key):+ return self.aux.has_tensor(key)if self.new_tensors and key in self.new_tensors:return Truereturn self._resolve(key) in self.infos@@ -173,6 +187,8 @@ class GGUFCollection:return Truedef get_tensor_sizes(self, key: str):+ if self._is_aux(key):+ return self.aux.get_tensor_sizes(key)info = self.infos.get(self._resolve(key))if info is None:raise KeyError(key)@@ -204,6 +220,8 @@ class GGUFCollection:pad_to: tuple | None = None,fidx=None,) -> torch.Tensor | None:+ if self._is_aux(key):+ return self.aux.get_tensor(key, device, optional, allow_bf16, float2half, no_defer, transpose, pad_to, fidx)if self.new_tensors and key in self.new_tensors:t = self.new_tensors[key]t = t.to(device) if device is not None else tdiff --git a/exllamav3/modules/attn.py b/exllamav3/modules/attn.pyindex afff251..eeefbf7 100644--- a/exllamav3/modules/attn.py+++ b/exllamav3/modules/attn.py@@ -11,6 +11,7 @@ from .quant.exl3 import MAX_BSZN_GEMV_R, row_pad_pitchfrom ..ext import exllamav3_ext as extfrom ..model.model_tp_alloc import TPAllocationfrom ..util import profile_opt, knobs+from ..util.row_inv import gguf_riimport osfrom .attention_fn.bc_attn import bc_attn_enable as _bc_attn_enable, build_bc_attn, MAX_BSZ as _bc_max_bsz, MAX_QLEN as _bc_max_qlen@@ -1467,7 +1468,7 @@ class Attention(Module):tq_batch = bool(getattr(_lyr, "tq", False))if (1 < seqlen <= MAX_BSZN_GEMV_R and non_causal_spans is None and not tq_batch and- knobs.knob_on("EXL3_VERIFY_ATTN_LOOP", "0")+ (knobs.knob_on("EXL3_VERIFY_ATTN_LOOP", "0") or gguf_ri("attn"))):# Row-invariant verify: the R-row paged decode tiles the KV span from the batch's single# cache_seqlens/q_len, a different float order than R batch-1 calls. Run the exact@@ -1608,7 +1609,7 @@ class Attention(Module):if max_kv_len is None and seqlen > 16 and not torch.version.hip:max_kv_len = int(params["cache_seqlens"][sl].max())# EXL3_VERIFY_ATTN_LOOP: the R-row paged decode as R one-row calls, as decode_flash_attn does- rows = range(seqlen) if 1 < seqlen <= MAX_BSZN_GEMV_R and knobs.knob_on("EXL3_VERIFY_ATTN_LOOP", "0") else None+ rows = range(seqlen) if 1 < seqlen <= MAX_BSZN_GEMV_R and (knobs.knob_on("EXL3_VERIFY_ATTN_LOOP", "0") or gguf_ri("attn")) else Nonedef call(qq, kk, vv, cs):return attn_dispatch(q = qq, k = kk, v = vv,diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.pyindex 36f4b6a..7c6094a 100644--- a/exllamav3/modules/block_sparse_mlp.py+++ b/exllamav3/modules/block_sparse_mlp.py@@ -21,7 +21,7 @@ from ..util import profile_optfrom ..util.knobs import knob_onfrom ..util.tensor import g_tensor_cache, buffered_interleaved_arangefrom .quant.exl3 import dec_workspace-from ..util.row_inv import ROW_INV_MAX_ROWS, job_slices+from ..util.row_inv import ROW_INV_MAX_ROWS, job_slices, GGUF_ROW_INV, GGUF_ROW_INV_MAX_ROWS, gguf_rifrom .block_sparse_mlp_routing import (RoutingCFG, ROUTING_ACT_SIGMOID, ROUTING_ACT_SQRTSP,routing_std, routing_std_bias, routing_ds3, routing_dots, routing_sqrtsp, routing_sqrtsp_hash,@@ -2526,6 +2526,10 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):out_dtype: torch.dtype | None = None) -> torch.Tensor:+ if gguf_ri("moe") and not params.get("autosplit_measure") and \+ 2 <= x.numel() // x.shape[-1] <= GGUF_ROW_INV_MAX_ROWS and self._gguf_experts():+ return self._forward_rows_single(x, params, out_dtype)+if _ROW_CHUNK_MAX and self.coop_rows < x.numel() // x.shape[-1] <= \(min(_ROW_CHUNK_MAX, _FUSED_3INST_MIN) if self.support_fused else _ROW_CHUNK_MAX) and self._row_chunk_ok() and \not params.get("autosplit_measure"):@@ -3506,6 +3510,29 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):return out+ def _gguf_experts(self) -> bool:+ from .foreign_linear import ForeignLinear+ for lst in (self.ups, self.downs):+ if lst and isinstance(lst[0], ForeignLinear):+ return True+ return False+++ def _forward_rows_single(self, x: torch.Tensor, params: dict, out_dtype: torch.dtype | None) -> torch.Tensor:+ # EXL3_GGUF_ROW_INV: the multi-row GGUF MoE paths (grouped prefill, per-expert token grouping + index_add) sum in another+ # order and take other kernels than the one-row step; run every row through the one-row path so it gets its exact bits.+ y = x.reshape(-1, x.shape[-1])+ routed = params.pop("dec_routed", None)+ outs = []+ for a in range(y.shape[0]):+ sub = {k: v for k, v in params.items() if k != "mlp_residual_out"}+ if routed is not None:+ sub["dec_routed"] = (routed[0][a:a + 1], routed[1][a:a + 1])+ o = self.forward(y[a:a + 1].unsqueeze(0), sub, out_dtype)+ outs.append(o.reshape(-1, o.shape[-1]).clone())+ return torch.cat(outs).view(x.shape[:-1] + (outs[0].shape[-1],))++def _row_chunk_ok(self) -> bool:# bszN decode kernels exist (BC, CUDA) and no fused MoE kernel would take the rows (or only the 3INST one, which# loses below _FUSED_3INST_MIN rows); ROCm has no BC objectdiff --git a/exllamav3/modules/block_sparse_mlp_routing.py b/exllamav3/modules/block_sparse_mlp_routing.pyindex e6fadef..2d7bc5b 100644--- a/exllamav3/modules/block_sparse_mlp_routing.py+++ b/exllamav3/modules/block_sparse_mlp_routing.py@@ -12,7 +12,7 @@ from dataclasses import dataclassfrom ..util.device_copy import to_devicefrom ..ext import exllamav3_ext as extfrom ..util.tensor import g_tensor_cache-from ..util.row_inv import ROW_INV, ROW_INV_MAX_ROWS+from ..util.row_inv import ROW_INV, ROW_INV_MAX_ROWS, GGUF_ROW_INV, GGUF_ROW_INV_MAX_ROWS, gguf_ridef _pad_rows(y):@@ -285,6 +285,12 @@ def _routing_nogroup_torch(cfg, y, params, scores):def routing_std(bsz, cfg, y, params):+ if (gguf_ri("router") and 2 <= bsz <= GGUF_ROW_INV_MAX_ROWS and y.dim() == 2 and y.shape[0] == bsz+ and not params.get("activate_all_experts")):+ # row-invariant few-row mode (GGUF + MTP): the router GEMM of an R-row call picks another kernel than the one-row call, so its+ # logits differ in the last bits and a near tie flips an expert. One one-row routing per row, the bits of the plain step.+ outs = [routing_std(1, cfg, y[i:i + 1], params) for i in range(bsz)]+ return torch.cat([o[0].clone() for o in outs]), torch.cat([o[1].clone() for o in outs])if _hip_router_call_supported(bsz, cfg, y, params):_prepare_hip_router_gate_t(cfg)scores, selected_experts, routing_weights = _hip_router_buffers(cfg, bsz)diff --git a/exllamav3/modules/foreign_linear.py b/exllamav3/modules/foreign_linear.pyindex b65f7ba..f04b58c 100644--- a/exllamav3/modules/foreign_linear.py+++ b/exllamav3/modules/foreign_linear.py@@ -27,6 +27,7 @@ from ..foreign_quant.gap_formats import dequant as gap_dequantfrom ..foreign_quant import triton_iqfrom ..foreign_quant import triton_gapfrom ..foreign_quant import triton_rows+from ..util.row_inv import GGUF_ROW_INV, GGUF_ROW_INV_MAX_ROWS, gguf_ri_ROWS_TRITON = os.environ.get("BOLT_FQ_ROWS_TRITON", "1") != "0"# Q8_0 rows 2..16 on CUDA: the Triton _rows_q8_0 kernel (tuned on Strix Halo) takes 172 us per launch on the 3090 (330 launches per step = 57 ms of an# 87 ms N8 step on the 35B-A3B UD-Q4_K_XL, 75 % of device time); the C++ q8_1 GEMV (fq_gemv_q8_0) takes 70-80 us. HIP keeps the Triton kernel.@@ -283,7 +284,8 @@ class ForeignLinear(Module):if not flat.is_contiguous():flat = flat.contiguous()out: Optional[torch.Tensor] = None- if (_MMQ_FEW and self.format in _MMQ_FEW_FMT and _MMQ_FEW_MINR[self.format] <= R <= 24 and flat.dtype == torch.half+ ri = gguf_ri("fl") and 2 <= R <= GGUF_ROW_INV_MAX_ROWS # row-invariant mode: every row gets the bits of the one-row launch+ if (_MMQ_FEW and not ri and self.format in _MMQ_FEW_FMT and _MMQ_FEW_MINR[self.format] <= R <= 24 and flat.dtype == torch.halfand K % 256 == 0 and K >= 2048 and hasattr(ext, "fq_mmq_few")and (self.format not in _MMQ_FEW_CAPTURE_ONLY or torch.cuda.is_current_stream_capturing())):N = self.out_features@@ -303,7 +305,11 @@ class ForeignLinear(Module):dev_idx = dev.index if dev.index is not None else torch.cuda.current_device()qb = ext.fq_q8_scratch(dev_idx, R, K)ext.fq_quant_q8_1_rows(flat, qb)- getattr(ext, _MMVQ_FN[self.format])(qb, self.packed.reshape(N, -1), out)+ if ri and R > 4: # 5..8 columns launch 2 warps per row (other sum order than the one-row launch's 4): at most 4 columns per launch+ for a in range(0, R, 4):+ getattr(ext, _MMVQ_FN[self.format])(qb[a:a + 4], self.packed.reshape(N, -1), out[a:a + 4])+ else:+ getattr(ext, _MMVQ_FN[self.format])(qb, self.packed.reshape(N, -1), out)if out.dtype != dtype:out = out.to(dtype)elif (_ROWS_TRITON and flat.dtype == torch.half and (_ROWS_TRITON_Q8 or self.format != "q8_0")diff --git a/exllamav3/modules/quant/fp16.py b/exllamav3/modules/quant/fp16.pyindex 3f48e8f..f03a738 100644--- a/exllamav3/modules/quant/fp16.py+++ b/exllamav3/modules/quant/fp16.py@@ -3,6 +3,7 @@ import torchfrom torch import nnfrom ...ext import exllamav3_ext as extimport os as _os+from ...util.row_inv import GGUF_ROW_INV, GGUF_ROW_INV_MAX_ROWS, gguf_ri_f32_via_f16 = _os.environ.get("EXL3_HIP_F32OUT_VIA_F16", "1") != "0" and bool(torch.version.hip)# 33, not 32: a 32-row multi-user verify step must stay on the exact row paths (a 32-row call widens an fp16 GEMM instead)_f32_via_f16_min_rows = int(_os.environ.get("EXL3_HIP_F32OUT_VIA_F16_MIN_ROWS", "33"))@@ -97,6 +98,10 @@ class LinearFP16:) -> torch.Tensor:out_shape = x.shape[:-1] + (self.out_features,)x = x.view(-1, x.shape[-1])+ if gguf_ri("fp16") and 2 <= x.shape[0] <= GGUF_ROW_INV_MAX_ROWS:+ # row-invariant few-row mode (GGUF + MTP): the dense GEMM of R rows picks another kernel than the one-row call;+ # one one-row call per row gives every row the bits of the plain step (these projections are tiny: gates, GDN a / b)+ return torch.cat([self.forward(x[i:i + 1], params, out_dtype) for i in range(x.shape[0])]).view(out_shape)dtype = out_dtype or self.out_dtype or torch.halfy = torch.empty((x.shape[0], self.out_features),diff --git a/exllamav3/util/row_inv.py b/exllamav3/util/row_inv.pyindex 2a6d9bd..a17772c 100644--- a/exllamav3/util/row_inv.py+++ b/exllamav3/util/row_inv.py@@ -16,6 +16,27 @@ ROW_INV = {"on": os.environ.get("EXL3_ROW_INV", "1") not in ("", "0")}ROW_INV_MAX_ROWS = max(1, int(os.environ.get("EXL3_ROW_INV_MAX_ROWS", "32" if torch.version.hip else "8")))+# GGUF / foreign-quant body (modules/foreign_linear.py): rows 2..GGUF_ROW_INV_MAX_ROWS of one forward (verify rows, a few sessions) run the same+# kernel arithmetic as the one-row step, so a greedy verify matches the plain step bit for bit. Off by default (the few-row int8 MMA kernel+# and the 5..8 column mmvq launch are faster); serve.py --gguf-mtp turns it on. Mutable at run time for one-load A/B (purge the graphs).+GGUF_ROW_INV = {"on": os.environ.get("EXL3_GGUF_ROW_INV", "0") not in ("", "0")}+GGUF_ROW_INV_MAX_ROWS = ROW_INV_MAX_ROWS+# EXL3_GGUF_RI_PARTS (A/B bisect only): comma list of the row-invariant parts to keep, from fl (ForeignLinear), fp16 (dense fp16 projections),+# router (per-row routing), moe (BlockSparseMLP row loop), attn (per-row verify attention). Default: all.+_RI_PARTS = set(os.environ.get("EXL3_GGUF_RI_PARTS", "fl,fp16,router,moe,attn").split(","))+++# The recurrent GDN kernel keeps the state of a multi-row call in registers in fp32 between rows (EXL3_GDN_RS_REG_GDN=1), the one-row step+# reloads it rounded to bf16 (EXL3_GDN_STATE_BF16): rows 2..R of a verify step then differ from the plain steps. The reload path+# rounds like the plain step, so row-invariant mode defaults to it (the caller's environment wins).+if GGUF_ROW_INV["on"]:+ os.environ.setdefault("EXL3_GDN_RS_REG_GDN", "0")+++def gguf_ri(part: str) -> bool:+ return GGUF_ROW_INV["on"] and part in _RI_PARTS++def job_slices(rows: int, w: int, cap: int) -> list:"""Row ranges (lo, hi) that cut `rows` verify rows into calls of at most `cap` rows. `w` is the rows of one job (consecutive rows ofone sequence share most of their experts, so whole jobs stay together when they fit, w > 1 and rows % w == 0). The slices arediff --git a/tools/qwen/gguf_mtp_fetch.py b/tools/qwen/gguf_mtp_fetch.pynew file mode 100644index 0000000..a2ff79d--- /dev/null+++ b/tools/qwen/gguf_mtp_fetch.py@@ -0,0 +1,123 @@+"""Fetch only the MTP head (mtp.* tensors) of a HF Qwen3.5 / 3.6 MoE checkpoint by HTTP range reads and store them as one+safetensors file, to sit beside a GGUF body (serve.py --gguf-mtp DIR).++ python tools/qwen/gguf_mtp_fetch.py --repo Qwen/Qwen3.6-35B-A3B --out DIR [--size-only]+"""+import argparse, json, os, struct, time, urllib.error, urllib.request+++def rng(url, a, b):+ req = urllib.request.Request(url, headers={"Range": f"bytes={a}-{b}"})+ for i in range(8):+ try:+ return urllib.request.urlopen(req).read()+ except urllib.error.HTTPError as e:+ if e.code != 429:+ raise+ time.sleep(15 * (i + 1))+ raise SystemExit("HTTP 429 persists")+++def experts_fp8(t, block=128):+ """Fused bf16 MoE experts -> one fp8 e4m3 tensor + weight_scale_inv block grid per expert projection (the engine's FP8 path,+ 1 byte per weight: the head's experts are 1.6 GB in bf16 and a 24 GB card running a GGUF body has no room for that)."""+ import torch+ out = {k: v for k, v in t.items() if not k.endswith(("experts.gate_up_proj", "experts.down_proj"))}+ def q(w):+ N, K = w.shape+ g = w.float().reshape(N // block, block, K // block, block)+ sc = (g.abs().amax(dim=(1, 3)) / 448.0).clamp(min=1e-12)+ return (g / sc[:, None, :, None]).clamp(-448, 448).reshape(N, K).to(torch.float8_e4m3fn), sc+ for k, v in t.items():+ if k.endswith("experts.gate_up_proj"):+ base, I = k[:-len("gate_up_proj")], v.shape[1] // 2+ dn = t[base + "down_proj"]+ for e in range(v.shape[0]):+ for name, w in (("gate_proj", v[e, :I]), ("up_proj", v[e, I:]), ("down_proj", dn[e])):+ out[f"{base}{e}.{name}.weight"], out[f"{base}{e}.{name}.weight_scale_inv"] = q(w.contiguous())+ return out+++GGML_TYPES = {"q4_k": (12, 144), "q5_k": (13, 176), "q6_k": (14, 210), "iq4_xs": (23, 136)} # ggml type id, bytes per 256 weights+++def experts_gguf(t, fmt, lib):+ """Fused bf16 MoE experts -> GGUF blocks (ggml_quantize_chunk of a llama.cpp libggml-base.so, no imatrix), one uint8 [N, K/256*bytes]+ tensor per expert projection: the head then runs on the same grouped K-quant MoE kernels as a GGUF body (q4_k: 0.56 byte per weight)."""+ import ctypes, torch+ ty, bb = GGML_TYPES[fmt]+ g = ctypes.CDLL(lib)+ g.ggml_quantize_chunk.restype = ctypes.c_size_t+ g.ggml_quantize_chunk.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_void_p]+ g.ggml_quantize_init.argtypes = [ctypes.c_int]+ g.ggml_quantize_init(ty)+ def q(w):+ N, K = w.shape+ assert K % 256 == 0, K+ src = w.float().contiguous()+ dst = torch.empty((N, K // 256 * bb), dtype=torch.uint8)+ n = g.ggml_quantize_chunk(ty, src.data_ptr(), dst.data_ptr(), 0, N, K, None)+ assert n == dst.numel(), (n, dst.numel())+ return dst+ out = {k: v for k, v in t.items() if not k.endswith(("experts.gate_up_proj", "experts.down_proj"))}+ for k, v in t.items():+ if k.endswith("experts.gate_up_proj"):+ base, I = k[:-len("gate_up_proj")], v.shape[1] // 2+ dn = t[base + "down_proj"]+ for e in range(v.shape[0]):+ for name, w in (("gate_proj", v[e, :I]), ("up_proj", v[e, I:]), ("down_proj", dn[e])):+ out[f"{base}{e}.{name}.weight"] = q(w.contiguous())+ return out+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--repo", default="Qwen/Qwen3.6-35B-A3B")+ ap.add_argument("--out", required=True)+ ap.add_argument("--size-only", action="store_true")+ ap.add_argument("--experts-fp8", action="store_true", help="store the routed experts as fp8 e4m3 + block scales (about half the size)")+ ap.add_argument("--experts-gguf", default="", choices=("", *GGML_TYPES), help="store the routed experts as GGUF blocks of this type (q4_k = 0.56 byte per weight)")+ ap.add_argument("--ggml-lib", default="", help="libggml-base.so of a llama.cpp build (for --experts-gguf)")+ ap.add_argument("--from-file", default="", help="convert an already fetched mtp safetensors instead of fetching")+ a = ap.parse_args()+ base = f"https://huggingface.co/{a.repo}/resolve/main/"+ idx = json.loads(urllib.request.urlopen(base + "model.safetensors.index.json").read())["weight_map"]+ keys = [k for k in idx if k.startswith("mtp.")]+ if a.from_file:+ from safetensors.torch import load_file, save_file+ os.makedirs(a.out, exist_ok=True)+ if a.experts_gguf:+ save_file(experts_gguf(load_file(a.from_file), a.experts_gguf, a.ggml_lib), os.path.join(a.out, f"mtp_{a.experts_gguf}e.safetensors"), metadata={"format": "pt"})+ return+ save_file(experts_fp8(load_file(a.from_file)), os.path.join(a.out, "mtp_fp8e.safetensors"), metadata={"format": "pt"})+ return+ hd, total = {}, 0+ for sh in sorted({idx[k] for k in keys}):+ n = struct.unpack("<Q", rng(base + sh, 0, 7))[0]+ hd[sh] = (8 + n, json.loads(rng(base + sh, 8, 8 + n - 1)))+ total += sum(hd[sh][1][k]["data_offsets"][1] - hd[sh][1][k]["data_offsets"][0] for k in keys if idx[k] == sh)+ print(f"{len(keys)} tensors, {total} bytes in {sorted(hd)}")+ if a.size_only:+ return+ import torch+ from safetensors.torch import save_file+ out = {}+ for sh, (off, h) in hd.items():+ for k in keys:+ if idx[k] != sh:+ continue+ m = h[k]; lo, hi = m["data_offsets"]; buf = bytearray(); p = lo+ while p < hi:+ q = min(hi, p + (256 << 20)) - 1+ buf += rng(base + sh, off + p, off + q); p = q + 1+ dt = {"BF16": torch.bfloat16, "F16": torch.float16, "F32": torch.float32}[m["dtype"]]+ out[k] = torch.frombuffer(buf, dtype=dt).reshape(m["shape"]).clone()+ os.makedirs(a.out, exist_ok=True)+ if a.experts_fp8:+ save_file(experts_fp8(out), os.path.join(a.out, "mtp_fp8e.safetensors"), metadata={"format": "pt"})+ return+ save_file(out, os.path.join(a.out, "mtp_bf16.safetensors"), metadata={"format": "pt"})+++if __name__ == "__main__":+ main()diff --git a/tools/qwen/serve.py b/tools/qwen/serve.pyindex 2023c39..94ab484 100644--- a/tools/qwen/serve.py+++ b/tools/qwen/serve.py@@ -2529,7 +2529,7 @@ def load_all(args: argparse.Namespace):f"defaults={ {k: v for k, v in defaults.items() if v is not None} }", flush=True)engine = QwenEngine(model_dir, args.ctx, ndt=args.ndt, draft_policy=args.draft_policy, vision=not args.no_vision,cache_bits=args.cache_bits, sessions=args.sessions,- k_bits=args.k_bits, v_bits=args.v_bits, dflash_dir=str(Path(args.dflash_dir).expanduser()), kv_mode=args.kv_mode)+ k_bits=args.k_bits, v_bits=args.v_bits, dflash_dir=str(Path(args.dflash_dir).expanduser()), kv_mode=args.kv_mode, max_chunk_size=args.max_chunk)env = {k: v for k, v in sorted(os.environ.items()) if k.startswith(("EXL3_", "MPW"))}print(f"qserve: effective env {env}", flush=True)from exllamav3.generator.slot_store import SlotStore@@ -2591,6 +2591,9 @@ def main() -> None:parser.add_argument("--kvwin", default=None, metavar="SINK:WINDOW",help="fp16 sink + window ring of the quantized cache (EXL3_KVWIN, e.g. 4:128; an EXL3_KVWIN already set wins); written by tools/qualify as the kw6 choice")parser.add_argument("--ndt", type=int, default=7, help="max draft tokens per round (default 7; the rule drafts up to 3 for most rounds, deeper only on confident chains)")+ parser.add_argument("--gguf-mtp", default="", help="GGUF body: directory with the MTP head tensors (mtp.* safetensors, tools/qwen/gguf_mtp_fetch.py); "+ "sets KYO_GGUF_MTP, use with --draft-policy mix|mtp")+ parser.add_argument("--max-chunk", type=int, default=2048, help="prefill rows per forward (default 2048); a smaller chunk frees activation memory on a full card")parser.add_argument("--draft-policy", choices=("mix", "mtp", "dflash", "off"), default="mix",help="mix = shipped rule (MTP + n-gram lookup, lossless), mtp = fixed MTP chain, dflash = DFlash2 block drafter ""from --dflash-dir (lossless; see --dflash-adapt), off = plain decode")@@ -2620,6 +2623,10 @@ def main() -> None:"pages for its prompt + reply budget when it starts, so a request that does not fit waits. A reply longer than ""its share of the context (-c / sessions) is requeued, not reserved up front")args = parser.parse_args()+ if args.gguf_mtp:+ os.environ["KYO_GGUF_MTP"] = os.path.abspath(os.path.expanduser(args.gguf_mtp))+ os.environ.setdefault("EXL3_GDN_RS_REG_GDN", "0") # GDN state of verify rows rounded to bf16 like the plain step+ os.environ.setdefault("EXL3_GGUF_ROW_INV", "1") # greedy verify rows = the one-row step's bits (util/row_inv.py GGUF_ROW_INV)if args.ngram_ram:os.environ["EXL3_NGRAM_STREAM"] = "0"if args.draft_policy == "dflash" and not args.dflash_dir: