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 and stored-format decode on HIP and CUDA, version 1.8.17 (#194)
Yaniss Amazouz14df5fd228b9
diff --git a/exllamav3/architecture/minicpm_v47.py b/exllamav3/architecture/minicpm_v47.pyindex 6eef146..2206f62 100644--- a/exllamav3/architecture/minicpm_v47.py+++ b/exllamav3/architecture/minicpm_v47.py@@ -39,7 +39,9 @@ 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", 8: "q8_0", 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",+ # ForeignLinear gap formats (fused Triton decode, torch dequant otherwise): unsloth UD-IQ packs mix these into the experts+ 16: "iq2_xxs", 17: "iq2_xs", 18: "iq3_xxs", 21: "iq3_s", 22: "iq2_s", 20: "iq4_nl", 2: "q4_0", 6: "q5_0", 7: "q5_1", 10: "q2_k", 11: "q3_k"}P = "model.language_model"@@ -106,9 +108,12 @@ class MiniCPMV47Config(Config):self.linear_key_head_dim = self.read_cfg(int, pfx("linear_key_head_dim"), 128)self.linear_value_head_dim = self.read_cfg(int, pfx("linear_value_head_dim"), 128)self.assert_cfg(str, pfx("hidden_act"), "silu", True)- self.moe_intermediate_size = self.read_cfg(int, pfx("moe_intermediate_size"), no_default)- self.num_experts = self.read_cfg(int, pfx("num_experts"), no_default)- self.num_experts_per_tok = self.read_cfg(int, pfx("num_experts_per_tok"), no_default)+ # dense variant (gguf qwen35): intermediate_size and no experts; the MoE fields stay None+ self.intermediate_size = self.read_cfg(int, pfx("intermediate_size"), None)+ moe_def = None if self.intermediate_size else no_default+ self.moe_intermediate_size = self.read_cfg(int, pfx("moe_intermediate_size"), moe_def)+ self.num_experts = self.read_cfg(int, pfx("num_experts"), moe_def)+ self.num_experts_per_tok = self.read_cfg(int, pfx("num_experts_per_tok"), moe_def)self.shared_expert_intermediate_size = self.read_cfg(int, pfx("shared_expert_intermediate_size"), 512)self.rms_norm_eps = self.read_cfg(float, pfx("rms_norm_eps"), no_default)@@ -153,10 +158,10 @@ class MiniCPMV47Config(Config):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, no- # per-block Python). Format-generic (IQ4_XS / Q4_K).- from ..foreign_quant.k_quants import dequant_iq4_xs_bulk, dequant_q4_K_bulk+ # per-block Python). Format-generic (IQ4_XS / Q4_K / Q6_K / Q8_0).+ from ..foreign_quant.k_quants import dequant_iq4_xs_bulk, dequant_q4_K_bulk, dequant_q6_K_bulkty, dims, off = self.gguf.infos["token_embd.weight"]- bbs = {23: 136, 12: 144, 8: 34}+ bbs = {23: 136, 12: 144, 14: 210, 8: 34}assert ty in bbs, f"token_embd type {ty}"bb = bbs[ty]K, N = dims[0], dims[1]@@ -170,7 +175,7 @@ class MiniCPMV47Config(Config):assert K % 256 == 0raw = self.gguf._pread(off, N * (K // 256) * bb).reshape(N, (K // 256) * bb)nb = N * (K // 256)- bulk = dequant_iq4_xs_bulk if ty == 23 else dequant_q4_K_bulk+ bulk = {23: dequant_iq4_xs_bulk, 12: dequant_q4_K_bulk, 14: dequant_q6_K_bulk}[ty]w = bulk(raw.reshape(nb, bb)).reshape(N, K)self.gguf.new_tensors = {f"{P}.embed_tokens.weight": torch.from_numpy(np.ascontiguousarray(w))}@@ -358,6 +363,16 @@ class MiniCPMV47TextModel(Model):@staticmethoddef _moe(config, L, G, H):+ if config.num_experts is None: # dense block (gguf qwen35): one gated MLP+ I = config.intermediate_size+ 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, select_hq_bits=2,+ gates=[_fl(config, f"{G}.ffn_gate", H, I)], ups=[_fl(config, f"{G}.ffn_up", H, I)],+ downs=[_fl(config, f"{G}.ffn_down", I, H, out_dtype=torch.float)])+ for m in mlp.gates + mlp.ups + mlp.downs:+ mlp.register_submodule(m)+ return mlpI = config.moe_intermediate_sizeE = config.num_expertsif MCPM_FOREIGN:diff --git a/exllamav3/architecture/qwen4_exp.py b/exllamav3/architecture/qwen4_exp.pyindex 7925d45..e46fbcf 100644--- a/exllamav3/architecture/qwen4_exp.py+++ b/exllamav3/architecture/qwen4_exp.py@@ -84,6 +84,81 @@ class Qwen4ExpConfig(Qwen3_5VLMoeBaseConfig):self.heads_per_ngram = self.read_cfg(int, pfx("heads_per_ngram"), no_default)self.ple_eos_token_id = self.read_cfg(int, pfx("eos_token_id"), no_default)+ # Plain GGUF config dir: GGUF backing store (weights served as stored, see _init_gguf)+ self.gguf = None+ if os.path.exists(os.path.join(directory, "model.gguf")):+ self._init_gguf(directory)++ def _init_gguf(self, directory: str):+ import json+ import numpy as np+ from ..loader.gguf_collection import GGUFCollection+ from ..loader.gguf_config import name_map_qwen4exp+ from .minicpm_v47 import _GGML_FMT, MiniCPMV47Config, _alog_override, _fp_override+ from ..foreign_quant.q8_0 import dequant_q8_0+ with open(os.path.join(directory, "config.json"), encoding = "utf8") as f:+ cfg = json.load(f)+ g = self.gguf = GGUFCollection(os.path.join(directory, "model.gguf"))+ g.name_map = nm = name_map_qwen4exp(cfg)+ self.stc = g+ self.gguf_formats = {n: _GGML_FMT.get(ty, f"unk{ty}") for n, (ty, _, _) in g.infos.items()}+ MiniCPMV47Config._load_embedding_override(self) # token_embd -> fp16 once (sets g.new_tensors)+ ov = g.new_tensors+ raw = lambda gname: g.get_tensor(gname).float() # F32 / BF16 in HF orientation [out, in]++ def q8(gname): # Q8_0 -> fp32, HF orientation [N, K]+ ty, dims, _ = g.infos[gname]+ assert ty == 8, (gname, ty)+ r = g.get_tensor(gname).numpy()+ K, N = dims[0], dims[1]+ return torch.from_numpy(np.ascontiguousarray(dequant_q8_0(r.reshape(N * (K // 32), 34)).reshape(N, K).astype(np.float32)))++ P = "model.language_model"+ for ek, gname in nm.items():+ if not isinstance(gname, str) or gname not in g.infos:+ continue+ if gname.endswith("norm.weight") and not gname.endswith("ssm_norm.weight"):+ ov[ek] = raw(gname) - 1.0 # GGUF stores 1 + w (zero-centered norms)+ elif gname.endswith("conv1d.weight"):+ ov[ek] = raw(gname).unsqueeze(1).contiguous() # (C, K) -> (C, 1, K)+ elif gname.endswith("ffn_gate_inp_shexp.weight"):+ ov[ek] = raw(gname).reshape(-1, 1).contiguous() # Linear override: engine orientation [in, out]+ elif (".hc_" in gname or gname.startswith("output_hc_")) and gname.endswith(("_down.weight", "_up.weight")):+ ov[ek] = q8(gname) # hyper-connection mixers are read raw by the module+ for i, lt in enumerate(self.layer_types):+ L = f"{P}.layers.{i}"+ if lt == "linear_attention":+ _alog_override(self, f"{L}.linear_attn.A_log", f"blk.{i}.ssm_a")+ _fp_override(self, f"{L}.linear_attn.in_proj_b.weight", f"blk.{i}.ssm_beta.weight")+ _fp_override(self, f"{L}.linear_attn.in_proj_a.weight", f"blk.{i}.ssm_alpha.weight")+ else:+ qk = torch.cat([raw(f"blk.{i}.indexer.q_proj.weight"), raw(f"blk.{i}.indexer.k_proj.weight")], 0)+ ov[f"{L}.self_attn.indexer.index_qk_proj.weight"] = qk.T.contiguous() # engine fp orientation [in, out]+++def _gguf_moe(config, key, layer_idx, qbits_key):+ from .minicpm_v47 import _fl+ H, I, E, SI = config.hidden_size, config.moe_intermediate_size, config.num_experts, config.shared_expert_intermediate_size+ G = f"blk.{layer_idx}"+ gates = [_fl(config, f"{G}.ffn_gate_exps.e{e}", H, I) for e in range(E)]+ ups = [_fl(config, f"{G}.ffn_up_exps.e{e}", H, I) for e in range(E)]+ downs = [_fl(config, f"{G}.ffn_down_exps.e{e}", I, H, out_dtype = torch.float) for e in range(E)]+ sh = GatedMLP(+ config = config, key = f"{key}.mlp.shared_expert", hidden_size = H, intermediate_size = SI,+ qmap = "block.mlp", interm_dtype = torch.half, out_dtype = torch.float, select_hq_bits = 2,+ gates = [_fl(config, f"{G}.ffn_gate_shexp", H, SI)], ups = [_fl(config, f"{G}.ffn_up_shexp", H, SI)],+ downs = [_fl(config, f"{G}.ffn_down_shexp", SI, H, out_dtype = torch.float)])+ for m in sh.gates + sh.ups + sh.downs:+ sh.register_submodule(m)+ mlp = BlockSparseMLP(+ config = config, key = f"{key}.mlp", hidden_size = H, intermediate_size = I, num_experts = E,+ num_experts_per_tok = config.num_experts_per_tok, key_up = None, key_gate = None, key_down = None,+ key_routing_gate = "gate", key_shared_gate = "shared_expert_gate", qmap = "block.mlp",+ interm_dtype = torch.half, out_dtype = torch.float, gates = gates, ups = ups, downs = downs, shared_experts = sh)+ for m in gates + ups + downs:+ mlp.register_submodule(m)+ return mlp+def build_qwen4_block(config: Qwen4ExpConfig,@@ -131,6 +206,7 @@ def build_qwen4_block(key_a = "in_proj_a",key_norm = "norm",key_o = "out_proj",+ blocked_gqa = getattr(config, "gguf", None) is not None,norm = GatedRMSNorm(config, f"{key}.linear_attn.norm",config.rms_norm_eps, out_dtype = torch.half,@@ -187,7 +263,7 @@ def build_qwen4_block(),)),- mlp = BlockSparseMLP(+ mlp = _gguf_moe(config, key, layer_idx, qbits_key) if getattr(config, "gguf", None) is not None else BlockSparseMLP(config = config,key = f"{key}.mlp",hidden_size = config.hidden_size,diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cppindex 02ae020..9515bab 100644--- a/exllamav3/exllamav3_ext/bindings.cpp+++ b/exllamav3/exllamav3_ext/bindings.cpp@@ -623,6 +623,12 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)py::arg("qb"), py::arg("packed"), py::arg("out"));m.def("fq_gemv_iq4_xs_q8", &fq_gemv_iq4_xs_q8, "fq_gemv_iq4_xs_q8",py::arg("qb"), py::arg("packed"), py::arg("out"));+ m.def("fq_gemv_iq3_xxs_q8", &fq_gemv_iq3_xxs_q8, "fq_gemv_iq3_xxs_q8",+ py::arg("qb"), py::arg("packed"), py::arg("out"));+ m.def("fq_gemv_iq2_s_q8", &fq_gemv_iq2_s_q8, "fq_gemv_iq2_s_q8",+ py::arg("qb"), py::arg("packed"), py::arg("out"));+ m.def("fq_gemv_iq3_s_q8", &fq_gemv_iq3_s_q8, "fq_gemv_iq3_s_q8",+ py::arg("qb"), py::arg("packed"), py::arg("out"));// grouped KQ/IQ4_XS decode MoE (fq_moe_kq.cu): portable dp4a kernels, built on ROCm toom.def("fq_moe_q4k_grouped_q8", &fq_moe_q4k_grouped_q8, "fq_moe_q4k_grouped_q8",py::arg("h"), py::arg("sel"), py::arg("wts"),diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_api.h b/exllamav3/exllamav3_ext/foreign_quant/fq_api.hindex 3367061..0ce6961 100644--- a/exllamav3/exllamav3_ext/foreign_quant/fq_api.h+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_api.h@@ -49,6 +49,9 @@ void fq_gemv_q4_k_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);void fq_gemv_q5_k_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);void fq_gemv_q6_k_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);void fq_gemv_iq4_xs_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);+void fq_gemv_iq3_xxs_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);+void fq_gemv_iq2_s_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);+void fq_gemv_iq3_s_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);// q8_1-activation grouped MoE for KQ/IQ4_XS SwiGLU experts (fq_moe_kq.cu):// gate/up/down_ptrs = per-expert base addresses (E int64);// strides are per-row bytes; partial = [S, K] float scratch.diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_gemv.cuh b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv.cuhindex 96ebcd7..eb9895f 100644--- a/exllamav3/exllamav3_ext/foreign_quant/fq_gemv.cuh+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv.cuh@@ -8,6 +8,7 @@#include <cstdlib>#include <cuda_fp16.h>#include "fq_dequant.cuh"+#include "fq_iq3_tables.cuh"namespace {@@ -79,6 +80,11 @@ __device__ __forceinline__ int fq_dp4a(int a, int b, int c){#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 610return __dp4a(a, b, c);+#elif defined(__HIP_DEVICE_COMPILE__) && (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || \+ defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__) || defined(__gfx1200__) || defined(__gfx1201__))+ // RDNA3 / RDNA3.5 / RDNA4: v_dot4_i32_iu8, signed x signed, no clamp (same call as llama.cpp ggml-cuda/common.cuh+ // ggml_cuda_dp4a, MIT). Exact integer dot: same results as the scalar arm below, which the compiler only sometimes fused.+ return __builtin_amdgcn_sudot4(true, a, true, b, c, false);#elseconst int8_t* a8 = reinterpret_cast<const int8_t*>(&a);const int8_t* b8 = reinterpret_cast<const int8_t*>(&b);@@ -923,6 +929,146 @@ __device__ __forceinline__ void fq_q4k_scales(const uint8_t* __restrict__ sc12,// Q4_K q8_1 lane dot: per-thread partial over 16-elem sub-chunks// (t = c & 15 within each 256-block b = c >> 4). Same integer arithmetic// and op order as ggml vec_dot_q4_K_q8_1 (vmmq arm).++// IQ3_XXS q8_1 lane dot (port of ggml vec_dot_iq3_xxs_q8_1, llama.cpp ggml-cuda/vecdotq.cuh, MIT): block = fp16 d, 64 grid indices,+// 8 x uint32 (4 x 7-bit sign index | 4-bit scale << 28). One lane takes 32-element chunks round-robin; per chunk 4 pairs of grid+// entries, signs applied bytewise without borrow (grid bytes are >= 4), 8 dp4a against the q8_1 chunk, then ggml's (ls*s + s/2)/2.+#define FQ_IQ3_XXS_BYTES 98+__device__ float fq_dot_iq3_xxs_q8(const uint8_t* __restrict__ wr,+ const uint8_t* __restrict__ aqb,+ int K, int tid, int nthreads)+{+ int nchunks = K / 32;+ float acc = 0.0f;+ for (int c = tid; c < nchunks; c += nthreads)+ {+ const uint8_t* blk = wr + (size_t)(c >> 3) * FQ_IQ3_XXS_BYTES;+ int sub = c & 7;+ __half dwh;+ memcpy(&dwh, blk, 2);+ const uint8_t* q3 = blk + 2 + sub * 8;+ uint32_t aux32;+ memcpy(&aux32, blk + 2 + 64 + sub * 4, 4);+ __half dah;+ memcpy(&dah, aqb + (size_t)c * FQ_Q8_1_BYTES, 2);+ const int32_t* aq32 = reinterpret_cast<const int32_t*>(aqb + (size_t)c * FQ_Q8_1_BYTES + 4);+ int sumi = 0;+ #pragma unroll+ for (int p = 0; p < 4; p++)+ {+ uint32_t si = (aux32 >> (7 * p)) & 127u;+ uint32_t slo = FQ_IQ3XXS_SIGNS32[2 * si];+ uint32_t shi = FQ_IQ3XXS_SIGNS32[2 * si + 1];+ uint32_t w0 = (FQ_IQ3XXS_GRID[q3[2 * p]] ^ slo) + (slo & 0x01010101u);+ uint32_t w1 = (FQ_IQ3XXS_GRID[q3[2 * p + 1]] ^ shi) + (shi & 0x01010101u);+ sumi = fq_dp4a((int32_t)w0, aq32[2 * p], sumi);+ sumi = fq_dp4a((int32_t)w1, aq32[2 * p + 1], sumi);+ }+ int ls = (int)(aux32 >> 28);+ sumi = (ls * sumi + sumi / 2) / 2;+ acc = __fadd_rn(acc, __fmul_rn(__fmul_rn(__half2float(dwh), __half2float(dah)), (float)sumi));+ }+ return acc;+}+++// IQ2_S q8_1 lane dot (port of ggml vec_dot_iq2_s_q8_1, llama.cpp ggml-cuda/vecdotq.cuh, MIT): block = fp16 d, 32 grid low bytes,+// 32 sign bytes, 8 qh (2 high index bits per grid entry), 8 scales (4-bit, one per 16 elements). One lane takes 32-element chunks+// round-robin; per chunk 4 grid entries of 8, explicit sign bytes applied without borrow (grid bytes are >= 8), 8 dp4a, then+// ggml's (s0*ls0 + s1*ls1 + (s0 + s1)/2)/4.+#define FQ_IQ2_S_BYTES 82+__device__ __forceinline__ uint32_t fq_sign_mask4(uint32_t b)+{+ return ((b * 0x00204081u) & 0x01010101u) * 0xFFu; // bit i of the low nibble -> byte i = 0xFF+}+__device__ float fq_dot_iq2_s_q8(const uint8_t* __restrict__ wr,+ const uint8_t* __restrict__ aqb,+ int K, int tid, int nthreads)+{+ int nchunks = K / 32;+ float acc = 0.0f;+ for (int c = tid; c < nchunks; c += nthreads)+ {+ const uint8_t* blk = wr + (size_t)(c >> 3) * FQ_IQ2_S_BYTES;+ int j = c & 7;+ __half dwh;+ memcpy(&dwh, blk, 2);+ const uint8_t* qs = blk + 2 + j * 4;+ const uint8_t* sg = blk + 2 + 32 + j * 4;+ uint32_t qh = blk[2 + 64 + j];+ uint32_t sc = blk[2 + 72 + j];+ __half dah;+ memcpy(&dah, aqb + (size_t)c * FQ_Q8_1_BYTES, 2);+ const int32_t* aq32 = reinterpret_cast<const int32_t*>(aqb + (size_t)c * FQ_Q8_1_BYTES + 4);+ int sumi0 = 0, sumi1 = 0;+ #pragma unroll+ for (int p = 0; p < 4; p++)+ {+ uint32_t idx = (uint32_t)qs[p] | ((qh << (8 - 2 * p)) & 0x300u);+ uint32_t mlo = fq_sign_mask4(sg[p] & 15u);+ uint32_t mhi = fq_sign_mask4(sg[p] >> 4);+ uint32_t w0 = (FQ_IQ2S_GRID[2 * idx] ^ mlo) + (mlo & 0x01010101u);+ uint32_t w1 = (FQ_IQ2S_GRID[2 * idx + 1] ^ mhi) + (mhi & 0x01010101u);+ if (p < 2)+ {+ sumi0 = fq_dp4a((int32_t)w0, aq32[2 * p], sumi0);+ sumi0 = fq_dp4a((int32_t)w1, aq32[2 * p + 1], sumi0);+ }+ else+ {+ sumi1 = fq_dp4a((int32_t)w0, aq32[2 * p], sumi1);+ sumi1 = fq_dp4a((int32_t)w1, aq32[2 * p + 1], sumi1);+ }+ }+ int sumi = (sumi0 * (int)(sc & 15u) + sumi1 * (int)(sc >> 4) + (sumi0 + sumi1) / 2) / 4;+ acc = __fadd_rn(acc, __fmul_rn(__fmul_rn(__half2float(dwh), __half2float(dah)), (float)sumi));+ }+ return acc;+}+++// IQ3_S q8_1 lane dot (port of ggml vec_dot_iq3_s_q8_1, llama.cpp ggml-cuda/vecdotq.cuh, MIT): block = fp16 d, qs[64], qh[8] (9th index+// bit per grid entry), signs[32], scales[4] (4-bit, one per 32 elements, value 1 + 2 s). One lane takes 32-element chunks round-robin:+// 8 grid entries of 4, explicit sign bytes applied without borrow (grid bytes are >= 1), 8 dp4a.+#define FQ_IQ3_S_BYTES 110+__device__ float fq_dot_iq3_s_q8(const uint8_t* __restrict__ wr,+ const uint8_t* __restrict__ aqb,+ int K, int tid, int nthreads)+{+ int nchunks = K / 32;+ float acc = 0.0f;+ for (int c = tid; c < nchunks; c += nthreads)+ {+ const uint8_t* blk = wr + (size_t)(c >> 3) * FQ_IQ3_S_BYTES;+ int j = c & 7;+ __half dwh;+ memcpy(&dwh, blk, 2);+ const uint8_t* qs = blk + 2 + j * 8;+ uint32_t qh = blk[2 + 64 + j];+ const uint8_t* sg = blk + 2 + 72 + j * 4;+ uint32_t sc = (blk[2 + 104 + j / 2] >> (4 * (j & 1))) & 15u;+ __half dah;+ memcpy(&dah, aqb + (size_t)c * FQ_Q8_1_BYTES, 2);+ const int32_t* aq32 = reinterpret_cast<const int32_t*>(aqb + (size_t)c * FQ_Q8_1_BYTES + 4);+ int sumi = 0;+ #pragma unroll+ for (int p = 0; p < 4; p++)+ {+ uint32_t i0 = (uint32_t)qs[2 * p] | ((qh << (8 - 2 * p)) & 0x100u);+ uint32_t i1 = (uint32_t)qs[2 * p + 1] | ((qh << (7 - 2 * p)) & 0x100u);+ uint32_t mlo = fq_sign_mask4(sg[p] & 15u);+ uint32_t mhi = fq_sign_mask4(sg[p] >> 4);+ uint32_t w0 = (FQ_IQ3S_GRID[i0] ^ mlo) + (mlo & 0x01010101u);+ uint32_t w1 = (FQ_IQ3S_GRID[i1] ^ mhi) + (mhi & 0x01010101u);+ sumi = fq_dp4a((int32_t)w0, aq32[2 * p], sumi);+ sumi = fq_dp4a((int32_t)w1, aq32[2 * p + 1], sumi);+ }+ sumi *= 1 + 2 * (int)sc;+ acc = __fadd_rn(acc, __fmul_rn(__fmul_rn(__half2float(dwh), __half2float(dah)), (float)sumi));+ }+ return acc;+}+__device__ float fq_dot_q4_k_q8(const uint8_t* __restrict__ wr,const uint8_t* __restrict__ aqb,int K, int tid, int nthreads)diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_kq.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_kq.cuindex e89d3f3..27ed5fb 100644--- a/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_kq.cu+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_kq.cu@@ -9,11 +9,17 @@// shared-memory reduction, fq_dp4a + fq_vsub4 builtins with scalar// fallbacks off-CUDA).#include <cuda_fp16.h>+#include <cstdint>+#include <cstdlib>+#include <cstring>+#include <type_traits>#include <torch/extension.h>#include <c10/cuda/CUDAGuard.h>#include <ATen/cuda/CUDAContext.h>#include "../util.h"#include "fq_gemv.cuh"+#include "fq_kq_item.cuh"+#include "fq_kq_wmma.cuh"#include "fq_api.h"namespace {@@ -49,8 +55,14 @@ __global__ void fq_gemv_kq_kernel(const uint8_t* __restrict__ aqb,acc = fq_dot_q5_k_q8(wr, aq, K, tid, nt);else if constexpr (FMT == 2)acc = fq_dot_q6_k_q8(wr, aq, K, tid, nt);- else+ else if constexpr (FMT == 3)acc = fq_dot_iq4_xs_q8(wr, aq, K, tid, nt);+ else if constexpr (FMT == 4)+ acc = fq_dot_iq3_xxs_q8(wr, aq, K, tid, nt);+ else if constexpr (FMT == 5)+ acc = fq_dot_iq2_s_q8(wr, aq, K, tid, nt);+ else+ acc = fq_dot_iq3_s_q8(wr, aq, K, tid, nt);}red[tid] = acc;__syncthreads();@@ -66,8 +78,623 @@ __global__ void fq_gemv_kq_kernel(const uint8_t* __restrict__ aqb,}}+// ---------------------------------------------------------------------------+// Q4_K / Q6_K decode GEMV v2 ("rows" kernel): same float result bit for bit as+// fq_gemv_kq_kernel above, but built for memory-level parallelism.+//+// What the v1 kernel above does wrong on a GPU with a deep memory pipeline (RTX 3090: Q4_K ran at ~36 % of+// the DRAM roof, llama.cpp mmvq at ~70 %):+// - its weight loads are memcpy() from a uint8_t*, which the compiler must treat as byte-aligned: LDG.U8+// chains instead of one 16-byte load per thread;+// - one 2.3 KB row per 256-thread block, and thread 0 then adds the 256 partials one after the other+// (about 1 us of dependent adds), so a block spends half of its life with no load in flight.+//+// v2: an "item" is the work one thread does with ONE aligned wide load pair (Q4_K: two 16-byte loads = 4 of+// the v1 chunks; Q6_K: 4 chunks from u16 pairs, the block is 210 bytes so only 2-byte aligned, like ggml+// get_int_b2). Items of ROWS output rows go to shared memory as per-chunk float values; then ROWS threads+// (one per row) add them in EXACTLY the order v1 does (per-lane partial c = l, l + nt, ..., then lane by lane),+// so every output is bit-identical to v1 (the integer dp4a parts are exact; only the float order matters and+// it is kept). The serial add chain is now shared by ROWS rows per block and overlaps with the loads of the+// other resident blocks.+//+// Dot structure after ggml-cuda mmvq vec_dot_q4_K_q8_1 / vec_dot_q6_K_q8_1 (llama.cpp ggml/src/ggml-cuda/+// vecdotq.cuh, MIT, Copyright (c) 2023-2024 The ggml authors). Portable like the rest of fq_*: no PTX, no+// shuffles (HIP builds the same source; fq_dp4a is sudot4 there).+// ---------------------------------------------------------------------------++// fq_h2f_lo, fq_ld_u16x2, fq_kq_item_q4_k, fq_kq_item_q6_k: fq_kq_item.cuh (shared with fq_moe_kq.cu)++// One block = ROWS consecutive output rows of x-row m = blockIdx.x / nbn, 64 threads per row. Thread j of a row owns+// the items j, j + 64, j + 128, ... (one 256-chunk window of v1 per step); those items are chunks whose v1 lane+// (c mod nt, nt = 256 when K >= 4096 / 2048) is fixed, so thread j keeps four v1 lane partials in registers, adding+// the windows in increasing order exactly as v1's per-thread loop does. The nt lane partials go to shared memory+// (row stride 260 floats: the ROWS chain threads hit different banks), then thread r < ROWS adds row r lane by lane+// in v1's order. Lanes >= nsub (K small, nt padded to a multiple of 32) are written as 0.0f like v1's idle threads.+template <typename OUT, int FMT, int ROWS>+__global__ void __launch_bounds__(64 * ROWS) fq_gemv_kq_rows_kernel(const uint8_t* __restrict__ aqb,+ const uint8_t* __restrict__ packed,+ OUT* __restrict__ out,+ int N, int K, int64_t packed_stride, int64_t qb_stride,+ int nbn, int nt)+{+ constexpr int PS = 260;+ __shared__ __align__(16) float part[ROWS * PS];+ constexpr int IPB = (FMT == 0) ? 4 : 8; // items per 256-block+ const int tid = threadIdx.x;+ const int r = tid >> 6, j = tid & 63;+ const int m = blockIdx.x / nbn;+ const int n0 = (blockIdx.x - m * nbn) * ROWS;+ const int n = n0 + r;+ const int nitems = (K / 256) * IPB;+ float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};+ if (n < N)+ {+ const uint8_t* aq = aqb + (int64_t)m * qb_stride;+ const uint8_t* wr = packed + (int64_t)n * packed_stride;+ for (int it = j; it < nitems; it += 64)+ {+ float t[4];+ if constexpr (FMT == 0)+ fq_kq_item_q4_k(wr, aq, it, t);+ else+ fq_kq_item_q6_k(wr, aq, it, t);+ #pragma unroll+ for (int q = 0; q < 4; q++)+ acc[q] = __fadd_rn(acc[q], t[q]);+ }+ }+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ const int lane = (FMT == 0) ? (4 * j + q) : (32 * (j >> 3) + (j & 7) + 8 * q);+ if (lane < nt)+ part[r * PS + lane] = acc[q];+ }+ __syncthreads();+ if (tid < ROWS && n0 + tid < N)+ {+ const float4* pv = reinterpret_cast<const float4*>(part + tid * PS);+ float s = 0.0f;+ #pragma unroll 8+ for (int l = 0; l < nt / 4; l++)+ {+ const float4 v = pv[l];+ s = __fadd_rn(s, v.x);+ s = __fadd_rn(s, v.y);+ s = __fadd_rn(s, v.z);+ s = __fadd_rn(s, v.w);+ }+ if constexpr (std::is_same<OUT, __half>::value)+ out[(int64_t)m * N + n0 + tid] = __float2half_rn(s);+ else+ out[(int64_t)m * N + n0 + tid] = s;+ }+}+++// ---------------------------------------------------------------------------+// Q4_K / Q6_K multi-row decode GEMV (R = 2..16 x-rows: multi-user decode, verify). Every weight block is loaded and+// unpacked ONCE per output row and dotted with all R q8_1 activation rows (the one-row kernels re-read the weights per+// x-row, the Triton rows kernels run at Triton speed; ggml mmvq does the same with ncols_dst <= 8). The weight half of+// fq_kq_item_q4_k / _q6_k is split from its activation half; the activation half repeats the item's float expressions in+// the same order, so output row m is bit-identical to the one-row kernel's output for x-row m: the batch composition+// never changes a result (tests/test_kq_gemv_mrows.py).+//+// Activations: the q8_1 blocks (36 bytes, 4-byte aligned) are read by 32 lanes with a 72-byte stride, and R rows multiply the loads.+// fq_kq_act_pack re-lays the R rows once per call (a tiny kernel, one thread per item) into "records" of 64 items (one window of the+// one-row kernel's thread loop) in structure-of-arrays form, so that lane j of a 64-thread row reads consecutive words (measured on the+// RTX 3090, 8B gate/up shape, 8 x-rows: 240 -> 154 us with this and the padded partial buffer):+// Q4_K record (1088 words): qs[w * 64 + j], w = 0..15 = the 16 words of the item's two q8_1 blocks (block 2g words 1..8, block+// 2g+1 words 1..8); dd[j] = d(block 2g) | d(block 2g+1) << 16 (the low halves of their word 0).+// Q6_K record (576 words): qs[s * 64 + j], s = 0..7 = word 1 + p of q8_1 block 8b + s; dd[s * 8 + (j >> 3)] = word 0 of that block.+// Dot structure after ggml-cuda mmvq vec_dot_q4_K_q8_1 / vec_dot_q6_K_q8_1 (llama.cpp ggml/src/ggml-cuda/vecdotq.cuh, MIT, Copyright+// (c) 2023-2024 The ggml authors), as the one-row items it mirrors. All integers are copied unchanged. The dot product's int -> float conversions use the exact magic-number form (every+// integer here is below 2^22 in magnitude), which runs on the integer/FP pipes instead of the quarter-rate conversion unit.+// ---------------------------------------------------------------------------++constexpr int FQ_KQ_REC_Q4 = 1088;+constexpr int FQ_KQ_REC_Q6 = 576;++template <int FMT>+__global__ void fq_kq_act_pack_kernel(const uint8_t* __restrict__ aqb, uint32_t* __restrict__ rec, int M, int nwin, int nitems,+ int64_t qb_stride)+{+ constexpr int RECW = (FMT == 0) ? FQ_KQ_REC_Q4 : FQ_KQ_REC_Q6;+ constexpr int IPB = (FMT == 0) ? 4 : 8;+ const int64_t tot = (int64_t)M * nwin * 64;+ const int64_t gid = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;+ if (gid >= tot)+ return;+ const int j = (int)(gid & 63);+ const int64_t mw = gid >> 6; // m * nwin + win+ const int m = (int)(mw / nwin), win = (int)(mw - (int64_t)m * nwin);+ const int it = win * 64 + j;+ if (it >= nitems)+ return;+ uint32_t* r = rec + mw * RECW;+ const uint8_t* aq = aqb + (int64_t)m * qb_stride;+ const int b = it / IPB;+ if constexpr (FMT == 0)+ {+ const int g = it & 3;+ const uint32_t* a0 = reinterpret_cast<const uint32_t*>(aq + (size_t)(b * 8 + 2 * g) * FQ_Q8_1_BYTES);+ const uint32_t* a1 = a0 + FQ_Q8_1_BYTES / 4;+ #pragma unroll+ for (int w = 0; w < 8; w++)+ {+ r[w * 64 + j] = a0[1 + w];+ r[(8 + w) * 64 + j] = a1[1 + w];+ }+ r[1024 + j] = (a0[0] & 0xFFFFu) | (a1[0] << 16);+ }+ else+ {+ const int p = it & 7;+ #pragma unroll+ for (int s = 0; s < 8; s++)+ {+ const uint32_t* a = reinterpret_cast<const uint32_t*>(aq + (size_t)(b * 8 + s) * FQ_Q8_1_BYTES);+ r[s * 64 + j] = a[1 + p];+ if (p == 0)+ r[512 + s * 8 + (j >> 3)] = a[0];+ }+ }+}++__device__ __forceinline__ float fq_i2f_exact(int x) // (float)x for |x| < 2^22, without the conversion unit+{+ return __int_as_float(0x4B400000 + x) - 12582912.0f;+}++struct FqKqW4 { uint32_t v0[4][2], v1[4][2]; float dm0, dm1; int sc[2], mn[2]; };++__device__ __forceinline__ void fq_kq_wld_q4_k(const uint8_t* __restrict__ wr, int it, FqKqW4& w)+{+ const int b = it >> 2, g = it & 3;+ const uint8_t* blk = wr + (size_t)b * FQ_Q4_K_BYTES;+ const uint32_t hd = *reinterpret_cast<const uint32_t*>(blk);+ const uint32_t* sp = reinterpret_cast<const uint32_t*>(blk + 4);+ const uint32_t sw0 = sp[0], sw1 = sp[1], sw2 = sp[2];+ const uint4 va = *reinterpret_cast<const uint4*>(blk + 16 + 32 * g);+ const uint4 vb = *reinterpret_cast<const uint4*>(blk + 16 + 32 * g + 16);+ w.dm0 = fq_h2f_lo(hd);+ w.dm1 = fq_h2f_lo(hd >> 16);+ const int sh = 16 * (g & 1);+ const uint32_t s0 = (sw0 >> sh) & 0xFFFFu, s2 = (sw1 >> sh) & 0xFFFFu, s4 = (sw2 >> sh) & 0xFFFFu;+ const uint32_t hi = (g >= 2) ? 0xFFFFFFFFu : 0u;+ const uint16_t aux0 = (uint16_t)(((s0 & 0x3F3Fu) & ~hi) | ((((s4 >> 0) & 0x0F0Fu) | ((s0 & 0xC0C0u) >> 2)) & hi));+ const uint16_t aux1 = (uint16_t)(((s2 & 0x3F3Fu) & ~hi) | ((((s4 >> 4) & 0x0F0Fu) | ((s2 & 0xC0C0u) >> 2)) & hi));+ w.sc[0] = (int)(aux0 & 0xFFu); w.sc[1] = (int)((aux0 >> 8) & 0xFFu);+ w.mn[0] = (int)(aux1 & 0xFFu); w.mn[1] = (int)((aux1 >> 8) & 0xFFu);+ const uint32_t w0[4] = {va.x, va.y, va.z, va.w};+ const uint32_t w1[4] = {vb.x, vb.y, vb.z, vb.w};+ #pragma unroll+ for (int qo = 0; qo < 4; qo++)+ {+ #pragma unroll+ for (int i = 0; i < 2; i++)+ {+ w.v0[qo][i] = (w0[qo] >> (4 * i)) & 0x0F0F0F0Fu;+ w.v1[qo][i] = (w1[qo] >> (4 * i)) & 0x0F0F0F0Fu;+ }+ }+}++// rec = record of (x-row, window) from fq_kq_act_pack, j = lane within the window (it & 63). WT weight rows share the activation+// loads. Same float expressions as fq_kq_item_q4_k.+template <int WT>+__device__ __forceinline__ void fq_kq_wdot_q4_k(const FqKqW4 (&w)[WT], const uint32_t* __restrict__ rec, int j, float (&dst)[WT][4])+{+ const uint32_t ddw = rec[1024 + j];+ const float d8[2] = {fq_h2f_lo(ddw), fq_h2f_lo(ddw >> 16)};+ float sumf_d[WT][4], sumf_m[WT][4];+ #pragma unroll+ for (int x = 0; x < WT; x++)+ {+ #pragma unroll+ for (int qo = 0; qo < 4; qo++)+ {+ sumf_d[x][qo] = 0.0f;+ sumf_m[x][qo] = 0.0f;+ }+ }+ #pragma unroll+ for (int i = 0; i < 2; i++)+ {+ #pragma unroll+ for (int qo = 0; qo < 4; qo++)+ {+ const int32_t u0 = (int32_t)rec[(8 * i + qo) * 64 + j], u1 = (int32_t)rec[(8 * i + 4 + qo) * 64 + j];+ #pragma unroll+ for (int x = 0; x < WT; x++)+ {+ int dot1 = fq_dp4a((int32_t)w[x].v0[qo][i], u0, 0);+ dot1 = fq_dp4a((int32_t)w[x].v1[qo][i], u1, dot1);+ int dot2 = fq_dp4a(0x01010101, u0, 0);+ dot2 = fq_dp4a(0x01010101, u1, dot2);+ sumf_d[x][qo] = __fadd_rn(sumf_d[x][qo], __fmul_rn(d8[i], fq_i2f_exact(dot1 * w[x].sc[i])));+ sumf_m[x][qo] = __fadd_rn(sumf_m[x][qo], __fmul_rn(d8[i], fq_i2f_exact(dot2 * w[x].mn[i])));+ }+ }+ }+ #pragma unroll+ for (int x = 0; x < WT; x++)+ {+ #pragma unroll+ for (int qo = 0; qo < 4; qo++)+ dst[x][qo] = __fadd_rn(__fmul_rn(w[x].dm0, sumf_d[x][qo]), -__fmul_rn(w[x].dm1, sumf_m[x][qo]));+ }+}++struct FqKqW6 { uint32_t vi[4][2]; int sc[4][2]; float d; };++__device__ __forceinline__ void fq_kq_wld_q6_k(const uint8_t* __restrict__ wr, int it, FqKqW6& w)+{+ const int b = it >> 3, p = it & 7;+ const uint8_t* blk = wr + (size_t)b * FQ_Q6_K_BYTES;+ uint32_t vl[4];+ #pragma unroll+ for (int q = 0; q < 4; q++)+ vl[q] = fq_ld_u16x2(blk + 4 * p + 32 * q);+ const uint32_t vhw[2] = {fq_ld_u16x2(blk + 128 + 4 * p), fq_ld_u16x2(blk + 128 + 32 + 4 * p)};+ const int8_t* scl = reinterpret_cast<const int8_t*>(blk + 192);+ w.d = fq_h2f_lo((uint32_t)*reinterpret_cast<const uint16_t*>(blk + 208));+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ const int sc_off = 8 * (q >> 1) + (p >> 2) + 2 * (q & 1);+ const uint32_t vh = vhw[q >> 1] >> (2 * (q & 1));+ #pragma unroll+ for (int i = 0; i < 2; i++)+ {+ w.sc[q][i] = (int)scl[sc_off + 4 * i];+ const uint32_t vil = (vl[q] >> (4 * i)) & 0x0F0F0F0Fu;+ const uint32_t vih = ((vh >> (4 * i)) << 4) & 0x30303030u;+ w.vi[q][i] = fq_vsub4(vil | vih, 0x20202020u);+ }+ }+}++template <int WT>+__device__ __forceinline__ void fq_kq_wdot_q6_k(const FqKqW6 (&w)[WT], const uint32_t* __restrict__ rec, int j, float (&dst)[WT][4])+{+ float sumf[WT][4];+ #pragma unroll+ for (int x = 0; x < WT; x++)+ {+ #pragma unroll+ for (int q = 0; q < 4; q++)+ sumf[x][q] = 0.0f;+ }+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ #pragma unroll+ for (int i = 0; i < 2; i++)+ {+ const int s = 4 * (q >> 1) + (q & 1) + 2 * i;+ const float d8 = fq_h2f_lo(rec[512 + s * 8 + (j >> 3)]);+ const int32_t u = (int32_t)rec[s * 64 + j];+ #pragma unroll+ for (int x = 0; x < WT; x++)+ sumf[x][q] = __fadd_rn(sumf[x][q], __fmul_rn(d8, fq_i2f_exact(fq_dp4a((int32_t)w[x].vi[q][i], u, 0) * w[x].sc[q][i])));+ }+ }+ #pragma unroll+ for (int x = 0; x < WT; x++)+ {+ #pragma unroll+ for (int q = 0; q < 4; q++)+ dst[x][q] = __fmul_rn(w[x].d, sumf[x][q]);+ }+}++// One block = WROWS x WT consecutive output rows x RT consecutive x-rows (x-row chunk blockIdx.y); a group of 64 threads handles WT+// output rows. Thread j owns items j, j + 64, ... exactly like the one-row kernel, but keeps WT x RT x 4 lane partials; x-rows >= M+// are skipped. The lane partials of every (output row, x-row) pair go to shared memory and one thread per pair adds them lane by+// lane in the one-row kernel's order.+template <typename OUT, int FMT, int WROWS, int RT, int WT>+__global__ void __launch_bounds__(64 * WROWS) fq_gemv_kq_mrows_kernel(const uint32_t* __restrict__ rec,+ const uint8_t* __restrict__ packed,+ OUT* __restrict__ out,+ int M, int N, int K, int64_t packed_stride,+ int nwin, int nt, int ny)+{+ constexpr int PS = 312; // 256 lanes + 8 floats of padding per 32 lanes (conflict-free partial stores)+ constexpr int RECW = (FMT == 0) ? FQ_KQ_REC_Q4 : FQ_KQ_REC_Q6;+ constexpr int NR = WROWS * WT; // output rows per block+ __shared__ __align__(16) float part[NR * RT * PS];+ constexpr int IPB = (FMT == 0) ? 4 : 8;+ using WTy = typename std::conditional<FMT == 0, FqKqW4, FqKqW6>::type;+ const int tid = threadIdx.x;+ const int r = tid >> 6, j = tid & 63;+ // x-row chunks of one weight tile are neighbouring blocks (they run together, the weights come from L2 for the later chunks)+ const int bid = blockIdx.x;+ const int m0 = (bid % ny) * RT;+ const int n0 = (bid / ny) * NR;+ const int nitems = (K / 256) * IPB;+ float acc[WT][RT][4];+ #pragma unroll+ for (int x = 0; x < WT; x++)+ {+ #pragma unroll+ for (int rr = 0; rr < RT; rr++)+ {+ #pragma unroll+ for (int q = 0; q < 4; q++)+ acc[x][rr][q] = 0.0f;+ }+ }+ if (n0 + r * WT < N)+ {+ const uint8_t* wrow[WT];+ #pragma unroll+ for (int x = 0; x < WT; x++)+ wrow[x] = packed + (int64_t)min(n0 + r * WT + x, N - 1) * packed_stride; // rows past N are computed, never stored+ const uint32_t* rec0 = rec + (int64_t)m0 * nwin * RECW;+ for (int it = j; it < nitems; it += 64)+ {+ const int win = it >> 6;+ WTy w[WT];+ #pragma unroll+ for (int x = 0; x < WT; x++)+ {+ if constexpr (FMT == 0)+ fq_kq_wld_q4_k(wrow[x], it, w[x]);+ else+ fq_kq_wld_q6_k(wrow[x], it, w[x]);+ }+ #pragma unroll+ for (int rr = 0; rr < RT; rr++)+ {+ if (m0 + rr < M)+ {+ float t[WT][4];+ const uint32_t* rc = rec0 + ((int64_t)rr * nwin + win) * RECW;+ if constexpr (FMT == 0)+ fq_kq_wdot_q4_k<WT>(w, rc, j, t);+ else+ fq_kq_wdot_q6_k<WT>(w, rc, j, t);+ #pragma unroll+ for (int x = 0; x < WT; x++)+ {+ #pragma unroll+ for (int q = 0; q < 4; q++)+ acc[x][rr][q] = __fadd_rn(acc[x][rr][q], t[x][q]);+ }+ }+ }+ }+ }+ if constexpr (FMT == 0)+ {+ // lanes 4j .. 4j+3 are contiguous: one 16-byte store per (output row, x-row)+ if (4 * j < nt)+ {+ #pragma unroll+ for (int x = 0; x < WT; x++)+ {+ #pragma unroll+ for (int rr = 0; rr < RT; rr++)+ *reinterpret_cast<float4*>(part + (((r * WT + x) * RT) + rr) * PS + 4 * j + 8 * (j >> 3)) =+ make_float4(acc[x][rr][0], acc[x][rr][1], acc[x][rr][2], acc[x][rr][3]);+ }+ }+ }+ else+ {+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ const int lane = 32 * (j >> 3) + (j & 7) + 8 * q;+ if (lane < nt)+ {+ #pragma unroll+ for (int x = 0; x < WT; x++)+ {+ #pragma unroll+ for (int rr = 0; rr < RT; rr++)+ part[(((r * WT + x) * RT) + rr) * PS + lane + 8 * (lane >> 5)] = acc[x][rr][q];+ }+ }+ }+ }+ __syncthreads();+ if (tid < NR * RT)+ {+ const int cr = tid / RT, rr = tid % RT;+ if (n0 + cr < N && m0 + rr < M)+ {+ const float4* pv = reinterpret_cast<const float4*>(part + (cr * RT + rr) * PS);+ float s = 0.0f;+ #pragma unroll 8+ for (int l = 0; l < nt / 4; l++)+ {+ const float4 v = pv[l + 2 * (l >> 3)];+ s = __fadd_rn(s, v.x);+ s = __fadd_rn(s, v.y);+ s = __fadd_rn(s, v.z);+ s = __fadd_rn(s, v.w);+ }+ if constexpr (std::is_same<OUT, __half>::value)+ out[(int64_t)(m0 + rr) * N + n0 + cr] = __float2half_rn(s);+ else+ out[(int64_t)(m0 + rr) * N + n0 + cr] = s;+ }+ }+}+} // namespace+// BOLT_FQ_KQ_ROWS: output rows per block of the v2 Q4_K / Q6_K kernel (1, 2, 4). 0 = the v1 kernel (A/B); unset = the per-format+// default measured on the RTX 3090 (Q4_K 4 rows, Q6_K 1 row: its item has ~2x the load instructions, 64-thread blocks keep more+// of them resident: down 4096x12288 Q6_K 85 % of the DRAM roof at 1 row vs 63 % at 4). HIP default 1 row (Strix Halo, Qwen3-8B+// Q4_K_M served N1 v1 36.9 -> 1 row 39.1 / 4 rows 39.3 tok/s, same output; 35B-A3B unchanged: 53.3 / 53.3 / 53.1).+static int fq_kq_rows_env(int fmt)+{+ static const char* e = std::getenv("BOLT_FQ_KQ_ROWS");+ static const int forced = e ? std::atoi(e) : -1;+ if (forced >= 0)+ return forced;+#if defined(USE_ROCM) || defined(__HIP_PLATFORM_AMD__)+ return 1;+#else+ return fmt == 0 ? 4 : 1;+#endif+}++template <typename OUT, int FMT>+static void fq_gemv_kq_rows_dispatch(int rows, int M, const uint8_t* qb, const uint8_t* packed, OUT* out, int N, int K,+ int64_t pstride, int64_t qb_stride, int nt, cudaStream_t stream)+{+ auto run = [&](auto rows_c)+ {+ constexpr int R = decltype(rows_c)::value;+ const int nbn = (N + R - 1) / R;+ fq_gemv_kq_rows_kernel<OUT, FMT, R><<<(unsigned)((int64_t)M * nbn), 64 * R, 0, stream>>>(+ qb, packed, out, N, K, pstride, qb_stride, nbn, nt);+ };+ if (rows >= 4) run(std::integral_constant<int, 4>());+ else if (rows >= 2) run(std::integral_constant<int, 2>());+ else run(std::integral_constant<int, 1>());+}++// BOLT_FQ_KQ_MROWS: x-rows 2..16 of the Q4_K / Q6_K decode GEMV run the multi-row kernel (weights read once for all rows). 0 = the+// per-row launch of the one-row kernels (A/B). Default on (CUDA and HIP).+// BOLT_FQ_KQ_MR_ROWS / BOLT_FQ_KQ_MR_RT force the output rows per block (1, 2, 4) / x-rows per pass (2, 4, 8, 16) for tuning.+static int fq_kq_mrows_env(const char* name, int dflt)+{+ const char* e = std::getenv(name);+ return e ? std::atoi(e) : dflt;+}++static bool fq_kq_mrows_on()+{+ static const int on = fq_kq_mrows_env("BOLT_FQ_KQ_MROWS", 1);+ return on != 0;+}++#if defined(USE_ROCM) || defined(__HIP_PLATFORM_AMD__)+// BOLT_FQ_KQ_WMMA: gfx11 HIP builds run x-rows 2..16 of the Q4_K GEMV on WMMA iu8 (fq_kq_wmma.cuh; per x-row bit-identical to the one-row+// kernel, like the generic multi-row kernel). 0 = never (generic multi-row kernel), 1 = whenever eligible, unset / other = auto: only where it+// won on gfx1151 (rule in the function), the other shapes keep the generic kernel. Eligible = Q4_K with+// K >= 4096 (the one-row kernel's 256 lanes), 16-byte aligned rows.+static int fq_kq_wmma_mode()+{+ static const char* e = std::getenv("BOLT_FQ_KQ_WMMA");+ static const int mode = e ? ((e[0] == '0' || e[0] == '1') && e[1] == 0 ? e[0] - '0' : 2) : 2;+ return mode;+}++static bool fq_kq_wmma_arch()+{+ return std::strncmp(at::cuda::getCurrentDeviceProperties()->gcnArchName, "gfx11", 5) == 0;+}++static bool fq_gemv_kq_wmma_try(const torch::Tensor& qb, const torch::Tensor& packed, torch::Tensor& out, int M, int N, int K,+ int64_t pstride, int64_t qb_stride, cudaStream_t stream)+{+ const int mode = fq_kq_wmma_mode();+ if (mode == 0 || M < 2 || M > 16 || K < 4096 || K % 256 != 0 || (uintptr_t)qb.data_ptr() % 4 != 0 || qb_stride % 4 != 0 ||+ (uintptr_t)packed.data_ptr() % 16 != 0 || pstride % 16 != 0)+ return false;+ if (mode == 2)+ {+ // measured on gfx1151 (Qwen3-8B shapes, cold, x-rows 1..16; the WMMA kernel's cost steps with ceil(R / 4)): thin matrices and deep K+ // (one wave walks all K positions serially) are latency bound there, so they need many x-rows to amortise it+ bool wins;+ if (K > 6144)+ wins = M >= 13; // 4096x12288: 1.25x at R = 16, 0.8-1.0x below+ else if (N < 2048)+ wins = M >= 8; // 1024x4096: 1.15x at R = 8+ else if (N < 8192)+ wins = true; // 4096x4096: 1.2x at R = 2 .. 2.2x at R = 16+ else+ wins = M >= 6; // 12288x4096: 1.09x at R = 6, 1.3x at R = 8, 2.0x at R = 16+ if (!wins)+ return false;+ }+ if (!fq_kq_wmma_arch())+ return false;+ auto topt = torch::TensorOptions().device(qb.device());+ const int nitems = (K / 256) * 4;+ const int P = (M + 3) / 4, TPW = P == 1 ? 4 : (P == 2 ? 2 : 1);+ torch::Tensor frag = torch::empty({(int64_t)P * nitems * 128}, topt.dtype(torch::kInt32));+ torch::Tensor tab = torch::empty({(int64_t)P * nitems * 40}, topt.dtype(torch::kFloat));+ const int64_t total = (int64_t)P * 4 * nitems;+ fq_kq_wpack_q4_kernel<<<(unsigned)((total + 127) / 128), 128, 0, stream>>>(+ qb.data_ptr<uint8_t>(), reinterpret_cast<uint4*>(frag.data_ptr<int32_t>()), tab.data_ptr<float>(), M, nitems, qb_stride, total);+ const unsigned grid = (unsigned)((((N + 31) / 32) + TPW - 1) / TPW), block = 32 * P * TPW;+ auto go = [&](auto* op)+ {+ using O = std::decay_t<decltype(*op)>;+ if (M <= 2)+ fq_gemv_kq_wmma_q4_kernel<O, 2, 2><<<grid, block, 0, stream>>>(packed.data_ptr<uint8_t>(), reinterpret_cast<const uint4*>(frag.data_ptr<int32_t>()),+ tab.data_ptr<float>(), op, M, N, pstride, nitems, P, TPW);+ else+ fq_gemv_kq_wmma_q4_kernel<O, 4, 2><<<grid, block, 0, stream>>>(packed.data_ptr<uint8_t>(), reinterpret_cast<const uint4*>(frag.data_ptr<int32_t>()),+ tab.data_ptr<float>(), op, M, N, pstride, nitems, P, TPW);+ };+ if (out.dtype() == torch::kHalf)+ go(reinterpret_cast<__half*>(out.data_ptr<at::Half>()));+ else+ go(out.data_ptr<float>());+ return true;+}+#endif++template <typename OUT, int FMT, int WROWS, int RT, int WT>+static void fq_gemv_kq_mrows_go(int M, const uint32_t* rec, const uint8_t* packed, OUT* out, int N, int K, int64_t pstride,+ int nwin, int nt, cudaStream_t stream)+{+ const unsigned ny = (unsigned)((M + RT - 1) / RT);+ dim3 grid(((unsigned)((N + WROWS * WT - 1) / (WROWS * WT))) * ny); // blockIdx.x = (weight tile, x-row chunk), chunk fastest+ fq_gemv_kq_mrows_kernel<OUT, FMT, WROWS, RT, WT><<<grid, 64 * WROWS, 0, stream>>>(rec, packed, out, M, N, K, pstride, nwin, nt, (int)ny);+}++// Launch shape: 2 x 2 output rows per block, 4 x-rows per pass (2 for R <= 2); measured on the RTX 3090 (tools/kq_mbench.py sweep).+template <typename OUT, int FMT>+static void fq_gemv_kq_mrows_dispatch(int M, const uint32_t* rec, const uint8_t* packed, OUT* out, int N, int K, int64_t pstride,+ int nwin, int nt, cudaStream_t stream)+{+ int rt = fq_kq_mrows_env("BOLT_FQ_KQ_MR_RT", 0);+ int wr = fq_kq_mrows_env("BOLT_FQ_KQ_MR_ROWS", 0);+ int wt = fq_kq_mrows_env("BOLT_FQ_KQ_MR_WT", 0);+ if (rt <= 0 && wr <= 0 && wt <= 0)+ {+ wr = 2; wt = 2; rt = M <= 2 ? 2 : 4; // best or within 5 % of the best on every 8B shape for R >= 3 (R = 2 within 10 %)+ }+ if (rt <= 0) rt = M <= 2 ? 2 : M <= 4 ? 4 : M <= 8 ? 8 : 16;+ if (wr <= 0) wr = 1;+ if (wt <= 0) wt = 1;+ auto go = [&](auto wc, auto rc, auto tc)+ {+ fq_gemv_kq_mrows_go<OUT, FMT, decltype(wc)::value, decltype(rc)::value, decltype(tc)::value>(M, rec, packed, out, N, K, pstride, nwin, nt, stream);+ };+ using I1 = std::integral_constant<int, 1>;+ using I2 = std::integral_constant<int, 2>;+ using I4 = std::integral_constant<int, 4>;+ using I8 = std::integral_constant<int, 8>;+ using I16 = std::integral_constant<int, 16>;+ if (wt >= 2)+ {+ if (rt <= 2) { if (wr >= 2) go(I2(), I2(), I2()); else go(I1(), I2(), I2()); }+ else { if (wr >= 2) go(I2(), I4(), I2()); else go(I1(), I4(), I2()); }+ }+ else if (wr >= 4)+ {+ if (rt <= 2) go(I4(), I2(), I1()); else go(I4(), I4(), I1());+ }+ else if (wr >= 2)+ {+ if (rt <= 2) go(I2(), I2(), I1()); else if (rt <= 4) go(I2(), I4(), I1()); else go(I2(), I8(), I1());+ }+ else+ {+ if (rt <= 2) go(I1(), I2(), I1()); else if (rt <= 4) go(I1(), I4(), I1()); else if (rt <= 8) go(I1(), I8(), I1()); else go(I1(), I16(), I1());+ }+}+// Shared row-per-block q8 launch sizing: threads take sub-chunks// round-robin (same as fq_q8_nt in fq_gemv_q8.cu, generalized).static inline int fq_kq_nt(int K, int sub)@@ -101,6 +728,56 @@ static void fq_gemv_kq_launch(torch::Tensor qb, torch::Tensor packed, torch::Tensize_t shmem = (size_t)nt * sizeof(float);at::cuda::CUDAGuard guard(qb.device());auto stream = at::cuda::getCurrentCUDAStream().stream();+#if defined(USE_ROCM) || defined(__HIP_PLATFORM_AMD__)+ if constexpr (FMT == 0)+ {+ if (fq_gemv_kq_wmma_try(qb, packed, out, M, N, K, pstride, qb_stride, stream))+ return;+ }+#endif+ if constexpr (FMT == 0 || FMT == 2)+ {+ if (M >= 2 && M <= 16 && fq_kq_mrows_on() && K % 256 == 0 && (uintptr_t)packed.data_ptr() % ((FMT == 0) ? 16 : 2) == 0 &&+ (uintptr_t)qb.data_ptr() % 4 == 0 && pstride % ((FMT == 0) ? 16 : 2) == 0 && qb_stride % 4 == 0)+ {+ // multi-row kernel (per x-row bit-identical to the one-row kernels): weights read once for all M rows+ constexpr int IPB = (FMT == 0) ? 4 : 8;+ constexpr int RECW = (FMT == 0) ? FQ_KQ_REC_Q4 : FQ_KQ_REC_Q6;+ const int nitems = (K / 256) * IPB;+ const int nwin = (nitems + 63) / 64;+ torch::Tensor rect = torch::empty({(int64_t)M * nwin * RECW}, torch::TensorOptions().dtype(torch::kInt32).device(qb.device()));+ uint32_t* rec = reinterpret_cast<uint32_t*>(rect.data_ptr<int32_t>());+ fq_kq_act_pack_kernel<FMT><<<(unsigned)(((int64_t)M * nwin * 64 + 127) / 128), 128, 0, stream>>>(+ qb.data_ptr<uint8_t>(), rec, M, nwin, nitems, qb_stride);+ auto go = [&](auto* op)+ {+ fq_gemv_kq_mrows_dispatch<std::decay_t<decltype(*op)>, FMT>(+ M, rec, packed.data_ptr<uint8_t>(), op, N, K, pstride, nwin, nt, stream);+ };+ if (out.dtype() == torch::kHalf)+ go(reinterpret_cast<__half*>(out.data_ptr<at::Half>()));+ else+ go(out.data_ptr<float>());+ return;+ }+ // v2 rows kernel (bit-identical to the v1 kernel below): 16-byte aligned Q4_K rows, 2-byte aligned Q6_K rows+ const int rows = fq_kq_rows_env(FMT);+ const uintptr_t align = (FMT == 0) ? 16 : 2;+ if (rows > 0 && K % 256 == 0 && (uintptr_t)packed.data_ptr() % align == 0 && (uintptr_t)qb.data_ptr() % 4 == 0 &&+ pstride % align == 0)+ {+ auto go = [&](auto* op)+ {+ fq_gemv_kq_rows_dispatch<std::decay_t<decltype(*op)>, FMT>(+ rows, M, qb.data_ptr<uint8_t>(), packed.data_ptr<uint8_t>(), op, N, K, pstride, qb_stride, nt, stream);+ };+ if (out.dtype() == torch::kHalf)+ go(reinterpret_cast<__half*>(out.data_ptr<at::Half>()));+ else+ go(out.data_ptr<float>());+ return;+ }+ }auto launch = [&](auto* op){fq_gemv_kq_kernel<std::decay_t<decltype(*op)>, FMT> <<<M * N, nt, shmem, stream>>>(@@ -132,3 +809,18 @@ void fq_gemv_iq4_xs_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out{fq_gemv_kq_launch<3, 32>(qb, packed, out, FQ_IQ4_XS_BYTES);}++void fq_gemv_iq3_xxs_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out)+{+ fq_gemv_kq_launch<4, 32>(qb, packed, out, FQ_IQ3_XXS_BYTES);+}++void fq_gemv_iq2_s_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out)+{+ fq_gemv_kq_launch<5, 32>(qb, packed, out, FQ_IQ2_S_BYTES);+}++void fq_gemv_iq3_s_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out)+{+ fq_gemv_kq_launch<6, 32>(qb, packed, out, FQ_IQ3_S_BYTES);+}diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_iq3_tables.cuh b/exllamav3/exllamav3_ext/foreign_quant/fq_iq3_tables.cuhnew file mode 100644index 0000000..46729ac--- /dev/null+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_iq3_tables.cuh@@ -0,0 +1,401 @@+#pragma once+// IQ3_XXS decode tables (llama.cpp ggml/src/ggml-common.h, MIT): iq3xxs_grid (4 magnitudes per entry) and, for each of the 128+// ksigns_iq2xs entries, the 8 per-element sign masks as two uint32 (byte 0xFF = negate). Generated by foreign_quant/iq_grids_gen.py.+// __device__ const (not __constant__): every lane of a dot reads a different grid entry (see fq_tables.cuh).+#include <cstdint>+__device__ const uint32_t FQ_IQ3XXS_GRID[256] = {+ 0x04040404u, 0x04040414u, 0x04040424u, 0x04040c0cu, 0x04040c1cu, 0x04040c3eu, 0x04041404u, 0x04041414u,+ 0x04041c0cu, 0x04042414u, 0x04043e1cu, 0x04043e2cu, 0x040c040cu, 0x040c041cu, 0x040c0c04u, 0x040c0c14u,+ 0x040c140cu, 0x040c142cu, 0x040c1c04u, 0x040c1c14u, 0x040c240cu, 0x040c2c24u, 0x040c3e04u, 0x04140404u,+ 0x04140414u, 0x04140424u, 0x04140c0cu, 0x04141404u, 0x04141414u, 0x04141c0cu, 0x04141c1cu, 0x04141c3eu,+ 0x04142c0cu, 0x04142c3eu, 0x04143e2cu, 0x041c040cu, 0x041c043eu, 0x041c0c04u, 0x041c0c14u, 0x041c142cu,+ 0x041c3e04u, 0x04240c1cu, 0x04241c3eu, 0x04242424u, 0x04242c3eu, 0x04243e1cu, 0x04243e2cu, 0x042c040cu,+ 0x042c043eu, 0x042c1c14u, 0x042c2c14u, 0x04341c2cu, 0x04343424u, 0x043e0c04u, 0x043e0c24u, 0x043e0c34u,+ 0x043e241cu, 0x043e340cu, 0x0c04040cu, 0x0c04041cu, 0x0c040c04u, 0x0c040c14u, 0x0c04140cu, 0x0c04141cu,+ 0x0c041c04u, 0x0c041c14u, 0x0c041c24u, 0x0c04243eu, 0x0c042c04u, 0x0c0c0404u, 0x0c0c0414u, 0x0c0c0c0cu,+ 0x0c0c1404u, 0x0c0c1414u, 0x0c14040cu, 0x0c14041cu, 0x0c140c04u, 0x0c140c14u, 0x0c14140cu, 0x0c141c04u,+ 0x0c143e14u, 0x0c1c0404u, 0x0c1c0414u, 0x0c1c1404u, 0x0c1c1c0cu, 0x0c1c2434u, 0x0c1c3434u, 0x0c24040cu,+ 0x0c24042cu, 0x0c242c04u, 0x0c2c1404u, 0x0c2c1424u, 0x0c2c2434u, 0x0c2c3e0cu, 0x0c34042cu, 0x0c3e1414u,+ 0x0c3e2404u, 0x14040404u, 0x14040414u, 0x14040c0cu, 0x14040c1cu, 0x14041404u, 0x14041414u, 0x14041434u,+ 0x14041c0cu, 0x14042414u, 0x140c040cu, 0x140c041cu, 0x140c042cu, 0x140c0c04u, 0x140c0c14u, 0x140c140cu,+ 0x140c1c04u, 0x140c341cu, 0x140c343eu, 0x140c3e04u, 0x14140404u, 0x14140414u, 0x14140c0cu, 0x14140c3eu,+ 0x14141404u, 0x14141414u, 0x14141c3eu, 0x14142404u, 0x14142c2cu, 0x141c040cu, 0x141c0c04u, 0x141c0c24u,+ 0x141c3e04u, 0x141c3e24u, 0x14241c2cu, 0x14242c1cu, 0x142c041cu, 0x142c143eu, 0x142c240cu, 0x142c3e24u,+ 0x143e040cu, 0x143e041cu, 0x143e0c34u, 0x143e242cu, 0x1c04040cu, 0x1c040c04u, 0x1c040c14u, 0x1c04140cu,+ 0x1c04141cu, 0x1c042c04u, 0x1c04342cu, 0x1c043e14u, 0x1c0c0404u, 0x1c0c0414u, 0x1c0c1404u, 0x1c0c1c0cu,+ 0x1c0c2424u, 0x1c0c2434u, 0x1c14040cu, 0x1c14041cu, 0x1c140c04u, 0x1c14142cu, 0x1c142c14u, 0x1c143e14u,+ 0x1c1c0c0cu, 0x1c1c1c1cu, 0x1c241c04u, 0x1c24243eu, 0x1c243e14u, 0x1c2c0404u, 0x1c2c0434u, 0x1c2c1414u,+ 0x1c2c2c2cu, 0x1c340c24u, 0x1c341c34u, 0x1c34341cu, 0x1c3e1c1cu, 0x1c3e3404u, 0x24040424u, 0x24040c3eu,+ 0x24041c2cu, 0x24041c3eu, 0x24042c1cu, 0x24042c3eu, 0x240c3e24u, 0x24141404u, 0x24141c3eu, 0x24142404u,+ 0x24143404u, 0x24143434u, 0x241c043eu, 0x241c242cu, 0x24240424u, 0x24242c0cu, 0x24243424u, 0x242c142cu,+ 0x242c241cu, 0x242c3e04u, 0x243e042cu, 0x243e0c04u, 0x243e0c14u, 0x243e1c04u, 0x2c040c14u, 0x2c04240cu,+ 0x2c043e04u, 0x2c0c0404u, 0x2c0c0434u, 0x2c0c1434u, 0x2c0c2c2cu, 0x2c140c24u, 0x2c141c14u, 0x2c143e14u,+ 0x2c1c0414u, 0x2c1c2c1cu, 0x2c240c04u, 0x2c24141cu, 0x2c24143eu, 0x2c243e14u, 0x2c2c0414u, 0x2c2c1c0cu,+ 0x2c342c04u, 0x2c3e1424u, 0x2c3e2414u, 0x34041424u, 0x34042424u, 0x34042434u, 0x34043424u, 0x340c140cu,+ 0x340c340cu, 0x34140c3eu, 0x34143424u, 0x341c1c04u, 0x341c1c34u, 0x34242424u, 0x342c042cu, 0x342c2c14u,+ 0x34341c1cu, 0x343e041cu, 0x343e140cu, 0x3e04041cu, 0x3e04042cu, 0x3e04043eu, 0x3e040c04u, 0x3e041c14u,+ 0x3e042c14u, 0x3e0c1434u, 0x3e0c2404u, 0x3e140c14u, 0x3e14242cu, 0x3e142c14u, 0x3e1c0404u, 0x3e1c0c2cu,+ 0x3e1c1c1cu, 0x3e1c3404u, 0x3e24140cu, 0x3e24240cu, 0x3e2c0404u, 0x3e2c0414u, 0x3e2c1424u, 0x3e341c04u+};+__device__ const uint32_t FQ_IQ3XXS_SIGNS32[256] = {+ 0x00000000u, 0x00000000u, 0x000000ffu, 0xff000000u, 0x0000ff00u, 0xff000000u, 0x0000ffffu, 0x00000000u,+ 0x00ff0000u, 0xff000000u, 0x00ff00ffu, 0x00000000u, 0x00ffff00u, 0x00000000u, 0x00ffffffu, 0xff000000u,+ 0xff000000u, 0xff000000u, 0xff0000ffu, 0x00000000u, 0xff00ff00u, 0x00000000u, 0xff00ffffu, 0xff000000u,+ 0xffff0000u, 0x00000000u, 0xffff00ffu, 0xff000000u, 0xffffff00u, 0xff000000u, 0xffffffffu, 0x00000000u,+ 0x00000000u, 0xff0000ffu, 0x000000ffu, 0x000000ffu, 0x0000ff00u, 0x000000ffu, 0x0000ffffu, 0xff0000ffu,+ 0x00ff0000u, 0x000000ffu, 0x00ff00ffu, 0xff0000ffu, 0x00ffff00u, 0xff0000ffu, 0x00ffffffu, 0x000000ffu,+ 0xff000000u, 0x000000ffu, 0xff0000ffu, 0xff0000ffu, 0xff00ff00u, 0xff0000ffu, 0xff00ffffu, 0x000000ffu,+ 0xffff0000u, 0xff0000ffu, 0xffff00ffu, 0x000000ffu, 0xffffff00u, 0x000000ffu, 0xffffffffu, 0xff0000ffu,+ 0x00000000u, 0xff00ff00u, 0x000000ffu, 0x0000ff00u, 0x0000ff00u, 0x0000ff00u, 0x0000ffffu, 0xff00ff00u,+ 0x00ff0000u, 0x0000ff00u, 0x00ff00ffu, 0xff00ff00u, 0x00ffff00u, 0xff00ff00u, 0x00ffffffu, 0x0000ff00u,+ 0xff000000u, 0x0000ff00u, 0xff0000ffu, 0xff00ff00u, 0xff00ff00u, 0xff00ff00u, 0xff00ffffu, 0x0000ff00u,+ 0xffff0000u, 0xff00ff00u, 0xffff00ffu, 0x0000ff00u, 0xffffff00u, 0x0000ff00u, 0xffffffffu, 0xff00ff00u,+ 0x00000000u, 0x0000ffffu, 0x000000ffu, 0xff00ffffu, 0x0000ff00u, 0xff00ffffu, 0x0000ffffu, 0x0000ffffu,+ 0x00ff0000u, 0xff00ffffu, 0x00ff00ffu, 0x0000ffffu, 0x00ffff00u, 0x0000ffffu, 0x00ffffffu, 0xff00ffffu,+ 0xff000000u, 0xff00ffffu, 0xff0000ffu, 0x0000ffffu, 0xff00ff00u, 0x0000ffffu, 0xff00ffffu, 0xff00ffffu,+ 0xffff0000u, 0x0000ffffu, 0xffff00ffu, 0xff00ffffu, 0xffffff00u, 0xff00ffffu, 0xffffffffu, 0x0000ffffu,+ 0x00000000u, 0xffff0000u, 0x000000ffu, 0x00ff0000u, 0x0000ff00u, 0x00ff0000u, 0x0000ffffu, 0xffff0000u,+ 0x00ff0000u, 0x00ff0000u, 0x00ff00ffu, 0xffff0000u, 0x00ffff00u, 0xffff0000u, 0x00ffffffu, 0x00ff0000u,+ 0xff000000u, 0x00ff0000u, 0xff0000ffu, 0xffff0000u, 0xff00ff00u, 0xffff0000u, 0xff00ffffu, 0x00ff0000u,+ 0xffff0000u, 0xffff0000u, 0xffff00ffu, 0x00ff0000u, 0xffffff00u, 0x00ff0000u, 0xffffffffu, 0xffff0000u,+ 0x00000000u, 0x00ff00ffu, 0x000000ffu, 0xffff00ffu, 0x0000ff00u, 0xffff00ffu, 0x0000ffffu, 0x00ff00ffu,+ 0x00ff0000u, 0xffff00ffu, 0x00ff00ffu, 0x00ff00ffu, 0x00ffff00u, 0x00ff00ffu, 0x00ffffffu, 0xffff00ffu,+ 0xff000000u, 0xffff00ffu, 0xff0000ffu, 0x00ff00ffu, 0xff00ff00u, 0x00ff00ffu, 0xff00ffffu, 0xffff00ffu,+ 0xffff0000u, 0x00ff00ffu, 0xffff00ffu, 0xffff00ffu, 0xffffff00u, 0xffff00ffu, 0xffffffffu, 0x00ff00ffu,+ 0x00000000u, 0x00ffff00u, 0x000000ffu, 0xffffff00u, 0x0000ff00u, 0xffffff00u, 0x0000ffffu, 0x00ffff00u,+ 0x00ff0000u, 0xffffff00u, 0x00ff00ffu, 0x00ffff00u, 0x00ffff00u, 0x00ffff00u, 0x00ffffffu, 0xffffff00u,+ 0xff000000u, 0xffffff00u, 0xff0000ffu, 0x00ffff00u, 0xff00ff00u, 0x00ffff00u, 0xff00ffffu, 0xffffff00u,+ 0xffff0000u, 0x00ffff00u, 0xffff00ffu, 0xffffff00u, 0xffffff00u, 0xffffff00u, 0xffffffffu, 0x00ffff00u,+ 0x00000000u, 0xffffffffu, 0x000000ffu, 0x00ffffffu, 0x0000ff00u, 0x00ffffffu, 0x0000ffffu, 0xffffffffu,+ 0x00ff0000u, 0x00ffffffu, 0x00ff00ffu, 0xffffffffu, 0x00ffff00u, 0xffffffffu, 0x00ffffffu, 0x00ffffffu,+ 0xff000000u, 0x00ffffffu, 0xff0000ffu, 0xffffffffu, 0xff00ff00u, 0xffffffffu, 0xff00ffffu, 0x00ffffffu,+ 0xffff0000u, 0xffffffffu, 0xffff00ffu, 0x00ffffffu, 0xffffff00u, 0x00ffffffu, 0xffffffffu, 0xffffffffu+};++// iq2s_grid (llama.cpp ggml/src/ggml-common.h, MIT): 1024 entries x 8 magnitudes (bytes 8 / 25 / 43) as two uint32 (elements 0-3, 4-7).+__device__ const uint32_t FQ_IQ2S_GRID[2048] = {+ 0x08080808u, 0x08080808u, 0x0808082bu, 0x08080808u, 0x08081919u, 0x08080808u, 0x08082b08u, 0x08080808u,+ 0x08082b2bu, 0x08080808u, 0x08190819u, 0x08080808u, 0x08191908u, 0x08080808u, 0x0819192bu, 0x08080808u,+ 0x08192b19u, 0x08080808u, 0x082b0808u, 0x08080808u, 0x082b082bu, 0x08080808u, 0x082b1919u, 0x08080808u,+ 0x082b2b08u, 0x08080808u, 0x19080819u, 0x08080808u, 0x19081908u, 0x08080808u, 0x1908192bu, 0x08080808u,+ 0x19082b19u, 0x08080808u, 0x19190808u, 0x08080808u, 0x1919082bu, 0x08080808u, 0x19191919u, 0x08080808u,+ 0x19192b08u, 0x08080808u, 0x192b0819u, 0x08080808u, 0x192b1908u, 0x08080808u, 0x192b192bu, 0x08080808u,+ 0x192b2b19u, 0x08080808u, 0x2b080808u, 0x08080808u, 0x2b08082bu, 0x08080808u, 0x2b081919u, 0x08080808u,+ 0x2b082b08u, 0x08080808u, 0x2b190819u, 0x08080808u, 0x2b191908u, 0x08080808u, 0x2b2b0808u, 0x08080808u,+ 0x2b2b1919u, 0x08080808u, 0x2b2b2b2bu, 0x08080808u, 0x08080819u, 0x08080819u, 0x08081908u, 0x08080819u,+ 0x0808192bu, 0x08080819u, 0x08082b19u, 0x08080819u, 0x08190808u, 0x08080819u, 0x0819082bu, 0x08080819u,+ 0x08191919u, 0x08080819u, 0x08192b08u, 0x08080819u, 0x082b0819u, 0x08080819u, 0x082b1908u, 0x08080819u,+ 0x19080808u, 0x08080819u, 0x1908082bu, 0x08080819u, 0x19081919u, 0x08080819u, 0x19082b08u, 0x08080819u,+ 0x19190819u, 0x08080819u, 0x19191908u, 0x08080819u, 0x1919192bu, 0x08080819u, 0x19192b19u, 0x08080819u,+ 0x192b0808u, 0x08080819u, 0x192b1919u, 0x08080819u, 0x192b2b08u, 0x08080819u, 0x2b080819u, 0x08080819u,+ 0x2b081908u, 0x08080819u, 0x2b190808u, 0x08080819u, 0x2b19082bu, 0x08080819u, 0x2b191919u, 0x08080819u,+ 0x2b2b0819u, 0x08080819u, 0x2b2b1908u, 0x08080819u, 0x08080808u, 0x0808082bu, 0x0808082bu, 0x0808082bu,+ 0x08081919u, 0x0808082bu, 0x08082b08u, 0x0808082bu, 0x08190819u, 0x0808082bu, 0x08191908u, 0x0808082bu,+ 0x082b0808u, 0x0808082bu, 0x082b2b2bu, 0x0808082bu, 0x19080819u, 0x0808082bu, 0x19081908u, 0x0808082bu,+ 0x1908192bu, 0x0808082bu, 0x19082b19u, 0x0808082bu, 0x19190808u, 0x0808082bu, 0x19191919u, 0x0808082bu,+ 0x2b080808u, 0x0808082bu, 0x2b081919u, 0x0808082bu, 0x2b082b2bu, 0x0808082bu, 0x2b191908u, 0x0808082bu,+ 0x2b2b082bu, 0x0808082bu, 0x08080819u, 0x08081908u, 0x08081908u, 0x08081908u, 0x0808192bu, 0x08081908u,+ 0x08082b19u, 0x08081908u, 0x08190808u, 0x08081908u, 0x0819082bu, 0x08081908u, 0x08191919u, 0x08081908u,+ 0x08192b08u, 0x08081908u, 0x082b0819u, 0x08081908u, 0x082b1908u, 0x08081908u, 0x082b192bu, 0x08081908u,+ 0x082b2b19u, 0x08081908u, 0x19080808u, 0x08081908u, 0x1908082bu, 0x08081908u, 0x19081919u, 0x08081908u,+ 0x19082b08u, 0x08081908u, 0x19082b2bu, 0x08081908u, 0x19190819u, 0x08081908u, 0x19191908u, 0x08081908u,+ 0x1919192bu, 0x08081908u, 0x19192b19u, 0x08081908u, 0x192b0808u, 0x08081908u, 0x192b082bu, 0x08081908u,+ 0x192b1919u, 0x08081908u, 0x2b080819u, 0x08081908u, 0x2b081908u, 0x08081908u, 0x2b08192bu, 0x08081908u,+ 0x2b082b19u, 0x08081908u, 0x2b190808u, 0x08081908u, 0x2b191919u, 0x08081908u, 0x2b192b08u, 0x08081908u,+ 0x2b2b0819u, 0x08081908u, 0x2b2b1908u, 0x08081908u, 0x08080808u, 0x08081919u, 0x0808082bu, 0x08081919u,+ 0x08081919u, 0x08081919u, 0x08082b08u, 0x08081919u, 0x08082b2bu, 0x08081919u, 0x08190819u, 0x08081919u,+ 0x08191908u, 0x08081919u, 0x0819192bu, 0x08081919u, 0x08192b19u, 0x08081919u, 0x082b0808u, 0x08081919u,+ 0x082b1919u, 0x08081919u, 0x082b2b08u, 0x08081919u, 0x19080819u, 0x08081919u, 0x19081908u, 0x08081919u,+ 0x1908192bu, 0x08081919u, 0x19082b19u, 0x08081919u, 0x19190808u, 0x08081919u, 0x1919082bu, 0x08081919u,+ 0x19191919u, 0x08081919u, 0x19192b08u, 0x08081919u, 0x192b0819u, 0x08081919u, 0x192b1908u, 0x08081919u,+ 0x2b080808u, 0x08081919u, 0x2b08082bu, 0x08081919u, 0x2b081919u, 0x08081919u, 0x2b082b08u, 0x08081919u,+ 0x2b190819u, 0x08081919u, 0x2b191908u, 0x08081919u, 0x2b2b0808u, 0x08081919u, 0x08080819u, 0x0808192bu,+ 0x08081908u, 0x0808192bu, 0x0808192bu, 0x0808192bu, 0x08082b19u, 0x0808192bu, 0x08190808u, 0x0808192bu,+ 0x08191919u, 0x0808192bu, 0x19080808u, 0x0808192bu, 0x19081919u, 0x0808192bu, 0x19082b08u, 0x0808192bu,+ 0x19190819u, 0x0808192bu, 0x19191908u, 0x0808192bu, 0x192b0808u, 0x0808192bu, 0x2b080819u, 0x0808192bu,+ 0x2b081908u, 0x0808192bu, 0x2b190808u, 0x0808192bu, 0x08080808u, 0x08082b08u, 0x0808082bu, 0x08082b08u,+ 0x08081919u, 0x08082b08u, 0x08082b08u, 0x08082b08u, 0x08190819u, 0x08082b08u, 0x08191908u, 0x08082b08u,+ 0x0819192bu, 0x08082b08u, 0x08192b19u, 0x08082b08u, 0x082b0808u, 0x08082b08u, 0x082b1919u, 0x08082b08u,+ 0x082b2b2bu, 0x08082b08u, 0x19080819u, 0x08082b08u, 0x19081908u, 0x08082b08u, 0x1908192bu, 0x08082b08u,+ 0x19082b19u, 0x08082b08u, 0x19190808u, 0x08082b08u, 0x1919082bu, 0x08082b08u, 0x19191919u, 0x08082b08u,+ 0x19192b08u, 0x08082b08u, 0x192b0819u, 0x08082b08u, 0x192b1908u, 0x08082b08u, 0x2b080808u, 0x08082b08u,+ 0x2b081919u, 0x08082b08u, 0x2b191908u, 0x08082b08u, 0x2b2b2b2bu, 0x08082b08u, 0x08080819u, 0x08082b19u,+ 0x08081908u, 0x08082b19u, 0x08190808u, 0x08082b19u, 0x0819082bu, 0x08082b19u, 0x08191919u, 0x08082b19u,+ 0x08192b08u, 0x08082b19u, 0x082b0819u, 0x08082b19u, 0x19080808u, 0x08082b19u, 0x19081919u, 0x08082b19u,+ 0x19082b08u, 0x08082b19u, 0x19190819u, 0x08082b19u, 0x19191908u, 0x08082b19u, 0x192b0808u, 0x08082b19u,+ 0x2b080819u, 0x08082b19u, 0x2b190808u, 0x08082b19u, 0x08080808u, 0x08082b2bu, 0x08190819u, 0x08082b2bu,+ 0x08191908u, 0x08082b2bu, 0x082b082bu, 0x08082b2bu, 0x082b2b08u, 0x08082b2bu, 0x082b2b2bu, 0x08082b2bu,+ 0x19190808u, 0x08082b2bu, 0x2b192b19u, 0x08082b2bu, 0x08080819u, 0x08190808u, 0x08081908u, 0x08190808u,+ 0x0808192bu, 0x08190808u, 0x08082b19u, 0x08190808u, 0x08190808u, 0x08190808u, 0x0819082bu, 0x08190808u,+ 0x08191919u, 0x08190808u, 0x08192b08u, 0x08190808u, 0x082b0819u, 0x08190808u, 0x082b1908u, 0x08190808u,+ 0x082b192bu, 0x08190808u, 0x19080808u, 0x08190808u, 0x1908082bu, 0x08190808u, 0x19081919u, 0x08190808u,+ 0x19082b08u, 0x08190808u, 0x19190819u, 0x08190808u, 0x19191908u, 0x08190808u, 0x1919192bu, 0x08190808u,+ 0x19192b19u, 0x08190808u, 0x192b0808u, 0x08190808u, 0x192b082bu, 0x08190808u, 0x192b1919u, 0x08190808u,+ 0x192b2b08u, 0x08190808u, 0x2b080819u, 0x08190808u, 0x2b081908u, 0x08190808u, 0x2b08192bu, 0x08190808u,+ 0x2b190808u, 0x08190808u, 0x2b191919u, 0x08190808u, 0x2b192b08u, 0x08190808u, 0x2b2b0819u, 0x08190808u,+ 0x2b2b1908u, 0x08190808u, 0x08080808u, 0x08190819u, 0x0808082bu, 0x08190819u, 0x08081919u, 0x08190819u,+ 0x08082b08u, 0x08190819u, 0x08082b2bu, 0x08190819u, 0x08190819u, 0x08190819u, 0x08191908u, 0x08190819u,+ 0x0819192bu, 0x08190819u, 0x08192b19u, 0x08190819u, 0x082b0808u, 0x08190819u, 0x082b082bu, 0x08190819u,+ 0x082b1919u, 0x08190819u, 0x082b2b08u, 0x08190819u, 0x19080819u, 0x08190819u, 0x19081908u, 0x08190819u,+ 0x1908192bu, 0x08190819u, 0x19082b19u, 0x08190819u, 0x19190808u, 0x08190819u, 0x1919082bu, 0x08190819u,+ 0x19191919u, 0x08190819u, 0x19192b08u, 0x08190819u, 0x192b0819u, 0x08190819u, 0x192b1908u, 0x08190819u,+ 0x2b080808u, 0x08190819u, 0x2b08082bu, 0x08190819u, 0x2b081919u, 0x08190819u, 0x2b082b08u, 0x08190819u,+ 0x2b190819u, 0x08190819u, 0x2b191908u, 0x08190819u, 0x08080819u, 0x0819082bu, 0x08081908u, 0x0819082bu,+ 0x08082b19u, 0x0819082bu, 0x08190808u, 0x0819082bu, 0x08191919u, 0x0819082bu, 0x082b0819u, 0x0819082bu,+ 0x082b1908u, 0x0819082bu, 0x19080808u, 0x0819082bu, 0x19081919u, 0x0819082bu, 0x19190819u, 0x0819082bu,+ 0x19191908u, 0x0819082bu, 0x2b080819u, 0x0819082bu, 0x2b081908u, 0x0819082bu, 0x2b190808u, 0x0819082bu,+ 0x08080808u, 0x08191908u, 0x0808082bu, 0x08191908u, 0x08081919u, 0x08191908u, 0x08082b08u, 0x08191908u,+ 0x08190819u, 0x08191908u, 0x08191908u, 0x08191908u, 0x0819192bu, 0x08191908u, 0x08192b19u, 0x08191908u,+ 0x082b0808u, 0x08191908u, 0x082b1919u, 0x08191908u, 0x082b2b08u, 0x08191908u, 0x19080819u, 0x08191908u,+ 0x19081908u, 0x08191908u, 0x1908192bu, 0x08191908u, 0x19082b19u, 0x08191908u, 0x19190808u, 0x08191908u,+ 0x1919082bu, 0x08191908u, 0x19191919u, 0x08191908u, 0x19192b08u, 0x08191908u, 0x192b0819u, 0x08191908u,+ 0x192b1908u, 0x08191908u, 0x2b080808u, 0x08191908u, 0x2b08082bu, 0x08191908u, 0x2b081919u, 0x08191908u,+ 0x2b082b08u, 0x08191908u, 0x2b190819u, 0x08191908u, 0x2b191908u, 0x08191908u, 0x2b2b0808u, 0x08191908u,+ 0x08080819u, 0x08191919u, 0x08081908u, 0x08191919u, 0x0808192bu, 0x08191919u, 0x08082b19u, 0x08191919u,+ 0x08190808u, 0x08191919u, 0x0819082bu, 0x08191919u, 0x08191919u, 0x08191919u, 0x08192b08u, 0x08191919u,+ 0x082b0819u, 0x08191919u, 0x082b1908u, 0x08191919u, 0x19080808u, 0x08191919u, 0x1908082bu, 0x08191919u,+ 0x19081919u, 0x08191919u, 0x19082b08u, 0x08191919u, 0x19190819u, 0x08191919u, 0x19191908u, 0x08191919u,+ 0x192b0808u, 0x08191919u, 0x2b080819u, 0x08191919u, 0x2b081908u, 0x08191919u, 0x2b190808u, 0x08191919u,+ 0x08080808u, 0x0819192bu, 0x08081919u, 0x0819192bu, 0x08082b08u, 0x0819192bu, 0x08190819u, 0x0819192bu,+ 0x08191908u, 0x0819192bu, 0x082b0808u, 0x0819192bu, 0x19080819u, 0x0819192bu, 0x19081908u, 0x0819192bu,+ 0x19190808u, 0x0819192bu, 0x2b080808u, 0x0819192bu, 0x2b2b2b2bu, 0x0819192bu, 0x08080819u, 0x08192b08u,+ 0x08081908u, 0x08192b08u, 0x0808192bu, 0x08192b08u, 0x08082b19u, 0x08192b08u, 0x08190808u, 0x08192b08u,+ 0x08191919u, 0x08192b08u, 0x08192b08u, 0x08192b08u, 0x082b0819u, 0x08192b08u, 0x19080808u, 0x08192b08u,+ 0x1908082bu, 0x08192b08u, 0x19081919u, 0x08192b08u, 0x19082b08u, 0x08192b08u, 0x19190819u, 0x08192b08u,+ 0x19191908u, 0x08192b08u, 0x192b0808u, 0x08192b08u, 0x2b080819u, 0x08192b08u, 0x2b081908u, 0x08192b08u,+ 0x08080808u, 0x08192b19u, 0x0808082bu, 0x08192b19u, 0x08081919u, 0x08192b19u, 0x08082b08u, 0x08192b19u,+ 0x08190819u, 0x08192b19u, 0x08191908u, 0x08192b19u, 0x082b0808u, 0x08192b19u, 0x19080819u, 0x08192b19u,+ 0x19081908u, 0x08192b19u, 0x19190808u, 0x08192b19u, 0x192b2b19u, 0x08192b19u, 0x2b2b082bu, 0x08192b19u,+ 0x08081908u, 0x08192b2bu, 0x08190808u, 0x08192b2bu, 0x19080808u, 0x08192b2bu, 0x1919192bu, 0x08192b2bu,+ 0x08080808u, 0x082b0808u, 0x0808082bu, 0x082b0808u, 0x08081919u, 0x082b0808u, 0x08082b08u, 0x082b0808u,+ 0x08190819u, 0x082b0808u, 0x08191908u, 0x082b0808u, 0x0819192bu, 0x082b0808u, 0x08192b19u, 0x082b0808u,+ 0x082b0808u, 0x082b0808u, 0x082b1919u, 0x082b0808u, 0x082b2b2bu, 0x082b0808u, 0x19080819u, 0x082b0808u,+ 0x19081908u, 0x082b0808u, 0x19190808u, 0x082b0808u, 0x1919082bu, 0x082b0808u, 0x19191919u, 0x082b0808u,+ 0x192b1908u, 0x082b0808u, 0x2b080808u, 0x082b0808u, 0x2b082b2bu, 0x082b0808u, 0x2b191908u, 0x082b0808u,+ 0x2b2b2b2bu, 0x082b0808u, 0x08080819u, 0x082b0819u, 0x08081908u, 0x082b0819u, 0x08190808u, 0x082b0819u,+ 0x0819082bu, 0x082b0819u, 0x08191919u, 0x082b0819u, 0x082b0819u, 0x082b0819u, 0x19080808u, 0x082b0819u,+ 0x1908082bu, 0x082b0819u, 0x19081919u, 0x082b0819u, 0x19190819u, 0x082b0819u, 0x19191908u, 0x082b0819u,+ 0x192b0808u, 0x082b0819u, 0x2b080819u, 0x082b0819u, 0x2b081908u, 0x082b0819u, 0x2b190808u, 0x082b0819u,+ 0x08080808u, 0x082b082bu, 0x08082b2bu, 0x082b082bu, 0x082b082bu, 0x082b082bu, 0x082b2b08u, 0x082b082bu,+ 0x082b2b2bu, 0x082b082bu, 0x19081908u, 0x082b082bu, 0x19190808u, 0x082b082bu, 0x2b082b08u, 0x082b082bu,+ 0x2b082b2bu, 0x082b082bu, 0x2b2b2b08u, 0x082b082bu, 0x08080819u, 0x082b1908u, 0x08081908u, 0x082b1908u,+ 0x0808192bu, 0x082b1908u, 0x08082b19u, 0x082b1908u, 0x08190808u, 0x082b1908u, 0x08191919u, 0x082b1908u,+ 0x08192b08u, 0x082b1908u, 0x082b0819u, 0x082b1908u, 0x082b1908u, 0x082b1908u, 0x19080808u, 0x082b1908u,+ 0x1908082bu, 0x082b1908u, 0x19081919u, 0x082b1908u, 0x19082b08u, 0x082b1908u, 0x19190819u, 0x082b1908u,+ 0x19191908u, 0x082b1908u, 0x192b0808u, 0x082b1908u, 0x2b080819u, 0x082b1908u, 0x2b081908u, 0x082b1908u,+ 0x2b190808u, 0x082b1908u, 0x08080808u, 0x082b1919u, 0x08081919u, 0x082b1919u, 0x08082b08u, 0x082b1919u,+ 0x08190819u, 0x082b1919u, 0x08191908u, 0x082b1919u, 0x082b0808u, 0x082b1919u, 0x19080819u, 0x082b1919u,+ 0x19081908u, 0x082b1919u, 0x19190808u, 0x082b1919u, 0x192b192bu, 0x082b1919u, 0x2b080808u, 0x082b1919u,+ 0x08080819u, 0x082b192bu, 0x08081908u, 0x082b192bu, 0x08190808u, 0x082b192bu, 0x19080808u, 0x082b192bu,+ 0x19192b19u, 0x082b192bu, 0x08080808u, 0x082b2b08u, 0x08081919u, 0x082b2b08u, 0x08190819u, 0x082b2b08u,+ 0x08191908u, 0x082b2b08u, 0x19080819u, 0x082b2b08u, 0x19081908u, 0x082b2b08u, 0x19190808u, 0x082b2b08u,+ 0x2b082b2bu, 0x082b2b08u, 0x2b2b2b2bu, 0x082b2b08u, 0x08080819u, 0x082b2b19u, 0x08081908u, 0x082b2b19u,+ 0x08190808u, 0x082b2b19u, 0x2b191919u, 0x082b2b19u, 0x08082b2bu, 0x082b2b2bu, 0x082b082bu, 0x082b2b2bu,+ 0x192b1908u, 0x082b2b2bu, 0x2b082b08u, 0x082b2b2bu, 0x2b082b2bu, 0x082b2b2bu, 0x08080819u, 0x19080808u,+ 0x08081908u, 0x19080808u, 0x0808192bu, 0x19080808u, 0x08082b19u, 0x19080808u, 0x08190808u, 0x19080808u,+ 0x0819082bu, 0x19080808u, 0x08191919u, 0x19080808u, 0x08192b08u, 0x19080808u, 0x08192b2bu, 0x19080808u,+ 0x082b0819u, 0x19080808u, 0x082b1908u, 0x19080808u, 0x082b192bu, 0x19080808u, 0x19080808u, 0x19080808u,+ 0x1908082bu, 0x19080808u, 0x19081919u, 0x19080808u, 0x19082b08u, 0x19080808u, 0x19082b2bu, 0x19080808u,+ 0x19190819u, 0x19080808u, 0x19191908u, 0x19080808u, 0x1919192bu, 0x19080808u, 0x19192b19u, 0x19080808u,+ 0x192b0808u, 0x19080808u, 0x192b082bu, 0x19080808u, 0x192b1919u, 0x19080808u, 0x2b080819u, 0x19080808u,+ 0x2b081908u, 0x19080808u, 0x2b190808u, 0x19080808u, 0x2b191919u, 0x19080808u, 0x2b192b08u, 0x19080808u,+ 0x2b2b0819u, 0x19080808u, 0x2b2b1908u, 0x19080808u, 0x08080808u, 0x19080819u, 0x0808082bu, 0x19080819u,+ 0x08081919u, 0x19080819u, 0x08082b08u, 0x19080819u, 0x08190819u, 0x19080819u, 0x08191908u, 0x19080819u,+ 0x0819192bu, 0x19080819u, 0x08192b19u, 0x19080819u, 0x082b0808u, 0x19080819u, 0x082b082bu, 0x19080819u,+ 0x082b1919u, 0x19080819u, 0x19080819u, 0x19080819u, 0x19081908u, 0x19080819u, 0x1908192bu, 0x19080819u,+ 0x19082b19u, 0x19080819u, 0x19190808u, 0x19080819u, 0x1919082bu, 0x19080819u, 0x19191919u, 0x19080819u,+ 0x19192b08u, 0x19080819u, 0x192b0819u, 0x19080819u, 0x192b1908u, 0x19080819u, 0x2b080808u, 0x19080819u,+ 0x2b08082bu, 0x19080819u, 0x2b081919u, 0x19080819u, 0x2b082b08u, 0x19080819u, 0x2b190819u, 0x19080819u,+ 0x2b191908u, 0x19080819u, 0x2b2b0808u, 0x19080819u, 0x08080819u, 0x1908082bu, 0x08081908u, 0x1908082bu,+ 0x08190808u, 0x1908082bu, 0x0819082bu, 0x1908082bu, 0x08191919u, 0x1908082bu, 0x08192b08u, 0x1908082bu,+ 0x082b1908u, 0x1908082bu, 0x19080808u, 0x1908082bu, 0x19081919u, 0x1908082bu, 0x19082b08u, 0x1908082bu,+ 0x19190819u, 0x1908082bu, 0x19191908u, 0x1908082bu, 0x192b0808u, 0x1908082bu, 0x2b080819u, 0x1908082bu,+ 0x2b081908u, 0x1908082bu, 0x08080808u, 0x19081908u, 0x0808082bu, 0x19081908u, 0x08081919u, 0x19081908u,+ 0x08082b08u, 0x19081908u, 0x08082b2bu, 0x19081908u, 0x08190819u, 0x19081908u, 0x08191908u, 0x19081908u,+ 0x0819192bu, 0x19081908u, 0x08192b19u, 0x19081908u, 0x082b0808u, 0x19081908u, 0x082b082bu, 0x19081908u,+ 0x082b1919u, 0x19081908u, 0x082b2b08u, 0x19081908u, 0x19080819u, 0x19081908u, 0x19081908u, 0x19081908u,+ 0x1908192bu, 0x19081908u, 0x19082b19u, 0x19081908u, 0x19190808u, 0x19081908u, 0x1919082bu, 0x19081908u,+ 0x19191919u, 0x19081908u, 0x19192b08u, 0x19081908u, 0x192b0819u, 0x19081908u, 0x192b1908u, 0x19081908u,+ 0x2b080808u, 0x19081908u, 0x2b08082bu, 0x19081908u, 0x2b081919u, 0x19081908u, 0x2b082b08u, 0x19081908u,+ 0x2b190819u, 0x19081908u, 0x2b191908u, 0x19081908u, 0x2b2b0808u, 0x19081908u, 0x08080819u, 0x19081919u,+ 0x08081908u, 0x19081919u, 0x0808192bu, 0x19081919u, 0x08082b19u, 0x19081919u, 0x08190808u, 0x19081919u,+ 0x0819082bu, 0x19081919u, 0x08191919u, 0x19081919u, 0x08192b08u, 0x19081919u, 0x082b0819u, 0x19081919u,+ 0x082b1908u, 0x19081919u, 0x19080808u, 0x19081919u, 0x1908082bu, 0x19081919u, 0x19081919u, 0x19081919u,+ 0x19082b08u, 0x19081919u, 0x19190819u, 0x19081919u, 0x19191908u, 0x19081919u, 0x192b0808u, 0x19081919u,+ 0x192b2b2bu, 0x19081919u, 0x2b080819u, 0x19081919u, 0x2b081908u, 0x19081919u, 0x2b190808u, 0x19081919u,+ 0x08080808u, 0x1908192bu, 0x0808082bu, 0x1908192bu, 0x08081919u, 0x1908192bu, 0x08082b08u, 0x1908192bu,+ 0x08190819u, 0x1908192bu, 0x08191908u, 0x1908192bu, 0x082b0808u, 0x1908192bu, 0x19080819u, 0x1908192bu,+ 0x19081908u, 0x1908192bu, 0x19190808u, 0x1908192bu, 0x2b080808u, 0x1908192bu, 0x2b2b1919u, 0x1908192bu,+ 0x08080819u, 0x19082b08u, 0x08081908u, 0x19082b08u, 0x08082b19u, 0x19082b08u, 0x08190808u, 0x19082b08u,+ 0x0819082bu, 0x19082b08u, 0x08191919u, 0x19082b08u, 0x08192b08u, 0x19082b08u, 0x082b0819u, 0x19082b08u,+ 0x082b1908u, 0x19082b08u, 0x19080808u, 0x19082b08u, 0x1908082bu, 0x19082b08u, 0x19081919u, 0x19082b08u,+ 0x19082b08u, 0x19082b08u, 0x19190819u, 0x19082b08u, 0x19191908u, 0x19082b08u, 0x192b0808u, 0x19082b08u,+ 0x2b081908u, 0x19082b08u, 0x2b190808u, 0x19082b08u, 0x08080808u, 0x19082b19u, 0x0808082bu, 0x19082b19u,+ 0x08081919u, 0x19082b19u, 0x08082b08u, 0x19082b19u, 0x08190819u, 0x19082b19u, 0x08191908u, 0x19082b19u,+ 0x082b0808u, 0x19082b19u, 0x19080819u, 0x19082b19u, 0x19081908u, 0x19082b19u, 0x19190808u, 0x19082b19u,+ 0x2b080808u, 0x19082b19u, 0x2b19192bu, 0x19082b19u, 0x08080819u, 0x19082b2bu, 0x08081908u, 0x19082b2bu,+ 0x08190808u, 0x19082b2bu, 0x19080808u, 0x19082b2bu, 0x08080808u, 0x19190808u, 0x0808082bu, 0x19190808u,+ 0x08081919u, 0x19190808u, 0x08082b08u, 0x19190808u, 0x08190819u, 0x19190808u, 0x08191908u, 0x19190808u,+ 0x0819192bu, 0x19190808u, 0x08192b19u, 0x19190808u, 0x082b0808u, 0x19190808u, 0x082b082bu, 0x19190808u,+ 0x082b1919u, 0x19190808u, 0x082b2b08u, 0x19190808u, 0x19080819u, 0x19190808u, 0x19081908u, 0x19190808u,+ 0x1908192bu, 0x19190808u, 0x19082b19u, 0x19190808u, 0x19190808u, 0x19190808u, 0x1919082bu, 0x19190808u,+ 0x19191919u, 0x19190808u, 0x19192b08u, 0x19190808u, 0x192b0819u, 0x19190808u, 0x192b1908u, 0x19190808u,+ 0x2b080808u, 0x19190808u, 0x2b08082bu, 0x19190808u, 0x2b081919u, 0x19190808u, 0x2b082b08u, 0x19190808u,+ 0x2b190819u, 0x19190808u, 0x2b191908u, 0x19190808u, 0x08080819u, 0x19190819u, 0x08081908u, 0x19190819u,+ 0x0808192bu, 0x19190819u, 0x08082b19u, 0x19190819u, 0x08190808u, 0x19190819u, 0x0819082bu, 0x19190819u,+ 0x08191919u, 0x19190819u, 0x08192b08u, 0x19190819u, 0x082b0819u, 0x19190819u, 0x082b1908u, 0x19190819u,+ 0x19080808u, 0x19190819u, 0x1908082bu, 0x19190819u, 0x19081919u, 0x19190819u, 0x19082b08u, 0x19190819u,+ 0x19190819u, 0x19190819u, 0x19191908u, 0x19190819u, 0x192b0808u, 0x19190819u, 0x2b080819u, 0x19190819u,+ 0x2b081908u, 0x19190819u, 0x2b190808u, 0x19190819u, 0x08080808u, 0x1919082bu, 0x08081919u, 0x1919082bu,+ 0x08082b08u, 0x1919082bu, 0x08190819u, 0x1919082bu, 0x08191908u, 0x1919082bu, 0x082b0808u, 0x1919082bu,+ 0x19080819u, 0x1919082bu, 0x19081908u, 0x1919082bu, 0x19190808u, 0x1919082bu, 0x192b2b19u, 0x1919082bu,+ 0x2b080808u, 0x1919082bu, 0x08080819u, 0x19191908u, 0x08081908u, 0x19191908u, 0x0808192bu, 0x19191908u,+ 0x08082b19u, 0x19191908u, 0x08190808u, 0x19191908u, 0x0819082bu, 0x19191908u, 0x08191919u, 0x19191908u,+ 0x08192b08u, 0x19191908u, 0x082b0819u, 0x19191908u, 0x082b1908u, 0x19191908u, 0x19080808u, 0x19191908u,+ 0x1908082bu, 0x19191908u, 0x19081919u, 0x19191908u, 0x19082b08u, 0x19191908u, 0x19190819u, 0x19191908u,+ 0x19191908u, 0x19191908u, 0x192b0808u, 0x19191908u, 0x2b080819u, 0x19191908u, 0x2b081908u, 0x19191908u,+ 0x2b190808u, 0x19191908u, 0x08080808u, 0x19191919u, 0x0808082bu, 0x19191919u, 0x08081919u, 0x19191919u,+ 0x08082b08u, 0x19191919u, 0x08190819u, 0x19191919u, 0x08191908u, 0x19191919u, 0x082b0808u, 0x19191919u,+ 0x19080819u, 0x19191919u, 0x19081908u, 0x19191919u, 0x19190808u, 0x19191919u, 0x2b080808u, 0x19191919u,+ 0x08080819u, 0x1919192bu, 0x08081908u, 0x1919192bu, 0x08190808u, 0x1919192bu, 0x082b192bu, 0x1919192bu,+ 0x19080808u, 0x1919192bu, 0x08080808u, 0x19192b08u, 0x0808082bu, 0x19192b08u, 0x08081919u, 0x19192b08u,+ 0x08082b08u, 0x19192b08u, 0x08190819u, 0x19192b08u, 0x08191908u, 0x19192b08u, 0x082b0808u, 0x19192b08u,+ 0x19080819u, 0x19192b08u, 0x19081908u, 0x19192b08u, 0x19190808u, 0x19192b08u, 0x19192b2bu, 0x19192b08u,+ 0x2b080808u, 0x19192b08u, 0x08080819u, 0x19192b19u, 0x08081908u, 0x19192b19u, 0x08190808u, 0x19192b19u,+ 0x19080808u, 0x19192b19u, 0x08080808u, 0x19192b2bu, 0x08192b19u, 0x19192b2bu, 0x2b081919u, 0x19192b2bu,+ 0x2b2b2b08u, 0x19192b2bu, 0x08080819u, 0x192b0808u, 0x08081908u, 0x192b0808u, 0x0808192bu, 0x192b0808u,+ 0x08190808u, 0x192b0808u, 0x0819082bu, 0x192b0808u, 0x08191919u, 0x192b0808u, 0x08192b08u, 0x192b0808u,+ 0x082b0819u, 0x192b0808u, 0x082b1908u, 0x192b0808u, 0x19080808u, 0x192b0808u, 0x19081919u, 0x192b0808u,+ 0x19082b08u, 0x192b0808u, 0x19190819u, 0x192b0808u, 0x19191908u, 0x192b0808u, 0x192b0808u, 0x192b0808u,+ 0x2b081908u, 0x192b0808u, 0x2b190808u, 0x192b0808u, 0x08080808u, 0x192b0819u, 0x0808082bu, 0x192b0819u,+ 0x08081919u, 0x192b0819u, 0x08082b08u, 0x192b0819u, 0x08190819u, 0x192b0819u, 0x08191908u, 0x192b0819u,+ 0x082b0808u, 0x192b0819u, 0x19080819u, 0x192b0819u, 0x19081908u, 0x192b0819u, 0x19190808u, 0x192b0819u,+ 0x2b080808u, 0x192b0819u, 0x2b192b19u, 0x192b0819u, 0x08081908u, 0x192b082bu, 0x08190808u, 0x192b082bu,+ 0x19080808u, 0x192b082bu, 0x1919192bu, 0x192b082bu, 0x2b2b0819u, 0x192b082bu, 0x08080808u, 0x192b1908u,+ 0x08081919u, 0x192b1908u, 0x08082b08u, 0x192b1908u, 0x08190819u, 0x192b1908u, 0x08191908u, 0x192b1908u,+ 0x082b0808u, 0x192b1908u, 0x19080819u, 0x192b1908u, 0x19081908u, 0x192b1908u, 0x19190808u, 0x192b1908u,+ 0x2b080808u, 0x192b1908u, 0x08080819u, 0x192b1919u, 0x08081908u, 0x192b1919u, 0x08190808u, 0x192b1919u,+ 0x19080808u, 0x192b1919u, 0x19082b2bu, 0x192b1919u, 0x192b2b08u, 0x192b1919u, 0x2b19082bu, 0x192b1919u,+ 0x08080808u, 0x192b192bu, 0x2b191908u, 0x192b192bu, 0x08080819u, 0x192b2b08u, 0x08081908u, 0x192b2b08u,+ 0x08190808u, 0x192b2b08u, 0x192b1919u, 0x192b2b08u, 0x2b192b08u, 0x192b2b08u, 0x08080808u, 0x192b2b19u,+ 0x082b2b2bu, 0x192b2b19u, 0x1908082bu, 0x192b2b2bu, 0x2b2b0819u, 0x192b2b2bu, 0x08080808u, 0x2b080808u,+ 0x0808082bu, 0x2b080808u, 0x08081919u, 0x2b080808u, 0x08082b08u, 0x2b080808u, 0x08190819u, 0x2b080808u,+ 0x08191908u, 0x2b080808u, 0x08192b19u, 0x2b080808u, 0x082b0808u, 0x2b080808u, 0x082b1919u, 0x2b080808u,+ 0x19080819u, 0x2b080808u, 0x19081908u, 0x2b080808u, 0x19190808u, 0x2b080808u, 0x1919082bu, 0x2b080808u,+ 0x19191919u, 0x2b080808u, 0x19192b08u, 0x2b080808u, 0x192b0819u, 0x2b080808u, 0x2b080808u, 0x2b080808u,+ 0x2b081919u, 0x2b080808u, 0x2b190819u, 0x2b080808u, 0x2b191908u, 0x2b080808u, 0x08080819u, 0x2b080819u,+ 0x08081908u, 0x2b080819u, 0x08082b19u, 0x2b080819u, 0x08190808u, 0x2b080819u, 0x0819082bu, 0x2b080819u,+ 0x08191919u, 0x2b080819u, 0x08192b08u, 0x2b080819u, 0x082b0819u, 0x2b080819u, 0x082b1908u, 0x2b080819u,+ 0x19080808u, 0x2b080819u, 0x1908082bu, 0x2b080819u, 0x19081919u, 0x2b080819u, 0x19082b08u, 0x2b080819u,+ 0x19190819u, 0x2b080819u, 0x19191908u, 0x2b080819u, 0x2b080819u, 0x2b080819u, 0x2b081908u, 0x2b080819u,+ 0x2b190808u, 0x2b080819u, 0x2b2b2b19u, 0x2b080819u, 0x08080808u, 0x2b08082bu, 0x08081919u, 0x2b08082bu,+ 0x08082b2bu, 0x2b08082bu, 0x08190819u, 0x2b08082bu, 0x08191908u, 0x2b08082bu, 0x19080819u, 0x2b08082bu,+ 0x19081908u, 0x2b08082bu, 0x19190808u, 0x2b08082bu, 0x08080819u, 0x2b081908u, 0x08081908u, 0x2b081908u,+ 0x0808192bu, 0x2b081908u, 0x08082b19u, 0x2b081908u, 0x08190808u, 0x2b081908u, 0x0819082bu, 0x2b081908u,+ 0x08191919u, 0x2b081908u, 0x08192b08u, 0x2b081908u, 0x082b0819u, 0x2b081908u, 0x19080808u, 0x2b081908u,+ 0x1908082bu, 0x2b081908u, 0x19081919u, 0x2b081908u, 0x19082b08u, 0x2b081908u, 0x19190819u, 0x2b081908u,+ 0x19191908u, 0x2b081908u, 0x192b0808u, 0x2b081908u, 0x2b080819u, 0x2b081908u, 0x2b081908u, 0x2b081908u,+ 0x2b190808u, 0x2b081908u, 0x08080808u, 0x2b081919u, 0x0808082bu, 0x2b081919u, 0x08081919u, 0x2b081919u,+ 0x08082b08u, 0x2b081919u, 0x08190819u, 0x2b081919u, 0x08191908u, 0x2b081919u, 0x082b0808u, 0x2b081919u,+ 0x19080819u, 0x2b081919u, 0x19081908u, 0x2b081919u, 0x19190808u, 0x2b081919u, 0x2b080808u, 0x2b081919u,+ 0x2b082b2bu, 0x2b081919u, 0x08080819u, 0x2b08192bu, 0x08081908u, 0x2b08192bu, 0x08190808u, 0x2b08192bu,+ 0x082b2b19u, 0x2b08192bu, 0x19080808u, 0x2b08192bu, 0x08080808u, 0x2b082b08u, 0x08081919u, 0x2b082b08u,+ 0x08190819u, 0x2b082b08u, 0x08191908u, 0x2b082b08u, 0x19080819u, 0x2b082b08u, 0x19081908u, 0x2b082b08u,+ 0x19190808u, 0x2b082b08u, 0x2b2b082bu, 0x2b082b08u, 0x08080819u, 0x2b082b19u, 0x08081908u, 0x2b082b19u,+ 0x19080808u, 0x2b082b19u, 0x192b1919u, 0x2b082b19u, 0x082b082bu, 0x2b082b2bu, 0x19192b08u, 0x2b082b2bu,+ 0x19192b2bu, 0x2b082b2bu, 0x2b08082bu, 0x2b082b2bu, 0x2b2b082bu, 0x2b082b2bu, 0x08080819u, 0x2b190808u,+ 0x08081908u, 0x2b190808u, 0x08082b19u, 0x2b190808u, 0x08190808u, 0x2b190808u, 0x0819082bu, 0x2b190808u,+ 0x08191919u, 0x2b190808u, 0x08192b08u, 0x2b190808u, 0x082b1908u, 0x2b190808u, 0x19080808u, 0x2b190808u,+ 0x1908082bu, 0x2b190808u, 0x19081919u, 0x2b190808u, 0x19082b08u, 0x2b190808u, 0x19190819u, 0x2b190808u,+ 0x19191908u, 0x2b190808u, 0x192b0808u, 0x2b190808u, 0x2b080819u, 0x2b190808u, 0x2b081908u, 0x2b190808u,+ 0x2b190808u, 0x2b190808u, 0x08080808u, 0x2b190819u, 0x08081919u, 0x2b190819u, 0x08190819u, 0x2b190819u,+ 0x08191908u, 0x2b190819u, 0x19080819u, 0x2b190819u, 0x19081908u, 0x2b190819u, 0x19190808u, 0x2b190819u,+ 0x19192b2bu, 0x2b190819u, 0x08080819u, 0x2b19082bu, 0x08081908u, 0x2b19082bu, 0x08190808u, 0x2b19082bu,+ 0x19080808u, 0x2b19082bu, 0x2b2b192bu, 0x2b19082bu, 0x08080808u, 0x2b191908u, 0x0808082bu, 0x2b191908u,+ 0x08081919u, 0x2b191908u, 0x08082b08u, 0x2b191908u, 0x08190819u, 0x2b191908u, 0x08191908u, 0x2b191908u,+ 0x082b0808u, 0x2b191908u, 0x19080819u, 0x2b191908u, 0x19081908u, 0x2b191908u, 0x19190808u, 0x2b191908u,+ 0x2b080808u, 0x2b191908u, 0x2b19192bu, 0x2b191908u, 0x08080819u, 0x2b191919u, 0x08081908u, 0x2b191919u,+ 0x08190808u, 0x2b191919u, 0x19080808u, 0x2b191919u, 0x2b192b08u, 0x2b191919u, 0x2b2b0819u, 0x2b191919u,+ 0x08080808u, 0x2b19192bu, 0x1908192bu, 0x2b19192bu, 0x192b1908u, 0x2b19192bu, 0x08080819u, 0x2b192b08u,+ 0x08081908u, 0x2b192b08u, 0x08190808u, 0x2b192b08u, 0x082b192bu, 0x2b192b08u, 0x19080808u, 0x2b192b08u,+ 0x2b2b2b19u, 0x2b192b08u, 0x08080808u, 0x2b192b19u, 0x19082b19u, 0x2b192b19u, 0x1919082bu, 0x2b192b19u,+ 0x2b190808u, 0x2b192b2bu, 0x08080808u, 0x2b2b0808u, 0x08081919u, 0x2b2b0808u, 0x08082b2bu, 0x2b2b0808u,+ 0x08191908u, 0x2b2b0808u, 0x082b082bu, 0x2b2b0808u, 0x082b2b2bu, 0x2b2b0808u, 0x19080819u, 0x2b2b0808u,+ 0x19081908u, 0x2b2b0808u, 0x19190808u, 0x2b2b0808u, 0x2b2b082bu, 0x2b2b0808u, 0x2b2b2b2bu, 0x2b2b0808u,+ 0x19080808u, 0x2b2b0819u, 0x192b1919u, 0x2b2b0819u, 0x0808082bu, 0x2b2b082bu, 0x08082b2bu, 0x2b2b082bu,+ 0x082b082bu, 0x2b2b082bu, 0x082b2b08u, 0x2b2b082bu, 0x082b2b2bu, 0x2b2b082bu, 0x2b08082bu, 0x2b2b082bu,+ 0x2b082b08u, 0x2b2b082bu, 0x2b082b2bu, 0x2b2b082bu, 0x2b2b2b08u, 0x2b2b082bu, 0x08080819u, 0x2b2b1908u,+ 0x08081908u, 0x2b2b1908u, 0x08190808u, 0x2b2b1908u, 0x19080808u, 0x2b2b1908u, 0x2b082b19u, 0x2b2b1908u,+ 0x2b2b1908u, 0x2b2b1908u, 0x08080808u, 0x2b2b1919u, 0x08192b19u, 0x2b2b1919u, 0x19190819u, 0x2b2b192bu,+ 0x08082b2bu, 0x2b2b2b08u, 0x082b2b08u, 0x2b2b2b08u, 0x2b2b082bu, 0x2b2b2b08u, 0x19191908u, 0x2b2b2b19u,+ 0x2b08192bu, 0x2b2b2b19u, 0x08082b08u, 0x2b2b2b2bu, 0x08082b2bu, 0x2b2b2b2bu, 0x082b0808u, 0x2b2b2b2bu,+ 0x082b082bu, 0x2b2b2b2bu, 0x082b2b08u, 0x2b2b2b2bu, 0x2b082b08u, 0x2b2b2b2bu, 0x2b2b2b2bu, 0x2b2b2b2bu+};++// iq3s_grid (llama.cpp ggml/src/ggml-common.h, MIT): 512 entries x 4 magnitudes (odd bytes 1..15).+__device__ const uint32_t FQ_IQ3S_GRID[512] = {+ 0x01010101u, 0x01010103u, 0x01010105u, 0x0101010bu, 0x0101010fu, 0x01010301u, 0x01010303u, 0x01010305u,+ 0x01010309u, 0x0101030du, 0x01010501u, 0x01010503u, 0x0101050bu, 0x01010707u, 0x01010901u, 0x01010905u,+ 0x0101090bu, 0x0101090fu, 0x01010b03u, 0x01010b07u, 0x01010d01u, 0x01010d05u, 0x01010f03u, 0x01010f09u,+ 0x01010f0fu, 0x01030101u, 0x01030103u, 0x01030105u, 0x01030109u, 0x01030301u, 0x01030303u, 0x0103030bu,+ 0x01030501u, 0x01030507u, 0x0103050fu, 0x01030703u, 0x0103070bu, 0x01030909u, 0x01030d03u, 0x01030d0bu,+ 0x01030f05u, 0x01050101u, 0x01050103u, 0x0105010bu, 0x0105010fu, 0x01050301u, 0x01050307u, 0x0105030du,+ 0x01050503u, 0x0105050bu, 0x01050701u, 0x01050709u, 0x01050905u, 0x0105090bu, 0x0105090fu, 0x01050b03u,+ 0x01050b07u, 0x01050f01u, 0x01050f07u, 0x01070107u, 0x01070303u, 0x0107030bu, 0x01070501u, 0x01070505u,+ 0x01070703u, 0x01070707u, 0x0107070du, 0x01070909u, 0x01070b01u, 0x01070b05u, 0x01070d0fu, 0x01070f03u,+ 0x01070f0bu, 0x01090101u, 0x01090307u, 0x0109030fu, 0x01090503u, 0x01090509u, 0x01090705u, 0x01090901u,+ 0x01090907u, 0x01090b03u, 0x01090f01u, 0x010b0105u, 0x010b0109u, 0x010b0501u, 0x010b0505u, 0x010b050du,+ 0x010b0707u, 0x010b0903u, 0x010b090bu, 0x010b090fu, 0x010b0d0du, 0x010b0f07u, 0x010d010du, 0x010d0303u,+ 0x010d0307u, 0x010d0703u, 0x010d0b05u, 0x010d0f03u, 0x010f0101u, 0x010f0105u, 0x010f0109u, 0x010f0501u,+ 0x010f0505u, 0x010f050du, 0x010f0707u, 0x010f0b01u, 0x010f0b09u, 0x03010101u, 0x03010103u, 0x03010105u,+ 0x03010109u, 0x03010301u, 0x03010303u, 0x03010307u, 0x0301030bu, 0x0301030fu, 0x03010501u, 0x03010505u,+ 0x03010703u, 0x03010709u, 0x0301070du, 0x03010b09u, 0x03010b0du, 0x03010d03u, 0x03010f05u, 0x03030101u,+ 0x03030103u, 0x03030107u, 0x0303010du, 0x03030301u, 0x03030309u, 0x03030503u, 0x03030701u, 0x03030707u,+ 0x03030903u, 0x03030b01u, 0x03030b05u, 0x03030f01u, 0x03030f0du, 0x03050101u, 0x03050305u, 0x0305030bu,+ 0x0305030fu, 0x03050501u, 0x03050509u, 0x03050705u, 0x03050901u, 0x03050907u, 0x03050b0bu, 0x03050d01u,+ 0x03050f05u, 0x03070103u, 0x03070109u, 0x0307010fu, 0x03070301u, 0x03070307u, 0x03070503u, 0x0307050fu,+ 0x03070701u, 0x03070709u, 0x03070903u, 0x03070d05u, 0x03070f01u, 0x03090107u, 0x0309010bu, 0x03090305u,+ 0x03090309u, 0x03090703u, 0x03090707u, 0x03090905u, 0x0309090du, 0x03090b01u, 0x03090b09u, 0x030b0103u,+ 0x030b0301u, 0x030b0307u, 0x030b0503u, 0x030b0701u, 0x030b0705u, 0x030b0b03u, 0x030d0501u, 0x030d0509u,+ 0x030d050fu, 0x030d0909u, 0x030d090du, 0x030f0103u, 0x030f0107u, 0x030f0301u, 0x030f0305u, 0x030f0503u,+ 0x030f070bu, 0x030f0903u, 0x030f0d05u, 0x030f0f01u, 0x05010101u, 0x05010103u, 0x05010107u, 0x0501010bu,+ 0x0501010fu, 0x05010301u, 0x05010305u, 0x05010309u, 0x0501030du, 0x05010503u, 0x05010507u, 0x0501050fu,+ 0x05010701u, 0x05010705u, 0x05010903u, 0x05010907u, 0x0501090bu, 0x05010b01u, 0x05010b05u, 0x05010d0fu,+ 0x05010f01u, 0x05010f07u, 0x05010f0bu, 0x05030101u, 0x05030105u, 0x05030301u, 0x05030307u, 0x0503030fu,+ 0x05030505u, 0x0503050bu, 0x05030703u, 0x05030709u, 0x05030905u, 0x05030b03u, 0x05050103u, 0x05050109u,+ 0x0505010fu, 0x05050503u, 0x05050507u, 0x05050701u, 0x0505070fu, 0x05050903u, 0x05050b07u, 0x05050b0fu,+ 0x05050f03u, 0x05050f09u, 0x05070101u, 0x05070105u, 0x0507010bu, 0x05070303u, 0x05070505u, 0x05070509u,+ 0x05070703u, 0x05070707u, 0x05070905u, 0x05070b01u, 0x05070d0du, 0x05090103u, 0x0509010fu, 0x05090501u,+ 0x05090507u, 0x05090705u, 0x0509070bu, 0x05090903u, 0x05090f05u, 0x05090f0bu, 0x050b0109u, 0x050b0303u,+ 0x050b0505u, 0x050b070fu, 0x050b0901u, 0x050b0b07u, 0x050b0f01u, 0x050d0101u, 0x050d0105u, 0x050d010fu,+ 0x050d0503u, 0x050d0b0bu, 0x050d0d03u, 0x050f010bu, 0x050f0303u, 0x050f050du, 0x050f0701u, 0x050f0907u,+ 0x050f0b01u, 0x07010105u, 0x07010303u, 0x07010307u, 0x0701030bu, 0x0701030fu, 0x07010505u, 0x07010703u,+ 0x07010707u, 0x0701070bu, 0x07010905u, 0x07010909u, 0x0701090fu, 0x07010b03u, 0x07010d07u, 0x07010f03u,+ 0x07030103u, 0x07030107u, 0x0703010bu, 0x07030309u, 0x07030503u, 0x07030507u, 0x07030901u, 0x07030d01u,+ 0x07030f05u, 0x07030f0du, 0x07050101u, 0x07050305u, 0x07050501u, 0x07050705u, 0x07050709u, 0x07050b01u,+ 0x07070103u, 0x07070301u, 0x07070309u, 0x07070503u, 0x07070507u, 0x0707050fu, 0x07070701u, 0x07070903u,+ 0x07070907u, 0x0707090fu, 0x07070b0bu, 0x07070f07u, 0x07090107u, 0x07090303u, 0x0709030du, 0x07090505u,+ 0x07090703u, 0x07090b05u, 0x07090d01u, 0x07090d09u, 0x070b0103u, 0x070b0301u, 0x070b0305u, 0x070b050bu,+ 0x070b0705u, 0x070b0909u, 0x070b0b0du, 0x070b0f07u, 0x070d030du, 0x070d0903u, 0x070f0103u, 0x070f0107u,+ 0x070f0501u, 0x070f0505u, 0x070f070bu, 0x09010101u, 0x09010109u, 0x09010305u, 0x09010501u, 0x09010509u,+ 0x0901050fu, 0x09010705u, 0x09010903u, 0x09010b01u, 0x09010f01u, 0x09030105u, 0x0903010fu, 0x09030303u,+ 0x09030307u, 0x09030505u, 0x09030701u, 0x0903070bu, 0x09030907u, 0x09030b03u, 0x09030b0bu, 0x09050103u,+ 0x09050107u, 0x09050301u, 0x0905030bu, 0x09050503u, 0x09050707u, 0x09050901u, 0x09050b0fu, 0x09050d05u,+ 0x09050f01u, 0x09070109u, 0x09070303u, 0x09070307u, 0x09070501u, 0x09070505u, 0x09070703u, 0x0907070bu,+ 0x09090101u, 0x09090105u, 0x09090509u, 0x0909070fu, 0x09090901u, 0x09090f03u, 0x090b010bu, 0x090b010fu,+ 0x090b0503u, 0x090b0d05u, 0x090d0307u, 0x090d0709u, 0x090d0d01u, 0x090f0301u, 0x090f030bu, 0x090f0701u,+ 0x090f0907u, 0x090f0b03u, 0x0b010105u, 0x0b010301u, 0x0b010309u, 0x0b010505u, 0x0b010901u, 0x0b010909u,+ 0x0b01090fu, 0x0b010b05u, 0x0b010d0du, 0x0b010f09u, 0x0b030103u, 0x0b030107u, 0x0b03010bu, 0x0b030305u,+ 0x0b030503u, 0x0b030705u, 0x0b030f05u, 0x0b050101u, 0x0b050303u, 0x0b050507u, 0x0b050701u, 0x0b05070du,+ 0x0b050b07u, 0x0b070105u, 0x0b07010fu, 0x0b070301u, 0x0b07050fu, 0x0b070909u, 0x0b070b03u, 0x0b070d0bu,+ 0x0b070f07u, 0x0b090103u, 0x0b090109u, 0x0b090501u, 0x0b090705u, 0x0b09090du, 0x0b0b0305u, 0x0b0b050du,+ 0x0b0b0b03u, 0x0b0b0b07u, 0x0b0d0905u, 0x0b0f0105u, 0x0b0f0109u, 0x0b0f0505u, 0x0d010303u, 0x0d010307u,+ 0x0d01030bu, 0x0d010703u, 0x0d010707u, 0x0d010d01u, 0x0d030101u, 0x0d030501u, 0x0d03050fu, 0x0d030d09u,+ 0x0d050305u, 0x0d050709u, 0x0d050905u, 0x0d050b0bu, 0x0d050d05u, 0x0d050f01u, 0x0d070101u, 0x0d070309u,+ 0x0d070503u, 0x0d070901u, 0x0d09050bu, 0x0d090907u, 0x0d090d05u, 0x0d0b0101u, 0x0d0b0107u, 0x0d0b0709u,+ 0x0d0b0d01u, 0x0d0d010bu, 0x0d0d0901u, 0x0d0f0303u, 0x0d0f0307u, 0x0f010101u, 0x0f010109u, 0x0f01010fu,+ 0x0f010501u, 0x0f010505u, 0x0f01070du, 0x0f010901u, 0x0f010b09u, 0x0f010d05u, 0x0f030105u, 0x0f030303u,+ 0x0f030509u, 0x0f030907u, 0x0f03090bu, 0x0f050103u, 0x0f050109u, 0x0f050301u, 0x0f05030du, 0x0f050503u,+ 0x0f050701u, 0x0f050b03u, 0x0f070105u, 0x0f070705u, 0x0f07070bu, 0x0f070b07u, 0x0f090103u, 0x0f09010bu,+ 0x0f090307u, 0x0f090501u, 0x0f090b01u, 0x0f0b0505u, 0x0f0b0905u, 0x0f0d0105u, 0x0f0d0703u, 0x0f0f0101u+};diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_kq_item.cuh b/exllamav3/exllamav3_ext/foreign_quant/fq_kq_item.cuhnew file mode 100644index 0000000..d40ef96--- /dev/null+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_kq_item.cuh@@ -0,0 +1,154 @@+// Q4_K / Q6_K v2 "items" (one thread, one aligned wide load pair = 4 consecutive v1 sub-chunk values), shared by the dense+// rows GEMV (fq_gemv_kq.cu) and the grouped MoE gate+up (fq_moe_kq.cu). Include after fq_gemv.cuh, inside no namespace.+#pragma once+#include <cstdint>+#include <cstring>+#include <cuda_fp16.h>++namespace {++__device__ __forceinline__ float fq_h2f_lo(uint32_t w)+{+ uint16_t lo = (uint16_t)(w & 0xFFFFu);+ __half h;+ memcpy(&h, &lo, 2);+ return __half2float(h);+}++__device__ __forceinline__ uint32_t fq_ld_u16x2(const uint8_t* __restrict__ p) // p is 2-byte aligned+{+ const uint16_t* q = reinterpret_cast<const uint16_t*>(p);+ return (uint32_t)q[0] | ((uint32_t)q[1] << 16);+}++// Q4_K item: 256-block b = it >> 2, group g = it & 3 (qs bytes 32g .. 32g+31: low nibbles = sub-block 2g,+// high nibbles = sub-block 2g+1). dst[qo] = v1 chunk value c = 16 b + 4 g + qo, qo = 0..3.+__device__ __forceinline__ void fq_kq_item_q4_k(const uint8_t* __restrict__ wr, const uint8_t* __restrict__ aq,+ int it, float* __restrict__ dst)+{+ const int b = it >> 2, g = it & 3;+ const uint8_t* blk = wr + (size_t)b * FQ_Q4_K_BYTES; // 144 B: 16-byte aligned rows+ const uint32_t hd = *reinterpret_cast<const uint32_t*>(blk); // d | dmin+ const uint32_t* sp = reinterpret_cast<const uint32_t*>(blk + 4);+ const uint32_t sw0 = sp[0], sw1 = sp[1], sw2 = sp[2];+ const uint4 va = *reinterpret_cast<const uint4*>(blk + 16 + 32 * g);+ const uint4 vb = *reinterpret_cast<const uint4*>(blk + 16 + 32 * g + 16);+ const int32_t* a0 = reinterpret_cast<const int32_t*>(aq + (size_t)(b * 8 + 2 * g) * FQ_Q8_1_BYTES);+ const int32_t* a1 = a0 + FQ_Q8_1_BYTES / 4;+ const float dm0 = fq_h2f_lo(hd);+ const float dm1 = fq_h2f_lo(hd >> 16);+ const float d8[2] = {fq_h2f_lo((uint32_t)a0[0]), fq_h2f_lo((uint32_t)a1[0])};+ // scales / mins of sub-blocks 2g, 2g+1 (verbatim fq_q4k_scales on the three u16 words it reads)+ const int sh = 16 * (g & 1);+ const uint32_t s0 = (sw0 >> sh) & 0xFFFFu, s2 = (sw1 >> sh) & 0xFFFFu, s4 = (sw2 >> sh) & 0xFFFFu;+ const uint32_t hi = (g >= 2) ? 0xFFFFFFFFu : 0u;+ const uint16_t aux0 = (uint16_t)(((s0 & 0x3F3Fu) & ~hi) | ((((s4 >> 0) & 0x0F0Fu) | ((s0 & 0xC0C0u) >> 2)) & hi));+ const uint16_t aux1 = (uint16_t)(((s2 & 0x3F3Fu) & ~hi) | ((((s4 >> 4) & 0x0F0Fu) | ((s2 & 0xC0C0u) >> 2)) & hi));+ const int sc[2] = {(int)(aux0 & 0xFFu), (int)((aux0 >> 8) & 0xFFu)};+ const int mn[2] = {(int)(aux1 & 0xFFu), (int)((aux1 >> 8) & 0xFFu)};+ const uint32_t w0[4] = {va.x, va.y, va.z, va.w};+ const uint32_t w1[4] = {vb.x, vb.y, vb.z, vb.w};+ #pragma unroll+ for (int qo = 0; qo < 4; qo++)+ {+ float sumf_d = 0.0f, sumf_m = 0.0f;+ #pragma unroll+ for (int i = 0; i < 2; i++)+ {+ const int32_t* a = i ? a1 : a0;+ const uint32_t v0i = (w0[qo] >> (4 * i)) & 0x0F0F0F0Fu;+ const uint32_t v1i = (w1[qo] >> (4 * i)) & 0x0F0F0F0Fu;+ const int32_t u0 = a[1 + qo], u1 = a[5 + qo];+ int dot1 = fq_dp4a((int32_t)v0i, u0, 0);+ dot1 = fq_dp4a((int32_t)v1i, u1, dot1);+ int dot2 = fq_dp4a(0x01010101, u0, 0);+ dot2 = fq_dp4a(0x01010101, u1, dot2);+ sumf_d = __fadd_rn(sumf_d, __fmul_rn(d8[i], (float)(dot1 * sc[i])));+ sumf_m = __fadd_rn(sumf_m, __fmul_rn(d8[i], (float)(dot2 * mn[i])));+ }+ dst[qo] = __fadd_rn(__fmul_rn(dm0, sumf_d), -__fmul_rn(dm1, sumf_m));+ }+}++// Q6_K item: 256-block b = it >> 3, lane p = it & 7; the four v1 chunks iqs = p + 8 q (q = 0..3) of that block,+// c = 32 b + p + 8 q. dst[q] = value of chunk q.+__device__ __forceinline__ void fq_kq_item_q6_k(const uint8_t* __restrict__ wr, const uint8_t* __restrict__ aq,+ int it, float* __restrict__ dst)+{+ const int b = it >> 3, p = it & 7;+ const uint8_t* blk = wr + (size_t)b * FQ_Q6_K_BYTES; // 210 B: 2-byte aligned only+ uint32_t vl[4];+ #pragma unroll+ for (int q = 0; q < 4; q++)+ vl[q] = fq_ld_u16x2(blk + 4 * p + 32 * q);+ const uint32_t vhw[2] = {fq_ld_u16x2(blk + 128 + 4 * p), fq_ld_u16x2(blk + 128 + 32 + 4 * p)};+ const int8_t* scl = reinterpret_cast<const int8_t*>(blk + 192);+ const float d = fq_h2f_lo((uint32_t)*reinterpret_cast<const uint16_t*>(blk + 208));+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ const int sc_off = 8 * (q >> 1) + (p >> 2) + 2 * (q & 1);+ const int bq8_off = 4 * (q >> 1) + (q & 1);+ const uint32_t vh = vhw[q >> 1] >> (2 * (q & 1));+ float sumf = 0.0f;+ #pragma unroll+ for (int i = 0; i < 2; i++)+ {+ const int scc = (int)scl[sc_off + 4 * i];+ const uint32_t vil = (vl[q] >> (4 * i)) & 0x0F0F0F0Fu;+ const uint32_t vih = ((vh >> (4 * i)) << 4) & 0x30303030u;+ const uint32_t vi = fq_vsub4(vil | vih, 0x20202020u);+ const int32_t* a = reinterpret_cast<const int32_t*>(aq + (size_t)(b * 8 + bq8_off + 2 * i) * FQ_Q8_1_BYTES);+ const float d8 = fq_h2f_lo((uint32_t)a[0]);+ sumf = __fadd_rn(sumf, __fmul_rn(d8, (float)(fq_dp4a((int32_t)vi, a[1 + p], 0) * scc)));+ }+ dst[q] = __fmul_rn(d, sumf);+ }+}++// Q5_K item (same grid as the Q4_K item): 256-block b = it >> 2, group g = it & 3; dst[qo] = fq_dot_q5_k_q8's chunk value+// c = 16 b + 4 g + qo (bo = 2 g). qs words come from two 16-byte loads at 48 + 32 g, the high-bit words from the two 16-byte+// loads at 16 and 32 (shared by all g, shifted by bo as in the v1 dot). 176-byte blocks: rows 16-byte aligned.+__device__ __forceinline__ void fq_kq_item_q5_k(const uint8_t* __restrict__ wr, const uint8_t* __restrict__ aq,+ int it, float* __restrict__ dst)+{+ const int b = it >> 2, g = it & 3, bo = 2 * g;+ const uint8_t* blk = wr + (size_t)b * FQ_Q5_K_BYTES;+ const uint32_t hd = *reinterpret_cast<const uint32_t*>(blk);+ const float dm0 = fq_h2f_lo(hd);+ const float dm1 = fq_h2f_lo(hd >> 16);+ uint8_t sc[2], m[2];+ fq_q4k_scales(blk + 4, g, sc, m);+ const uint4 la = *reinterpret_cast<const uint4*>(blk + 48 + 32 * g);+ const uint4 lb = *reinterpret_cast<const uint4*>(blk + 48 + 32 * g + 16);+ const uint4 ha = *reinterpret_cast<const uint4*>(blk + 16);+ const uint4 hb = *reinterpret_cast<const uint4*>(blk + 32);+ const uint32_t l0[4] = {la.x, la.y, la.z, la.w}, l1[4] = {lb.x, lb.y, lb.z, lb.w};+ const uint32_t h0[4] = {ha.x, ha.y, ha.z, ha.w}, h1[4] = {hb.x, hb.y, hb.z, hb.w};+ const int32_t* a0 = reinterpret_cast<const int32_t*>(aq + (size_t)(b * 8 + bo) * FQ_Q8_1_BYTES);+ const int32_t* a1 = a0 + FQ_Q8_1_BYTES / 4;+ const float d8[2] = {fq_h2f_lo((uint32_t)a0[0]), fq_h2f_lo((uint32_t)a1[0])};+ #pragma unroll+ for (int qo = 0; qo < 4; qo++)+ {+ const uint32_t vh0 = h0[qo] >> bo, vh1 = h1[qo] >> bo;+ float sumf_d = 0.0f, sumf_m = 0.0f;+ #pragma unroll+ for (int i = 0; i < 2; i++)+ {+ const int32_t* a = i ? a1 : a0;+ const uint32_t v0i = ((l0[qo] >> (4 * i)) & 0x0F0F0F0Fu) | (((vh0 >> i) << 4) & 0x10101010u);+ const uint32_t v1i = ((l1[qo] >> (4 * i)) & 0x0F0F0F0Fu) | (((vh1 >> i) << 4) & 0x10101010u);+ const int32_t u0 = a[1 + qo], u1 = a[5 + qo];+ int dot1 = fq_dp4a((int32_t)v0i, u0, 0);+ dot1 = fq_dp4a((int32_t)v1i, u1, dot1);+ int dot2 = fq_dp4a(0x01010101, u0, 0);+ dot2 = fq_dp4a(0x01010101, u1, dot2);+ sumf_d = __fadd_rn(sumf_d, __fmul_rn(d8[i], (float)(dot1 * sc[i])));+ sumf_m = __fadd_rn(sumf_m, __fmul_rn(d8[i], (float)(dot2 * m[i])));+ }+ dst[qo] = __fadd_rn(__fmul_rn(dm0, sumf_d), -__fmul_rn(dm1, sumf_m));+ }+}++} // namespacediff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_kq_wmma.cuh b/exllamav3/exllamav3_ext/foreign_quant/fq_kq_wmma.cuhnew file mode 100644index 0000000..23d5634--- /dev/null+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_kq_wmma.cuh@@ -0,0 +1,262 @@+// gfx11 (RDNA3 / RDNA3.5) WMMA path of the Q4_K multi-row decode GEMV (x-rows 2..16). Include after fq_kq_item.cuh (fq_h2f_lo) and after+// FQ_Q4_K_BYTES / FQ_Q8_1_BYTES are defined, outside any namespace. HIP builds only.+//+// Every output row is bit-identical to the one-row v2 kernel. The one-row kernel's float result is a function of exact integer sums over 8+// activation values (one "chunk" of one 32-value sub-block) and of the float combine of these sums in a fixed order; WMMA iu8 gives the same+// exact integer sums, and the float combine is repeated expression for expression, in the same lane order and window order, so only the unit+// that produces the integers changes. (The compiler fuses the one-row kernel's __fadd_rn(x, __fmul_rn(y, z)) chains into FMAs, HIP defines both+// as plain x + y / x * y; the fused form is the reference result, so the FMAs are written explicitly below.)+//+// WMMA 16x16x16 iu8 on gfx11 (checked on gfx1151): the two half-waves are independent 8x16 products. Lanes 0-15 hold B columns 0..15 and A rows+// 0,2,..,14 (the odd A lanes are ignored); lanes 16-31 hold their own B columns and A rows 1,3,..,15 (the even A lanes are ignored). D register+// v of lane l = row 2v + (l >> 4), column l & 15. So one wave covers 32 weight rows (lane l = weight row l, B operand) against 4 x-rows (A+// operand, same data in both halves); a lane owns every partial of its own (weight row, x-row) pairs: there is no cross-lane reduction, the+// one-row kernel's lane-ordered sum runs in registers.+//+// A K=16 slot holds two chunks (8 values each): A row 2m+h selects half h (the other half is zero), so D[v = 2m+h] is the exact 8-value dot of+// x-row m with chunk 2p+h of WMMA p. Per position (block b, group g = 4 chunks x 2 sub-blocks): 4 WMMAs.+//+// Measured on gfx1151 (cold, see the patch notes): Q4_K 12288x4096 R=8 260 -> 200 us, R=16 499 -> 253 us; 4096x4096 R=8 96 -> 58 us. At R = 2, 3 and on+// thin matrices (N = 1024) the kernel is latency bound (one wave walks all K positions serially, a lane = a row, so too few waves) and loses to the+// generic kernel; the dispatcher keeps the generic kernel there.+// Q6_K has no WMMA path: its 210-byte blocks make the per-lane-row loads the bottleneck (see the patch notes).+#pragma once+#if defined(USE_ROCM) || defined(__HIP_PLATFORM_AMD__)+#if defined(__HIP_DEVICE_COMPILE__) && (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || \+ defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__))+#define FQ_KQ_WMMA_DEV 1+#endif++typedef int fq_v4i __attribute__((ext_vector_type(4)));+typedef int fq_v8i __attribute__((ext_vector_type(8)));++// Activation pack for the Q4_K WMMA kernel. One thread = one (pass, x-row-in-pass ml, position it).+// afrag[((pass * nitems + it) * 8 + v) * 4 + ip] (uint4), v = 2 ml + h, ip = 2 i + p: the A operand of WMMA (i, p) for A row v+// = {x, y, 0, 0} (h = 0) or {0, 0, x, y} (h = 1), x / y = q8_1 words 1 + qo / 5 + qo of sub-block 2g + i, qo = 2p + h.+// atab[(pass * nitems + it) * 40 + ml * 8 + 4 i + qo] = exact sum of the 8 int8 values of (i, qo) as float,+// atab[... + 32 + 2 ml + i] = d of sub-block 2g + i as float. Rows m >= M are all zero.+__global__ void fq_kq_wpack_q4_kernel(const uint8_t* __restrict__ aqb, uint4* __restrict__ afrag, float* __restrict__ atab,+ int M, int nitems, int64_t qb_stride, int64_t total)+{+ const int64_t gid = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;+ if (gid >= total)+ return;+ const int it = (int)(gid % nitems);+ const int64_t rest = gid / nitems;+ const int ml = (int)(rest & 3), pass = (int)(rest >> 2);+ const int m = pass * 4 + ml;+ const int b = it >> 2, g = it & 3;+ uint32_t xw[2][8];+ float d8[2];+ #pragma unroll+ for (int i = 0; i < 2; i++)+ {+ #pragma unroll+ for (int w = 0; w < 8; w++)+ xw[i][w] = 0u;+ d8[i] = 0.0f;+ }+ if (m < M)+ {+ const uint8_t* aq = aqb + (int64_t)m * qb_stride;+ #pragma unroll+ for (int i = 0; i < 2; i++)+ {+ const uint32_t* a = reinterpret_cast<const uint32_t*>(aq + (size_t)(b * 8 + 2 * g + i) * FQ_Q8_1_BYTES);+ d8[i] = fq_h2f_lo(a[0]);+ #pragma unroll+ for (int w = 0; w < 8; w++)+ xw[i][w] = a[1 + w];+ }+ }+ const size_t pidx = (size_t)pass * nitems + it;+ float* tab = atab + pidx * 40;+ #pragma unroll+ for (int i = 0; i < 2; i++)+ {+ #pragma unroll+ for (int qo = 0; qo < 4; qo++)+ {+ int s = 0;+ #pragma unroll+ for (int t = 0; t < 4; t++)+ s += (int)(int8_t)(xw[i][qo] >> (8 * t)) + (int)(int8_t)(xw[i][4 + qo] >> (8 * t));+ tab[ml * 8 + 4 * i + qo] = (float)s;+ }+ tab[32 + 2 * ml + i] = d8[i];+ }+ #pragma unroll+ for (int h = 0; h < 2; h++)+ {+ #pragma unroll+ for (int i = 0; i < 2; i++)+ {+ #pragma unroll+ for (int p = 0; p < 2; p++)+ {+ const int qo = 2 * p + h;+ const uint32_t x = xw[i][qo], y = xw[i][4 + qo];+ afrag[(pidx * 8 + 2 * ml + h) * 4 + 2 * i + p] = h ? make_uint4(0u, 0u, x, y) : make_uint4(x, y, 0u, 0u);+ }+ }+ }+}++// Weights / activation fragments of one Q4_K position (block b = it >> 2, group g = it & 3) of one lane, loaded one position ahead.+struct FqKqWmmaLd4 { uint4 hdr, va, vb, a00, a01, a10, a11; };++__device__ __forceinline__ FqKqWmmaLd4 fq_kq_wmma_ld4(const uint8_t* __restrict__ wr, const uint4* __restrict__ afrag, int it, size_t pidx, int vA)+{+ FqKqWmmaLd4 l;+ const uint8_t* blk = wr + (size_t)(it >> 2) * FQ_Q4_K_BYTES;+ const int g = it & 3;+ l.hdr = *reinterpret_cast<const uint4*>(blk);+ l.va = *reinterpret_cast<const uint4*>(blk + 16 + 32 * g);+ l.vb = *reinterpret_cast<const uint4*>(blk + 32 + 32 * g);+ const uint4* af = afrag + (pidx * 8 + vA) * 4;+ l.a00 = af[0]; l.a01 = af[1]; l.a10 = af[2]; l.a11 = af[3];+ return l;+}++// Computes one Q4_K position of one lane for the 4 x-rows (MT of them) of a pass: 4 WMMAs, then the one-row kernel's float combine.+// acc[m][qo] = lane partial of one-row lane 4 jpos + qo (windows added in order: `first` starts it).+template <int MT>+__device__ __forceinline__ void fq_kq_wmma_pos4(const FqKqWmmaLd4& cur, const float* __restrict__ tab, int g, bool first, float (&acc)[MT][4])+{+ const int sh = 16 * (g & 1);+ const uint32_t hi = (g >= 2) ? 0xFFFFFFFFu : 0u;+ // scales / mins of sub-blocks 2g, 2g+1 (verbatim fq_kq_wld_q4_k)+ const float dm0 = fq_h2f_lo(cur.hdr.x), dm1 = fq_h2f_lo(cur.hdr.x >> 16);+ const uint32_t s0 = (cur.hdr.y >> sh) & 0xFFFFu, s2 = (cur.hdr.z >> sh) & 0xFFFFu, s4 = (cur.hdr.w >> sh) & 0xFFFFu;+ const uint16_t aux0 = (uint16_t)(((s0 & 0x3F3Fu) & ~hi) | ((((s4 >> 0) & 0x0F0Fu) | ((s0 & 0xC0C0u) >> 2)) & hi));+ const uint16_t aux1 = (uint16_t)(((s2 & 0x3F3Fu) & ~hi) | ((((s4 >> 4) & 0x0F0Fu) | ((s2 & 0xC0C0u) >> 2)) & hi));+ const float scf[2] = {(float)(int)(aux0 & 0xFFu), (float)(int)((aux0 >> 8) & 0xFFu)};+ const float mnf[2] = {(float)(int)(aux1 & 0xFFu), (float)(int)((aux1 >> 8) & 0xFFu)};+ const uint32_t w0[4] = {cur.va.x, cur.va.y, cur.va.z, cur.va.w};+ const uint32_t w1[4] = {cur.vb.x, cur.vb.y, cur.vb.z, cur.vb.w};+ const uint4 af4[2][2] = {{cur.a00, cur.a01}, {cur.a10, cur.a11}};+ fq_v8i c[2][2];+ #pragma unroll+ for (int i = 0; i < 2; i++)+ {+ #pragma unroll+ for (int p = 0; p < 2; p++)+ {+ const fq_v4i bf = {(int)((w0[2 * p] >> (4 * i)) & 0x0F0F0F0Fu), (int)((w1[2 * p] >> (4 * i)) & 0x0F0F0F0Fu),+ (int)((w0[2 * p + 1] >> (4 * i)) & 0x0F0F0F0Fu), (int)((w1[2 * p + 1] >> (4 * i)) & 0x0F0F0F0Fu)};+ const fq_v4i af_ = {(int)af4[i][p].x, (int)af4[i][p].y, (int)af4[i][p].z, (int)af4[i][p].w};+ const fq_v8i z = {0, 0, 0, 0, 0, 0, 0, 0};+ c[i][p] = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(true, af_, true, bf, z, false);+ }+ }+ #pragma unroll+ for (int m = 0; m < MT; m++)+ {+ const float d80 = tab[32 + 2 * m], d81 = tab[33 + 2 * m];+ #pragma unroll+ for (int qo = 0; qo < 4; qo++)+ {+ const int p = qo >> 1, v = 2 * m + (qo & 1);+ const float a0 = (float)c[0][p][v] * scf[0];+ const float a1 = (float)c[1][p][v] * scf[1];+ const float b0 = tab[m * 8 + qo] * mnf[0];+ const float b1 = tab[m * 8 + 4 + qo] * mnf[1];+ // the compiler fuses the one-row kernel's __fadd_rn(x, __fmul_rn(y, z)) chains into FMAs (HIP defines both as plain+ // x + y / x * y under -ffp-contract=fast); the fused form is the reference result, so it is written explicitly+ const float fd = __builtin_fmaf(d81, a1, d80 * a0);+ const float fm = __builtin_fmaf(d81, b1, d80 * b0);+ const float t = __builtin_fmaf(dm0, fd, -(dm1 * fm));+ acc[m][qo] = first ? t : (acc[m][qo] + t);+ }+ }+}++// One wave = 32 consecutive weight rows (lane = row) x the 4 x-rows of one pass. A workgroup of P * TPW waves: wave w = (tile+// blockIdx.x * TPW + w / P, pass w % P); the P waves of a tile read the same weights at the same time (L0 hits). MT = x-rows computed+// per pass (2 or 4). Positions it = jpos + 64 win (win ascending, as the one-row kernel's thread loop) are processed jpos by jpos. The loads run+// ND - 1 positions ahead of the compute (ring of ND register buffers, indices known at compile time).+template <typename OUT, int MT, int ND>+__global__ void __launch_bounds__(128) fq_gemv_kq_wmma_q4_kernel(const uint8_t* __restrict__ packed, const uint4* __restrict__ afrag,+ const float* __restrict__ atab, OUT* __restrict__ out,+ int M, int N, int64_t pstride, int nitems, int P, int TPW)+{+#if defined(FQ_KQ_WMMA_DEV)+#pragma clang fp contract(off)+ const int lane = threadIdx.x & 31;+ const int wid = __builtin_amdgcn_readfirstlane((int)(threadIdx.x >> 5));+ const int pass = wid % P;+ const int n_base = (blockIdx.x * TPW + wid / P) * 32;+ const uint8_t* wr = packed + (int64_t)min(n_base + lane, N - 1) * pstride;+ const int vA = (lane & 15) >> 1;+ float s[MT];+ float acc[MT][4];+ #pragma unroll+ for (int m = 0; m < MT; m++)+ {+ s[m] = 0.0f;+ #pragma unroll+ for (int qo = 0; qo < 4; qo++)+ acc[m][qo] = 0.0f;+ }+ const size_t pbase = (size_t)pass * nitems;+ int cj = 0, ci = 0; // compute cursor (jpos, it)+ int lj = 0, li = 0; // load cursor+ // The load cursor stops on the last position (the loads stay unconditional: the compiler can then count the loads in flight and wait+ // for the oldest buffer only).+#define FQ_KQ_ADV4(J, I) \+ { \+ int ni = I + 64, nj = J; \+ if (ni >= nitems) { nj = J + 1; ni = nj; } \+ if (nj < 64) { J = nj; I = ni; } \+ }+ FqKqWmmaLd4 buf[ND];+ #pragma unroll+ for (int j = 0; j < ND - 1; j++)+ {+ buf[j] = fq_kq_wmma_ld4(wr, afrag, li, pbase + li, vA);+ FQ_KQ_ADV4(lj, li)+ }+ bool fin = false;+ for (;;)+ {+ #pragma unroll+ for (int j = 0; j < ND; j++)+ {+ buf[(j + ND - 1) % ND] = fq_kq_wmma_ld4(wr, afrag, li, pbase + li, vA);+ FQ_KQ_ADV4(lj, li)+ __builtin_amdgcn_sched_barrier(0); // keep the prefetch above the compute (the scheduler would sink the loads to their first use)+ fq_kq_wmma_pos4<MT>(buf[j], atab + (pbase + ci) * 40, ci & 3, ci == cj, acc);+ ci += 64;+ if (ci >= nitems) // all windows of this jpos done: one-row lanes 4 jpos .. 4 jpos + 3, in order+ {+ #pragma unroll+ for (int m = 0; m < MT; m++)+ {+ #pragma unroll+ for (int qo = 0; qo < 4; qo++)+ s[m] = s[m] + acc[m][qo];+ }+ cj++; ci = cj;+ if (cj >= 64) { fin = true; break; }+ }+ }+ if (fin)+ break;+ }+#undef FQ_KQ_ADV4+ const int n = n_base + lane;+ #pragma unroll+ for (int m = 0; m < MT; m++)+ {+ if (pass * 4 + m < M && n < N)+ {+ if constexpr (std::is_same<OUT, __half>::value)+ out[(int64_t)(pass * 4 + m) * N + n] = __float2half_rn(s[m]);+ else+ out[(int64_t)(pass * 4 + m) * N + n] = s[m];+ }+ }+#endif+}++#endif // USE_ROCMdiff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_moe_kq.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_moe_kq.cuindex 851c944..450748f 100644--- a/exllamav3/exllamav3_ext/foreign_quant/fq_moe_kq.cu+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_moe_kq.cu@@ -5,7 +5,7 @@// epilogue (MiniCPM MoE is SwiGLU, unlike Bolt's gateless latent MoE).// h [1, K] is quantized once; the [S, I] act scratch is quantized per slot// row for the down dots. FMT selects the dot (0 = Q4_K, 1 = Q5_K,-// 2 = Q6_K, 3 = IQ4_XS). Portable (no PTX/shuffles).+// 2 = Q6_K, 3 = IQ4_XS, 4 = IQ3_XXS, 5 = IQ2_S). Portable (no PTX/shuffles).#include <cuda_fp16.h>#include <map>#include <torch/extension.h>@@ -13,6 +13,8 @@#include <ATen/cuda/CUDAContext.h>#include "../util.h"#include "fq_gemv.cuh"+#include "fq_kq_item.cuh"+#include <cstdlib>#include "fq_api.h"namespace {@@ -65,11 +67,21 @@ __global__ void fq_moe_kq_upgate_kernel(const uint8_t* __restrict__ aqb,g = fq_dot_q6_k_q8(gr, aq, K, lane, FQ_GEMV_LANES);u = fq_dot_q6_k_q8(ur, aq, K, lane, FQ_GEMV_LANES);}- else+ else if constexpr (FMT == 3){g = fq_dot_iq4_xs_q8(gr, aq, K, lane, FQ_GEMV_LANES);u = fq_dot_iq4_xs_q8(ur, aq, K, lane, FQ_GEMV_LANES);}+ else if constexpr (FMT == 4)+ {+ g = fq_dot_iq3_xxs_q8(gr, aq, K, lane, FQ_GEMV_LANES);+ u = fq_dot_iq3_xxs_q8(ur, aq, K, lane, FQ_GEMV_LANES);+ }+ else+ {+ g = fq_dot_iq2_s_q8(gr, aq, K, lane, FQ_GEMV_LANES);+ u = fq_dot_iq2_s_q8(ur, aq, K, lane, FQ_GEMV_LANES);+ }}// Two reductions in one shared row: red[2*tid] = g, red[2*tid+1] = u.red[2 * threadIdx.x] = g;@@ -93,6 +105,209 @@ __global__ void fq_moe_kq_upgate_kernel(const uint8_t* __restrict__ aqb,}}+// Q4_K gate+up, v2 loads (bit-identical to fq_moe_kq_upgate_kernel<0>): 32 rows per block, 8 threads per row. Thread j of a+// row runs the items it = j, j + 8, ... (fq_kq_item_q4_k: 4 consecutive v1 sub-chunks from two 16-byte loads); sub-chunk+// c = 4 it + qo belongs to v1 lane c & 31 = 4 j + qo, so the four register partials are v1's lane partials 4j .. 4j+3 summed+// in the same increasing c order. Lane partials go to shared memory and one thread per row adds them lane by lane as v1 does.+constexpr int FQ_MOE_V2_ROWS = 32;+constexpr int FQ_MOE_V2_PS = 33;+__global__ void __launch_bounds__(256) fq_moe_kq_upgate_v2_kernel(const uint8_t* __restrict__ aqb,+ const int64_t* __restrict__ sel,+ const uint8_t* const* __restrict__ gate_bases,+ const uint8_t* const* __restrict__ up_bases,+ int64_t gate_stride,+ int64_t up_stride,+ int64_t qb_stride,+ __half* __restrict__ act,+ int S, int I, int K, int E, int ntiles_u, int topk)+{+ __shared__ float pg[FQ_MOE_V2_ROWS * FQ_MOE_V2_PS];+ __shared__ float pu[FQ_MOE_V2_ROWS * FQ_MOE_V2_PS];+ const int s = blockIdx.x / ntiles_u;+ const int t = blockIdx.x % ntiles_u;+ const int r = threadIdx.x >> 3, j = threadIdx.x & 7;+ int64_t e = sel[s];+ e = (e < 0 || e >= E) ? 0 : e;+ const int n = t * FQ_MOE_V2_ROWS + r;+ const uint8_t* aq = aqb + (int64_t)(s / topk) * qb_stride;+ float ag[4] = {0.0f, 0.0f, 0.0f, 0.0f}, au[4] = {0.0f, 0.0f, 0.0f, 0.0f};+ if (n < I)+ {+ const uint8_t* gr = gate_bases[e] + (int64_t)n * gate_stride;+ const uint8_t* ur = up_bases[e] + (int64_t)n * up_stride;+ if ((((uintptr_t)gr | (uintptr_t)ur) & 15) == 0)+ {+ const int nitems = (K / 256) * 4;+ for (int it = j; it < nitems; it += 8)+ {+ float tg[4], tu[4];+ fq_kq_item_q4_k(gr, aq, it, tg);+ fq_kq_item_q4_k(ur, aq, it, tu);+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ ag[q] = __fadd_rn(ag[q], tg[q]);+ au[q] = __fadd_rn(au[q], tu[q]);+ }+ }+ }+ else+ {+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ ag[q] = fq_dot_q4_k_q8(gr, aq, K, 4 * j + q, FQ_GEMV_LANES);+ au[q] = fq_dot_q4_k_q8(ur, aq, K, 4 * j + q, FQ_GEMV_LANES);+ }+ }+ }+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ pg[r * FQ_MOE_V2_PS + 4 * j + q] = ag[q];+ pu[r * FQ_MOE_V2_PS + 4 * j + q] = au[q];+ }+ __syncthreads();+ if (n < I && j == 0)+ {+ float sg = 0.0f, su = 0.0f;+ #pragma unroll+ for (int l = 0; l < 32; l++)+ {+ sg = __fadd_rn(sg, pg[r * FQ_MOE_V2_PS + l]);+ su = __fadd_rn(su, pu[r * FQ_MOE_V2_PS + l]);+ }+ float gh = __half2float(__float2half_rn(sg));+ float uh = __half2float(__float2half_rn(su));+ float sig = 1.0f / (1.0f + expf(-gh));+ act[(int64_t)s * I + n] = __float2half_rn(sig * gh * uh);+ }+}++// Down, v2 items (bit-identical to fq_moe_kq_down_kernel<FMT>, FMT 0 Q4_K / 1 Q5_K / 2 Q6_K): 32 rows per block, 8 threads per+// row, thread j runs items j, j + 8, ...; the item's four values belong to v1 lanes 4 j + q (Q4_K / Q5_K) or j + 8 q (Q6_K),+// each added in increasing sub-chunk order as v1 does; then one thread per row adds the 32 lane partials lane by lane.+template <int FMT>+__global__ void __launch_bounds__(256) fq_moe_kq_down_v2_kernel(const uint8_t* __restrict__ aqb,+ int64_t qb_stride,+ const int64_t* __restrict__ sel,+ const uint8_t* __restrict__ const* down_bases,+ int64_t down_stride,+ float* __restrict__ partial,+ int S, int I, int K, int E, int ntiles_d)+{+ __shared__ float pp[FQ_MOE_V2_ROWS * FQ_MOE_V2_PS];+ const int s = blockIdx.x / ntiles_d;+ const int t = blockIdx.x % ntiles_d;+ const int r = threadIdx.x >> 3, j = threadIdx.x & 7;+ int64_t e = sel[s];+ e = (e < 0 || e >= E) ? 0 : e;+ const int n = t * FQ_MOE_V2_ROWS + r;+ float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};+ if (n < K)+ {+ const uint8_t* dr = down_bases[e] + (int64_t)n * down_stride;+ const uint8_t* aq = aqb + (int64_t)s * qb_stride;+ const uintptr_t amask = (FMT == 2) ? 1 : 15;+ if (((uintptr_t)dr & amask) == 0)+ {+ const int nitems = (I / 256) * ((FMT == 2) ? 8 : 4);+ for (int it = j; it < nitems; it += 8)+ {+ float tv[4];+ if constexpr (FMT == 0) fq_kq_item_q4_k(dr, aq, it, tv);+ else if constexpr (FMT == 1) fq_kq_item_q5_k(dr, aq, it, tv);+ else fq_kq_item_q6_k(dr, aq, it, tv);+ #pragma unroll+ for (int q = 0; q < 4; q++)+ acc[q] = __fadd_rn(acc[q], tv[q]);+ }+ }+ else+ {+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ const int l = (FMT == 2) ? (j + 8 * q) : (4 * j + q);+ if constexpr (FMT == 0) acc[q] = fq_dot_q4_k_q8(dr, aq, I, l, FQ_GEMV_LANES);+ else if constexpr (FMT == 1) acc[q] = fq_dot_q5_k_q8(dr, aq, I, l, FQ_GEMV_LANES);+ else acc[q] = fq_dot_q6_k_q8(dr, aq, I, l, FQ_GEMV_LANES);+ }+ }+ }+ #pragma unroll+ for (int q = 0; q < 4; q++)+ pp[r * FQ_MOE_V2_PS + ((FMT == 2) ? (j + 8 * q) : (4 * j + q))] = acc[q];+ __syncthreads();+ if (n < K && j == 0)+ {+ float sp = 0.0f;+ #pragma unroll+ for (int l = 0; l < 32; l++)+ sp = __fadd_rn(sp, pp[r * FQ_MOE_V2_PS + l]);+ partial[(int64_t)s * K + n] = sp;+ }+}++template <int FMT>+static void fq_moe_kq_down_v2_launch(const uint8_t* aq, int64_t qb_stride, const int64_t* sel, const uint8_t* const* bases,+ int64_t down_stride, float* partial, int S, int I, int K, int E, cudaStream_t stream)+{+ if constexpr (FMT <= 2)+ {+ const int nt2 = (K + FQ_MOE_V2_ROWS - 1) / FQ_MOE_V2_ROWS;+ fq_moe_kq_down_v2_kernel<FMT><<<S * nt2, 256, 0, stream>>>(aq, qb_stride, sel, bases, down_stride, partial, S, I, K, E, nt2);+ }+}++static bool fq_moe_v2_on()+{+ static const char* e = std::getenv("BOLT_FQ_MOE_V2");+ static const bool on = !(e && e[0] == '0');+ return on;+}++// Q5_1 x q8_1 dot (ggml vec_dot_q5_1_q8_1 arithmetic): per 32-block, 8 dp4a over the 5-bit values (0..31) and the int8 activations,+// then d_w * d_a * sumi + m_w * s_a (s_a = the q8_1 block's stored sum). Lanes take 32-blocks round-robin like fq_dot_q8_0_q8.+constexpr int FQ_Q5_1_BYTES = 24;+__device__ __forceinline__ float fq_dot_q5_1_q8(const uint8_t* __restrict__ wr, const uint8_t* __restrict__ aqb,+ int K, int tid, int nthreads)+{+ const int nchunks = K / 32;+ float acc = 0.0f;+ for (int c = tid; c < nchunks; c += nthreads)+ {+ const uint8_t* blk = wr + (size_t)c * FQ_Q5_1_BYTES;+ __half dwh, mwh, dah, sah;+ memcpy(&dwh, blk, 2);+ memcpy(&mwh, blk + 2, 2);+ const uint8_t* ab = aqb + (size_t)c * FQ_Q8_1_BYTES;+ memcpy(&dah, ab, 2);+ memcpy(&sah, ab + 2, 2);+ const uint32_t qh = (uint32_t)blk[4] | ((uint32_t)blk[5] << 8) | ((uint32_t)blk[6] << 16) | ((uint32_t)blk[7] << 24);+ const uint8_t* qs = blk + 8;+ const int32_t* aq32 = reinterpret_cast<const int32_t*>(ab + 4);+ int sumi = 0;+ #pragma unroll+ for (int w = 0; w < 4; w++)+ {+ int32_t lo = 0, hi = 0;+ #pragma unroll+ for (int b = 0; b < 4; b++)+ {+ const int j = 4 * w + b;+ lo |= (int32_t)((qs[j] & 15) | (((qh >> j) & 1) << 4)) << (8 * b);+ hi |= (int32_t)((qs[j] >> 4) | (((qh >> (j + 16)) & 1) << 4)) << (8 * b);+ }+ sumi = fq_dp4a(lo, aq32[w], sumi);+ sumi = fq_dp4a(hi, aq32[w + 4], sumi);+ }+ const float dw = __half2float(dwh), mw = __half2float(mwh), da = __half2float(dah), sa = __half2float(sah);+ acc = __fadd_rn(acc, __fadd_rn(__fmul_rn(__fmul_rn(dw, da), (float)sumi), __fmul_rn(mw, sa)));+ }+ return acc;+}+// Down kernel: block (s, t) dots down[sel[s]] rows against the// pre-quantized act row s into partial[s]. Same lane split as above.template <int FMT>@@ -126,8 +341,16 @@ __global__ void fq_moe_kq_down_kernel(const uint8_t* __restrict__ aqb,p = fq_dot_q5_k_q8(dr, aq, I, lane, FQ_GEMV_LANES);else if constexpr (FMT == 2)p = fq_dot_q6_k_q8(dr, aq, I, lane, FQ_GEMV_LANES);- else+ else if constexpr (FMT == 3)p = fq_dot_iq4_xs_q8(dr, aq, I, lane, FQ_GEMV_LANES);+ else if constexpr (FMT == 4)+ p = fq_dot_iq3_xxs_q8(dr, aq, I, lane, FQ_GEMV_LANES);+ else if constexpr (FMT == 6)+ p = fq_dot_q8_0_q8(dr, aq, I, lane, FQ_GEMV_LANES);+ else if constexpr (FMT == 7)+ p = fq_dot_q5_1_q8(dr, aq, I, lane, FQ_GEMV_LANES);+ else+ p = fq_dot_iq2_s_q8(dr, aq, I, lane, FQ_GEMV_LANES);}red[threadIdx.x] = p;__syncthreads();@@ -183,7 +406,7 @@ static void fq_moe_kq_grouped_launch(torch::Tensor h, torch::Tensor sel, torch::int E = (int)up_ptrs.numel();// I from the down row stride (down rows are I-wide, like Bolt's// derivation from down_stride).- int I = (int)(down_stride / block_bytes) * FQ_Q4_K_GROUP;+ int I = (int)(down_stride / block_bytes) * ((FMT_D >= 6) ? 32 : FQ_Q4_K_GROUP); // ids 6 / 7: 32-element blocksat::cuda::CUDAGuard guard(h.device());auto stream = at::cuda::getCurrentCUDAStream().stream();int ntiles_u = (I + FQ_GEMV_OUT_PER_BLOCK - 1) / FQ_GEMV_OUT_PER_BLOCK;@@ -204,6 +427,18 @@ static void fq_moe_kq_grouped_launch(torch::Tensor h, torch::Tensor sel, torch::}// Up+gate: 2 floats per thread in shared (g and u side by side).size_t shmem_u = (size_t)FQ_GEMV_THREADS * 2 * sizeof(float);+ if (FMT_UG == 0 && K % 256 == 0 && fq_moe_v2_on())+ {+ const int nt2 = (I + FQ_MOE_V2_ROWS - 1) / FQ_MOE_V2_ROWS;+ fq_moe_kq_upgate_v2_kernel<<<S * nt2, 256, 0, stream>>>(+ qb_h.data_ptr<uint8_t>(), sel.data_ptr<int64_t>(),+ reinterpret_cast<const uint8_t* const*>(gate_ptrs.data_ptr<int64_t>()),+ reinterpret_cast<const uint8_t* const*>(up_ptrs.data_ptr<int64_t>()),+ gate_stride, up_stride, qb_stride_h,+ reinterpret_cast<__half*>(act.data_ptr<at::Half>()),+ S, I, K, E, nt2, topk);+ }+ elsefq_moe_kq_upgate_kernel<FMT_UG><<<S * ntiles_u, FQ_GEMV_THREADS, shmem_u, stream>>>(qb_h.data_ptr<uint8_t>(), sel.data_ptr<int64_t>(),reinterpret_cast<const uint8_t* const*>(gate_ptrs.data_ptr<int64_t>()),@@ -215,6 +450,11 @@ static void fq_moe_kq_grouped_launch(torch::Tensor h, torch::Tensor sel, torch::fq_quant_q8_1_rows(act, qb_act);int64_t qb_stride_a = (int64_t)(I / FQ_Q8_1_GROUP) * FQ_Q8_1_BYTES;size_t shmem_d = (size_t)FQ_GEMV_THREADS * sizeof(float);+ if (FMT_D <= 2 && I % 256 == 0 && fq_moe_v2_on())+ fq_moe_kq_down_v2_launch<FMT_D>(qb_act.data_ptr<uint8_t>(), qb_stride_a, sel.data_ptr<int64_t>(),+ reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr<int64_t>()),+ down_stride, partial.data_ptr<float>(), S, I, K, E, stream);+ elsefq_moe_kq_down_kernel<FMT_D><<<S * ntiles_d, FQ_GEMV_THREADS, shmem_d, stream>>>(qb_act.data_ptr<uint8_t>(), qb_stride_a, sel.data_ptr<int64_t>(),reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr<int64_t>()),@@ -270,7 +510,8 @@ void fq_moe_iq4xs_grouped_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor wFQ_IQ4_XS_BYTES, partial, out);}-static const int64_t kFmtBytes[4] = {FQ_Q4_K_BYTES, FQ_Q5_K_BYTES, FQ_Q6_K_BYTES, FQ_IQ4_XS_BYTES};+static const int64_t kFmtBytes[8] = {FQ_Q4_K_BYTES, FQ_Q5_K_BYTES, FQ_Q6_K_BYTES, FQ_IQ4_XS_BYTES, FQ_IQ3_XXS_BYTES, FQ_IQ2_S_BYTES,+ FQ_Q8_0_BYTES, FQ_Q5_1_BYTES};template <int FU>static void fq_moe_kq_dispatch_d(int fd, torch::Tensor h, torch::Tensor sel, torch::Tensor wts,@@ -284,11 +525,15 @@ static void fq_moe_kq_dispatch_d(int fd, torch::Tensor h, torch::Tensor sel, torcase 1: fq_moe_kq_grouped_launch<FU, 1>(h, sel, wts, gp, up, dp, gs, us, ds, kFmtBytes[1], partial, out); break;case 2: fq_moe_kq_grouped_launch<FU, 2>(h, sel, wts, gp, up, dp, gs, us, ds, kFmtBytes[2], partial, out); break;case 3: fq_moe_kq_grouped_launch<FU, 3>(h, sel, wts, gp, up, dp, gs, us, ds, kFmtBytes[3], partial, out); break;+ case 4: fq_moe_kq_grouped_launch<FU, 4>(h, sel, wts, gp, up, dp, gs, us, ds, kFmtBytes[4], partial, out); break;+ case 5: fq_moe_kq_grouped_launch<FU, 5>(h, sel, wts, gp, up, dp, gs, us, ds, kFmtBytes[5], partial, out); break;+ case 6: fq_moe_kq_grouped_launch<FU, 6>(h, sel, wts, gp, up, dp, gs, us, ds, kFmtBytes[6], partial, out); break;+ case 7: fq_moe_kq_grouped_launch<FU, 7>(h, sel, wts, gp, up, dp, gs, us, ds, kFmtBytes[7], partial, out); break;default: TORCH_CHECK(false, "fq_moe_kq: bad down format ", fd);}}-// Mixed per-projection formats (unsloth UD: gate/up Q4_K + down Q5_K). fmt ids: 0 q4_k, 1 q5_k, 2 q6_k, 3 iq4_xs.+// Mixed per-projection formats (unsloth UD: gate/up Q4_K + down Q5_K). fmt ids: 0 q4_k, 1 q5_k, 2 q6_k, 3 iq4_xs, 4 iq3_xxs, 5 iq2_s.void fq_moe_kq_grouped_mixed_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,torch::Tensor gate_ptrs, torch::Tensor up_ptrs,torch::Tensor down_ptrs,@@ -302,6 +547,8 @@ void fq_moe_kq_grouped_mixed_q8(torch::Tensor h, torch::Tensor sel, torch::Tensocase 1: fq_moe_kq_dispatch_d<1>((int)fmt_down, h, sel, wts, gate_ptrs, up_ptrs, down_ptrs, gate_stride, up_stride, down_stride, partial, out); break;case 2: fq_moe_kq_dispatch_d<2>((int)fmt_down, h, sel, wts, gate_ptrs, up_ptrs, down_ptrs, gate_stride, up_stride, down_stride, partial, out); break;case 3: fq_moe_kq_dispatch_d<3>((int)fmt_down, h, sel, wts, gate_ptrs, up_ptrs, down_ptrs, gate_stride, up_stride, down_stride, partial, out); break;+ case 4: fq_moe_kq_dispatch_d<4>((int)fmt_down, h, sel, wts, gate_ptrs, up_ptrs, down_ptrs, gate_stride, up_stride, down_stride, partial, out); break;+ case 5: fq_moe_kq_dispatch_d<5>((int)fmt_down, h, sel, wts, gate_ptrs, up_ptrs, down_ptrs, gate_stride, up_stride, down_stride, partial, out); break;default: TORCH_CHECK(false, "fq_moe_kq: bad gate/up format ", fmt_ug);}}diff --git a/exllamav3/exllamav3_ext/quant/exl3_dec.cu b/exllamav3/exllamav3_ext/quant/exl3_dec.cuindex bae0b07..15233a5 100644--- a/exllamav3/exllamav3_ext/quant/exl3_dec.cu+++ b/exllamav3/exllamav3_ext/quant/exl3_dec.cu@@ -1943,7 +1943,7 @@ __device__ __forceinline__ float block_sum(float v, float* red)constexpr int NORM_MAX_PER_THREAD = 32;// mode 0: y = norm(x) (* w); 1: y += norm(x); 2 (res_in): r += x, y = norm(r)-template <typename TX, typename TY, typename TR>+template <typename TX, typename TY, typename TR, int PER>__global__ __launch_bounds__(256)void rms_norm_kernel(const TX* __restrict__ x, const void* w, int wtype, TY* y, TR* r, int dim,float eps, float constant_bias, float constant_scale, int mode)@@ -1953,12 +1953,12 @@ void rms_norm_kernel(const TX* __restrict__ x, const void* w, int wtype, TY* y,x += row * dim;y += row * dim;if (r) r += row * dim;- float v[NORM_MAX_PER_THREAD];- float wv[NORM_MAX_PER_THREAD];+ float v[PER];+ float wv[PER];float ss = 0.0f;// weights and (mode 1) the old output are fetched up front, in the same memory round trip as x#pragma unroll- for (int j = 0; j < NORM_MAX_PER_THREAD; ++j)+ for (int j = 0; j < PER; ++j){const int i = threadIdx.x + j * 256;wv[j] = 0.0f;@@ -1967,15 +1967,15 @@ void rms_norm_kernel(const TX* __restrict__ x, const void* w, int wtype, TY* y,wv[j] = wtype ? ld_w(w, wtype, i) + constant_bias : 1.0f;}}- float yo[NORM_MAX_PER_THREAD];+ float yo[PER];#pragma unroll- for (int j = 0; j < NORM_MAX_PER_THREAD; ++j)+ for (int j = 0; j < PER; ++j){const int i = threadIdx.x + j * 256;yo[j] = (mode == 1 && i < dim) ? ld_f<TY>(y, i) : 0.0f;}#pragma unroll- for (int j = 0; j < NORM_MAX_PER_THREAD; ++j)+ for (int j = 0; j < PER; ++j){const int i = threadIdx.x + j * 256;if (i < dim)@@ -1993,7 +1993,7 @@ void rms_norm_kernel(const TX* __restrict__ x, const void* w, int wtype, TY* y,}const float scale = rsqrtf(block_sum(ss, red) / (float) dim + eps) * constant_scale;#pragma unroll- for (int j = 0; j < NORM_MAX_PER_THREAD; ++j)+ for (int j = 0; j < PER; ++j){const int i = threadIdx.x + j * 256;if (i < dim)@@ -2007,6 +2007,19 @@ void rms_norm_kernel(const TX* __restrict__ x, const void* w, int wtype, TY* y,}// ------------------------------------------------------------------------------------------------+// PER = values per thread: the smallest of 8 / 16 / 32 that covers the row (256 threads), same arithmetic for every PER.+template <typename TX, typename TY, typename TR>+static void rn_launch(int rows, cudaStream_t stream, const TX* x, const void* w, int wtype, TY* y, TR* r, int dim,+ float eps, float constant_bias, float constant_scale, int mode)+{+ if (dim <= 256 * 8)+ rms_norm_kernel<TX, TY, TR, 8><<<rows, 256, 0, stream>>>(x, w, wtype, y, r, dim, eps, constant_bias, constant_scale, mode);+ else if (dim <= 256 * 16)+ rms_norm_kernel<TX, TY, TR, 16><<<rows, 256, 0, stream>>>(x, w, wtype, y, r, dim, eps, constant_bias, constant_scale, mode);+ else+ rms_norm_kernel<TX, TY, TR, NORM_MAX_PER_THREAD><<<rows, 256, 0, stream>>>(x, w, wtype, y, r, dim, eps, constant_bias, constant_scale, mode);+}+// Host side// k-tiles per wave (ktw). Measured on gfx1151 at MiMo shapes (tools/decode/sweep.py): the best@@ -3391,7 +3404,7 @@ void exl3_dec_rms_normTORCH_CHECK(r.has_value() && r->is_contiguous() && r->numel() == x.numel(), "exl3_dec_rms_norm: residual");const bool fr = r->dtype() == at::kFloat;TORCH_CHECK(fr || r->dtype() == at::kHalf, "exl3_dec_rms_norm: residual dtype");- #define RN_LAUNCH(TX, TY, TR) rms_norm_kernel<TX, TY, TR><<<rows, 256, 0, stream>>>( \+ #define RN_LAUNCH(TX, TY, TR) rn_launch<TX, TY, TR>(rows, stream, \reinterpret_cast<const TX*>(x.data_ptr()), wp, wtype, reinterpret_cast<TY*>(y.data_ptr()), \reinterpret_cast<TR*>(r->data_ptr()), dim, e, cb, cs, 2)if (fx && fr && !fy) RN_LAUNCH(float, half, float);@@ -3403,7 +3416,7 @@ void exl3_dec_rms_norm}else{- #define RN_LAUNCH(TX, TY) rms_norm_kernel<TX, TY, float><<<rows, 256, 0, stream>>>( \+ #define RN_LAUNCH(TX, TY) rn_launch<TX, TY, float>(rows, stream, \reinterpret_cast<const TX*>(x.data_ptr()), wp, wtype, reinterpret_cast<TY*>(y.data_ptr()), \nullptr, dim, e, cb, cs, (int) mode)if (fx && fy) RN_LAUNCH(float, float);diff --git a/exllamav3/exllamav3_ext/routing_std_gfx12.cu b/exllamav3/exllamav3_ext/routing_std_gfx12.cuindex 068aee2..d270cfb 100644--- a/exllamav3/exllamav3_ext/routing_std_gfx12.cu+++ b/exllamav3/exllamav3_ext/routing_std_gfx12.cu@@ -17,10 +17,8 @@namespace {constexpr int WAVE_SIZE = 32;-constexpr int GEMV_WAVES = 8;-constexpr int ROUTER_HIDDEN = 2560;-constexpr int ROUTER_EXPERTS = 512;-constexpr int ROUTER_TOP_K = 10;+constexpr int GEMV_WAVES = 2; // 2 expert rows per block: E / 2 blocks (8 per block left most CUs idle at E = 256)+// Supported (hidden, experts, top-k) decode shapes: see routing_std_gfx12_bsz1 below and _HIP_ROUTER_SHAPES in block_sparse_mlp_routing.pyconstexpr int MAX_ROUTER_ROWS = 16;constexpr float NEG_INF = -std::numeric_limits<float>::infinity();@@ -64,6 +62,7 @@ float wave_reduce_sum(float value)return __shfl(value, 0, WAVE_SIZE);}+template <int ROUTER_HIDDEN, int ROUTER_EXPERTS>__global__ __launch_bounds__(GEMV_WAVES * WAVE_SIZE)void routing_gemv_gfx12_bsz1_kernel(@@ -85,7 +84,7 @@ void routing_gemv_gfx12_bsz1_kernelgate_t + static_cast<size_t>(expert) * ROUTER_HIDDEN);float sum = 0.0f;- #pragma unroll 2+ #pragma unroll 8for (int col = lane; col < ROUTER_HIDDEN / 2; col += WAVE_SIZE){const half2 h = hidden2[col];@@ -98,9 +97,10 @@ void routing_gemv_gfx12_bsz1_kernelif (lane == 0) scores[expert] = __float2half_rn(sum);}-// This is the standard routing top-k reduction from routing.cu, specialized to the-// validated E=512/K=10 wave32 decode shape. Each wave first contributes its ten best-// candidates; wave 0 then selects and normalizes the global ten in descending order.+// Top-k by rank (same result as the standard routing.cu reduction): every thread holds one expert score and counts, from shared+// memory, the scores that beat it (greater, or equal with a lower expert index); a rank below K is that expert's output slot.+// Then the softmax over the K selected exactly as before: exp(score - max over all experts), lane-order sum, divide.+template <int ROUTER_EXPERTS, int ROUTER_TOP_K>__global__ __launch_bounds__(ROUTER_EXPERTS)void routing_std_topk_gfx12_bsz1_kernel(@@ -110,10 +110,9 @@ void routing_std_topk_gfx12_bsz1_kernel){constexpr int NUM_WAVES = ROUTER_EXPERTS / WAVE_SIZE;- constexpr int NUM_CANDIDATES = NUM_WAVES * ROUTER_TOP_K;+ static_assert(ROUTER_EXPERTS % WAVE_SIZE == 0 && NUM_WAVES <= WAVE_SIZE && ROUTER_TOP_K < WAVE_SIZE, "router shape");- __shared__ float candidates_key[NUM_CANDIDATES];- __shared__ int candidates_idx[NUM_CANDIDATES];+ __shared__ float logits[ROUTER_EXPERTS];__shared__ float wave_max[NUM_WAVES];__shared__ float global_max;__shared__ float selected_exp[ROUTER_TOP_K];@@ -126,6 +125,7 @@ void routing_std_topk_gfx12_bsz1_kerneltopk_indices += static_cast<size_t>(blockIdx.x) * ROUTER_TOP_K;topk_weights += static_cast<size_t>(blockIdx.x) * ROUTER_TOP_K;const float logit = __half2float(scores[tid]);+ logits[tid] = logit;float max_logit = wave_reduce_max(logit);if (lane == 0) wave_max[wave] = max_logit;@@ -137,88 +137,23 @@ void routing_std_topk_gfx12_bsz1_kernelif (lane == 0) global_max = max_logit;}- float key = logit;- int idx = tid;- #pragma unroll- for (int rank = 0; rank < ROUTER_TOP_K; ++rank)+ int rank = 0;+ #pragma unroll 8+ for (int j = 0; j < ROUTER_EXPERTS; ++j){- float best_key = key;- int best_idx = idx;- wave_reduce_best(best_key, best_idx);- if (lane == rank)- {- candidates_key[wave * ROUTER_TOP_K + rank] = best_key;- candidates_idx[wave * ROUTER_TOP_K + rank] = best_idx;- }- if (idx == best_idx)- {- key = NEG_INF;- idx = -1;- }+ const float other = logits[j];+ rank += (other > logit || (other == logit && j < tid)) ? 1 : 0;}__syncthreads();-- // 160 candidates are compacted to 50, then 20, then the final ten. The fixed- // bounds avoid dynamic masks and shifts and preserve routing.cu's candidate order.- int num_candidates = NUM_CANDIDATES;- while (num_candidates > WAVE_SIZE)+ if (rank < ROUTER_TOP_K){- const int stage_waves = (num_candidates + WAVE_SIZE - 1) / WAVE_SIZE;- const bool active_wave = wave < stage_waves;- const int pos = wave * WAVE_SIZE + lane;- key = active_wave && pos < num_candidates ? candidates_key[pos] : NEG_INF;- idx = active_wave && pos < num_candidates ? candidates_idx[pos] : -1;- // All candidates must be loaded into registers before compacted output overwrites- // the front of the same shared arrays; wave scheduling is otherwise unconstrained.- __syncthreads();- if (active_wave)- {- #pragma unroll- for (int rank = 0; rank < ROUTER_TOP_K; ++rank)- {- float best_key = key;- int best_idx = idx;- wave_reduce_best(best_key, best_idx);- if (lane == rank)- {- candidates_key[wave * ROUTER_TOP_K + rank] = best_key;- candidates_idx[wave * ROUTER_TOP_K + rank] = best_idx;- }- if (idx == best_idx)- {- key = NEG_INF;- idx = -1;- }- }- }- __syncthreads();- num_candidates = stage_waves * ROUTER_TOP_K;+ selected_exp[rank] = logit == global_max ? 1.0f : expf(logit - global_max);+ selected_idx[rank] = tid;}+ __syncthreads();if (wave == 0){- key = lane < num_candidates ? candidates_key[lane] : NEG_INF;- idx = lane < num_candidates ? candidates_idx[lane] : -1;- #pragma unroll- for (int rank = 0; rank < ROUTER_TOP_K; ++rank)- {- float best_key = key;- int best_idx = idx;- wave_reduce_best(best_key, best_idx);- if (lane == rank)- {- selected_exp[rank] = best_key == global_max ?- 1.0f : expf(best_key - global_max);- selected_idx[rank] = best_idx;- }- if (idx == best_idx)- {- key = NEG_INF;- idx = -1;- }- }- __syncwarp();-const float e = lane < ROUTER_TOP_K ? selected_exp[lane] : 0.0f;const float sum = wave_reduce_sum(e) + 1.0e-20f;if (lane < ROUTER_TOP_K)@@ -292,29 +227,31 @@ void routing_std_gfx12_bsz1const int64_t rows = hidden.size(0);TORCH_CHECK(rows > 0 && rows <= MAX_ROUTER_ROWS,"routing_std_gfx12_bsz1 supports 1 through ", MAX_ROUTER_ROWS, " rows");- check_tensor(hidden, hidden.device(), at::kHalf, {rows, ROUTER_HIDDEN}, "hidden", 16);- check_tensor(gate_t, hidden.device(), at::kHalf,- {ROUTER_EXPERTS, ROUTER_HIDDEN}, "gate_t", 16);- check_tensor(scores, hidden.device(), at::kHalf, {rows, ROUTER_EXPERTS}, "scores", 16);- check_tensor(topk_indices, hidden.device(), at::kLong,- {rows, ROUTER_TOP_K}, "topk_indices", 16);- check_tensor(topk_weights, hidden.device(), at::kHalf,- {rows, ROUTER_TOP_K}, "topk_weights", 16);+ TORCH_CHECK(hidden.dim() == 2 && gate_t.dim() == 2 && topk_indices.dim() == 2,+ "routing_std_gfx12_bsz1: 2D tensors expected");+ const int64_t H = hidden.size(1), E = gate_t.size(0), K = topk_indices.size(1);+ check_tensor(hidden, hidden.device(), at::kHalf, {rows, H}, "hidden", 16);+ check_tensor(gate_t, hidden.device(), at::kHalf, {E, H}, "gate_t", 16);+ check_tensor(scores, hidden.device(), at::kHalf, {rows, E}, "scores", 16);+ check_tensor(topk_indices, hidden.device(), at::kLong, {rows, K}, "topk_indices", 16);+ check_tensor(topk_weights, hidden.device(), at::kHalf, {rows, K}, "topk_weights", 16);hipStream_t stream = at::cuda::getCurrentCUDAStream(device).stream();- routing_gemv_gfx12_bsz1_kernel<<<dim3(ROUTER_EXPERTS / GEMV_WAVES, rows),- GEMV_WAVES * WAVE_SIZE, 0, stream>>>- (- reinterpret_cast<const half*>(hidden.data_ptr()),- reinterpret_cast<const half*>(gate_t.data_ptr()),- reinterpret_cast<half*>(scores.data_ptr())- );- routing_std_topk_gfx12_bsz1_kernel<<<rows, ROUTER_EXPERTS, 0, stream>>>- (- reinterpret_cast<const half*>(scores.data_ptr()),- reinterpret_cast<int64_t*>(topk_indices.data_ptr()),- reinterpret_cast<half*>(topk_weights.data_ptr())- );+ const half* h = reinterpret_cast<const half*>(hidden.data_ptr());+ const half* g = reinterpret_cast<const half*>(gate_t.data_ptr());+ half* sc = reinterpret_cast<half*>(scores.data_ptr());+ int64_t* ti = reinterpret_cast<int64_t*>(topk_indices.data_ptr());+ half* tw = reinterpret_cast<half*>(topk_weights.data_ptr());+ #define ROUTER_SHAPE(HH, EE, KK) \+ if (H == HH && E == EE && K == KK) \+ { \+ routing_gemv_gfx12_bsz1_kernel<HH, EE><<<dim3(EE / GEMV_WAVES, rows), GEMV_WAVES * WAVE_SIZE, 0, stream>>>(h, g, sc); \+ routing_std_topk_gfx12_bsz1_kernel<EE, KK><<<rows, EE, 0, stream>>>(sc, ti, tw); \+ } else+ ROUTER_SHAPE(2560, 512, 10) // Qwen3.8-Flash-Next+ ROUTER_SHAPE(2048, 256, 8) // Qwen3.6-35B-A3B (GGUF and EXL3 packs)+ TORCH_CHECK(false, "routing_std_gfx12_bsz1: unsupported router shape ", H, " x ", E, " top-", K);+ #undef ROUTER_SHAPEcuda_check(hipPeekAtLastError());}diff --git a/exllamav3/foreign_quant/gap_formats.py b/exllamav3/foreign_quant/gap_formats.pyindex 25093a4..b72d580 100644--- a/exllamav3/foreign_quant/gap_formats.py+++ b/exllamav3/foreign_quant/gap_formats.py@@ -11,9 +11,9 @@ import torchfrom .gguf_tables import IQ3_S_GRID, IQ3_XXS_GRID, IQ4_NL_VALUES, KSIGNS# name -> (elements per block, bytes per block)-BLOCKS = {"q8_0": (32, 34), "q4_0": (32, 18), "q5_0": (32, 22), "iq4_nl": (32, 18), "iq3_xxs": (256, 98), "iq3_s": (256, 110),+BLOCKS = {"q8_0": (32, 34), "q4_0": (32, 18), "q5_0": (32, 22), "q5_1": (32, 24), "iq4_nl": (32, 18), "iq3_xxs": (256, 98), "iq3_s": (256, 110), "iq2_xs": (256, 74), "iq2_s": (256, 82), "q3_k": (256, 110), "q2_k": (256, 84),"mxfp4": (32, 17), "nvfp4_gguf": (64, 36)}-GGML_TYPE_IDS = {"q8_0": 8, "q4_0": 2, "q5_0": 6, "iq3_xxs": 18, "iq4_nl": 20, "iq3_s": 21, "mxfp4": 39, "nvfp4_gguf": 40}+GGML_TYPE_IDS = {"q8_0": 8, "q4_0": 2, "q5_0": 6, "q5_1": 7, "iq3_xxs": 18, "iq4_nl": 20, "iq3_s": 21, "mxfp4": 39, "nvfp4_gguf": 40, "iq2_xs": 17, "iq2_s": 22, "q3_k": 11, "q2_k": 10}# MXFP4 / NVFP4 nibble -> value in half units (the scale carries the other factor 0.5)_FP4_HALF = (0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12)@@ -31,6 +31,9 @@ def _table(name: str, device) -> torch.Tensor:t = torch.frombuffer(bytearray(IQ3_XXS_GRID), dtype=torch.uint8).reshape(256, 4).float()elif name == "iq3_s":t = torch.frombuffer(bytearray(IQ3_S_GRID), dtype=torch.uint8).reshape(512, 4).float()+ elif name in ("iq2_xs", "iq2_s"):+ from .iq_grids_gen import iq2_grid+ t = torch.from_numpy(iq2_grid(name[4:]).copy()).float() # [512 | 1024, 8]else:t = torch.frombuffer(bytearray(KSIGNS), dtype=torch.uint8).long()_TABLES[key] = t.to(device)@@ -41,6 +44,51 @@ def _f16(b: torch.Tensor) -> torch.Tensor:return b.contiguous().view(torch.float16).float() # [..., 2] bytes -> [..., 1]+_Q51_TRITON = __import__("os").environ.get("EXL3_Q51_TRITON", "1") != "0"+_q51_kernel = None+++def _dequant_q5_1_triton(raw: torch.Tensor) -> torch.Tensor:+ """raw [rows, nb * 24] uint8 Q5_1 blocks -> [rows, nb * 32] half, bit-identical to the torch chain below."""+ global _q51_kernel+ import triton+ import triton.language as tl+ if _q51_kernel is None:+ @triton.jit+ def k(src, dst, nblk, BLOCKS: tl.constexpr):+ pid = tl.program_id(0)+ bi = pid * BLOCKS + tl.arange(0, BLOCKS) # block ids+ ok = bi < nblk+ j = tl.arange(0, 32) # element in block+ base = bi.to(tl.int64) * 24+ b0 = tl.load(src + base + 0, mask = ok, other = 0).to(tl.uint32)+ b1 = tl.load(src + base + 1, mask = ok, other = 0).to(tl.uint32)+ b2 = tl.load(src + base + 2, mask = ok, other = 0).to(tl.uint32)+ b3 = tl.load(src + base + 3, mask = ok, other = 0).to(tl.uint32)+ b4 = tl.load(src + base + 4, mask = ok, other = 0).to(tl.uint32)+ b5 = tl.load(src + base + 5, mask = ok, other = 0).to(tl.uint32)+ b6 = tl.load(src + base + 6, mask = ok, other = 0).to(tl.uint32)+ b7 = tl.load(src + base + 7, mask = ok, other = 0).to(tl.uint32)+ d = (b0 | (b1 << 8)).to(tl.uint16).to(tl.float16, bitcast = True).to(tl.float32)+ mm = (b2 | (b3 << 8)).to(tl.uint16).to(tl.float16, bitcast = True).to(tl.float32)+ qh = b0 * 0 + (b4 | (b5 << 8) | (b6 << 16) | (b7 << 24))+ qs = tl.load(src + base[:, None] + 8 + (j % 16)[None, :], mask = ok[:, None], other = 0).to(tl.uint32)+ lo = tl.where((j < 16)[None, :], qs & 15, qs >> 4)+ hb = (qh[:, None] >> j[None, :].to(tl.uint32)) & 1+ v = (lo | (hb << 4)).to(tl.float32)+ t = d[:, None] * v+ o = t + mm[:, None]+ tl.store(dst + bi.to(tl.int64)[:, None] * 32 + j[None, :], o.to(tl.float16), mask = ok[:, None])+ _q51_kernel = k+ rows, w = raw.shape+ assert w % 24 == 0+ nblk = rows * (w // 24)+ out = torch.empty((rows, (w // 24) * 32), dtype = torch.half, device = raw.device)+ B = 64+ _q51_kernel[(triton.cdiv(nblk, B),)](raw.contiguous(), out, nblk, BLOCKS = B, enable_fp_fusion = False)+ return out++def _bits(x: torch.Tensor, n: int) -> torch.Tensor:"""[...] integer -> [..., n] bits, least significant first."""sh = torch.arange(n, device=x.device, dtype=torch.int64)@@ -78,7 +126,70 @@ def dequant(fmt: str, raw: torch.Tensor) -> torch.Tensor:qs = b[:, 4:36].reshape(nb, 4, 8)v = _table("fp4", raw.device)[torch.cat([qs & 15, qs >> 4], dim=2).long()] # [nb, 4, 16]return (sc.unsqueeze(-1) * v).reshape(n, -1).half()+ if fmt == "q2_k": # [scales 16 (low 4 scale, high 4 min)][qs 64][d fp16][dmin fp16] (ggml dequantize_row_q2_K)+ d, dm = _f16(b[:, 80:82]).unsqueeze(-1), _f16(b[:, 82:84]).unsqueeze(-1) # [nb, 1, 1, 1]+ sc = b[:, 0:16].long().reshape(nb, 2, 4, 2).repeat_interleave(16, dim=3) # [nb, n, j, 32]: scale of 16-weight half+ q = (b[:, 16:80].long().reshape(nb, 2, 1, 32) >> (2 * torch.arange(4, device=raw.device)).reshape(1, 1, 4, 1)) & 3+ return (d.unsqueeze(-1) * (sc & 15).float() * q.float() - dm.unsqueeze(-1) * (sc >> 4).float()).reshape(n, -1).half()+ if fmt == "q3_k": # [hmask 32][qs 64][scales 12][d fp16] (ggml dequantize_row_q3_K)+ d = _f16(b[:, 108:110]) # [nb, 1]+ hm = b[:, 0:32].long()+ qs = b[:, 32:96].long()+ a3 = b[:, 96:108].contiguous().view(torch.int32).long() & 0xFFFFFFFF # [nb, 3]+ k1, k2 = 0x03030303, 0x0F0F0F0F+ t = a3[:, 2]+ aux = torch.stack([(a3[:, 0] & k2) | (((t >> 0) & k1) << 4), (a3[:, 1] & k2) | (((t >> 2) & k1) << 4),+ ((a3[:, 0] >> 4) & k2) | (((t >> 4) & k1) << 4), ((a3[:, 1] >> 4) & k2) | (((t >> 6) & k1) << 4)], 1)+ sc = ((aux.unsqueeze(-1) >> (torch.arange(4, device=raw.device) * 8)) & 255).reshape(nb, 16)+ sc = (sc - 256 * (sc >= 128).long() - 32).float() # int8 - 32+ out = torch.empty((nb, 256), dtype=torch.float32, device=raw.device)+ i = 0+ for hh in range(2):+ q = qs[:, 32 * hh:32 * hh + 32]+ for j in range(4):+ sh, m = 2 * j, 1 << (4 * hh + j)+ for half in range(2):+ sl = slice(16 * half, 16 * half + 16)+ v = ((q[:, sl] >> sh) & 3) - torch.where((hm[:, sl] & m) != 0, 0, 4)+ o = 128 * hh + 32 * j + 16 * half+ out[:, o:o + 16] = d * sc[:, i:i + 1] * v.float()+ i += 1+ return out.reshape(raw.shape[0], -1).half()+ if fmt == "iq2_xs": # [d fp16][qs 32 x uint16: 9-bit grid index | 7-bit sign index][scales 8]+ d = _f16(b[:, 0:2])+ q = b[:, 2:66].contiguous().view(torch.int16).long() & 0xFFFF # [nb, 32]+ scb = b[:, 66:74].long() # [nb, 8]+ sc = torch.stack([scb & 15, scb >> 4], -1).reshape(nb, 16).float() # one per 16 = per pair of groups of 8+ db = d * (0.5 + sc) * 0.25 # [nb, 16]+ grid = _table("iq2_xs", raw.device)[q & 511] # [nb, 32, 8]+ sgn = 1.0 - 2.0 * _bits(_table("ksigns", raw.device)[q >> 9], 8).float()+ out = (db.repeat_interleave(2, 1).unsqueeze(-1) * grid * sgn).reshape(nb, 256)+ return out.reshape(raw.shape[0], -1).half()+ if fmt == "iq2_s": # [d fp16][qs 32 grid low bytes][signs 32][qh 8][scales 8]+ d = _f16(b[:, 0:2])+ ql = b[:, 2:34].long()+ sg = b[:, 34:66]+ qh = b[:, 66:74].long() # [nb, 8]+ scb = b[:, 74:82].long()+ sc = torch.stack([scb & 15, scb >> 4], -1).reshape(nb, 16).float()+ db = d * (0.5 + sc) * 0.25 # [nb, 16]: groups l 0,1 -> low nibble, l 2,3 -> high+ l = torch.arange(4, device=raw.device)+ hi = ((qh.unsqueeze(-1) << (8 - 2 * l)) & 0x300).reshape(nb, 32)+ grid = _table("iq2_s", raw.device)[ql | hi] # [nb, 32, 8]+ sgn = 1.0 - 2.0 * _bits(sg, 8).float() # [nb, 32, 8]+ out = (db.repeat_interleave(2, 1).unsqueeze(-1) * grid * sgn).reshape(nb, 256)+ return out.reshape(raw.shape[0], -1).half()+ if fmt == "q5_1" and raw.is_cuda and _Q51_TRITON:+ return _dequant_q5_1_triton(raw)d = _f16(b[:, 0:2]) # [nb, 1]+ if fmt == "q5_1": # [d fp16][m fp16][qh u32][qs 16]: x = d * (low nibble | high bit << 4) + m+ m = _f16(b[:, 2:4])+ qs = b[:, 8:24]+ q = torch.cat([qs & 15, qs >> 4], dim=1).long()+ qh = b[:, 4:8].contiguous().view(torch.int32).long() & 0xFFFFFFFF+ hb = _bits(qh.reshape(nb), 32)+ out = d * (q | (hb << 4)).float() + m+ return out.reshape(raw.shape[0], -1).half()if fmt in ("q4_0", "iq4_nl", "q5_0"):qs = b[:, 2:18] if fmt != "q5_0" else b[:, 6:22]q = torch.cat([qs & 15, qs >> 4], dim=1).long() # elements 0..15 low nibbles, 16..31 high nibbles@@ -95,7 +206,7 @@ def dequant(fmt: str, raw: torch.Tensor) -> torch.Tensor:qs = b[:, 2:66].long() # [nb, 64] grid indicessc = b[:, 66:98].contiguous().view(torch.int32).long() & 0xFFFFFFFF # [nb, 8]db = d.reshape(nb, 1) * (0.5 + (sc >> 28).float()) * 0.5 # [nb, 8]- sh = torch.tensor([0, 7, 14, 21], device=raw.device)+ sh = torch.arange(4, device=raw.device) * 7 # on-device (no host copy inside a graph capture)sidx = (sc.unsqueeze(-1) >> sh) & 0x7F # [nb, 8, 4]sbits = _bits(_table("ksigns", raw.device)[sidx], 8) # [nb, 8, 4, 8]sgn = 1.0 - 2.0 * sbits.float()diff --git a/exllamav3/foreign_quant/iq_grids_gen.py b/exllamav3/foreign_quant/iq_grids_gen.pynew file mode 100644index 0000000..0d71cda--- /dev/null+++ b/exllamav3/foreign_quant/iq_grids_gen.py@@ -0,0 +1,39 @@+# SPDX-License-Identifier: MIT+"""Decode grids of IQ1_S/IQ1_M/IQ2_XXS/IQ2_XS/IQ2_S (and a cross-check of IQ3_XXS/IQ3_S) built the way ggml's iq2xs_init_impl / iq3xs_init_impl+build `the_grid`: entry k is the seed word kgrid[k] read as 8 (2-bit) or 4 (3-bit) little-endian digits l, each turned into a byte value.+init_impl itself writes 2*l+1; the decode tables of ggml-common.h hold a per-type value of that digit, fixed below (checked against ggml's+own tables in tests/test_gguf_types.py and by the ggml build in docs/reports/cgguftypes.md). The seeds come from foreign_seeds (extracted by script)."""+import functools++import numpy as np++from . import iq_seeds as S++IQ2_LEVELS = (8, 25, 43) # digit 0,1,2 -> byte of iq2xxs_grid / iq2xs_grid / iq2s_grid (init_impl: 1,3,5)+IQ3XXS_LEVELS = (4, 12, 20, 28, 36, 44, 52, 62) # digit 0..7 -> byte of iq3xxs_grid (init_impl: 1,3,..,15)+++def _digits(seed, bits, n):+ k = np.asarray(seed, np.uint32)[:, None]+ return ((k >> (bits * np.arange(n, dtype=np.uint32))) & ((1 << bits) - 1)).astype(np.int64)++[email protected]_cache(None)+def iq2_grid(kind):+ """kind in xxs/xs/s -> uint8 [N, 8] (float-ready magnitudes)."""+ seed = {"xxs": S.KGRID_2BIT_256, "xs": S.KGRID_2BIT_512, "s": S.KGRID_2BIT_1024}[kind]+ return np.array(IQ2_LEVELS + (0,), np.uint8)[_digits(seed, 2, 8)]++[email protected]_cache(None)+def iq1_grid():+ """int8 [2048, 8] in {-1, 0, 1}: (2*l+1 - 3) / 2 = l - 1, as quantize_iq1_s reads it back."""+ return (_digits(S.KGRID_1BIT_2048, 2, 8) - 1).astype(np.int8)++[email protected]_cache(None)+def iq3_grid(kind):+ """kind xxs/s -> uint8 [N, 4]."""+ if kind == "xxs":+ return np.array(IQ3XXS_LEVELS, np.uint8)[_digits(S.KGRID_256, 3, 4)]+ return (2 * _digits(S.KGRID_512, 3, 4) + 1).astype(np.uint8)diff --git a/exllamav3/foreign_quant/iq_seeds.py b/exllamav3/foreign_quant/iq_seeds.pynew file mode 100644index 0000000..1be5e0a--- /dev/null+++ b/exllamav3/foreign_quant/iq_seeds.py@@ -0,0 +1,303 @@+# SPDX-License-Identifier: MIT+"""Seed lists of ggml iq2xs_init_impl / iq3xs_init_impl (ggml/src/ggml-quants.c, llama.cpp commit 29c720eaf72fcf8e4e61a56a88b994d92668261d, MIT), extracted by tools/gen_gguf_seeds.py."""+COMMIT = "29c720eaf72fcf8e4e61a56a88b994d92668261d"+KGRID_2BIT_256 = (+ 0, 2, 5, 8, 10, 17, 20, 32, 34, 40, 42, 65, 68, 80, 88, 97,+ 100, 128, 130, 138, 162, 257, 260, 272, 277, 320, 388, 408, 512, 514, 546, 642,+ 1025, 1028, 1040, 1057, 1060, 1088, 1090, 1096, 1120, 1153, 1156, 1168, 1188, 1280, 1282, 1288,+ 1312, 1350, 1385, 1408, 1425, 1545, 1552, 1600, 1668, 1700, 2048, 2053, 2056, 2068, 2088, 2113,+ 2116, 2128, 2130, 2184, 2308, 2368, 2562, 2580, 4097, 4100, 4112, 4129, 4160, 4192, 4228, 4240,+ 4245, 4352, 4360, 4384, 4432, 4442, 4480, 4644, 4677, 5120, 5128, 5152, 5157, 5193, 5248, 5400,+ 5474, 5632, 5654, 6145, 6148, 6160, 6208, 6273, 6400, 6405, 6560, 6737, 8192, 8194, 8202, 8260,+ 8289, 8320, 8322, 8489, 8520, 8704, 8706, 9217, 9220, 9232, 9280, 9302, 9472, 9537, 9572, 9872,+ 10248, 10272, 10388, 10820, 16385, 16388, 16400, 16408, 16417, 16420, 16448, 16456, 16470, 16480, 16513, 16516,+ 16528, 16640, 16672, 16737, 16768, 16773, 16897, 16912, 16968, 16982, 17000, 17408, 17416, 17440, 17536, 17561,+ 17682, 17700, 17920, 18433, 18436, 18448, 18496, 18501, 18688, 18776, 18785, 18818, 19013, 19088, 20480, 20488,+ 20497, 20505, 20512, 20608, 20616, 20740, 20802, 20900, 21137, 21648, 21650, 21770, 22017, 22100, 22528, 22545,+ 22553, 22628, 22848, 23048, 24580, 24592, 24640, 24680, 24832, 24917, 25112, 25184, 25600, 25605, 25872, 25874,+ 25988, 26690, 32768, 32770, 32778, 32833, 32898, 33028, 33048, 33088, 33297, 33793, 33796, 33808, 33813, 33856,+ 33888, 34048, 34118, 34196, 34313, 34368, 34400, 34818, 35076, 35345, 36868, 36880, 36900, 36928, 37025, 37142,+ 37248, 37445, 37888, 37922, 37956, 38225, 39041, 39200, 40962, 41040, 41093, 41225, 41472, 42008, 43088, 43268,+)+KGRID_2BIT_512 = (+ 0, 2, 5, 8, 10, 17, 20, 22, 25, 32, 34, 37, 40, 65, 68, 70,+ 73, 80, 82, 85, 88, 97, 100, 128, 130, 133, 136, 145, 148, 153, 160, 257,+ 260, 262, 265, 272, 274, 277, 280, 282, 289, 292, 320, 322, 325, 328, 337, 340,+ 352, 360, 385, 388, 400, 512, 514, 517, 520, 529, 532, 544, 577, 580, 592, 597,+ 640, 650, 1025, 1028, 1030, 1033, 1040, 1042, 1045, 1048, 1057, 1060, 1088, 1090, 1093, 1096,+ 1105, 1108, 1110, 1120, 1153, 1156, 1168, 1280, 1282, 1285, 1288, 1297, 1300, 1312, 1345, 1348,+ 1360, 1377, 1408, 1537, 1540, 1552, 1574, 1600, 1602, 1668, 2048, 2050, 2053, 2056, 2058, 2065,+ 2068, 2080, 2085, 2113, 2116, 2128, 2136, 2176, 2208, 2218, 2305, 2308, 2320, 2368, 2433, 2441,+ 2560, 2592, 2600, 2710, 2720, 4097, 4100, 4102, 4105, 4112, 4114, 4117, 4120, 4129, 4132, 4160,+ 4162, 4165, 4168, 4177, 4180, 4192, 4202, 4225, 4228, 4240, 4352, 4354, 4357, 4360, 4369, 4372,+ 4384, 4417, 4420, 4432, 4480, 4500, 4502, 4609, 4612, 4614, 4624, 4672, 4704, 5120, 5122, 5125,+ 5128, 5137, 5140, 5152, 5185, 5188, 5193, 5200, 5220, 5248, 5377, 5380, 5392, 5440, 5632, 5652,+ 5705, 6145, 6148, 6160, 6162, 6208, 6228, 6278, 6400, 6405, 6502, 6737, 6825, 8192, 8194, 8197,+ 8200, 8202, 8209, 8212, 8224, 8257, 8260, 8272, 8320, 8352, 8449, 8452, 8464, 8512, 8520, 8549,+ 8704, 8738, 8832, 8872, 9217, 9220, 9232, 9257, 9280, 9472, 9537, 9554, 9625, 9729, 9754, 9894,+ 10240, 10248, 10250, 10272, 10325, 10376, 10402, 10600, 10640, 10760, 10784, 10882, 10888, 10890, 16385, 16388,+ 16390, 16393, 16400, 16402, 16405, 16408, 16417, 16420, 16448, 16450, 16453, 16456, 16458, 16465, 16468, 16480,+ 16485, 16513, 16516, 16528, 16640, 16642, 16645, 16648, 16657, 16660, 16672, 16705, 16708, 16720, 16768, 16773,+ 16802, 16897, 16900, 16912, 16914, 16937, 16960, 17408, 17410, 17413, 17416, 17425, 17428, 17433, 17440, 17473,+ 17476, 17488, 17536, 17556, 17665, 17668, 17680, 17700, 17728, 17818, 17920, 17930, 17988, 18000, 18433, 18436,+ 18448, 18496, 18501, 18516, 18530, 18688, 18705, 18756, 18768, 18793, 18948, 20480, 20482, 20485, 20488, 20497,+ 20500, 20512, 20520, 20545, 20548, 20560, 20608, 20737, 20740, 20752, 20757, 20800, 20802, 20992, 21060, 21162,+ 21505, 21508, 21520, 21537, 21568, 21600, 21633, 21665, 21760, 21768, 21888, 21896, 22049, 22120, 22177, 22528,+ 22548, 22593, 22608, 22681, 22810, 22848, 22850, 23173, 24577, 24580, 24592, 24640, 24660, 24674, 24710, 24745,+ 24832, 25124, 25162, 25234, 25600, 25622, 25872, 25920, 25925, 26020, 26625, 26730, 26917, 27142, 27220, 27234,+ 32768, 32770, 32773, 32776, 32785, 32788, 32800, 32810, 32833, 32836, 32848, 32896, 32898, 32936, 32938, 33025,+ 33028, 33030, 33040, 33088, 33105, 33113, 33280, 33312, 33408, 33410, 33440, 33448, 33793, 33796, 33808, 33810,+ 33813, 33856, 33888, 33929, 34048, 34116, 34213, 34328, 34410, 34816, 34824, 34853, 34906, 34944, 34946, 34984,+ 35078, 35362, 35456, 35464, 35478, 35496, 36865, 36868, 36880, 36928, 36950, 36996, 37120, 37154, 37220, 37462,+ 37513, 37888, 37893, 37956, 37968, 37976, 38185, 38288, 38290, 38465, 38993, 39078, 39241, 39445, 39520, 40960,+ 40962, 40968, 40970, 40992, 41002, 41120, 41297, 41305, 41382, 41472, 41474, 41480, 41514, 41600, 41632, 42048,+ 42133, 42597, 42648, 43018, 43040, 43042, 43048, 43168, 43176, 43268, 43396, 43398, 43560, 43562, 43665, 43690,+)+KGRID_2BIT_1024 = (+ 0, 2, 5, 8, 10, 17, 20, 22, 25, 32, 34, 37, 40, 65, 68, 70,+ 73, 80, 82, 85, 88, 97, 100, 102, 105, 128, 130, 133, 136, 145, 148, 160,+ 165, 170, 257, 260, 262, 265, 272, 274, 277, 280, 289, 292, 320, 322, 325, 328,+ 337, 340, 342, 345, 352, 357, 360, 385, 388, 400, 402, 405, 417, 420, 512, 514,+ 517, 520, 529, 532, 544, 554, 577, 580, 582, 585, 592, 597, 640, 645, 650, 660,+ 674, 1025, 1028, 1030, 1033, 1040, 1042, 1045, 1048, 1057, 1060, 1062, 1065, 1088, 1090, 1093,+ 1096, 1098, 1105, 1108, 1110, 1113, 1120, 1122, 1125, 1153, 1156, 1158, 1161, 1168, 1173, 1176,+ 1185, 1188, 1280, 1282, 1285, 1288, 1290, 1297, 1300, 1302, 1305, 1312, 1317, 1320, 1345, 1348,+ 1350, 1353, 1360, 1362, 1365, 1368, 1377, 1380, 1408, 1410, 1413, 1416, 1425, 1428, 1440, 1537,+ 1540, 1542, 1545, 1552, 1557, 1600, 1605, 1608, 1617, 1620, 1632, 1665, 1668, 1680, 2048, 2050,+ 2053, 2056, 2065, 2068, 2070, 2073, 2080, 2085, 2090, 2113, 2116, 2118, 2121, 2128, 2130, 2133,+ 2136, 2145, 2148, 2176, 2181, 2196, 2218, 2305, 2308, 2320, 2322, 2325, 2328, 2337, 2368, 2373,+ 2376, 2385, 2388, 2400, 2433, 2448, 2560, 2577, 2580, 2594, 2600, 2602, 2640, 2713, 4097, 4100,+ 4102, 4105, 4112, 4114, 4117, 4120, 4129, 4132, 4134, 4160, 4162, 4165, 4168, 4177, 4180, 4182,+ 4185, 4192, 4194, 4197, 4200, 4225, 4228, 4230, 4240, 4245, 4248, 4257, 4260, 4352, 4354, 4357,+ 4360, 4362, 4369, 4372, 4374, 4377, 4384, 4386, 4389, 4392, 4417, 4420, 4422, 4425, 4432, 4434,+ 4437, 4440, 4449, 4452, 4480, 4482, 4485, 4488, 4497, 4500, 4609, 4612, 4617, 4624, 4629, 4641,+ 4644, 4672, 4677, 4689, 4692, 4737, 4740, 4752, 5120, 5122, 5125, 5128, 5137, 5140, 5142, 5145,+ 5152, 5157, 5160, 5185, 5188, 5190, 5193, 5200, 5202, 5205, 5208, 5217, 5220, 5248, 5250, 5253,+ 5256, 5265, 5268, 5280, 5377, 5380, 5382, 5385, 5392, 5394, 5397, 5400, 5409, 5412, 5440, 5442,+ 5445, 5448, 5457, 5460, 5472, 5505, 5508, 5520, 5632, 5637, 5640, 5649, 5652, 5664, 5697, 5700,+ 5712, 5760, 5802, 6145, 6148, 6150, 6153, 6160, 6165, 6168, 6177, 6208, 6210, 6213, 6216, 6225,+ 6228, 6240, 6273, 6276, 6400, 6402, 6405, 6408, 6417, 6420, 6432, 6465, 6468, 6480, 6505, 6562,+ 6660, 6672, 6720, 6742, 8192, 8194, 8197, 8200, 8209, 8212, 8214, 8217, 8224, 8229, 8234, 8257,+ 8260, 8272, 8274, 8277, 8292, 8320, 8330, 8340, 8362, 8449, 8452, 8464, 8466, 8469, 8481, 8512,+ 8514, 8517, 8529, 8532, 8544, 8577, 8580, 8592, 8704, 8714, 8738, 8744, 8746, 8772, 8784, 8840,+ 8842, 8872, 9217, 9220, 9222, 9225, 9232, 9237, 9240, 9249, 9252, 9280, 9282, 9285, 9288, 9297,+ 9300, 9312, 9345, 9348, 9360, 9472, 9477, 9480, 9489, 9492, 9504, 9537, 9540, 9552, 9574, 9600,+ 9729, 9732, 9744, 9792, 9817, 10240, 10245, 10257, 10260, 10305, 10308, 10320, 10378, 10410, 10497, 10500,+ 10512, 10645, 10762, 10786, 10852, 10888, 10890, 16385, 16388, 16390, 16393, 16400, 16402, 16405, 16408, 16410,+ 16417, 16420, 16422, 16448, 16450, 16453, 16456, 16458, 16465, 16468, 16470, 16473, 16480, 16482, 16485, 16513,+ 16516, 16528, 16533, 16536, 16545, 16548, 16640, 16642, 16645, 16648, 16657, 16660, 16662, 16665, 16672, 16674,+ 16677, 16705, 16708, 16710, 16713, 16720, 16722, 16725, 16728, 16737, 16740, 16768, 16770, 16773, 16776, 16785,+ 16788, 16800, 16897, 16900, 16912, 16914, 16917, 16920, 16932, 16960, 16965, 16968, 16977, 16980, 16992, 17025,+ 17028, 17408, 17410, 17413, 17416, 17418, 17425, 17428, 17430, 17433, 17440, 17442, 17445, 17448, 17473, 17476,+ 17478, 17481, 17488, 17490, 17493, 17496, 17505, 17508, 17536, 17538, 17541, 17544, 17553, 17556, 17568, 17665,+ 17668, 17670, 17673, 17680, 17682, 17685, 17688, 17697, 17700, 17728, 17730, 17733, 17736, 17745, 17748, 17760,+ 17770, 17793, 17796, 17808, 17920, 17922, 17925, 17928, 17937, 17940, 17952, 17985, 17988, 18000, 18048, 18085,+ 18433, 18436, 18441, 18448, 18450, 18453, 18456, 18465, 18468, 18496, 18498, 18501, 18504, 18513, 18516, 18528,+ 18564, 18576, 18688, 18690, 18693, 18696, 18705, 18708, 18720, 18753, 18756, 18768, 18816, 18838, 18945, 18948,+ 18960, 19008, 20480, 20482, 20485, 20488, 20497, 20500, 20502, 20505, 20512, 20514, 20517, 20520, 20545, 20548,+ 20550, 20553, 20560, 20562, 20565, 20568, 20577, 20580, 20608, 20610, 20613, 20616, 20625, 20628, 20737, 20740,+ 20742, 20745, 20752, 20754, 20757, 20760, 20769, 20772, 20800, 20802, 20805, 20808, 20817, 20820, 20832, 20865,+ 20868, 20880, 20992, 20997, 21000, 21009, 21012, 21024, 21057, 21060, 21072, 21097, 21120, 21505, 21508, 21510,+ 21513, 21520, 21522, 21525, 21528, 21537, 21540, 21568, 21570, 21573, 21576, 21585, 21588, 21600, 21633, 21636,+ 21648, 21760, 21762, 21765, 21768, 21777, 21780, 21792, 21825, 21828, 21840, 21888, 22017, 22020, 22032, 22054,+ 22080, 22528, 22530, 22533, 22536, 22545, 22548, 22560, 22593, 22596, 22608, 22618, 22656, 22785, 22788, 22800,+ 22848, 23040, 23065, 23173, 23208, 24577, 24580, 24582, 24592, 24594, 24597, 24600, 24609, 24612, 24640, 24645,+ 24648, 24657, 24660, 24672, 24708, 24720, 24832, 24834, 24837, 24840, 24849, 24852, 24864, 24897, 24900, 24912,+ 24960, 24985, 25092, 25104, 25152, 25174, 25249, 25600, 25605, 25608, 25617, 25620, 25632, 25665, 25668, 25680,+ 25728, 25857, 25860, 25872, 25920, 25930, 25960, 26002, 26112, 26260, 26625, 26628, 26640, 26725, 26776, 26880,+ 26922, 27202, 27297, 32768, 32770, 32773, 32776, 32785, 32788, 32793, 32800, 32805, 32833, 32836, 32848, 32850,+ 32853, 32856, 32865, 32896, 32901, 32913, 32916, 33025, 33028, 33033, 33040, 33042, 33045, 33048, 33057, 33060,+ 33088, 33090, 33093, 33096, 33105, 33108, 33153, 33156, 33168, 33193, 33280, 33285, 33290, 33297, 33300, 33345,+ 33348, 33360, 33793, 33796, 33798, 33801, 33808, 33810, 33813, 33816, 33825, 33856, 33858, 33861, 33864, 33873,+ 33876, 33888, 33921, 33924, 33936, 34048, 34050, 34053, 34056, 34065, 34068, 34080, 34113, 34116, 34128, 34176,+ 34186, 34305, 34308, 34320, 34345, 34368, 34816, 34821, 34833, 34836, 34881, 34884, 34896, 34978, 35073, 35076,+ 35136, 35173, 35362, 35416, 35418, 35458, 35490, 36865, 36868, 36873, 36880, 36882, 36885, 36888, 36900, 36928,+ 36930, 36933, 36936, 36945, 36948, 36960, 36993, 36996, 37008, 37120, 37125, 37137, 37140, 37185, 37188, 37200,+ 37210, 37377, 37380, 37392, 37440, 37542, 37888, 37890, 37893, 37896, 37905, 37908, 37920, 37953, 37956, 37968,+ 38016, 38038, 38145, 38148, 38160, 38208, 38296, 38305, 38400, 38470, 38500, 38913, 38916, 38928, 38950, 38976,+ 39081, 39168, 39241, 39250, 39568, 40960, 40965, 40970, 40980, 40994, 41002, 41025, 41028, 41040, 41122, 41130,+ 41280, 41317, 41474, 41482, 41506, 41512, 41514, 41602, 41608, 41610, 41640, 41985, 41988, 42000, 42048, 42121,+ 42148, 42240, 42265, 42577, 43018, 43048, 43170, 43348, 43398, 43528, 43530, 43552, 43554, 43560, 43656, 43690,+)+KGRID_1BIT_2048 = (+ 0, 2, 5, 8, 10, 17, 21, 32, 34, 40, 42, 69, 81, 84, 86, 101,+ 128, 130, 136, 138, 149, 160, 162, 168, 170, 260, 261, 273, 276, 278, 281, 282,+ 293, 321, 326, 329, 338, 341, 346, 353, 356, 358, 360, 389, 401, 404, 406, 421,+ 512, 514, 520, 522, 533, 544, 546, 552, 554, 581, 593, 601, 612, 617, 640, 642,+ 648, 650, 657, 661, 665, 672, 674, 680, 682, 1041, 1044, 1046, 1061, 1089, 1097, 1109,+ 1114, 1124, 1125, 1169, 1177, 1189, 1281, 1284, 1285, 1286, 1301, 1304, 1306, 1321, 1344, 1349,+ 1354, 1360, 1361, 1364, 1365, 1366, 1369, 1376, 1378, 1381, 1384, 1386, 1409, 1425, 1429, 1432,+ 1434, 1441, 1444, 1445, 1446, 1449, 1556, 1561, 1601, 1604, 1616, 1618, 1621, 1624, 1632, 1633,+ 1638, 1641, 1669, 1681, 1684, 1689, 2048, 2050, 2056, 2058, 2069, 2080, 2082, 2088, 2090, 2117,+ 2129, 2134, 2149, 2176, 2178, 2184, 2186, 2197, 2208, 2210, 2216, 2218, 2309, 2321, 2324, 2329,+ 2340, 2341, 2369, 2384, 2385, 2389, 2401, 2404, 2409, 2449, 2452, 2454, 2457, 2469, 2560, 2562,+ 2568, 2570, 2581, 2592, 2594, 2600, 2602, 2629, 2641, 2649, 2657, 2661, 2688, 2690, 2693, 2696,+ 2698, 2709, 2720, 2722, 2728, 2730, 4112, 4113, 4116, 4121, 4132, 4133, 4161, 4164, 4176, 4181,+ 4184, 4193, 4196, 4197, 4201, 4241, 4244, 4246, 4257, 4261, 4353, 4356, 4358, 4361, 4368, 4370,+ 4373, 4376, 4385, 4388, 4393, 4421, 4426, 4432, 4433, 4434, 4436, 4437, 4438, 4441, 4448, 4453,+ 4484, 4498, 4501, 4513, 4516, 4625, 4628, 4630, 4645, 4672, 4678, 4681, 4690, 4693, 4696, 4698,+ 4708, 4710, 4741, 4753, 4756, 4758, 4773, 5121, 5126, 5129, 5140, 5141, 5144, 5145, 5153, 5158,+ 5185, 5189, 5190, 5192, 5194, 5201, 5204, 5205, 5206, 5209, 5218, 5221, 5224, 5252, 5257, 5264,+ 5268, 5269, 5272, 5273, 5274, 5281, 5284, 5285, 5289, 5378, 5381, 5386, 5393, 5396, 5397, 5398,+ 5401, 5408, 5410, 5413, 5416, 5418, 5441, 5444, 5445, 5446, 5457, 5458, 5460, 5461, 5462, 5465,+ 5466, 5473, 5476, 5477, 5478, 5481, 5504, 5506, 5508, 5509, 5512, 5514, 5520, 5521, 5524, 5525,+ 5526, 5529, 5530, 5536, 5538, 5541, 5633, 5636, 5637, 5638, 5653, 5654, 5656, 5658, 5665, 5670,+ 5696, 5698, 5700, 5701, 5704, 5706, 5713, 5717, 5718, 5720, 5721, 5729, 5732, 5733, 5736, 5737,+ 5738, 5766, 5770, 5778, 5781, 5796, 5801, 6161, 6166, 6181, 6209, 6212, 6214, 6217, 6224, 6229,+ 6232, 6234, 6240, 6241, 6244, 6246, 6249, 6277, 6289, 6292, 6309, 6416, 6418, 6421, 6426, 6433,+ 6437, 6466, 6468, 6469, 6472, 6481, 6484, 6485, 6486, 6489, 6490, 6496, 6501, 6506, 6537, 6545,+ 6546, 6549, 6552, 6561, 6566, 6569, 6665, 6678, 6692, 6694, 6724, 6726, 6729, 6736, 6738, 6741,+ 6744, 6753, 6758, 6761, 6789, 6801, 6806, 6810, 8192, 8194, 8200, 8202, 8213, 8224, 8226, 8229,+ 8232, 8234, 8261, 8273, 8281, 8289, 8293, 8320, 8322, 8328, 8330, 8341, 8352, 8354, 8357, 8360,+ 8362, 8453, 8465, 8468, 8473, 8485, 8514, 8516, 8521, 8533, 8536, 8538, 8545, 8548, 8549, 8550,+ 8581, 8592, 8598, 8601, 8613, 8705, 8712, 8714, 8721, 8725, 8736, 8738, 8744, 8746, 8773, 8785,+ 8790, 8793, 8805, 8833, 8840, 8842, 8849, 8853, 8864, 8866, 8872, 8874, 9221, 9236, 9238, 9241,+ 9253, 9284, 9285, 9286, 9289, 9298, 9301, 9304, 9306, 9318, 9349, 9361, 9364, 9369, 9377, 9381,+ 9481, 9493, 9505, 9513, 9536, 9541, 9544, 9553, 9556, 9557, 9561, 9570, 9573, 9576, 9609, 9616,+ 9620, 9621, 9624, 9626, 9633, 9636, 9638, 9641, 9733, 9744, 9746, 9753, 9765, 9793, 9801, 9813,+ 9824, 9825, 9833, 9860, 9862, 9872, 9882, 10240, 10242, 10248, 10250, 10261, 10272, 10274, 10280, 10282,+ 10309, 10321, 10324, 10341, 10368, 10370, 10376, 10378, 10400, 10402, 10408, 10410, 10505, 10513, 10516, 10521,+ 10533, 10566, 10569, 10578, 10581, 10593, 10596, 10598, 10601, 10629, 10640, 10646, 10649, 10660, 10661, 10752,+ 10754, 10760, 10762, 10784, 10786, 10792, 10794, 10821, 10833, 10838, 10841, 10853, 10880, 10882, 10888, 10890,+ 10901, 10912, 10914, 10920, 10922, 16389, 16401, 16406, 16421, 16457, 16466, 16469, 16472, 16474, 16481, 16484,+ 16486, 16532, 16537, 16545, 16550, 16640, 16641, 16644, 16646, 16649, 16658, 16661, 16662, 16664, 16666, 16673,+ 16678, 16681, 16709, 16712, 16714, 16721, 16724, 16725, 16726, 16729, 16730, 16741, 16744, 16746, 16769, 16772,+ 16774, 16784, 16786, 16789, 16800, 16801, 16802, 16901, 16913, 16916, 16918, 16933, 16961, 16978, 16981, 16986,+ 16996, 17001, 17033, 17044, 17061, 17409, 17429, 17433, 17449, 17477, 17480, 17482, 17489, 17492, 17493, 17494,+ 17505, 17506, 17509, 17512, 17514, 17537, 17542, 17545, 17552, 17554, 17557, 17568, 17569, 17577, 17665, 17666,+ 17669, 17674, 17681, 17684, 17685, 17686, 17689, 17696, 17701, 17706, 17729, 17732, 17733, 17734, 17737, 17744,+ 17745, 17748, 17749, 17750, 17752, 17753, 17761, 17764, 17765, 17766, 17769, 17794, 17796, 17797, 17800, 17809,+ 17812, 17813, 17814, 17817, 17818, 17829, 17832, 17834, 17921, 17925, 17929, 17940, 17941, 17944, 17946, 17953,+ 17956, 17961, 17984, 17986, 17989, 17992, 18000, 18001, 18002, 18005, 18006, 18009, 18018, 18021, 18024, 18049,+ 18053, 18058, 18068, 18069, 18081, 18084, 18086, 18437, 18449, 18453, 18458, 18469, 18498, 18505, 18512, 18517,+ 18520, 18529, 18532, 18534, 18537, 18565, 18577, 18580, 18582, 18585, 18597, 18689, 18693, 18694, 18698, 18704,+ 18708, 18709, 18712, 18721, 18724, 18726, 18752, 18757, 18762, 18769, 18770, 18772, 18773, 18774, 18777, 18784,+ 18786, 18789, 18790, 18794, 18822, 18825, 18834, 18837, 18838, 18840, 18849, 18852, 18854, 18857, 18966, 19012,+ 19014, 19017, 19029, 19032, 19034, 19044, 19049, 19092, 19109, 20481, 20484, 20485, 20486, 20489, 20498, 20501,+ 20506, 20513, 20516, 20521, 20544, 20549, 20552, 20561, 20564, 20565, 20566, 20569, 20581, 20584, 20614, 20617,+ 20629, 20632, 20640, 20641, 20646, 20649, 20741, 20744, 20745, 20746, 20753, 20756, 20757, 20758, 20760, 20761,+ 20768, 20773, 20774, 20776, 20778, 20801, 20804, 20805, 20806, 20809, 20816, 20817, 20818, 20820, 20821, 20822,+ 20824, 20825, 20826, 20833, 20836, 20837, 20838, 20841, 20866, 20869, 20881, 20884, 20885, 20886, 20889, 20896,+ 20901, 20906, 20993, 20998, 21010, 21013, 21018, 21025, 21028, 21058, 21061, 21066, 21073, 21076, 21077, 21078,+ 21081, 21090, 21093, 21125, 21136, 21138, 21141, 21145, 21146, 21156, 21508, 21509, 21521, 21524, 21525, 21526,+ 21528, 21529, 21537, 21541, 21544, 21546, 21569, 21572, 21573, 21574, 21577, 21578, 21584, 21585, 21588, 21589,+ 21590, 21592, 21593, 21594, 21601, 21602, 21604, 21605, 21606, 21609, 21632, 21640, 21642, 21649, 21652, 21653,+ 21654, 21657, 21665, 21668, 21669, 21674, 21761, 21762, 21764, 21765, 21766, 21769, 21776, 21777, 21778, 21780,+ 21781, 21782, 21785, 21786, 21793, 21796, 21797, 21798, 21801, 21824, 21825, 21826, 21828, 21829, 21830, 21832,+ 21833, 21840, 21841, 21842, 21844, 21845, 21846, 21848, 21849, 21850, 21856, 21857, 21860, 21861, 21862, 21864,+ 21865, 21866, 21889, 21892, 21893, 21897, 21898, 21904, 21905, 21908, 21909, 21910, 21912, 21913, 21921, 21924,+ 21925, 21926, 21929, 22016, 22017, 22018, 22020, 22022, 22024, 22025, 22033, 22036, 22037, 22040, 22041, 22048,+ 22049, 22050, 22052, 22053, 22054, 22056, 22057, 22081, 22085, 22086, 22088, 22089, 22090, 22096, 22097, 22098,+ 22100, 22101, 22102, 22104, 22105, 22106, 22113, 22116, 22117, 22121, 22146, 22149, 22150, 22152, 22153, 22154,+ 22161, 22165, 22170, 22178, 22181, 22182, 22184, 22185, 22532, 22533, 22534, 22537, 22544, 22549, 22552, 22561,+ 22570, 22597, 22600, 22602, 22609, 22612, 22613, 22614, 22616, 22617, 22624, 22626, 22628, 22629, 22658, 22665,+ 22672, 22674, 22677, 22680, 22689, 22697, 22785, 22786, 22789, 22794, 22801, 22804, 22805, 22806, 22809, 22821,+ 22849, 22852, 22853, 22854, 22857, 22864, 22865, 22866, 22868, 22869, 22870, 22872, 22873, 22874, 22881, 22884,+ 22885, 22886, 22889, 22913, 22917, 22921, 22929, 22932, 22933, 22934, 22936, 22937, 22949, 23044, 23048, 23061,+ 23066, 23072, 23077, 23078, 23081, 23109, 23112, 23113, 23121, 23125, 23126, 23128, 23129, 23138, 23141, 23144,+ 23146, 23169, 23178, 23186, 23189, 23190, 23192, 23194, 23201, 24581, 24596, 24598, 24601, 24613, 24644, 24656,+ 24661, 24662, 24664, 24666, 24673, 24676, 24678, 24681, 24705, 24726, 24741, 24833, 24836, 24838, 24841, 24850,+ 24853, 24865, 24866, 24870, 24873, 24901, 24905, 24913, 24917, 24918, 24921, 24933, 24934, 24938, 24964, 24970,+ 24978, 24981, 24993, 24998, 25001, 25105, 25110, 25113, 25152, 25153, 25158, 25173, 25174, 25176, 25184, 25221,+ 25233, 25238, 25253, 25617, 25618, 25621, 25622, 25626, 25633, 25638, 25641, 25664, 25666, 25669, 25672, 25674,+ 25681, 25684, 25685, 25686, 25689, 25690, 25696, 25698, 25701, 25732, 25733, 25737, 25744, 25746, 25748, 25749,+ 25750, 25752, 25754, 25761, 25764, 25769, 25861, 25864, 25866, 25873, 25877, 25878, 25881, 25924, 25925, 25926,+ 25929, 25936, 25937, 25940, 25941, 25942, 25945, 25953, 25956, 25957, 25958, 25961, 25990, 25993, 25994, 26001,+ 26005, 26006, 26009, 26010, 26018, 26021, 26022, 26024, 26114, 26121, 26133, 26144, 26150, 26152, 26153, 26176,+ 26181, 26184, 26186, 26193, 26196, 26197, 26198, 26200, 26202, 26208, 26213, 26216, 26240, 26242, 26245, 26250,+ 26260, 26262, 26264, 26265, 26272, 26276, 26278, 26282, 26646, 26649, 26661, 26689, 26706, 26709, 26714, 26721,+ 26729, 26757, 26769, 26776, 26790, 26881, 26884, 26896, 26901, 26913, 26916, 26918, 26921, 26944, 26945, 26949,+ 26950, 26952, 26961, 26964, 26965, 26966, 26969, 26976, 26981, 26986, 27010, 27012, 27018, 27029, 27041, 27044,+ 27045, 27049, 27153, 27158, 27160, 27201, 27204, 27209, 27216, 27221, 27224, 27226, 27236, 27237, 27241, 27270,+ 27284, 27288, 27290, 27302, 32768, 32770, 32776, 32778, 32800, 32802, 32808, 32810, 32837, 32848, 32849, 32852,+ 32854, 32857, 32869, 32896, 32898, 32904, 32906, 32917, 32928, 32930, 32936, 32938, 33029, 33041, 33044, 33046,+ 33049, 33061, 33089, 33092, 33097, 33104, 33106, 33109, 33110, 33112, 33113, 33124, 33126, 33129, 33157, 33161,+ 33172, 33174, 33177, 33189, 33280, 33282, 33288, 33290, 33301, 33312, 33314, 33320, 33322, 33361, 33364, 33369,+ 33381, 33408, 33410, 33416, 33418, 33429, 33440, 33442, 33448, 33450, 33812, 33817, 33857, 33860, 33873, 33877,+ 33882, 33889, 33892, 33897, 33940, 33945, 34049, 34057, 34066, 34069, 34074, 34086, 34089, 34112, 34113, 34117,+ 34120, 34129, 34132, 34133, 34134, 34137, 34138, 34149, 34150, 34152, 34154, 34177, 34180, 34182, 34185, 34192,+ 34194, 34197, 34200, 34214, 34321, 34326, 34329, 34341, 34369, 34372, 34377, 34378, 34384, 34389, 34393, 34394,+ 34401, 34406, 34410, 34437, 34449, 34458, 34468, 34816, 34818, 34824, 34826, 34837, 34848, 34850, 34856, 34858,+ 34881, 34885, 34897, 34900, 34905, 34917, 34921, 34944, 34946, 34952, 34954, 34965, 34976, 34978, 34984, 34986,+ 35077, 35078, 35089, 35092, 35094, 35109, 35137, 35140, 35142, 35145, 35152, 35154, 35157, 35162, 35169, 35172,+ 35205, 35222, 35225, 35237, 35328, 35330, 35336, 35338, 35349, 35360, 35362, 35368, 35370, 35397, 35409, 35412,+ 35414, 35456, 35458, 35464, 35466, 35477, 35488, 35490, 35496, 35498, 36869, 36881, 36886, 36888, 36889, 36901,+ 36929, 36934, 36937, 36949, 36952, 36954, 36969, 36970, 36997, 37009, 37012, 37014, 37017, 37029, 37121, 37124,+ 37126, 37129, 37136, 37141, 37144, 37146, 37153, 37156, 37158, 37161, 37184, 37189, 37200, 37201, 37204, 37205,+ 37206, 37209, 37218, 37221, 37252, 37254, 37266, 37269, 37272, 37281, 37284, 37286, 37289, 37381, 37393, 37396,+ 37401, 37413, 37444, 37446, 37449, 37456, 37458, 37461, 37464, 37478, 37481, 37509, 37524, 37526, 37545, 37889,+ 37892, 37894, 37904, 37909, 37912, 37926, 37952, 37962, 37969, 37972, 37973, 37974, 37976, 37977, 37984, 37985,+ 37986, 37989, 38020, 38022, 38034, 38036, 38037, 38040, 38049, 38057, 38144, 38149, 38152, 38154, 38160, 38161,+ 38164, 38165, 38166, 38169, 38177, 38181, 38185, 38186, 38209, 38212, 38213, 38214, 38217, 38224, 38225, 38226,+ 38228, 38229, 38230, 38232, 38233, 38234, 38241, 38244, 38245, 38246, 38249, 38273, 38277, 38280, 38289, 38290,+ 38292, 38293, 38294, 38297, 38298, 38304, 38306, 38309, 38312, 38314, 38401, 38404, 38416, 38421, 38425, 38432,+ 38438, 38441, 38469, 38472, 38473, 38481, 38482, 38485, 38486, 38489, 38501, 38504, 38530, 38532, 38537, 38538,+ 38546, 38548, 38549, 38564, 38566, 38569, 38917, 38934, 38937, 38949, 38977, 38982, 38992, 38994, 38997, 38998,+ 39002, 39012, 39013, 39045, 39057, 39062, 39065, 39077, 39172, 39174, 39177, 39184, 39186, 39189, 39192, 39194,+ 39200, 39201, 39204, 39206, 39232, 39234, 39237, 39240, 39242, 39249, 39252, 39253, 39254, 39257, 39266, 39269,+ 39270, 39274, 39297, 39300, 39312, 39314, 39317, 39322, 39329, 39334, 39429, 39445, 39461, 39492, 39494, 39497,+ 39504, 39509, 39512, 39521, 39557, 39569, 39572, 39573, 39574, 40960, 40962, 40968, 40970, 40981, 40992, 40994,+ 41000, 41002, 41029, 41041, 41044, 41046, 41049, 41088, 41090, 41096, 41098, 41109, 41120, 41122, 41128, 41130,+ 41221, 41225, 41233, 41236, 41238, 41241, 41242, 41286, 41289, 41297, 41301, 41304, 41306, 41313, 41316, 41349,+ 41360, 41362, 41366, 41369, 41474, 41480, 41482, 41488, 41497, 41506, 41512, 41514, 41541, 41553, 41558, 41561,+ 41573, 41600, 41602, 41608, 41610, 41621, 41632, 41634, 41640, 41642, 42009, 42021, 42049, 42052, 42064, 42068,+ 42069, 42072, 42074, 42081, 42085, 42086, 42088, 42089, 42117, 42246, 42249, 42256, 42258, 42261, 42264, 42278,+ 42281, 42306, 42309, 42321, 42324, 42325, 42326, 42329, 42341, 42346, 42369, 42372, 42373, 42374, 42377, 42386,+ 42389, 42392, 42501, 42513, 42518, 42522, 42529, 42533, 42564, 42566, 42570, 42578, 42581, 42582, 42584, 42592,+ 42594, 42630, 42640, 42645, 42646, 42649, 42657, 42660, 42662, 43008, 43010, 43016, 43018, 43040, 43042, 43048,+ 43050, 43089, 43092, 43094, 43097, 43136, 43138, 43144, 43146, 43157, 43168, 43170, 43176, 43178, 43269, 43284,+ 43289, 43297, 43301, 43329, 43344, 43349, 43354, 43361, 43366, 43369, 43408, 43414, 43520, 43522, 43528, 43530,+ 43552, 43554, 43560, 43562, 43601, 43604, 43606, 43648, 43650, 43656, 43658, 43669, 43680, 43682, 43688, 43690,+)+KGRID_256 = (+ 0, 2, 4, 9, 11, 15, 16, 18, 25, 34, 59, 61, 65, 67, 72, 74,+ 81, 85, 88, 90, 97, 108, 120, 128, 130, 132, 137, 144, 146, 153, 155, 159,+ 169, 175, 189, 193, 199, 200, 202, 213, 248, 267, 287, 292, 303, 315, 317, 321,+ 327, 346, 362, 413, 436, 456, 460, 462, 483, 497, 513, 515, 520, 522, 529, 531,+ 536, 538, 540, 551, 552, 576, 578, 585, 592, 594, 641, 643, 648, 650, 657, 664,+ 698, 704, 706, 720, 729, 742, 758, 769, 773, 808, 848, 852, 870, 889, 901, 978,+ 992, 1024, 1026, 1033, 1035, 1040, 1042, 1046, 1049, 1058, 1089, 1091, 1093, 1096, 1098, 1105,+ 1112, 1139, 1143, 1144, 1152, 1154, 1161, 1167, 1168, 1170, 1183, 1184, 1197, 1217, 1224, 1228,+ 1272, 1276, 1309, 1323, 1347, 1367, 1377, 1404, 1473, 1475, 1486, 1509, 1537, 1544, 1546, 1553,+ 1555, 1576, 1589, 1594, 1600, 1602, 1616, 1625, 1636, 1638, 1665, 1667, 1672, 1685, 1706, 1722,+ 1737, 1755, 1816, 1831, 1850, 1856, 1862, 1874, 1901, 1932, 1950, 1971, 2011, 2032, 2052, 2063,+ 2077, 2079, 2091, 2095, 2172, 2192, 2207, 2208, 2224, 2230, 2247, 2277, 2308, 2345, 2356, 2389,+ 2403, 2424, 2501, 2504, 2506, 2520, 2570, 2593, 2616, 2624, 2630, 2646, 2669, 2700, 2714, 2746,+ 2754, 2795, 2824, 2835, 2839, 2874, 2882, 2905, 2984, 3028, 3042, 3092, 3108, 3110, 3124, 3153,+ 3185, 3215, 3252, 3288, 3294, 3364, 3397, 3434, 3483, 3523, 3537, 3587, 3589, 3591, 3592, 3610,+ 3626, 3670, 3680, 3722, 3749, 3754, 3776, 3789, 3803, 3824, 3857, 3873, 3904, 3906, 3924, 3992,+)+KGRID_512 = (+ 0, 1, 2, 5, 7, 8, 9, 10, 12, 14, 16, 17, 21, 27, 32, 34,+ 37, 39, 41, 43, 48, 50, 57, 60, 63, 64, 65, 66, 68, 72, 73, 77,+ 80, 83, 87, 89, 93, 100, 113, 117, 122, 128, 129, 133, 135, 136, 139, 142,+ 145, 149, 152, 156, 162, 165, 167, 169, 171, 184, 187, 195, 201, 205, 208, 210,+ 217, 219, 222, 228, 232, 234, 247, 249, 253, 256, 267, 271, 273, 276, 282, 288,+ 291, 297, 312, 322, 324, 336, 338, 342, 347, 353, 357, 359, 374, 379, 390, 393,+ 395, 409, 426, 441, 448, 450, 452, 464, 466, 470, 475, 488, 492, 512, 513, 514,+ 516, 520, 521, 523, 525, 527, 528, 530, 537, 540, 542, 556, 558, 561, 570, 576,+ 577, 579, 582, 584, 588, 593, 600, 603, 609, 616, 618, 632, 638, 640, 650, 653,+ 655, 656, 660, 666, 672, 675, 685, 688, 698, 705, 708, 711, 712, 715, 721, 727,+ 728, 732, 737, 754, 760, 771, 773, 778, 780, 793, 795, 802, 806, 808, 812, 833,+ 840, 843, 849, 856, 858, 873, 912, 916, 919, 932, 934, 961, 963, 968, 970, 977,+ 989, 993, 1010, 1016, 1024, 1025, 1027, 1029, 1031, 1032, 1034, 1036, 1038, 1041, 1043, 1047,+ 1048, 1050, 1057, 1059, 1061, 1064, 1066, 1079, 1080, 1083, 1085, 1088, 1090, 1096, 1099, 1103,+ 1106, 1109, 1113, 1116, 1122, 1129, 1153, 1156, 1159, 1169, 1171, 1176, 1183, 1185, 1195, 1199,+ 1209, 1212, 1216, 1218, 1221, 1225, 1234, 1236, 1241, 1243, 1250, 1256, 1270, 1281, 1287, 1296,+ 1299, 1306, 1309, 1313, 1338, 1341, 1348, 1353, 1362, 1375, 1376, 1387, 1400, 1408, 1410, 1415,+ 1425, 1453, 1457, 1477, 1481, 1494, 1496, 1507, 1512, 1538, 1545, 1547, 1549, 1551, 1554, 1561,+ 1563, 1565, 1570, 1572, 1575, 1577, 1587, 1593, 1601, 1603, 1605, 1612, 1617, 1619, 1632, 1648,+ 1658, 1662, 1664, 1674, 1680, 1690, 1692, 1704, 1729, 1736, 1740, 1745, 1747, 1751, 1752, 1761,+ 1763, 1767, 1773, 1787, 1795, 1801, 1806, 1810, 1817, 1834, 1840, 1844, 1857, 1864, 1866, 1877,+ 1882, 1892, 1902, 1915, 1934, 1953, 1985, 1987, 2000, 2002, 2013, 2048, 2052, 2058, 2064, 2068,+ 2071, 2074, 2081, 2088, 2104, 2114, 2119, 2121, 2123, 2130, 2136, 2141, 2147, 2153, 2157, 2177,+ 2179, 2184, 2189, 2193, 2203, 2208, 2223, 2226, 2232, 2244, 2249, 2251, 2256, 2258, 2265, 2269,+ 2304, 2306, 2324, 2335, 2336, 2361, 2373, 2375, 2385, 2418, 2443, 2460, 2480, 2504, 2509, 2520,+ 2531, 2537, 2562, 2568, 2572, 2578, 2592, 2596, 2599, 2602, 2614, 2620, 2625, 2627, 2629, 2634,+ 2641, 2650, 2682, 2688, 2697, 2707, 2712, 2718, 2731, 2754, 2759, 2760, 2775, 2788, 2793, 2805,+ 2811, 2817, 2820, 2832, 2842, 2854, 2890, 2902, 2921, 2923, 2978, 3010, 3012, 3026, 3081, 3083,+ 3085, 3097, 3099, 3120, 3136, 3152, 3159, 3188, 3210, 3228, 3234, 3245, 3250, 3256, 3264, 3276,+ 3281, 3296, 3349, 3363, 3378, 3392, 3395, 3420, 3440, 3461, 3488, 3529, 3531, 3584, 3588, 3591,+ 3600, 3602, 3614, 3616, 3628, 3634, 3650, 3657, 3668, 3683, 3685, 3713, 3716, 3720, 3726, 3729,+ 3736, 3753, 3778, 3802, 3805, 3819, 3841, 3845, 3851, 3856, 3880, 3922, 3938, 3970, 3993, 4032,+)diff --git a/exllamav3/foreign_quant/k_quants.py b/exllamav3/foreign_quant/k_quants.pyindex 98fd8ff..10d7f7d 100644--- a/exllamav3/foreign_quant/k_quants.py+++ b/exllamav3/foreign_quant/k_quants.py@@ -207,6 +207,30 @@ def dequant_q4_K_bulk(raw: np.ndarray) -> np.ndarray:return y.astype(np.float16)+def dequant_q6_K_bulk(raw: np.ndarray) -> np.ndarray:+ """Vectorized Q6_K dequant: raw uint8 [nb, 210] -> float16 [nb, 256].++ Same math as dequant_q6_K_block (ql low/high nibbles + 2 bits of qh, minus 32,+ times d * the int8 scale of each 16), no per-block Python (Q6_K embedding tables).+ """+ raw = np.ascontiguousarray(raw).reshape(-1, 210)+ nb = raw.shape[0]+ d = raw[:, 208:210].copy().view(np.float16).astype(np.float32).reshape(nb)+ sc = raw[:, 192:208].copy().view(np.int8).astype(np.float32)+ y = np.empty((nb, 256), dtype=np.float32)+ for n in range(2):+ ql = raw[:, n * 64:n * 64 + 64].astype(np.int32)+ qh = raw[:, 128 + n * 32:128 + n * 32 + 32].astype(np.int32)+ q = (np.bitwise_or(np.bitwise_and(ql[:, 0:32], 0xF), np.left_shift(np.bitwise_and(qh, 3), 4)),+ np.bitwise_or(np.bitwise_and(ql[:, 32:64], 0xF), np.left_shift(np.bitwise_and(np.right_shift(qh, 2), 3), 4)),+ np.bitwise_or(np.right_shift(ql[:, 0:32], 4), np.left_shift(np.bitwise_and(np.right_shift(qh, 4), 3), 4)),+ np.bitwise_or(np.right_shift(ql[:, 32:64], 4), np.left_shift(np.bitwise_and(np.right_shift(qh, 6), 3), 4)))+ for j in range(4):+ s16 = np.repeat(sc[:, n * 8 + 2 * j:n * 8 + 2 * j + 2], 16, axis=1) # l // 16 picks scale 2j or 2j + 1+ y[:, n * 128 + 32 * j:n * 128 + 32 * j + 32] = d[:, None] * s16 * (q[j] - 32)+ return y.astype(np.float16)++def quantize_q8_1_row(x: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:"""ggml quantize_q8_1: per-32 amax/127, round-half-away, returns (q, d, s)."""x = np.asarray(x, dtype=np.float32)diff --git a/exllamav3/foreign_quant/triton_f16gemv.py b/exllamav3/foreign_quant/triton_f16gemv.pynew file mode 100644index 0000000..2312cb4--- /dev/null+++ b/exllamav3/foreign_quant/triton_f16gemv.py@@ -0,0 +1,47 @@+"""Decode-row GEMV for fp16 weights stored (K, N) (LinearFP16 orientation), <= 16 rows, for ROCm where hipBLAS GEMV on small / skinny+shapes runs far under the read roof (Strix: 2880 x 512 at 47 GB/s, 4096 x 2880 at 153). One program = BN output columns, K walked in+BK chunks with coalesced (BK, BN) weight tiles; fp32 accumulation, fp16 out."""+from __future__ import annotations++import os++import torch+import triton+import triton.language as tl++MAX_ROWS = 16+# Strix sweep 11/11 (run_f16gemv.py, gpt-oss shapes, R1): BN 32 BK 64 nw 2: 2880x512 47 -> 138 GB/s, 4096x2880 153 -> 213 vs hipBLAS+BN = int(os.environ.get("EXL3_F16GEMV_BN", "32"))+BK = int(os.environ.get("EXL3_F16GEMV_BK", "64"))+NW = int(os.environ.get("EXL3_F16GEMV_NW", "2"))+++def _f16_gemv(x_ptr, w_ptr, y_ptr, R, K, N, BN: tl.constexpr, BK: tl.constexpr, RP: tl.constexpr):+ pid = tl.program_id(0)+ rn = pid * BN + tl.arange(0, BN)+ mn = rn < N+ rr = tl.arange(0, RP)+ mr = rr < R+ acc = tl.zeros((RP, BN), dtype=tl.float32)+ for k0 in range(0, K, BK):+ rk = k0 + tl.arange(0, BK)+ mk = rk < K+ w = tl.load(w_ptr + rk[:, None].to(tl.int64) * N + rn[None, :], mask=mk[:, None] & mn[None, :], other=0.0)+ xv = tl.load(x_ptr + rr[:, None] * K + rk[None, :], mask=mr[:, None] & mk[None, :], other=0.0)+ acc = tl.dot(xv, w, acc)+ tl.store(y_ptr + rr[:, None] * N + rn[None, :], acc.to(tl.float16), mask=mr[:, None] & mn[None, :])+++def supported(R: int, K: int, N: int) -> bool:+ # hipBLAS stays faster for wide outputs (2880 x 4096: 196 vs 167 GB/s): only N in [128, 3072]+ return 1 <= R <= MAX_ROWS and 128 <= N <= 3072 and os.environ.get("EXL3_F16GEMV", "1") != "0"+++def gemv(x: torch.Tensor, w: torch.Tensor, out: torch.Tensor | None = None) -> torch.Tensor:+ """x fp16 (R, K) contiguous, w fp16 (K, N) contiguous -> fp16 (R, N)."""+ R, K = x.shape+ N = w.shape[1]+ y = out if out is not None else torch.empty((R, N), dtype=torch.float16, device=x.device)+ _f16_gemv[(triton.cdiv(N, BN),)](x, w, y, R, K, N, BN=BN, BK=BK, RP=16, num_warps=NW)+ return ydiff --git a/exllamav3/foreign_quant/triton_gap.py b/exllamav3/foreign_quant/triton_gap.pyindex c99edb2..dbd005a 100644--- a/exllamav3/foreign_quant/triton_gap.py+++ b/exllamav3/foreign_quant/triton_gap.py@@ -10,11 +10,18 @@ import torchimport tritonimport triton.language as tl-FUSED = {"q4_0": 0, "iq4_nl": 1, "mxfp4": 2, "q5_0": 3}-_BB = {"q4_0": 18, "iq4_nl": 18, "mxfp4": 17, "q5_0": 22}+FUSED = {"q4_0": 0, "iq4_nl": 1, "mxfp4": 2, "q5_0": 3, "q5_1": 4}+_BB = {"q4_0": 18, "iq4_nl": 18, "mxfp4": 17, "q5_0": 22, "q5_1": 24}MAX_ROWS = 16+# 32-blocks per loop iteration (static unroll): Strix sweep 11/11 (gap_nb.py, 17408 x 5120) q4_0 NB 8 141 -> 181 GB/s, q5_0 NB 4 156 -> 192;+# iq4_nl / mxfp4 lose or gain < 5 %: 1. EXL3_GAP_NB forces one value for every format (A/B).+_NB = {"q4_0": 8, "q5_0": 4} if getattr(__import__("torch").version, "hip", None) else {}+GAP_NB = int(__import__("os").environ.get("EXL3_GAP_NB", "0"))# (BN, num_warps) per format, from a 3090 sweep at N=12288, K=4096, 4 rows-_CFG = {"q4_0": (32, 1), "q5_0": (32, 1), "mxfp4": (32, 1), "iq4_nl": (16, 1)}+_CFG = {"q4_0": (32, 1), "q5_0": (32, 1), "q5_1": (32, 1), "mxfp4": (32, 1), "iq4_nl": (16, 1)}+# Strix Halo (gfx1151) sweep 11/11 (gap_tiles.py, 17408 x 5120, R1 / R4): q4_0 117 -> 136-139 GB/s at (16, 1), q5_0 133 -> 152-156 at (64, 4)+if getattr(__import__("torch").version, "hip", None) and __import__("os").environ.get("EXL3_GAP_HIP_CFG", "1") != "0":+ _CFG.update({"q4_0": (16, 1), "q5_0": (64, 4), "iq4_nl": (64, 2)})@triton.jit@@ -37,7 +44,7 @@ def _fp4half(q):@triton.jit-def _gemv32(x_ptr, w_ptr, o_ptr, R, K, N, FMT: tl.constexpr, BB: tl.constexpr, BN: tl.constexpr, RP: tl.constexpr):+def _gemv32(x_ptr, w_ptr, o_ptr, R, K, N, FMT: tl.constexpr, BB: tl.constexpr, BN: tl.constexpr, RP: tl.constexpr, NB: tl.constexpr = 1):pid = tl.program_id(0)Kb = K // 32rn = pid * BN + tl.arange(0, BN)@@ -45,7 +52,9 @@ def _gemv32(x_ptr, w_ptr, o_ptr, R, K, N, FMT: tl.constexpr, BB: tl.constexpr, Bj = tl.arange(0, 16)acc = tl.zeros((RP, BN), dtype=tl.float32)row = rn.to(tl.int64) * (Kb * BB)- for kb in range(0, Kb):+ for kb0 in range(0, Kb, NB):+ for t in tl.static_range(NB):+ kb = kb0 + tbase = row + kb * BBif FMT == 2:e = tl.load(w_ptr + base).to(tl.float32)@@ -58,6 +67,8 @@ def _gemv32(x_ptr, w_ptr, o_ptr, R, K, N, FMT: tl.constexpr, BB: tl.constexpr, Bqoff = 2if FMT == 3:qoff = 6+ if FMT == 4:+ qoff = 8qs = tl.load(w_ptr + base[:, None] + qoff + j[None, :]).to(tl.int32)lo = qs & 15hi = qs >> 4@@ -70,13 +81,25 @@ def _gemv32(x_ptr, w_ptr, o_ptr, R, K, N, FMT: tl.constexpr, BB: tl.constexpr, Belif FMT == 2:wl = _fp4half(lo)wh = _fp4half(hi)- else:+ elif FMT == 3:qh = tl.load(w_ptr + base + 2).to(tl.int32) | (tl.load(w_ptr + base + 3).to(tl.int32) << 8) \| (tl.load(w_ptr + base + 4).to(tl.int32) << 16) | (tl.load(w_ptr + base + 5).to(tl.int32) << 24)wl = ((lo | (((qh[:, None] >> j[None, :]) & 1) << 4)) - 16).to(tl.float32)wh = ((hi | (((qh[:, None] >> (j[None, :] + 16)) & 1) << 4)) - 16).to(tl.float32)- wl = (wl * d[:, None]).to(tl.float16)- wh = (wh * d[:, None]).to(tl.float16)+ else: # FMT 4 = q5_1: [d][m][qh u32][qs], x = d * q + m+ qh = tl.load(w_ptr + base + 4).to(tl.int32) | (tl.load(w_ptr + base + 5).to(tl.int32) << 8) \+ | (tl.load(w_ptr + base + 6).to(tl.int32) << 16) | (tl.load(w_ptr + base + 7).to(tl.int32) << 24)+ wl = (lo | (((qh[:, None] >> j[None, :]) & 1) << 4)).to(tl.float32)+ wh = (hi | (((qh[:, None] >> (j[None, :] + 16)) & 1) << 4)).to(tl.float32)+ if FMT == 4:+ m0 = tl.load(w_ptr + base + 2).to(tl.int32)+ m1 = tl.load(w_ptr + base + 3).to(tl.int32)+ mm = (m0 | (m1 << 8)).to(tl.int16).to(tl.float16, bitcast=True).to(tl.float32)+ wl = (wl * d[:, None] + mm[:, None]).to(tl.float16)+ wh = (wh * d[:, None] + mm[:, None]).to(tl.float16)+ else:+ wl = (wl * d[:, None]).to(tl.float16)+ wh = (wh * d[:, None]).to(tl.float16)a_lo = tl.load(x_ptr + rr[:, None] * K + kb * 32 + j[None, :], mask=rr[:, None] < R, other=0.0)a_hi = tl.load(x_ptr + rr[:, None] * K + kb * 32 + 16 + j[None, :], mask=rr[:, None] < R, other=0.0)acc = tl.dot(a_lo, tl.trans(wl), acc)@@ -98,5 +121,7 @@ def gemv(fmt: str, x: torch.Tensor, raw: torch.Tensor, out: torch.Tensor | Noneif out is None:out = torch.empty((R, N), dtype=torch.float16, device=x.device)RP = 16- _gemv32[(N // BN,)](x, raw, out, R, K, N, FUSED[fmt], _BB[fmt], BN, RP, num_warps=num_warps)+ nb = GAP_NB or _NB.get(fmt, 1)+ nb = nb if (K // 32) % nb == 0 else 1+ _gemv32[(N // BN,)](x, raw, out, R, K, N, FUSED[fmt], _BB[fmt], BN, RP, nb, num_warps=num_warps)return outdiff --git a/exllamav3/foreign_quant/triton_iq.py b/exllamav3/foreign_quant/triton_iq.pynew file mode 100644index 0000000..0b048b9--- /dev/null+++ b/exllamav3/foreign_quant/triton_iq.py@@ -0,0 +1,161 @@+"""Fused decode GEMV (<= 16 rows) for the GGUF 256-element blocks IQ3_XXS, IQ3_S, IQ2_XS, IQ2_S and Q3_K, read in their native layout.++One program = BN output rows; the K loop walks 32-element units (8 per 256 block): each unit is decoded into a (BN, 32) fp16 tile+(grid / sign tables gathered from small device tables) and multiplied with tl.dot against up to 16 activation rows. Values equal+gap_formats.dequant (the torch reference) up to the fp32 accumulation order. Formats: FMT 0 iq3_xxs, 1 iq3_s, 2 iq2_xs, 3 iq2_s, 4 q3_k, 5 iq2_xxs (rows 2..16 only: the C++ GEMV serves 1 row).+"""+from __future__ import annotations++import os++import torch+import triton+import triton.language as tl++FUSED = {"iq3_xxs": 0, "iq3_s": 1, "iq2_xs": 2, "iq2_s": 3, "q3_k": 4, "iq2_xxs": 5, "q2_k": 6}+_BB = {"iq3_xxs": 98, "iq3_s": 110, "iq2_xs": 74, "iq2_s": 82, "q3_k": 110, "iq2_xxs": 66, "q2_k": 84}+MAX_ROWS = 16+BN = int(os.environ.get("EXL3_IQ_BN", "16"))+# Strix tile sweep 11/11 (iq_tiles.py): nw 1 iq2_s +8 %, iq3_s +13 % at R1; served UD-IQ2_M 15.4 -> 17.3 tok/s+NW = int(os.environ.get("EXL3_IQ_NW", "1"))+NB = int(os.environ.get("EXL3_IQ_NB", "0")) # 32-units per loop iteration (static unroll); 0 = per-format default below+# Strix sweep 11/11 (iq_tiles.py, R1): iq3_xxs NB 4 68 -> 92 GB/s, iq2_s NB 4 61 -> 69, iq3_s NB 2 114 -> 124+_NB = {"iq3_xxs": 4, "iq2_s": 4, "iq3_s": 2}+_TABS: dict = {}+++def _tabs(device):+ key = str(device)+ if key not in _TABS:+ from . import gap_formats as G+ from .gguf_tables import IQ3_XXS_GRID, IQ3_S_GRID, KSIGNS+ from .iq_grids_gen import iq2_grid+ u8 = lambda b: torch.frombuffer(bytearray(b), dtype=torch.uint8)+ _TABS[key] = (u8(IQ3_XXS_GRID).to(device), u8(IQ3_S_GRID).to(device), u8(KSIGNS).to(device),+ torch.from_numpy(iq2_grid("xs").copy()).reshape(-1).to(device),+ torch.from_numpy(iq2_grid("s").copy()).reshape(-1).to(device),+ torch.from_numpy(iq2_grid("xxs").copy()).reshape(-1).to(device))+ return _TABS[key]+++def _b(p, off, m):+ return tl.load(p + off, mask=m, other=0).to(tl.int32)+++def _gemv_iq(x_ptr, w_ptr, o_ptr, t3x, t3s, tks, t2x, t2s, t2xx, R, K, N, FMT: tl.constexpr, BB: tl.constexpr, BN: tl.constexpr,+ RP: tl.constexpr, NB: tl.constexpr = 1):+ pid = tl.program_id(0)+ rn = pid * BN + tl.arange(0, BN)+ mn = rn < N+ m2 = mn[:, None]+ rr = tl.arange(0, RP)+ e = tl.arange(0, 32)[None, :]+ acc = tl.zeros((RP, BN), dtype=tl.float32)+ row = rn.to(tl.int64) * ((K // 256) * BB)+ for u0 in range(0, K // 32, NB):+ for t_ in tl.static_range(NB):+ u = u0 + t_+ blk = row + (u // 8) * BB+ ib = u % 8+ b2 = blk[:, None]+ if FMT == 4:+ d = _h(tl.load(w_ptr + blk + 108, mask=mn, other=0), tl.load(w_ptr + blk + 109, mask=mn, other=0))+ elif FMT == 6:+ d = _h(tl.load(w_ptr + blk + 80, mask=mn, other=0), tl.load(w_ptr + blk + 81, mask=mn, other=0))+ else:+ d = _h(tl.load(w_ptr + blk, mask=mn, other=0), tl.load(w_ptr + blk + 1, mask=mn, other=0))+ d2 = d[:, None]+ if FMT == 0: # iq3_xxs: qs[64] grid idx (4 values each), then 8 x uint32 (4 x 7-bit sign idx | 4-bit scale << 28)+ idx = _b(w_ptr, b2 + 2 + 8 * ib + e // 4, m2)+ g = tl.load(t3x + idx * 4 + e % 4).to(tl.float32)+ aw = blk + 66 + 4 * ib+ aux = _b(w_ptr, aw, mn) | (_b(w_ptr, aw + 1, mn) << 8) | (_b(w_ptr, aw + 2, mn) << 16) | (_b(w_ptr, aw + 3, mn) << 24)+ db = d * (0.5 + ((aux >> 28) & 15).to(tl.float32)) * 0.5+ sidx = (aux[:, None] >> (7 * (e // 8))) & 127+ sg = (tl.load(tks + sidx).to(tl.int32) >> (e % 8)) & 1+ w = db[:, None] * g * (1.0 - 2.0 * sg.to(tl.float32))+ elif FMT == 1: # iq3_s: qs[64] @2, qh[8] @66, signs[32] @74, scales[4] @106+ l = e // 4+ idx = _b(w_ptr, b2 + 2 + 8 * ib + l, m2) | (((_b(w_ptr, blk + 66 + ib, mn)[:, None] >> l) & 1) << 8)+ g = tl.load(t3s + idx * 4 + e % 4).to(tl.float32)+ sc = (_b(w_ptr, blk + 106 + ib // 2, mn) >> (4 * (ib % 2))) & 15+ db = d * (1.0 + 2.0 * sc.to(tl.float32))+ sg = (_b(w_ptr, b2 + 74 + 4 * ib + e // 8, m2) >> (e % 8)) & 1+ w = db[:, None] * g * (1.0 - 2.0 * sg.to(tl.float32))+ elif FMT == 2: # iq2_xs: 32 x uint16 (9-bit grid idx | 7-bit sign idx) @2, scales[8] @66+ l = e // 8+ qo = b2 + 2 + 2 * (4 * ib + l)+ q = _b(w_ptr, qo, m2) | (_b(w_ptr, qo + 1, m2) << 8)+ g = tl.load(t2x + (q & 511) * 8 + e % 8).to(tl.float32)+ sg = (tl.load(tks + (q >> 9)).to(tl.int32) >> (e % 8)) & 1+ sc = (_b(w_ptr, blk + 66 + ib, mn)[:, None] >> (4 * (l // 2))) & 15+ w = d2 * (0.5 + sc.to(tl.float32)) * 0.25 * g * (1.0 - 2.0 * sg.to(tl.float32))+ elif FMT == 3: # iq2_s: grid low bytes[32] @2, signs[32] @34, qh[8] @66, scales[8] @74+ l = e // 8+ idx = _b(w_ptr, b2 + 2 + 4 * ib + l, m2) | ((_b(w_ptr, blk + 66 + ib, mn)[:, None] << (8 - 2 * l)) & 0x300)+ g = tl.load(t2s + idx * 8 + e % 8).to(tl.float32)+ sg = (_b(w_ptr, b2 + 34 + 4 * ib + l, m2) >> (e % 8)) & 1+ sc = (_b(w_ptr, blk + 74 + ib, mn)[:, None] >> (4 * (l // 2))) & 15+ w = d2 * (0.5 + sc.to(tl.float32)) * 0.25 * g * (1.0 - 2.0 * sg.to(tl.float32))+ elif FMT == 5: # iq2_xxs: per 32-unit 8 bytes @2 + 8 ib: 4 x 8-bit grid idx, then uint32 (4 x 7-bit sign idx | 4-bit scale << 28)+ l = e // 8+ idx = _b(w_ptr, b2 + 2 + 8 * ib + l, m2)+ g = tl.load(t2xx + idx * 8 + e % 8).to(tl.float32)+ aw = blk + 6 + 8 * ib+ aux = _b(w_ptr, aw, mn) | (_b(w_ptr, aw + 1, mn) << 8) | (_b(w_ptr, aw + 2, mn) << 16) | (_b(w_ptr, aw + 3, mn) << 24)+ db = d * (0.5 + ((aux >> 28) & 15).to(tl.float32)) * 0.25+ sidx = (aux[:, None] >> (7 * l)) & 127+ sg = (tl.load(tks + sidx).to(tl.int32) >> (e % 8)) & 1+ w = db[:, None] * g * (1.0 - 2.0 * sg.to(tl.float32))+ elif FMT == 6: # q2_k: scales[16] @0, qs[64] @16, d @80, dmin @82; unit ib = 32 * (4 * n + j)+ n2 = ib // 4+ j = ib % 4+ q = (_b(w_ptr, b2 + 16 + 32 * n2 + e, m2) >> (2 * j)) & 3+ sc = _b(w_ptr, b2 + 8 * n2 + 2 * j + e // 16, m2)+ dm = _h(tl.load(w_ptr + blk + 82, mask=mn, other=0), tl.load(w_ptr + blk + 83, mask=mn, other=0))+ w = d2 * (sc & 15).to(tl.float32) * q.to(tl.float32) - dm[:, None] * (sc >> 4).to(tl.float32)+ else: # q3_k: hmask[32] @0, qs[64] @32, scales[12] @96, d @108; unit ib = 32 * (4 * hh + j)+ hh = ib // 4+ j = ib % 4+ half = e // 16+ q = (_b(w_ptr, b2 + 32 + 32 * hh + e, m2) >> (2 * j)) & 3+ hm = (_b(w_ptr, b2 + e, m2) >> (4 * hh + j)) & 1+ v = q - 4 * (1 - hm)+ i = 8 * hh + 2 * j + half # scale index 0..15, (1, 32)+ bq = i % 4+ gq = i // 4+ lo = (_b(w_ptr, b2 + 96 + bq + 4 * (gq % 2), m2) >> (4 * (gq // 2))) & 15+ hi = (_b(w_ptr, b2 + 104 + bq, m2) >> (2 * gq)) & 3+ sc = (lo | (hi << 4)) - 32+ w = d2 * sc.to(tl.float32) * v.to(tl.float32)+ wt = w.to(tl.float16)+ xv = tl.load(x_ptr + rr[:, None] * K + u * 32 + e, mask=rr[:, None] < R, other=0.0)+ acc = tl.dot(xv, tl.trans(wt), acc)+ tl.store(o_ptr + rr[:, None] * N + rn[None, :], acc.to(tl.float16), mask=(rr[:, None] < R) & mn[None, :])+++def _h(lo, hi):+ return (lo.to(tl.int16) | (hi.to(tl.int16) << 8)).to(tl.float16, bitcast=True).to(tl.float32)+++def supported(fmt: str, rows: int, k: int, n: int) -> bool:+ # iq2_xxs: every width comes here. The C++ fq_gemv_iq2_xxs returns wrong rows on real GGUF blocks (rel 1.5 vs its own dequant,+ # Qwen3-8B-UD-IQ2_XXS up_proj) and its header scratch covers K <= 8192 only.+ lo = 1+ return fmt in FUSED and lo <= rows <= MAX_ROWS and k % 256 == 0 and os.environ.get("EXL3_IQ_FUSED", "1") != "0"+++def gemv(fmt: str, x: torch.Tensor, raw: torch.Tensor) -> torch.Tensor:+ """x fp16 [R, K] contiguous, raw uint8 [N, K/256*bb] -> fp16 [R, N]."""+ R, K = x.shape+ N = raw.shape[0]+ assert R <= MAX_ROWS and K % 256 == 0 and raw.shape[1] == K // 256 * _BB[fmt]+ out = torch.empty((R, N), dtype=torch.float16, device=x.device)+ t3x, t3s, tks, t2x, t2s, t2xx = _tabs(x.device)+ nb = NB or _NB.get(fmt, 1)+ nb = nb if (K // 32) % nb == 0 else 1+ _gemv_iq[(triton.cdiv(N, BN),)](x, raw, out, t3x, t3s, tks, t2x, t2s, t2xx, R, K, N, FUSED[fmt], _BB[fmt], BN, 16, nb, num_warps=NW)+ return outdiff --git a/exllamav3/foreign_quant/triton_moe_mxfp4.py b/exllamav3/foreign_quant/triton_moe_mxfp4.pynew file mode 100644index 0000000..e0d5f9f--- /dev/null+++ b/exllamav3/foreign_quant/triton_moe_mxfp4.py@@ -0,0 +1,55 @@+"""Grouped decode GEMV over routed MXFP4 experts (GGUF block_mxfp4 layout: per 32-block [E8M0][16 bytes, elements j | j + 16 << 4]).++Program (tile, slot) computes y[slot, tile] = x[slot // XDIV] . W[sel[slot]]^T + b[sel[slot]], the expert's bytes and bias found+through int64 pointer tables (data_ptr of each expert's packed rows / fp16 bias). One launch per projection for all (row, expert) slots,+instead of one GEMV launch per expert. Same decode as triton_gap._gemv32 FMT 2 (fp4 value x2, scale 2^(e - 128)).+"""+from __future__ import annotations++import os++import torch+import triton+import triton.language as tl++from .triton_gap import _fp4half++# Strix sweep 11/11: BN 16 101 -> BN 32 115 GB/s, served gpt-oss 24.4 -> 25.7 tok/s+BN = int(os.environ.get("EXL3_MXFP4_MOE_BN", "32"))+NW = int(os.environ.get("EXL3_MXFP4_MOE_NW", "2"))+++def _mxfp4_moe(x_ptr, wtab, btab, sel_ptr, y_ptr, K, N, XDIV, HAS_B: tl.constexpr, BN: tl.constexpr):+ pid = tl.program_id(0)+ slot = tl.program_id(1)+ e = tl.load(sel_ptr + slot).to(tl.int64)+ w_ptr = tl.load(wtab + e).to(tl.pointer_type(tl.uint8))+ xr = x_ptr + (slot // XDIV).to(tl.int64) * K+ Kb = K // 32+ rn = pid * BN + tl.arange(0, BN)+ mn = rn < N+ j = tl.arange(0, 16)+ row = rn.to(tl.int64) * (Kb * 17)+ acc = tl.zeros((BN,), dtype=tl.float32)+ for kb in range(0, Kb):+ base = row + kb * 17+ d = tl.exp2(tl.load(w_ptr + base, mask=mn, other=0).to(tl.float32) - 128.0)+ qs = tl.load(w_ptr + base[:, None] + 1 + j[None, :], mask=mn[:, None], other=0).to(tl.int32)+ xl = tl.load(xr + kb * 32 + j).to(tl.float32)+ xh = tl.load(xr + kb * 32 + 16 + j).to(tl.float32)+ part = tl.sum(_fp4half(qs & 15) * xl[None, :] + _fp4half(qs >> 4) * xh[None, :], axis=1)+ acc += part * d+ if HAS_B:+ b_ptr = tl.load(btab + e).to(tl.pointer_type(tl.float16))+ acc += tl.load(b_ptr + rn, mask=mn, other=0.0).to(tl.float32)+ tl.store(y_ptr + slot.to(tl.int64) * N + rn, acc, mask=mn)+++def moe_gemv(x: torch.Tensor, wtab: torch.Tensor, btab: torch.Tensor | None, sel: torch.Tensor, N: int, K: int, xdiv: int) -> torch.Tensor:+ """x (rows, K) fp16 contiguous; sel (slots,) int32 expert ids; returns (slots, N) fp32."""+ slots = sel.numel()+ y = torch.empty((slots, N), dtype=torch.float32, device=x.device)+ _mxfp4_moe[(triton.cdiv(N, BN), slots)](x, wtab, btab if btab is not None else wtab, sel, y, K, N, xdiv,+ HAS_B=btab is not None, BN=BN, num_warps=NW)+ return ydiff --git a/exllamav3/foreign_quant/triton_rows.py b/exllamav3/foreign_quant/triton_rows.pynew file mode 100644index 0000000..632cce3--- /dev/null+++ b/exllamav3/foreign_quant/triton_rows.py@@ -0,0 +1,205 @@+"""Multi-row decode GEMV (2..16 rows: verify / multi-user) for Q8_0 and NVFP4 read once for all rows (tl.dot over 16 padded rows).+The C++ fq_gemv kernels re-read the weights for every row (Strix 17408 x 5120: R4 ~50 GB/s, R8 ~25 vs ~200 at R1); R1 stays on them.+Values match gap dequant + matmul up to the fp32 accumulation order. BOLT_FQ_ROWS_TRITON=0 disables."""+from __future__ import annotations++import torch+import triton+import triton.language as tl++FORMATS = ("q8_0", "nvfp4", "q4_k", "q6_k", "q5_k", "iq4_xs")+MAX_ROWS = 16+BN, BK = 32, 64+++def _e4m3(b):+ return ((((b & 0x80) << 8) | ((b & 0x7F) << 7)).to(tl.float16, bitcast=True) * 256.0).to(tl.float32)+++def _e2m1(n):+ # E2M1 nibble -> value by bit placement in fp16: sign | exp(2) | mant(1) -> fp16 bits s eeeee m.. with bias fix (x 2^14),+ # subnormal 0b0001 (0.5) handled by the same placement (fp16 subnormal 2^-15 * 2^14 = 0.5)+ h = (((n & 8) << 12) | ((n & 7) << 9)).to(tl.int16).to(tl.float16, bitcast=True).to(tl.float32)+ return h * 16384.0+++def _rows_q8_0(x_ptr, p_ptr, y_ptr, R, K, N, BN: tl.constexpr, BK: tl.constexpr, RP: tl.constexpr):+ pid = tl.program_id(0)+ rn = pid * BN + tl.arange(0, BN)+ mn = rn < N+ rr = tl.arange(0, RP)+ mr = rr < R+ rowb = rn.to(tl.int64) * ((K // 32) * 34)+ acc = tl.zeros((RP, BN), dtype=tl.float32)+ for k0 in range(0, K, BK):+ rk = k0 + tl.arange(0, BK)+ off = (rk // 32) * 34+ q = tl.load(p_ptr + rowb[:, None] + off[None, :] + 2 + (rk % 32)[None, :], mask=mn[:, None], other=0).to(tl.int8).to(tl.float32)+ lo = tl.load(p_ptr + rowb[:, None] + off[None, :], mask=mn[:, None], other=0).to(tl.int16)+ hi = tl.load(p_ptr + rowb[:, None] + off[None, :] + 1, mask=mn[:, None], other=0).to(tl.int16)+ d = (lo | (hi << 8)).to(tl.float16, bitcast=True).to(tl.float32)+ w = (q * d).to(tl.float16)+ xv = tl.load(x_ptr + rr[:, None] * K + rk[None, :], mask=mr[:, None], other=0.0)+ acc += tl.dot(xv, tl.trans(w), out_dtype=tl.float32)+ tl.store(y_ptr + rr[:, None] * N + rn[None, :], acc, mask=mr[:, None] & mn[None, :])+++def _rows_nvfp4(x_ptr, p_ptr, s_ptr, y_ptr, R, K, N, G, BN: tl.constexpr, BK: tl.constexpr, RP: tl.constexpr):+ pid = tl.program_id(0)+ rn = pid * BN + tl.arange(0, BN)+ mn = rn < N+ rr = tl.arange(0, RP)+ mr = rr < R+ acc = tl.zeros((RP, BN), dtype=tl.float32)+ for k0 in range(0, K, BK):+ rk = k0 + tl.arange(0, BK)+ rb = k0 // 2 + tl.arange(0, BK // 2)+ byte = tl.load(p_ptr + rn[:, None].to(tl.int64) * (K // 2) + rb[None, :], mask=mn[:, None], other=0).to(tl.int32)+ v = tl.reshape(tl.join(_e2m1(byte & 15), _e2m1(byte >> 4)), (BN, BK)) # each byte once: low nibble = even k+ rs = k0 // 16 + tl.arange(0, BK // 16)+ sc = _e4m3(tl.load(s_ptr + rn[:, None].to(tl.int64) * (K // 16) + rs[None, :], mask=mn[:, None], other=0).to(tl.int16))+ w = tl.reshape(tl.reshape(v, (BN, BK // 16, 16)) * sc[:, :, None], (BN, BK)).to(tl.float16)+ xv = tl.load(x_ptr + rr[:, None] * K + rk[None, :], mask=mr[:, None], other=0.0)+ acc += tl.dot(xv, tl.trans(w), out_dtype=tl.float32)+ tl.store(y_ptr + rr[:, None] * N + rn[None, :], acc * G, mask=mr[:, None] & mn[None, :])+++def _h16(lo, hi):+ return (lo.to(tl.int16) | (hi.to(tl.int16) << 8)).to(tl.float16, bitcast=True).to(tl.float32)+++def _rows_q4_k(x_ptr, p_ptr, y_ptr, R, K, N, BN: tl.constexpr, RP: tl.constexpr, Q5: tl.constexpr = False):+ """Q4_K super-block 144 B / 256: d, dmin (fp16), 12 B of 6-bit scales / mins, 128 B of nibbles (64-chunk i: low = sub 2i, high = sub 2i+1)."""+ pid = tl.program_id(0)+ rn = pid * BN + tl.arange(0, BN)+ mn = rn < N+ rr = tl.arange(0, RP)+ mr = rr < R+ l = tl.arange(0, 32)+ BB: tl.constexpr = 176 if Q5 else 144+ QS: tl.constexpr = 48 if Q5 else 16+ row = p_ptr + rn.to(tl.int64) * ((K // 256) * BB)+ acc = tl.zeros((RP, BN), dtype=tl.float32)+ for k0 in range(0, K, 64):+ b = row + (k0 // 256) * BB+ i = (k0 % 256) // 64+ d = _h16(tl.load(b, mask=mn, other=0), tl.load(b + 1, mask=mn, other=0))+ dm = _h16(tl.load(b + 2, mask=mn, other=0), tl.load(b + 3, mask=mn, other=0))+ sb = b + 4+ out = []+ for h in tl.static_range(2):+ j = 2 * i + h+ if j < 4:+ sc = tl.load(sb + j, mask=mn, other=0).to(tl.int32) & 63+ m = tl.load(sb + j + 4, mask=mn, other=0).to(tl.int32) & 63+ else:+ a = tl.load(sb + j + 4, mask=mn, other=0).to(tl.int32)+ sc = (a & 15) | ((tl.load(sb + j - 4, mask=mn, other=0).to(tl.int32) >> 6) << 4)+ m = (a >> 4) | ((tl.load(sb + j, mask=mn, other=0).to(tl.int32) >> 6) << 4)+ q = tl.load(b[:, None] + QS + 32 * i + l[None, :], mask=mn[:, None], other=0).to(tl.int32)+ q = (q >> (4 * h)) & 15+ if Q5:+ qh = tl.load(b[:, None] + 16 + l[None, :], mask=mn[:, None], other=0).to(tl.int32)+ q = q | (((qh >> (2 * i + h)) & 1) << 4)+ w = (q.to(tl.float32) * (d * sc.to(tl.float32))[:, None] - (dm * m.to(tl.float32))[:, None]).to(tl.float16)+ xv = tl.load(x_ptr + rr[:, None] * K + (k0 + 32 * h + l)[None, :], mask=mr[:, None], other=0.0)+ acc += tl.dot(xv, tl.trans(w), out_dtype=tl.float32)+ tl.store(y_ptr + rr[:, None] * N + rn[None, :], acc, mask=mr[:, None] & mn[None, :])+++def _rows_q6_k(x_ptr, p_ptr, y_ptr, R, K, N, BN: tl.constexpr, RP: tl.constexpr):+ """Q6_K super-block 210 B / 256: ql[128], qh[64], int8 scales[16] (one per 16), d fp16 at 208. Half n of 128: 4 groups of 32."""+ pid = tl.program_id(0)+ rn = pid * BN + tl.arange(0, BN)+ mn = rn < N+ rr = tl.arange(0, RP)+ mr = rr < R+ l = tl.arange(0, 32)+ row = p_ptr + rn.to(tl.int64) * ((K // 256) * 210)+ acc = tl.zeros((RP, BN), dtype=tl.float32)+ for k0 in range(0, K, 128):+ b = row + (k0 // 256) * 210+ n = (k0 % 256) // 128+ d = _h16(tl.load(b + 208, mask=mn, other=0), tl.load(b + 209, mask=mn, other=0))+ m2 = mn[:, None]+ ql0 = tl.load(b[:, None] + 64 * n + l[None, :], mask=m2, other=0).to(tl.int32)+ ql1 = tl.load(b[:, None] + 64 * n + 32 + l[None, :], mask=m2, other=0).to(tl.int32)+ qh = tl.load(b[:, None] + 128 + 32 * n + l[None, :], mask=m2, other=0).to(tl.int32)+ for g in tl.static_range(4):+ src = ql0 if g % 2 == 0 else ql1+ q = (((src >> (4 * (g // 2))) & 15) | (((qh >> (2 * g)) & 3) << 4)) - 32+ sc = tl.load(b[:, None] + 192 + 8 * n + 2 * g + (l // 16)[None, :], mask=m2, other=0).to(tl.int8).to(tl.float32)+ w = (q.to(tl.float32) * sc * d[:, None]).to(tl.float16)+ xv = tl.load(x_ptr + rr[:, None] * K + (k0 + 32 * g + l)[None, :], mask=mr[:, None], other=0.0)+ acc += tl.dot(xv, tl.trans(w), out_dtype=tl.float32)+ tl.store(y_ptr + rr[:, None] * N + rn[None, :], acc, mask=mr[:, None] & mn[None, :])+++def _rows_iq4_xs(x_ptr, p_ptr, kv_ptr, y_ptr, R, K, N, BN: tl.constexpr, RP: tl.constexpr):+ """IQ4_XS super-block 136 B / 256: d fp16, scales_h u16, scales_l[4], qs[128] (sub-block ib: 16 B, low nibbles = first 16, high = next 16)."""+ pid = tl.program_id(0)+ rn = pid * BN + tl.arange(0, BN)+ mn = rn < N+ rr = tl.arange(0, RP)+ mr = rr < R+ l = tl.arange(0, 16)+ row = p_ptr + rn.to(tl.int64) * ((K // 256) * 136)+ acc = tl.zeros((RP, BN), dtype=tl.float32)+ for k0 in range(0, K, 32):+ b = row + (k0 // 256) * 136+ ib = (k0 % 256) // 32+ d = _h16(tl.load(b, mask=mn, other=0), tl.load(b + 1, mask=mn, other=0))+ sh = tl.load(b + 2, mask=mn, other=0).to(tl.int32) | (tl.load(b + 3, mask=mn, other=0).to(tl.int32) << 8)+ sl = tl.load(b + 4 + ib // 2, mask=mn, other=0).to(tl.int32)+ ls = ((sl >> (4 * (ib % 2))) & 15) | (((sh >> (2 * ib)) & 3) << 4)+ dl = d * (ls - 32).to(tl.float32)+ q = tl.load(b[:, None] + 8 + 16 * ib + l[None, :], mask=mn[:, None], other=0).to(tl.int32)+ for h in tl.static_range(2):+ v = tl.load(kv_ptr + ((q >> (4 * h)) & 15))+ w = (v * dl[:, None]).to(tl.float16)+ xv = tl.load(x_ptr + rr[:, None] * K + (k0 + 16 * h + l)[None, :], mask=mr[:, None], other=0.0)+ acc += tl.dot(xv, tl.trans(w), out_dtype=tl.float32)+ tl.store(y_ptr + rr[:, None] * N + rn[None, :], acc, mask=mr[:, None] & mn[None, :])+++_KV = {}+++def _kvalues(dev):+ t = _KV.get(dev)+ if t is None:+ t = _KV[dev] = torch.tensor([-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113], dtype=torch.float32, device=dev)+ return t+++def supported(fmt: str, R: int, K: int) -> bool:+ return fmt in FORMATS and 2 <= R <= MAX_ROWS and K % (256 if fmt.endswith("_k") or fmt == "iq4_xs" else BK) == 0+++def gemv(fmt: str, x: torch.Tensor, packed: torch.Tensor, scales=None, global_scale: float = 1.0) -> torch.Tensor:+ """x half [R, K] contiguous -> float32 [R, N]."""+ R, K = x.shape+ N = packed.shape[0]+ y = torch.empty((R, N), dtype=torch.float32, device=x.device)+ grid = (triton.cdiv(N, BN),)+ if fmt == "q8_0":+ _rows_q8_0[grid](x, packed, y, R, K, N, BN=BN, BK=BK, RP=16, num_warps=4)+ elif fmt == "q4_k":+ _rows_q4_k[grid](x, packed, y, R, K, N, BN=BN, RP=16, num_warps=4)+ elif fmt == "q5_k":+ _rows_q4_k[grid](x, packed, y, R, K, N, BN=BN, RP=16, Q5=True, num_warps=4)+ elif fmt == "iq4_xs":+ _rows_iq4_xs[grid](x, packed, _kvalues(x.device), y, R, K, N, BN=BN, RP=16, num_warps=4)+ elif fmt == "q6_k":+ _rows_q6_k[grid](x, packed, y, R, K, N, BN=BN, RP=16, num_warps=4)+ else:+ _rows_nvfp4[grid](x, packed, scales, y, R, K, N, float(global_scale), BN=BN, BK=BK, RP=16, num_warps=4)+ return ydiff --git a/exllamav3/foreign_quant/triton_shgate.py b/exllamav3/foreign_quant/triton_shgate.pynew file mode 100644index 0000000..eab83be--- /dev/null+++ b/exllamav3/foreign_quant/triton_shgate.py@@ -0,0 +1,28 @@+"""Shared-expert gate tail for MoE decode: out[r, k] = routed[r, k] + float(se[r, k]) * sigmoid(sum_j x[r, j] * w[j]), fp32,+one program per row (decode rows 1..16). Replaces cast + mul + sum + sigmoid + mul + add (6 launches). Written in place into routed."""+import torch+import triton+import triton.language as tl+++def _shgate_tail(x_ptr, w_ptr, se_ptr, out_ptr, K, BK: tl.constexpr):+ r = tl.program_id(0)+ acc = tl.zeros((BK,), dtype=tl.float32)+ for k0 in range(0, K, BK):+ o = k0 + tl.arange(0, BK)+ m = o < K+ acc += tl.load(x_ptr + r * K + o, mask=m, other=0.0).to(tl.float32) * tl.load(w_ptr + o, mask=m, other=0.0)+ g = tl.sigmoid(tl.sum(acc, axis=0))+ for k0 in range(0, K, BK):+ o = k0 + tl.arange(0, BK)+ m = o < K+ y = tl.load(out_ptr + r * K + o, mask=m, other=0.0) + tl.load(se_ptr + r * K + o, mask=m, other=0.0).to(tl.float32) * g+ tl.store(out_ptr + r * K + o, y, mask=m)+++def shgate_tail_(routed: torch.Tensor, se: torch.Tensor, x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:+ """routed (R, K) fp32 contiguous, updated in place and returned; se (R, K) half; x (R, K) half; w (K,) fp32."""+ R, K = routed.shape+ _shgate_tail[(R,)](x, w, se, routed, K, BK=1024)+ return routeddiff --git a/exllamav3/loader/gguf_collection.py b/exllamav3/loader/gguf_collection.pyindex a785e57..847e674 100644--- a/exllamav3/loader/gguf_collection.py+++ b/exllamav3/loader/gguf_collection.py@@ -15,6 +15,7 @@ get_tensor_sizes. Anything else raises.from __future__ import annotationsimport os+import reimport structimport numpy as np@@ -28,8 +29,8 @@ GGML_BBS = {}# (elements, bytes) per block of the formats served by gap_formats / fq_gemv_q8_0 (32- and 64-element blocks)GGML_BLK = {t: (256, bb) for t, bb in GGML_BBS.items()}-GGML_BLK.update({2: (32, 18), 6: (32, 22), 8: (32, 34), 20: (32, 18), 18: (256, 98), 21: (256, 110),- 39: (32, 17), 40: (64, 36)})+GGML_BLK.update({2: (32, 18), 6: (32, 22), 7: (32, 24), 8: (32, 34), 20: (32, 18), 18: (256, 98), 21: (256, 110),+ 39: (32, 17), 40: (64, 36), 11: (256, 110), 17: (256, 74), 22: (256, 82), 10: (256, 84), 16: (256, 66)})GGML_QUANT = set(GGML_BLK.keys())_META_SZ = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}@@ -60,8 +61,35 @@ class GGUFCollection:def __init__(self, path: str):self.path = path- self.fd = os.open(path, os.O_RDONLY)- with open(path, "rb") as f:+ # split packs: "<name>-00001-of-0000N.gguf" -> every file; tensor offsets carry the file index in bits 48++ real = os.path.realpath(path)+ m = re.search(r"-(\d{5})-of-(\d{5})\.gguf$", real)+ paths = [real] if m is None else [real[:m.start()] + f"-{i:05d}-of-{m.group(2)}.gguf" for i in range(1, int(m.group(2)) + 1)]+ self.fds, self.bases, self.meta, self.infos = [], [], {}, {}+ self.paths = paths+ for i, p in enumerate(paths):+ meta, infos, base = self._read_header(p)+ for k, v in meta.items():+ self.meta.setdefault(k, v)+ for name, (ty, dims, off) in infos.items():+ self.infos[name] = (ty, dims, off | (i << 48))+ self.fds.append(os.open(p, os.O_RDONLY))+ self.bases.append(base)+ self.fd, self.base = self.fds[0], self.bases[0]+ # SafetensorsCollection attrs poked by Config/model_init paths+ self.directory = os.path.dirname(self.path)+ self.tensor_file_map = {k: self.path for k in self.infos}+ self.file_headers = {}+ # Engine-key -> gguf-name translation (set by the arch config).+ # Values are gguf names, or (gguf name, "T") when the engine wants+ # the transpose of the stored orientation (e.g. the GDN conv).+ 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++ @staticmethod+ def _read_header(p: str):+ with open(p, "rb") as f:assert f.read(4) == b"GGUF"f.read(4)nt = struct.unpack("<Q", f.read(8))[0]@@ -87,29 +115,20 @@ class GGUFCollection:raise ValueError(f"gguf metadata type {t}")# Metadata kept (config + tokenizer are derived from it, see loader/gguf_config.py)- self.meta = {}+ meta = {}for _ in range(nm):k = rs()- self.meta[k] = sv()- self.infos = {}+ meta[k] = sv()+ infos = {}for _ in range(nt):name = rs()nd = struct.unpack("<I", f.read(4))[0]dims = [struct.unpack("<Q", f.read(8))[0] for _ in range(nd)]ty = struct.unpack("<I", f.read(4))[0]off = struct.unpack("<Q", f.read(8))[0]- self.infos[name] = (ty, tuple(dims), off)- self.base = (f.tell() + 31) // 32 * 32- # SafetensorsCollection attrs poked by Config/model_init paths- self.directory = os.path.dirname(path)- self.tensor_file_map = {k: path for k in self.infos}- self.file_headers = {}- # Engine-key -> gguf-name translation (set by the arch config).- # Values are gguf names, or (gguf name, "T") when the engine wants- # the transpose of the stored orientation (e.g. the GDN conv).- 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+ infos[name] = (ty, tuple(dims), off)+ base = (f.tell() + 31) // 32 * 32+ return meta, infos, basedef _resolve(self, key: str) -> str:mapped = self.name_map.get(key, key)@@ -136,10 +155,11 @@ class GGUFCollection:return Nonedef close(self):- try:- os.close(self.fd)- except OSError:- pass+ for fd in getattr(self, "fds", [self.fd]):+ try:+ os.close(fd)+ except OSError:+ passdef has_tensor_group(self, key, subkeys) -> bool:if isinstance(key, list):@@ -159,11 +179,13 @@ class GGUFCollection:return info[1]def _pread(self, off: int, n: int) -> np.ndarray:+ fi, off = off >> 48, off & ((1 << 48) - 1)+ fd, base = self.fds[fi], self.bases[fi]buf = bytearray(n)mv = memoryview(buf)got = 0while got < n:- r = os.pread(self.fd, n - got, self.base + off + got)+ r = os.pread(fd, n - got, base + off + got)if not r:raise IOError(f"short read at {off + got}")mv[got:got + len(r)] = r@@ -226,12 +248,15 @@ class GGUFCollection:if transpose:raise ValueError("transpose not supported for quant payloads")return t.to(dev)- if ty in (0, 1): # F32 / F16+ if ty in (0, 1, 30): # F32 / F16 / BF16 (BF16 widened to float32: bit shift, exact)dt = np.float32 if ty == 0 else np.float16es = 4 if ty == 0 else 2n = int(np.prod(dims))raw = self._pread(off, n * es)- a = np.frombuffer(raw, dtype=dt)+ if ty == 30:+ a = (np.frombuffer(raw, dtype=np.uint16).astype(np.uint32) << 16).view(np.float32)+ else:+ a = np.frombuffer(raw, dtype=dt)# GGUF dims are ggml order (ne[0] = row length, fastest): the TRUE# matrix orientation is [dims[1], dims[0}] (dims[1] rows of dims[0]).# (A scrambled (dims[0], dims[1]) view silently corrupts every 2-Ddiff --git a/exllamav3/loader/gguf_config.py b/exllamav3/loader/gguf_config.pyindex 7b8a2d9..3a04824 100644--- a/exllamav3/loader/gguf_config.py+++ b/exllamav3/loader/gguf_config.py@@ -16,12 +16,16 @@ GGUF_ARCHS = {# 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 formatGGML_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",+ 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",}@@ -31,8 +35,10 @@ 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)+ 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 = {@@ -57,8 +63,9 @@ def hf_config(g: GGUFCollection) -> dict:return cfg-def _hf_config_qwen35moe(g: GGUFCollection, m: dict) -> dict:- p = "qwen35moe."+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",@@ -74,10 +81,11 @@ def _hf_config_qwen35moe(g: GGUFCollection, m: dict) -> dict:"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"],+ **({"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"],@@ -85,7 +93,109 @@ def _hf_config_qwen35moe(g: GGUFCollection, m: dict) -> dict:"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}+ "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 nmdef name_map(cfg: dict) -> dict:@@ -119,6 +229,10 @@ def write_config_dir(gguf_path: str, outdir: str) -> str: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:diff --git a/exllamav3/model/model_ls.py b/exllamav3/model/model_ls.pyindex d3b222c..ac3edae 100644--- a/exllamav3/model/model_ls.py+++ b/exllamav3/model/model_ls.py@@ -290,6 +290,9 @@ class Model_LSMixin(ABC):f"margin (EXL3_AUTOSPLIT_MARGIN_MB)")+ if os.environ.get("EXL3_LOAD_DIAG") and load_device.type == "cuda":+ print(f"[loaddiag] {idx:3d} {module.key:48s} alloc {torch.cuda.memory_allocated(load_device)/2**30:7.3f}G "+ f"reserved {torch.cuda.memory_reserved(load_device)/2**30:7.3f}G peak {torch.cuda.max_memory_allocated(load_device)/2**30:7.3f}G", flush=True)# Account for max_output_factor after last layerextra_dummy_out_states = Noneif is_logits_layer:@@ -317,6 +320,20 @@ class Model_LSMixin(ABC):"HIP out of memory" in str(e):# Exception object will hold references to tensors so we can't free them herefail = True+ if os.environ.get("EXL3_LOAD_DIAG"):+ import gc, collections+ agg = collections.defaultdict(lambda: [0, 0]); seen = set()+ for o in gc.get_objects():+ try:+ if isinstance(o, torch.Tensor) and o.is_cuda:+ ptr = o.untyped_storage().data_ptr()+ if ptr in seen: continue+ seen.add(ptr)+ a = agg[(str(o.dtype), tuple(o.shape))]; a[0] += 1; a[1] += o.untyped_storage().nbytes()+ except Exception: pass+ print(f"[loaddiag] OOM at {module.key}: live CUDA storages {sum(v[1] for v in agg.values())/2**30:.3f} GiB, allocated {torch.cuda.memory_allocated()/2**30:.3f}", flush=True)+ for k, v in sorted(agg.items(), key=lambda kv: -kv[1][1])[:25]:+ print(f"[loaddiag] {v[1]/2**20:10.1f} MiB n={v[0]:5d} {k[0]} {k[1]}", flush=True)else:raisediff --git a/exllamav3/modules/attn.py b/exllamav3/modules/attn.pyindex 8ca1758..91cb0cf 100644--- a/exllamav3/modules/attn.py+++ b/exllamav3/modules/attn.py@@ -24,6 +24,7 @@ _shared_check = os.environ.get("EXL3_ATTN_SHARED_CHECK", "0") != "0"_batch_qsa = os.environ.get("EXL3_ATTN_BATCH_QSA", "1") != "0"_SHARED_STATS = [0, 0]_QKV_IG_MULTI = os.environ.get("EXL3_ATTN_QKV_IG_MULTI", "1") != "0" # (q|gate, k, v one launch)+_QKVCAT = os.environ.get("EXL3_ATTN_QKVCAT", "1" if torch.version.hip else "0") != "0" # GGUF Q8_0 q / k / v decode in one launch (_qkv_q8cat)def _sim_kvq_inplace(t: torch.Tensor, bits: int | None, compand_a: float):@@ -633,6 +634,50 @@ class Attention(Module):def load(self, device: torch.Device, **kwargs):super().load(device, **kwargs)self.load_local(device, **kwargs)+ self._q8cat_build()++ def _q8cat_build(self):+ """GGUF Q8_0 q / k / v weights as one [nq + nk + nv, row] tensor, the ForeignLinears re-pointed to views of it (same bytes,+ no copy kept). Done at load, before any decode graph is captured. Nothing for other formats."""+ self._q8cat_w = None+ if not _QKVCAT or self.use_k_as_v:+ return+ from .foreign_linear import ForeignLinear+ lins = (self.q_proj, self.k_proj, self.v_proj)+ if not all(isinstance(l, ForeignLinear) and l.format == "q8_0" and l.packed is not None and l.packed.dtype == torch.uint8+ for l in lins):+ return+ if len({l.in_features for l in lins}) != 1 or len({l.packed.device for l in lins}) != 1:+ return+ shapes = [l.packed.shape for l in lins]+ cat = torch.cat([l.packed.reshape(l.out_features, -1) for l in lins], dim = 0)+ a = 0+ for l, sh in zip(lins, shapes):+ l.packed = cat[a:a + l.out_features].view(sh)+ a += l.out_features+ self._q8cat_w = cat+ if not getattr(Attention, "_q8cat_said", False):+ Attention._q8cat_said = True+ print(f" -- attention q / k / v Q8_0 decode rows concatenated ({' + '.join(str(l.out_features) for l in lins)})", flush = True)++ def _qkv_q8cat(self, x: torch.Tensor, params: dict, bsz: int, q_len: int):+ """q, k, v of one decode row from ONE fq_gemv_q8_0 launch over the rows concatenated at load: the same per-row q8_1 x Q8_0+ dot as three launches (bit-exact), one quantization instead of three. None = fall back to the three projections."""+ cat = getattr(self, "_q8cat_w", None)+ if cat is None or bsz * q_len != 1 or not x.is_contiguous() or "capture" in params or "ovr" in params:+ return None+ lins = (self.q_proj, self.k_proj, self.v_proj)+ flat = x.reshape(1, -1)+ dts = {l.out_dtype or torch.half for l in lins}+ if len(dts) != 1 or not all(l.q8_fused_gemv_ok(flat) for l in lins):+ return None+ n = [l.out_features for l in lins]+ out = torch.empty((1, sum(n)), dtype = dts.pop(), device = x.device)+ ext.fq_gemv_q8_0(flat, cat.view(sum(n), -1, 34), out)+ q = out[:, :n[0]].view(bsz, q_len, n[0])+ k = out[:, n[0]:n[0] + n[1]].view(bsz, q_len, n[1])+ v = out[:, n[0] + n[1]:].view(bsz, q_len, n[2])+ return q, k, v@override@@ -861,8 +906,9 @@ class Attention(Module):q, k, v, g = self.project_qkv_sliced(x, bsz, q_len)return self.finish_qkv(q, k, v, g, bsz, q_len, params)+ qkv8 = self._qkv_q8cat(x, params, bsz, q_len)if self.multi_qg is None or bsz * q_len > 32:- q = self.q_proj.forward(x, params)+ q = qkv8[0] if qkv8 is not None else self.q_proj.forward(x, params)if self.interleaved_gate:if self.head_dim % 8 == 0 and q.dtype == torch.half:qg = q@@ -909,7 +955,9 @@ class Attention(Module):q = qg[0].view(bsz, q_len, self.num_q_heads * self.head_dim)g = qg[1].view(bsz, q_len, self.num_q_heads * self.head_dim)- if self.multi_kv is None or bsz * q_len > 32:+ if qkv8 is not None:+ k, v = qkv8[1], qkv8[2]+ elif self.multi_kv is None or bsz * q_len > 32:k = self.k_proj.forward(x, params)v = self.v_proj.forward(x, params) if not self.use_k_as_v else kdiff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.pyindex 3fb8e27..99a7229 100644--- a/exllamav3/modules/block_sparse_mlp.py+++ b/exllamav3/modules/block_sparse_mlp.py@@ -25,7 +25,7 @@ from ..util.row_inv import ROW_INV_MAX_ROWS, job_slicesfrom .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,- _HIP_ROUTER_HIDDEN, _HIP_ROUTER_EXPERTS, _HIP_ROUTER_TOP_K,+ _HIP_ROUTER_HIDDEN, _HIP_ROUTER_EXPERTS, _HIP_ROUTER_TOP_K, _HIP_ROUTER_SHAPES,_HIP_GROUPED_MAX_ROWS, _HIP_PREFILL_MIN_ROWS, _HIP_PREFILL_MAX_ROWS, _HIP_PREFILL_MAX_EXPERT_ROWS,_hip_grouped_rows_eligible, _hip_prefill_rows_eligible, _prepare_hip_router_gate_t, _MOE_VALU,)@@ -208,6 +208,13 @@ def _aligned_expert_layout(flat: torch.Tensor, num_tokens: int, top_k: int, num_return order[:total], sel_flat[:total], dummy_tokens+# EXL3_SHGATE_FUSE (default 1): the KQ grouped decode path runs the shared-expert gate tail in one Triton launch+_SHGATE_FUSE = os.environ.get("EXL3_SHGATE_FUSE", "1") != "0"+++# MCPM_FQ_MOE_IQ (default 1): IQ3_XXS / IQ2_S experts take the grouped q8_1 decode MoE (fq_moe_kq.cu FMT 4 / 5)+_FQ_MOE_IQ = os.environ.get("MCPM_FQ_MOE_IQ", "1") != "0"+@dataclassclass FusedBuffers:temp_state_g: torch.Tensor@@ -431,9 +438,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# source must therefore be filled before deferred loading completes.no_defer_load = bool(torch.version.hip and router_type == "std" and- hidden_size == _HIP_ROUTER_HIDDEN and- num_experts == _HIP_ROUTER_EXPERTS and- num_experts_per_tok == _HIP_ROUTER_TOP_K and+ (hidden_size, num_experts, num_experts_per_tok) in _HIP_ROUTER_SHAPES andkey_per_expert_scale is None and interm_div == 1.0),)@@ -1756,10 +1761,17 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):return None# gate/up share one format, down has its own (unsloth UD: gate/up Q4_K + down Q5_K)fmt = fmt_d = None- for m in self.gates + self.ups + self.downs:+ _ug_ok = ("q4_k", "q5_k", "q6_k", "iq4_xs") + (("iq3_xxs", "iq2_s") if _FQ_MOE_IQ else ())+ for m in self.gates + self.ups:+ if not isinstance(m, ForeignLinear) or m.format not in _ug_ok:+ return None+ if m.packed is None or not m.packed.is_contiguous():+ return None+ # downs may also be 32-element blocks (Q8_0 / Q5_1: expert widths not a multiple of 256, e.g. 640)+ for m in self.downs:if not isinstance(m, ForeignLinear):return None- if m.format not in ("q4_k", "q5_k", "q6_k", "iq4_xs"):+ if m.format not in _ug_ok and not (m.format in ("q8_0", "q5_1") and m.in_features % 32 == 0):return Noneif m.packed is None or not m.packed.is_contiguous():return None@@ -1781,7 +1793,8 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):return NoneK = self.expert_sizeI = self.intermediate_size- if K % 256 != 0 or I % 256 != 0:+ # down with 32-element blocks (q8_0 / q5_1) only needs I % 32 (tests/test_moe_down32.py: I = 640)+ if K % 256 != 0 or I % (32 if fmt_d in ("q8_0", "q5_1") else 256) != 0:return Noneif self.gates[0].in_features != K or self.gates[0].out_features != I:return None@@ -1791,6 +1804,139 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):return Nonereturn fmt, fmt_d+ def _fp8_grouped_ok(self, y):+ """FP8 routed experts (quant_type "fp8", modules/quant/fp8.py), gated SiLU, plain layer: one grouped launch per projection.+ EXL3_FP8_MOE_GROUPED=0 disables."""+ if os.environ.get("EXL3_FP8_MOE_GROUPED", "1") == "0" or not self.gated or self.activation_fn != "silu":+ return None+ if self.latent_in is not None or self.latent_out is not None or self.tier is not None or getattr(self, "cpu_offload", False):+ return None+ if getattr(self, "cpu_split_first", None) is not None or self.routing_device is not None or self.tp_reduce or self.tp_mode is not None:+ return None+ if self.alt_residual_channel or self.routed_post_norm is not None or self.shared_experts_post_norm is not None:+ return None+ mods = self.gates + self.ups + self.downs+ if len(self.gates) != self.num_experts or len(self.ups) != self.num_experts or len(self.downs) != self.num_experts:+ return None+ if not all(getattr(m, "quant_type", None) == "fp8" for m in mods):+ return None+ g0 = self.gates[0].inner+ if any(m.inner.grid != g0.grid or m.inner.block != g0.block or m.inner.bias is not None for m in mods):+ return None+ if y.dtype != torch.half:+ return None+ return g0.grid, g0.block++ def _mxfp4_grouped_ok(self, y):+ """gpt-oss routed experts kept as stored MXFP4 (Linear.inner = _ForeignInner over ForeignLinear 'mxfp4'), plain layer.+ EXL3_MXFP4_MOE_GROUPED=0 disables."""+ if os.environ.get("EXL3_MXFP4_MOE_GROUPED", "1") == "0" or not self.gated or self.activation_fn not in ("swiglu_oai", "silu"):+ return False+ if self.latent_in is not None or self.latent_out is not None or getattr(self, "tier", None) is not None or getattr(self, "cpu_offload", False):+ return False+ if getattr(self, "cpu_split_first", None) is not None or self.routing_device is not None or self.tp_reduce or self.tp_mode is not None:+ return False+ if self.alt_residual_channel or self.routed_post_norm is not None or self.shared_experts_post_norm is not None:+ return False+ if self.router_pre_norm is not None or self.routed_pre_norm is not None:+ return False+ if y.dtype != torch.half:+ return False+ if len(self.gates) != self.num_experts or len(self.ups) != self.num_experts or len(self.downs) != self.num_experts:+ return False+ for m in self.gates + self.ups + self.downs:+ fl = getattr(getattr(m, "inner", None), "fl", None)+ if fl is None or getattr(fl, "format", None) != "mxfp4" or fl.packed is None or not fl.packed.is_contiguous():+ return False+ return True++ def _forward_mxfp4_grouped(self, x, y, selected_experts, routing_weights, params, out_dtype, eshape):+ """Grouped MXFP4 MoE decode: gate, up, down of every (row, expert) slot in one launch each (biases in-kernel),+ the layer's own activation (swiglu_oai clamp for gpt-oss), weighted fold per row."""+ if not self._mxfp4_grouped_ok(y):+ return None+ from ..foreign_quant import triton_moe_mxfp4 as MX+ S = self.num_experts_per_tok+ R = y.shape[0] if y.dim() == 2 else y.reshape(-1, y.shape[-1]).shape[0]+ if R > FQ_GROUPED_MAX_ROWS or selected_experts.numel() != R * S:+ return None+ h = y.reshape(R, -1).contiguous()+ dev = h.device+ H = h.shape[1]+ K = self.gates[0].inner.fl.in_features # experts padded to 128 (gpt-oss 2880 -> 2944): zero-extend the input+ if K != H:+ h = torch.nn.functional.pad(h, (0, K - H)).contiguous()+ I = self.gates[0].inner.fl.out_features+ tbl = getattr(self, "_mx_ptrs", None)+ if tbl is None or tbl[0] != self.gates[0].inner.fl.packed.data_ptr() or tbl[1] != dev:+ mk = lambda ms: torch.tensor([m.inner.fl.packed.data_ptr() for m in ms], dtype=torch.int64, device=dev)+ mb = lambda ms: torch.tensor([m.inner.bias.data_ptr() for m in ms], dtype=torch.int64, device=dev) \+ if all(m.inner.bias is not None for m in ms) else None+ tbl = (self.gates[0].inner.fl.packed.data_ptr(), dev, mk(self.gates), mb(self.gates), mk(self.ups), mb(self.ups),+ mk(self.downs), mb(self.downs))+ self._mx_ptrs = tbl+ _, _, gw, gb, uw, ub, dw, db = tbl+ sel = selected_experts.reshape(-1).to(torch.int32).contiguous()+ g = MX.moe_gemv(h, gw, gb, sel, I, K, S).half()+ u = MX.moe_gemv(h, uw, ub, sel, I, K, S).half()+ a = torch.empty_like(g)+ self.activation_fn_call(g, u, a, self.act_limit)+ d = MX.moe_gemv(a, dw, db, sel, self.downs[0].inner.fl.out_features, I, 1)+ routed = (d.view(R, S, -1)[..., :H] * routing_weights.reshape(R, S, 1).float()).sum(1)+ final_hidden_states = routed.view(x.shape)+ if self.shared_experts is not None:+ se = self.shared_experts.forward(x, params)+ final_hidden_states = final_hidden_states + se.to(torch.float).view(final_hidden_states.shape)+ if out_dtype is not None:+ final_hidden_states = final_hidden_states.to(out_dtype)+ return final_hidden_states++ def _forward_fp8_grouped(self, x, y, selected_experts, routing_weights, params, out_dtype, eshape):+ """Grouped FP8 MoE decode (R <= FQ_GROUPED_MAX_ROWS rows): gate and up of every (row, expert) slot in one launch each,+ SiLU * up in torch, down in one launch, weighted fold per row; then the shared expert as the KQ grouped path does."""+ ok = self._fp8_grouped_ok(y)+ if ok is None:+ return None+ grid, block = ok+ from .quant import fp8 as F8+ S = self.num_experts_per_tok+ R = y.shape[0] if y.dim() == 2 else y.reshape(-1, y.shape[-1]).shape[0]+ if R > FQ_GROUPED_MAX_ROWS or selected_experts.numel() != R * S:+ return None+ h = y.reshape(R, -1).contiguous()+ dev = h.device+ K = h.shape[1]+ I = self.intermediate_size+ tbl = getattr(self, "_fp8_ptrs", None)+ if tbl is None or tbl[0] != self.gates[0].inner.q.data_ptr() or tbl[1] != dev:+ mk = lambda ms, a: torch.tensor([getattr(m.inner, a).data_ptr() for m in ms], dtype=torch.int64, device=dev)+ tbl = (self.gates[0].inner.q.data_ptr(), dev, mk(self.gates, "q"), mk(self.gates, "s"), mk(self.ups, "q"), mk(self.ups, "s"),+ mk(self.downs, "q"), mk(self.downs, "s"))+ self._fp8_ptrs = tbl+ _, _, gq, gs, uq, us, dq, ds = tbl+ sel = selected_experts.reshape(-1).to(torch.int32).contiguous()+ sc_gu = self.gates[0].inner.s.shape[1] if grid else 1+ sc_d = self.downs[0].inner.s.shape[1] if grid else 1+ if os.environ.get("EXL3_FP8_MOE_FUSED", "1") != "0": # 2 launches: gate|up, then down with SwiGLU staging + weighted fold+ routed = F8.moe_fused(h, (gq, gs, uq, us, dq, ds), sel, routing_weights.reshape(-1).contiguous(), I, K, grid, block, S, sc_gu, sc_d)+ else:+ g = F8.moe_gemv(h, gq, gs, sel, I, K, grid, block, S, sc_gu)+ u = F8.moe_gemv(h, uq, us, sel, I, K, grid, block, S, sc_gu)+ a = (torch.nn.functional.silu(g) * u).half()+ d = F8.moe_gemv(a, dq, ds, sel, K, I, grid, block, 1, sc_d)+ routed = (d.view(R, S, K) * routing_weights.reshape(R, S, 1).float()).sum(1)+ final_hidden_states = routed.view(x.shape) if R > 1 else routed+ if self.shared_experts is not None:+ se = self.shared_experts.forward(x, params)+ if self.shared_gate is not None:+ gt = self._shgate_hip(x)+ final_hidden_states = final_hidden_states + se.to(torch.float).view(final_hidden_states.shape) * gt.view(*final_hidden_states.shape[:-1], -1)+ else:+ final_hidden_states = final_hidden_states + se.to(torch.float).view(final_hidden_states.shape)+ if out_dtype is not None:+ final_hidden_states = final_hidden_states.to(out_dtype)+ return final_hidden_states+def _forward_foreign_grouped_kq(self, x, y, selected_experts, routing_weights,params, out_dtype, eshape):"""Grouped KQ MoE for SwiGLU decode, R = 1..FQ_GROUPED_MAX_ROWS rows (one per user / session). One fq_moe kernel@@ -1815,7 +1961,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):h = y.reshape(R, -1)dev = h.deviceK = h.shape[1]- _BB = {"q4_k": 144, "q5_k": 176, "q6_k": 210, "iq4_xs": 136}+ _BB = {"q4_k": 144, "q5_k": 176, "q6_k": 210, "iq4_xs": 136, "iq3_xxs": 98, "iq2_s": 82, "q8_0": 34, "q5_1": 24}bb = _BB[fmt]bb_d = _BB[fmt_d]tbl = getattr(self, "_fq_kq_ptrs", None)@@ -1832,7 +1978,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):I = self.intermediate_sizegate_stride = (K // 256) * bbup_stride = gate_stride- down_stride = (I // 256) * bb_d+ down_stride = (I // (32 if fmt_d in ("q8_0", "q5_1") else 256)) * bb_d# buffers sized once for the largest row count (stable pointers for CUDA graphs); the kernel gets row-prefix viewsif getattr(self, "_fq_kq_partial", None) is None or \self._fq_kq_partial.shape != (FQ_GROUPED_MAX_ROWS * S, K) or self._fq_kq_partial.device != dev:@@ -1842,22 +1988,36 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):routed_v = self._fq_kq_routed[:R]_FN = {"q4_k": "fq_moe_q4k_grouped_q8", "q5_k": "fq_moe_q5k_grouped_q8","q6_k": "fq_moe_q6k_grouped_q8", "iq4_xs": "fq_moe_iq4xs_grouped_q8"}- if fmt == fmt_d:+ if fmt == fmt_d and fmt in _FN:getattr(ext, _FN[fmt])(h, sel, wts, gate_ptrs, up_ptrs, down_ptrs,gate_stride, up_stride, down_stride,partial_v, routed_v)else:- _FID = {"q4_k": 0, "q5_k": 1, "q6_k": 2, "iq4_xs": 3}+ _FID = {"q4_k": 0, "q5_k": 1, "q6_k": 2, "iq4_xs": 3, "iq3_xxs": 4, "iq2_s": 5, "q8_0": 6, "q5_1": 7}ext.fq_moe_kq_grouped_mixed_q8(h, sel, wts, gate_ptrs, up_ptrs, down_ptrs,gate_stride, up_stride, down_stride, _FID[fmt], _FID[fmt_d],partial_v, routed_v)final_hidden_states = routed_v.view(x.shape) if R > 1 else routed_v # rows -> [jobs, q, K] like the per-expert pathif self.shared_experts is not None:se_params = {**params, "moe_valu": True} if _MOE_VALU else params+ if R == 1 and h.data_ptr() == x.data_ptr() and h.dtype == x.dtype:+ # the routed call above left q8_1(x) in fq_q8_scratch(dev, 1, K): the shared gate+up reads it (mlp._fq_gu_cat)+ se_params = {**se_params, "fq_q8_x": x.data_ptr()}se = self.shared_experts.forward(x, se_params)- if self.shared_gate is not None and torch.version.hip:+ if self.shared_gate is not None and torch.version.hip and _SHGATE_FUSE and R <= 16 and \+ se.dtype in (torch.half, torch.float) and x.dtype == torch.half and se.is_contiguous() and x.is_contiguous() and \+ self.shared_gate.inner.weight.dim() == 2 and self.shared_gate.inner.weight.shape[1] == 1:+ # shared-expert gate tail in one launch (triton_shgate.py): routed + float(se) * sigmoid(x . w_gate), in place+ wr = getattr(self, "_shgate_row", None)+ w = self.shared_gate.inner.weight+ if wr is None or wr.device != w.device or wr.numel() != w.numel():+ wr = w.to(torch.float).reshape(-1).contiguous()+ self._shgate_row = wr+ from ..foreign_quant.triton_shgate import shgate_tail_+ shgate_tail_(routed_v, se.reshape(R, K), x.reshape(R, K), wr)+ elif self.shared_gate is not None and torch.version.hip:# ROCm add_sigmoid_gate_proj takes a float shared-expert output: same math in torch- g = torch.sigmoid((x.to(torch.float) @ self.shared_gate.inner.weight.to(torch.float)))+ g = self._shgate_hip(x)final_hidden_states = final_hidden_states + se.to(torch.float) * gelif self.shared_gate is not None:ext.add_sigmoid_gate_proj(se, x, final_hidden_states,@@ -1868,6 +2028,18 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):final_hidden_states = final_hidden_states.to(out_dtype)return final_hidden_states+ def _shgate_hip(self, x):+ """sigmoid(x . w_gate) for the shared expert gate: a (1, K) x (K, 1) fp32 matmul costs ~64 us on ROCm (hipBLAS GEMV), an+ elementwise product + row sum over a cached fp32 row ~14 us (Strix, K 2048). EXL3_SHGATE_MULSUM=0 restores the matmul."""+ w = self.shared_gate.inner.weight+ if os.environ.get("EXL3_SHGATE_MULSUM", "1") == "0" or w.dim() != 2 or w.shape[1] != 1:+ return torch.sigmoid((x.to(torch.float) @ w.to(torch.float)))+ wr = getattr(self, "_shgate_row", None)+ if wr is None or wr.device != w.device or wr.numel() != w.numel():+ wr = w.to(torch.float).reshape(-1).contiguous()+ self._shgate_row = wr+ return torch.sigmoid((x.to(torch.float) * wr).sum(-1, keepdim = True))+def _forward_foreign_shared(self, x, params):"""Fused dense shared-expert up+relu2 (fq_mlp.cu) + ForeignLineardown for batch-1 decode. Bit-identical to the shared MLP torch path@@ -1924,11 +2096,17 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):fmts = self._fq_grouped_kq_ok(y)_KQ = {"q4_k": 0, "q5_k": 1, "q6_k": 2}use_kq = fmts is not None and fmts[0] in _KQ and fmts[1] in _KQ # Q4_K/Q5_K/Q6_K (mixed gate-up/down ok)+ # IQ packs (gate/up IQ2_S + down IQ3_XXS / IQ4_XS): grouped dequant + fp16 grouped GEMM (fq_moe_prefill_iq.py)+ use_iq = _FQ_MOE_IQ and fmts is not None and not use_kq and set(fmts) <= {"iq3_xxs", "iq2_s", "iq4_xs"} and \+ fmts != ("iq4_xs", "iq4_xs")# K-quant: grouped from 33 rows (just above the multi-row decode kernel, FQ_GROUPED_MAX_ROWS=32); below that the# per-expert loop launched ~1650 small gemvs per forward (3090 cut4 8K prefill +14..25 %). Others keep 256.- if R < int(os.environ.get("MCPM_FQ_PF_GROUPED_MIN", "33" if use_kq else "256")):+ # IQ: the grouped path dequantizes every expert per forward (fixed cost): on HIP it pays from 512 rows (35B UD-IQ3_XXS: from 33+ # rows, 8 different users -20 %; from 512, prefill 8K 21.8 -> 8.6 s with the other cells unchanged)+ if R < int(os.environ.get("MCPM_FQ_PF_GROUPED_MIN", "512" if (use_iq and torch.version.hip) else+ "33" if (use_kq or use_iq) else "256")):return None- if fmts is None or not (use_kq or fmts == ("iq4_xs", "iq4_xs")) or self.act_limit or \+ if fmts is None or not (use_kq or use_iq or fmts == ("iq4_xs", "iq4_xs")) or self.act_limit or \self.activation_fn not in ("silu", None):return None# Scratch path (grouped dequant + fp16 grouped GEMM): CUDA 2.4-4.2x on the MoE layer. ROCm iGPU with the@@ -1947,7 +2125,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):if tuple(selected_experts.shape) != (R, top_k) or selected_experts.dtype != torch.long:return Nonefrom .fq_moe_prefill import build_tiles, gmm_iq4, perm_cols- if use_kq:+ if use_kq or use_iq:from .fq_moe_prefill_kq import moe_kq_prefill, gmm_kq, PF_BME = self.num_expertsdev = y.device@@ -1962,7 +2140,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):weight_sorted = wts.reshape(-1)[order]counts = _scatter_expert_count(flat_expert, E + 1)[:E]M = R * top_k- bm = PF_BM if use_kq else 64+ bm = PF_BM if (use_kq or use_iq) else 64tile_e, tile_r0, offs = build_tiles(counts, M, bm)tbl = getattr(self, "_fq_pf_ptrs", None)if tbl is None or tbl[0] != self.gates[0].packed.data_ptr() or tbl[3] != dev:@@ -1981,6 +2159,11 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):else:moe_kq_prefill(xs, gu_ptrs, dn_ptrs, a, dn, tile_e, tile_r0, offs, weight_sorted, E, I, K,_KQ[fmts[0]], _KQ[fmts[1]], bm)+ elif use_iq:+ from .fq_moe_prefill_iq import moe_iq_prefill, FMT_ID+ xs = y.index_select(0, token_sorted)+ moe_iq_prefill(xs, gu_ptrs, dn_ptrs, a, dn, tile_e, tile_r0, offs, weight_sorted, E, I, K,+ FMT_ID[fmts[0]], FMT_ID[fmts[1]], bm)else:xs = perm_cols(y.index_select(0, token_sorted))gmm_iq4(xs, gu_ptrs, a, tile_e, tile_r0, offs, I, K, E, swiglu=True)@@ -2171,6 +2354,14 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# without latent projs anyway).if bsz <= FQ_GROUPED_MAX_ROWS and not params.get("activate_all_experts") and \not params.get("reconstruct") and not params.get("autosplit_measure"):+ grouped = self._forward_fp8_grouped(+ x, y, selected_experts, routing_weights, params, out_dtype, eshape)+ if grouped is not None:+ return grouped+ grouped = self._forward_mxfp4_grouped(+ x, y, selected_experts, routing_weights, params, out_dtype, eshape)+ if grouped is not None:+ return groupedgrouped = self._forward_foreign_grouped_kq(x, y, selected_experts, routing_weights, params, out_dtype, eshape)if grouped is not None:diff --git a/exllamav3/modules/block_sparse_mlp_routing.py b/exllamav3/modules/block_sparse_mlp_routing.pyindex ce4be86..e6fadef 100644--- a/exllamav3/modules/block_sparse_mlp_routing.py+++ b/exllamav3/modules/block_sparse_mlp_routing.py@@ -88,6 +88,8 @@ class RoutingCFG:_HIP_ROUTER_HIDDEN = 2560_HIP_ROUTER_EXPERTS = 512_HIP_ROUTER_TOP_K = 10+# (hidden, experts, top-k) shapes the fused HIP decode router serves (routing_std_gfx12.cu ROUTER_SHAPE list)+_HIP_ROUTER_SHAPES = {(2560, 512, 10), (2048, 256, 8)}_HIP_ROUTER_MAX_ROWS = 16@@ -153,12 +155,11 @@ def _hip_router_device_supported(device):def _hip_router_config_supported(cfg):gate = cfg.gate_tensorreturn (- cfg.num_experts == _HIP_ROUTER_EXPERTS and- cfg.num_experts_per_tok == _HIP_ROUTER_TOP_K and+ (gate.shape[0], cfg.num_experts, cfg.num_experts_per_tok) in _HIP_ROUTER_SHAPES andcfg.per_expert_scale is None andcfg.router_bias is None andgate.dtype == torch.half and gate.is_contiguous() and- tuple(gate.shape) == (_HIP_ROUTER_HIDDEN, _HIP_ROUTER_EXPERTS) and+ tuple(gate.shape) == (gate.shape[0], cfg.num_experts) and_hip_router_device_supported(gate.device))@@ -169,7 +170,7 @@ def _hip_router_call_supported(bsz, cfg, y, params):1 <= bsz <= _HIP_ROUTER_MAX_ROWS and not params.get("activate_all_experts") and_hip_router_config_supported(cfg) andy.dtype == torch.half and y.is_contiguous() and- tuple(y.shape) == (bsz, _HIP_ROUTER_HIDDEN)+ tuple(y.shape) == (bsz, cfg.gate_tensor.shape[0]))@@ -190,11 +191,11 @@ def _prepare_hip_router_buffers(cfg):# needing separate buffers for speculative streams.device = cfg.gate_tensor.devicecfg.router_logits_gfx12 = torch.empty(- (_HIP_ROUTER_MAX_ROWS, _HIP_ROUTER_EXPERTS), device = device, dtype = torch.half)+ (_HIP_ROUTER_MAX_ROWS, cfg.num_experts), device = device, dtype = torch.half)cfg.selected_experts_gfx12 = torch.empty(- (_HIP_ROUTER_MAX_ROWS, _HIP_ROUTER_TOP_K), device = device, dtype = torch.long)+ (_HIP_ROUTER_MAX_ROWS, cfg.num_experts_per_tok), device = device, dtype = torch.long)cfg.routing_weights_gfx12 = torch.empty(- (_HIP_ROUTER_MAX_ROWS, _HIP_ROUTER_TOP_K), device = device, dtype = torch.half)+ (_HIP_ROUTER_MAX_ROWS, cfg.num_experts_per_tok), device = device, dtype = torch.half)def _hip_router_buffers(cfg, rows):@@ -207,8 +208,21 @@ def _hip_router_buffers(cfg, rows):cfg.routing_weights_gfx12[:rows],)+def _router_logits(cfg, y):+ """y @ gate. On ROCm a decode-row fp16 matmul against the (H, E) gate is a hipBLAS GEMV at ~41 us (Strix, 2048 x 256); an+ elementwise product with a cached fp32 (E, H) copy + row sum is ~18 us, rounded to fp16 like the matmul output so the stable+ sort below sees the same dtype. Rows <= 16 on HIP only; EXL3_ROUTER_MULSUM=0 restores the matmul."""+ if (torch.version.hip and y.dim() == 2 and y.shape[0] <= 16 and y.is_cuda and os.environ.get("EXL3_ROUTER_MULSUM", "1") != "0"):+ gt = getattr(cfg, "_gate_tf", None)+ if gt is None or gt.device != y.device:+ gt = cfg.gate_tensor.T.float().contiguous()+ cfg._gate_tf = gt+ return (y.float().unsqueeze(1) * gt.unsqueeze(0)).sum(-1).half()+ return torch.matmul(_pad_rows(y), cfg.gate_tensor)++def _routing_std_torch(cfg, y, params, include_bias = False):- router_logits = torch.matmul(_pad_rows(y), cfg.gate_tensor)+ router_logits = _router_logits(cfg, y)# EXL3_ROUTER_TOPK (default 1, read per call): prefill rows select top-k with one Triton pass (router_topk.py)# instead of the stable sort below over all experts; same ids, same values into the same softmaxif (router_logits.dim() == 2 and router_logits.shape[0] > 16 and router_logits.is_cuda and router_logits.stride(1) == 1diff --git a/exllamav3/modules/foreign_linear.py b/exllamav3/modules/foreign_linear.pyindex 0f3842e..373a505 100644--- a/exllamav3/modules/foreign_linear.py+++ b/exllamav3/modules/foreign_linear.py@@ -24,7 +24,20 @@ import torchfrom .module import Modulefrom ..ext import exllamav3_ext as extfrom ..foreign_quant.gap_formats import dequant as gap_dequant+from ..foreign_quant import triton_iqfrom ..foreign_quant import triton_gap+from ..foreign_quant import triton_rows+_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.+# BOLT_FQ_ROWS_TRITON_Q8=1 restores it on CUDA (A/B).+_ROWS_TRITON_Q8 = os.environ.get("BOLT_FQ_ROWS_TRITON_Q8", "0" if (torch.version.cuda and not torch.version.hip) else "1") != "0"++# Q4_K / Q6_K rows 2..16: the C++ multi-row q8_1 GEMV (fq_gemv_kq.cu fq_gemv_kq_mrows_kernel: weights read once for all rows, per-row result bit-identical to+# the one-row kernel) instead of the Triton rows kernel (fp16 activations, Triton speed). Default on CUDA; HIP keeps Triton until measured on gfx1151.+# BOLT_FQ_KQ_MROWS=0 restores the Triton rows kernel (A/B); default on for CUDA and HIP. Read here and in the extension (same variable).+_KQ_MROWS = os.environ.get("BOLT_FQ_KQ_MROWS", "1") != "0"+_KQ_MROWS_FORMATS = ("q4_k", "q6_k")FUSED_ROWS_MAX = 16_FUSED = os.environ.get("BOLT_FQ_FUSED", "1") != "0"@@ -42,17 +55,20 @@ _UNFUSED_ROWS = int(os.environ.get("BOLT_FQ_UNFUSED_ROWS", "8192"))_PAIR = os.environ.get("BOLT_FQ_PAIR", "1") != "0"_FORMATS = ("q8_0", "iq2_xxs", "nvfp4", "q4_k", "q5_k", "q6_k", "iq4_xs",- "q4_0", "q5_0", "iq4_nl", "iq3_xxs", "iq3_s", "mxfp4", "nvfp4_gguf")+ "q4_0", "q5_0", "q5_1", "iq4_nl", "iq3_xxs", "iq3_s", "mxfp4", "nvfp4_gguf", "iq2_xs", "iq2_s", "q3_k", "q2_k")# GGUF blocks without a fused kernel yet: torch dequant (foreign_quant/gap_formats.py) + matmul at every width.# BOLT_FQ_GAP_FUSED=0 turns the fused Triton decode kernel off (A/B)._GAP_FUSED = os.environ.get("BOLT_FQ_GAP_FUSED", "1") != "0"-_GAP_FORMATS = ("q4_0", "q5_0", "iq4_nl", "iq3_xxs", "iq3_s", "mxfp4", "nvfp4_gguf")+_GAP_FORMATS = ("q4_0", "q5_0", "q5_1", "iq4_nl", "iq3_xxs", "iq3_s", "mxfp4", "nvfp4_gguf", "iq2_xs", "iq2_s", "q3_k", "q2_k")# GGUF K-quant formats: decode (rows < 16) via the q8_1-# activation row kernels; prefill (rows >= 16) via the unfused fp16 dequant# + cuBLAS GEMM path, one GEMM per call -- i.e. one GEMM per# expert token-group in the dense MoE prefill path. MCPM_FQ_KQ_GEMM=0 forces# the q8 row kernels for every width (A/B)._KQ_FORMATS = ("q4_k", "q5_k", "q6_k", "iq4_xs")+# EXL3_IQ3_Q8 (default 1): IQ3_XXS decode rows run the q8_1 dp4a GEMV (fq_gemv_iq3_xxs_q8) instead of the Triton decode+_IQ3_Q8 = os.environ.get("EXL3_IQ3_Q8", "1") != "0"+_IQ_Q8_FN = {"iq3_xxs": "fq_gemv_iq3_xxs_q8", "iq2_s": "fq_gemv_iq2_s_q8", "iq3_s": "fq_gemv_iq3_s_q8"}_KQ_BLOCK_BYTES = {"q4_k": 144, "q5_k": 176, "q6_k": 210, "iq4_xs": 136}_KQ_GEMM_ROWS = 16_KQ_GEMM = os.environ.get("MCPM_FQ_KQ_GEMM", "1") != "0"@@ -197,6 +213,18 @@ class ForeignLinear(Module):self.global_scale, out)return out+ def q8_fused_gemv_ok(self, flat: torch.Tensor) -> bool:+ """True when forward() serves this flat input with the plain ext.fq_gemv_q8_0 launch (the _FUSED branch below)."""+ R, K = flat.shape[0], self.in_features+ if self.format != "q8_0" or flat.device != self.packed.device or flat.shape[-1] != K:+ return False+ if _ROWS_TRITON and flat.dtype == torch.half and _ROWS_TRITON_Q8 and triton_rows.supported(self.format, R, K):+ return False+ if self.format in triton_iq.FUSED or self.format in _GAP_FORMATS or self.format in _KQ_FORMATS or self.format in _IQ_Q8_FN:+ return False+ return (_FUSED and 1 <= R <= FUSED_ROWS_MAX and flat.is_contiguous() and flat.dtype in (torch.half, torch.float)+ and hasattr(ext, "fq_gemv_q8_0") and _GEMV)+def forward(self,x: torch.Tensor,@@ -215,7 +243,35 @@ class ForeignLinear(Module):if not flat.is_contiguous():flat = flat.contiguous()out: Optional[torch.Tensor] = None- if (+ if (_ROWS_TRITON and flat.dtype == torch.half and (_ROWS_TRITON_Q8 or self.format != "q8_0")+ and not (_KQ_MROWS and self.format in _KQ_MROWS_FORMATS)+ and triton_rows.supported(self.format, R, K)):+ # 2..16 rows (verify / multi-user): weights read once for all rows (the fq_gemv kernels re-read them per row)+ out = triton_rows.gemv(self.format, flat, self.packed.reshape(self.out_features, -1), self.scales.reshape(self.out_features, -1)+ if self.scales is not None else None, self.global_scale if self.global_scale is not None else 1.0)+ if out.dtype != dtype:+ out = out.to(dtype)+ elif (+ self.format in _IQ_Q8_FN and _IQ3_Q8 and R == 1 and flat.dtype == torch.half and K % 256 == 0+ and hasattr(ext, _IQ_Q8_FN[self.format])+ ):+ # IQ3_XXS / IQ2_S / IQ3_S single decode row (2+ rows stay on the Triton decode, which reads the weights once for all rows): q8_1 activations + integer dp4a dots (ggml vec_dot_iq3_xxs_q8_1 port, fq_gemv_kq.cu FMT 4)+ N = self.out_features+ out = torch.empty((R, N), dtype=dtype if dtype in (torch.half, torch.float) else torch.half, device=dev)+ 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, _IQ_Q8_FN[self.format])(qb, self.packed.reshape(N, -1), out)+ if out.dtype != dtype:+ out = out.to(dtype)+ elif (+ self.format in triton_iq.FUSED and flat.dtype == torch.half and triton_iq.supported(self.format, R, K, self.out_features)+ ):+ # IQ3_XXS / IQ3_S / IQ2_XS / IQ2_S / Q3_K decode rows: fused Triton decode of the stored blocks (EXL3_IQ_FUSED=0: torch dequant)+ out = triton_iq.gemv(self.format, flat, self.packed.reshape(self.out_features, -1))+ if out.dtype != dtype:+ out = out.to(dtype)+ elif (_GAP_FUSED and self.format in _GAP_FORMATS and flat.dtype == torch.halfand triton_gap.supported(self.format, R, K, self.out_features)):@@ -234,7 +290,7 @@ class ForeignLinear(Module):bb = _KQ_BLOCK_BYTES[self.format]assert self.packed.shape[1] == (K // 256) * bb, \f"{self.key}: packed width {self.packed.shape[1]} != K={K} ({bb}B)"- if _KQ_GEMM and R >= _KQ_GEMM_ROWS:+ if _KQ_GEMM and R >= _KQ_GEMM_ROWS + (1 if (_KQ_MROWS and self.format in _KQ_MROWS_FORMATS) else 0): # multi-row kernel covers R == 16 tooxuse = flat.half() if flat.dtype != torch.half else flatout = torch.empty((R, N), dtype=dtype, device=dev)_RCH = 2048diff --git a/exllamav3/modules/fq_moe_prefill_iq.py b/exllamav3/modules/fq_moe_prefill_iq.pynew file mode 100644index 0000000..72b0c51--- /dev/null+++ b/exllamav3/modules/fq_moe_prefill_iq.py@@ -0,0 +1,92 @@+"""Grouped prefill MoE for IQ experts (unsloth UD-IQ packs: gate/up IQ2_S, down IQ3_XXS or IQ4_XS), same flow as fq_moe_prefill_kq.moe_kq_prefill:+dequant a chunk of experts to fp16 scratch (one Triton launch per matrix kind, decode as triton_iq / gap_formats.dequant), then the fused+gate/up/SwiGLU and down GEMMs (_gmm_f16) over the rows routed to those experts. Replaces the per-expert loop (torch dequant + mm per+expert, hundreds of small launches per layer). Formats: 0 iq3_xxs, 3 iq2_s, 7 iq4_xs."""+from __future__ import annotations++import os++import torch+import triton+import triton.language as tl++from ..foreign_quant.triton_iq import _tabs, _b, _h+from .fq_moe_prefill_kq import _gmm_f16, _buf++FMT_ID = {"iq3_xxs": 0, "iq2_s": 3, "iq4_xs": 7}+_KV = {}+++def _kv(dev):+ k = str(dev)+ if k not in _KV:+ _KV[k] = torch.tensor([-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113],+ dtype=torch.float32, device=dev)+ return _KV[k]+++def _dq_iq(ptrs, out, e0, N, K, t3x, tks, t2s, kv, FMT: tl.constexpr, BN: tl.constexpr):+ """Decode super-block program_id(1) of rows tile program_id(0) of expert e0 + program_id(2) into fp16 out[e, n, k]."""+ BB: tl.constexpr = 98 if FMT == 0 else (82 if FMT == 3 else 136)+ pid_n = tl.program_id(0)+ sb = tl.program_id(1)+ ec = tl.program_id(2)+ rn = pid_n * BN + tl.arange(0, BN)+ mn = rn < N+ m2 = mn[:, None]+ e = tl.arange(0, 32)[None, :]+ w_ptr = tl.load(ptrs + e0 + ec).to(tl.pointer_type(tl.uint8))+ blk = rn.to(tl.int64) * ((K // 256) * BB) + sb * BB+ b2 = blk[:, None]+ d = _h(tl.load(w_ptr + blk, mask=mn, other=0), tl.load(w_ptr + blk + 1, mask=mn, other=0))+ d2 = d[:, None]+ o = out + (ec.to(tl.int64) * N + rn.to(tl.int64))[:, None] * K + sb * 256+ for ib in tl.static_range(8):+ if FMT == 0: # iq3_xxs+ idx = _b(w_ptr, b2 + 2 + 8 * ib + e // 4, m2)+ g = tl.load(t3x + idx * 4 + e % 4).to(tl.float32)+ aw = blk + 66 + 4 * ib+ aux = _b(w_ptr, aw, mn) | (_b(w_ptr, aw + 1, mn) << 8) | (_b(w_ptr, aw + 2, mn) << 16) | (_b(w_ptr, aw + 3, mn) << 24)+ db = d * (0.5 + ((aux >> 28) & 15).to(tl.float32)) * 0.5+ sidx = (aux[:, None] >> (7 * (e // 8))) & 127+ sg = (tl.load(tks + sidx).to(tl.int32) >> (e % 8)) & 1+ w = db[:, None] * g * (1.0 - 2.0 * sg.to(tl.float32))+ elif FMT == 3: # iq2_s+ l = e // 8+ idx = _b(w_ptr, b2 + 2 + 4 * ib + l, m2) | ((_b(w_ptr, blk + 66 + ib, mn)[:, None] << (8 - 2 * l)) & 0x300)+ g = tl.load(t2s + idx * 8 + e % 8).to(tl.float32)+ sg = (_b(w_ptr, b2 + 34 + 4 * ib + l, m2) >> (e % 8)) & 1+ sc = (_b(w_ptr, blk + 74 + ib, mn)[:, None] >> (4 * (l // 2))) & 15+ w = d2 * (0.5 + sc.to(tl.float32)) * 0.25 * g * (1.0 - 2.0 * sg.to(tl.float32))+ else: # iq4_xs: d, scales_h u16 @2, scales_l[4] @4, qs[128] @8 (sub-block ib: 16 bytes, low nibbles 0..15, high 16..31)+ sh = _b(w_ptr, blk + 2, mn) | (_b(w_ptr, blk + 3, mn) << 8)+ ls = ((_b(w_ptr, blk + 4 + ib // 2, mn) >> (4 * (ib % 2))) & 15) | (((sh >> (2 * ib)) & 3) << 4)+ dl = d * (ls - 32).to(tl.float32)+ q = (_b(w_ptr, b2 + 8 + 16 * ib + e % 16, m2) >> (4 * (e // 16))) & 15+ w = dl[:, None] * tl.load(kv + q)+ tl.store(o + 32 * ib + e, w.to(tl.float16), mask=m2)+++def moe_iq_prefill(y_sorted, gu_ptrs, dn_ptrs, a, dn, tile_e, tile_r0, offs, wrow, E, I, K, fmt_gu, fmt_dn, bm, chunk=None):+ dev = y_sorted.device+ chunk = chunk or int(os.environ.get("MCPM_FQ_PF_CHUNK", "64"))+ t3x, _, tks, _, t2s, _ = _tabs(dev)+ kv = _kv(dev)+ BNd = 32+ for e0 in range(0, E, chunk):+ ec = min(chunk, E - e0)+ wg = _buf(dev, "g", ec * I * K)+ wu = _buf(dev, "u", ec * I * K)+ wd = _buf(dev, "d", ec * K * I)+ _dq_iq[(triton.cdiv(I, BNd), K // 256, ec)](gu_ptrs, wg, e0, I, K, t3x, tks, t2s, kv, FMT=fmt_gu, BN=BNd, num_warps=4)+ _dq_iq[(triton.cdiv(I, BNd), K // 256, ec)](gu_ptrs, wu, E + e0, I, K, t3x, tks, t2s, kv, FMT=fmt_gu, BN=BNd, num_warps=4)+ _dq_iq[(triton.cdiv(K, BNd), I // 256, ec)](dn_ptrs, wd, e0, K, I, t3x, tks, t2s, kv, FMT=fmt_dn, BN=BNd, num_warps=4)+ T = tile_e.shape[0]+ BN, BK, nw, ns = 128, 64, 8, (2 if torch.version.hip else 3)+ _gmm_f16[(triton.cdiv(I, BN), T)](y_sorted, wg, wu, a, tile_e, tile_r0, offs, offs, I, K, y_sorted.stride(0),+ a.stride(0), e0, e0 + ec, SWIGLU=True, SCALE_ROWS=False,+ BM=bm, BN=BN, BK=BK, num_warps=nw, num_stages=ns)+ _gmm_f16[(triton.cdiv(K, BN), T)](a, wd, wd, dn, tile_e, tile_r0, offs, wrow, K, I, a.stride(0),+ dn.stride(0), e0, e0 + ec, SWIGLU=False, SCALE_ROWS=True,+ BM=bm, BN=BN, BK=BK, num_warps=nw, num_stages=ns)diff --git a/exllamav3/modules/gated_delta_net.py b/exllamav3/modules/gated_delta_net.pyindex 3f5c1ff..f8f1f41 100644--- a/exllamav3/modules/gated_delta_net.py+++ b/exllamav3/modules/gated_delta_net.py@@ -15,6 +15,7 @@ from ..cache import Cachefrom ..util.tensor import g_tensor_cachefrom .multilinear import SlicedMultiLinearimport os+_QZCAT = os.environ.get("EXL3_GDN_QZCAT", "1" if torch.version.hip else "0") != "0" # GGUF Q8_0 qkv + z decode in one launch (project_qkvz_q8cat)# Sliced qkv+z projection bundle at decode for the split-projection GDN (Qwen3.5 / Qwen3.8 style):# one mgemm over equal-width column slices, see attn.py. EXL3_QKV_SLICE=0 disables it@@ -1008,6 +1009,7 @@ class GatedDeltaNet(Module):self.conv1d_v_weight = self.config.stc.get_tensor(self.key_conv1d_v_weight, self.device, optional = False, allow_bf16 = True, no_defer = True)self.norm.load(device, **kwargs)self.load_local(device, **kwargs)+ self._q8cat_build()@override@@ -1023,6 +1025,7 @@ class GatedDeltaNet(Module):self.ba_weight_filled = Falseself.multi_qkvz = Noneself.prealloc_qkvz_carrier = None+ self._q8cat_w = Noneself.a_log = Noneself.dt_bias = Noneself.conv1d_weight = None@@ -1134,6 +1137,44 @@ class GatedDeltaNet(Module):return (qkv.view(bsz, seqlen, -1), z.view(bsz, seqlen, -1))+ def _q8cat_build(self):+ """GGUF Q8_0 qkv + z weights as one [nq + nz, row] tensor, both ForeignLinears re-pointed to views of it (same bytes, no+ copy kept). Done at load, before any decode graph is captured. Nothing for other formats."""+ self._q8cat_w = None+ if not _QZCAT or self.qkv_proj is None or self.z_proj is None:+ return+ from .foreign_linear import ForeignLinear+ fq, fz = self.qkv_proj, self.z_proj+ if not (isinstance(fq, ForeignLinear) and isinstance(fz, ForeignLinear) and fq.format == "q8_0" and fz.format == "q8_0"+ and fq.in_features == fz.in_features and fq.packed is not None and fz.packed is not None+ and fq.packed.device == fz.packed.device and fq.packed.dtype == torch.uint8 and fz.packed.dtype == torch.uint8):+ return+ nq, nz = fq.out_features, fz.out_features+ sq, sz = fq.packed.shape, fz.packed.shape+ cat = torch.cat([fq.packed.reshape(nq, -1), fz.packed.reshape(nz, -1)], dim = 0)+ fq.packed = cat[:nq].view(sq)+ fz.packed = cat[nq:].view(sz)+ self._q8cat_w = cat+ if not getattr(GatedDeltaNet, "_q8cat_said", False):+ GatedDeltaNet._q8cat_said = True+ print(f" -- GDN qkv + z Q8_0 decode rows concatenated ({nq} + {nz})", flush = True)++ def project_qkvz_q8cat(self, x: torch.Tensor, params: dict, qkv_dt, z_dt, bsz: int, seqlen: int):+ """GGUF Q8_0 qkv + z of one decode row in ONE fq_gemv_q8_0 launch over the rows concatenated at load (_q8cat_build): one q8_1+ quant and one launch instead of two, the same per-row dot: bit-exact. None = fall back to the two projections."""+ cat = getattr(self, "_q8cat_w", None)+ if cat is None or bsz * seqlen != 1 or not x.is_contiguous() or "capture" in params or "ovr" in params:+ return None+ fq, fz = self.qkv_proj, self.z_proj+ flat = x.reshape(1, -1)+ dq = qkv_dt or fq.out_dtype or torch.half+ if dq != (z_dt or fz.out_dtype or torch.half) or not (fq.q8_fused_gemv_ok(flat) and fz.q8_fused_gemv_ok(flat)):+ return None+ nq, nz = fq.out_features, fz.out_features+ out = torch.empty((1, nq + nz), dtype = dq, device = x.device)+ ext.fq_gemv_q8_0(flat, cat.view(nq + nz, -1, 34), out)+ return out[:, :nq].view(bsz, seqlen, nq), out[:, nq:].view(bsz, seqlen, nz)+def _ab_cat(self, x: torch.Tensor, params: dict, bsz: int, seqlen: int):"""decode b and a skinny projections in ONE launch (ext.skinny_cat_w, same per-column reduction order as the twoseparate skinny launches, bit-identical). Returns (b, a) fp32 [bsz, seqlen, heads] or None to fall back. EXL3_QWD4_ABCAT=0 = off."""@@ -1791,8 +1832,12 @@ class GatedDeltaNet(Module):else:qkv_dt = torch.half if self._pfe_f16_out(self.qkv_proj, x, params, "EXL3_PFE_QKVZ") else Nonez_dt = torch.half if self._pfe_f16_out(self.z_proj, x, params, "EXL3_PFE_QKVZ") else None- qkv = self.qkv_proj.forward(x, params, qkv_dt)- z = self.z_proj.forward(x, params, z_dt)+ qz8 = self.project_qkvz_q8cat(x, params, qkv_dt, z_dt, bsz, seqlen)+ if qz8 is not None:+ qkv, z = qz8+ else:+ qkv = self.qkv_proj.forward(x, params, qkv_dt)+ z = self.z_proj.forward(x, params, z_dt)z = z.view(bsz, seqlen, self.num_v_heads, self.v_head_dim)if not ab_first and qzab is None:_c = getattr(self, "_qd3_ba", None)@@ -1868,7 +1913,8 @@ class GatedDeltaNet(Module):_kd2 = 2 * self.k_dim_q = _mq[..., :self.k_dim]_k = _mq[..., self.k_dim:_kd2]- _mq = torch.cat([_q, _q, _k, _k, _mq[..., _kd2:]], dim=-1)+ _r = self.num_v_heads // self.num_k_heads # 2 on the 35B-A3B, 3 on the dense 27B (48 v / 16 k)+ _mq = torch.cat([_q] * _r + [_k] * _r + [_mq[..., _kd2:]], dim=-1)_nk, _kd = self.num_v_heads, self.v_dimcore_attn_out = gated_delta_rule_fn(mixed_qkv = _mq,diff --git a/exllamav3/modules/linear.py b/exllamav3/modules/linear.pyindex 1144a9a..7102be7 100644--- a/exllamav3/modules/linear.py+++ b/exllamav3/modules/linear.py@@ -41,6 +41,15 @@ def _mxfp4_dequant(blocks: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:return w.view(blocks.shape[0], -1).half()+def _mxfp4_to_gguf(blocks: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:+ """OpenAI MXFP4 (N, G, 16) blocks (byte j = elements 2j | 2j+1 << 4) + (N, G) E8M0 scales -> GGUF MXFP4 rows (N, G * 17):+ per 32-block the E8M0 byte then 16 bytes with element j in the low nibble and element j + 16 in the high one (ggml block_mxfp4)."""+ b = blocks.to(torch.uint8)+ e = torch.stack((b & 0x0F, b >> 4), dim = -1).view(b.shape[0], b.shape[1], 32) # elements in order+ q = e[..., :16] | (e[..., 16:] << 4)+ return torch.cat((scales.to(torch.uint8).unsqueeze(-1), q), dim = -1).reshape(b.shape[0], -1).contiguous()++def _scale_block(n: int, s: int, block: int | None) -> int:"""Block length along an axis of n elements covered by s scales (config block first, else exact division)."""if block and -(-n // block) == s:@@ -69,6 +78,34 @@ def apply_scale_grid(w: torch.Tensor, scale: torch.Tensor, block: tuple | None =return w * full++class _ForeignInner:+ """Linear inner over a ForeignLinear payload (NVFP4 served as stored): the ForeignLinear kernels, Linear's interface."""++ def __init__(self, fl, bias):+ self.fl, self.bias = fl, bias+ self.in_features, self.out_features = fl.in_features, fl.out_features+ self.bc = None+ self._pinned_store = None+ self.swap_device = None++ def unload(self):+ pass++ def get_tensors(self, key):+ return self.fl.get_tensors()++ def get_weight_tensor(self):+ return self.fl._dequant_rows(0, self.out_features).T++ def get_bias_tensor(self):+ return self.bias++ def forward(self, x, params, out_dtype = None):+ y = self.fl.forward(x, params, out_dtype)+ return y + self.bias if self.bias is not None else y++class Linear(Module):def __init__(@@ -201,6 +238,72 @@ class Linear(Module):return self.apply_fp8_scales_(weight, scale_inv)+ def load_nvfp4_stored_(self, key: str, dev) -> bool:+ """NVFP4 linear (ModelOpt weight / weight_scale / weight_scale_2, or compressed-tensors weight_packed / weight_scale /+ weight_global_scale divisor) kept as stored: the ForeignLinear nvfp4 kernels (fq_gemv_nvfp4 <= 16 rows) instead of the+ fp16 dequant. quant_type "nvfp4". EXL3_NVFP4_STORED=0 restores the fp16 dequant."""+ if os.environ.get("EXL3_NVFP4_STORED", "1") == "0" or self.is_sliced or self.weight_scale != 1.0 or self.alt_key and key == self.alt_key:+ return False+ stc = self.config.stc+ if not isinstance(key, str) or not stc.has_tensor(key + ".weight_scale"):+ return False+ ws = stc.get_tensor(key + ".weight_scale", dev, optional = True, no_defer = True)+ if ws is None or ws.dtype != torch.float8_e4m3fn or ws.dim() != 2:+ return False+ g = stc.get_tensor(key + ".weight_scale_2", dev, optional = True, no_defer = True)+ inv = g is None+ if inv:+ g = stc.get_tensor(key + ".weight_global_scale", dev, optional = True, no_defer = True)+ if g is None:+ return False+ wname = ".weight_packed" if stc.has_tensor(key + ".weight_packed") else ".weight"+ packed = stc.get_tensor(key + wname, dev, no_defer = True).contiguous().view(torch.uint8)+ N, K = self.out_features, self.in_features+ if tuple(packed.shape) != (N, K // 2) or tuple(ws.shape) != (N, K // 16) or K % 512:+ return False+ from .foreign_linear import ForeignLinear+ fl = ForeignLinear(self.config, self.key, K, N, "nvfp4", out_dtype = self.out_dtype)+ fl.packed, fl.scales = packed, ws.contiguous().view(torch.uint8)+ gv = float(g.float().reshape(-1)[0].item())+ fl.global_scale = 1.0 / gv if inv else gv+ bias = stc.get_tensor(key + ".bias", dev, float2half = True, optional = True, no_defer = True)+ self.used_alt_key = key == self.alt_key+ self.inner = _ForeignInner(fl, bias)+ self.quant_type = "nvfp4"+ return True++ def load_fp8_stored_(self, key: str, dev, has_scale: bool, has_scale_inv: bool) -> bool:+ """FP8 E4M3 linear kept as stored (quant_type "fp8", modules/quant/fp8.py): one byte per weight instead of the fp16 dequant.+ Per-row / per-tensor weight_scale or the weight_scale_inv block grid. EXL3_FP8_STORED=0 restores the fp16 dequant."""+ if os.environ.get("EXL3_FP8_STORED", "1") == "0" or self.is_sliced or self.weight_scale != 1.0 or not (has_scale or has_scale_inv):+ return False+ stc = self.config.stc+ w = stc.get_tensor(key + ".weight", dev, no_defer = True)+ if w.dtype != torch.float8_e4m3fn or tuple(w.shape) != (self.out_features, self.in_features):+ return False+ s = stc.get_tensor(key + (".weight_scale" if has_scale else ".weight_scale_inv"), dev, no_defer = True)+ s = (s.float() - 127.0).exp2() if s.dtype == torch.uint8 else s.float()+ N, K = w.shape+ from .quant.fp8 import LinearFP8, ok as fp8_ok+ if s.numel() == 1:+ s, grid, block = s.reshape(1).expand(N).contiguous(), False, (1, 1)+ elif s.dim() == 1 or (s.dim() == 2 and s.shape == (N, 1)):+ s, grid, block = s.reshape(N).contiguous(), False, (1, 1)+ elif s.dim() == 2:+ qb = self.quant_block_()+ block = (_scale_block(N, s.shape[0], qb[0] if qb else None), _scale_block(K, s.shape[1], qb[1] if qb else None))+ grid = True+ if not fp8_ok(N, K, grid, block):+ return False+ else:+ return False+ bias = stc.get_tensor(key + ".bias", dev, float2half = True, optional = True, no_defer = True)+ self.used_alt_key = key == self.alt_key+ self.inner = LinearFP8(K, N, w.view(torch.uint8), s, grid, block, bias, self.out_dtype, key = self.key)+ self.quant_type = "fp8"+ return True++# NVFP4: packed e2m1 (U8 [out, in/2], low nibble first) x E4M3 scale per 16 inputs x one fp32 global scale.# ModelOpt: weight / weight_scale / weight_scale_2 (multiplier); compressed-tensors: weight_packed /# weight_scale / weight_global_scale (divisor). Returns (out, in) fp16 in checkpoint orientation, or None.@@ -266,6 +369,8 @@ class Linear(Module):dev = "cpu" if self.is_sliced else self.devicepad1 = (self.out_features,) if not self.is_sliced else Nonepad2 = (self.in_features, self.out_features) if not self.is_sliced else None+ if self.load_nvfp4_stored_(key, dev):+ return Truescale_q = self.config.stc.get_tensor(key + ".scale", dev, optional = True, no_defer = True)nv = self.dequant_nvfp4_(key, dev) if scale_q is None and self.config.stc.has_tensor(key + ".weight_scale") else Noneif nv is None and scale_q is None and self.config.stc.has_tensor(key + ".weight_scale"):@@ -302,6 +407,8 @@ class Linear(Module):scale_inv = (scale_inv.float() - 127.0).exp2()if scale is not None and scale.dtype == torch.uint8:scale = (scale.float() - 127.0).exp2()+ if self.load_fp8_stored_(key, dev, scale is not None, scale_inv is not None):+ return Trueno_defer = self.no_defer_load or scale is not None or scale_inv is not None or self.weight_scale != 1.0weight = self.config.stc.get_tensor(key + ".weight", dev, float2half = True, transpose = self.transposed_load, pad_to = pad2, no_defer = no_defer)bias = self.config.stc.get_tensor(key + ".bias", dev, float2half = True, optional = True, pad_to = pad1, no_defer = no_defer)@@ -410,6 +517,22 @@ class Linear(Module):scales = scales[sl].contiguous()if bias is not None:bias = bias[sl].contiguous()+ if os.environ.get("EXL3_MXFP4_STORED", "1") != "0" and self.weight_scale == 1.0 and not self.is_sliced \+ and blocks.shape[0] <= self.out_features and blocks.shape[1] * 32 <= self.in_features and self.in_features % 32 == 0:+ # kept as stored: the ForeignLinear mxfp4 kernels (GGUF block layout, same E8M0 bytes) instead of the fp16 dequant.+ # The engine pads both dims to 128 (gpt-oss 2880 -> 2944): zero blocks / zero rows (weight 0, bias 0) fill the pad.+ from .foreign_linear import ForeignLinear+ pk = _mxfp4_to_gguf(blocks, scales)+ Kb, Kp = blocks.shape[1], self.in_features // 32+ if Kp > Kb:+ pk = torch.cat((pk, torch.zeros((pk.shape[0], (Kp - Kb) * 17), dtype = torch.uint8, device = pk.device)), dim = 1)+ if self.out_features > pk.shape[0]:+ pk = torch.cat((pk, torch.zeros((self.out_features - pk.shape[0], pk.shape[1]), dtype = torch.uint8, device = pk.device)), dim = 0)+ fl = ForeignLinear(self.config, self.key, self.in_features, self.out_features, "mxfp4", out_dtype = self.out_dtype)+ fl.packed = pk.contiguous()+ self.inner = _ForeignInner(fl, self.pad_out(bias).half() if bias is not None else None)+ self.quant_type = "mxfp4"+ return Trueweight = _mxfp4_dequant(blocks, scales)weight = weight.T.contiguous()weight = self.pad_out(weight)@@ -546,10 +669,31 @@ class Linear(Module):keys = [self.key]if self.alt_key:keys += [self.alt_key]+ if any(self.load_gguf_(k, device) for k in keys): returnif any(self.load_exl3(k) for k in keys): returnif any(self.load_fp16(k) for k in keys): returnraise ValueError(f"No tensors found for {self.key} matching supported quantization format.")+ def load_gguf_(self, key, dev) -> bool:+ """GGUF backing store (config.gguf + config.gguf_formats): a weight stored in a ggml quant format loads as a ForeignLinear+ (kernels on the stored blocks, no dequant); fp / bf16 tensors go on to load_fp16 as before."""+ g, fm = getattr(self.config, "gguf", None), getattr(self.config, "gguf_formats", None)+ if g is None or not fm or not isinstance(key, str) or self.is_sliced or self.weight_scale != 1.0:+ return False+ gname = g.name_map.get(key + ".weight")+ gname = gname[0] if isinstance(gname, tuple) else gname+ fmt = fm.get(gname) if gname else None+ if fmt is None or fmt == "fp" or fmt.startswith("unk"):+ return False+ from .foreign_linear import ForeignLinear+ fl = ForeignLinear(self.config, key, self.in_features, self.out_features, fmt, out_dtype = self.out_dtype)+ fl.load(dev)+ bias = self.config.stc.get_tensor(key + ".bias", dev, float2half = True, optional = True, no_defer = True)+ self.used_alt_key = key == self.alt_key+ self.inner = _ForeignInner(fl, bias)+ self.quant_type = fmt+ return True+@overridedef pin_linears(self):diff --git a/exllamav3/modules/mlp.py b/exllamav3/modules/mlp.pyindex 3c92e71..766f6df 100644--- a/exllamav3/modules/mlp.py+++ b/exllamav3/modules/mlp.py@@ -454,6 +454,48 @@ def _vf_plain_exl3(l, dim: int) -> bool:)+_FQ_GU_CAT = os.environ.get("EXL3_FQ_GU_CAT", "1") != "0"+++# EXL3_MOE_Q8_REUSE (default 1): the MoE shared expert reuses the routed call's q8_1(x) (only with the q8q8 path, BOLT_FQ_Q8Q8)+_Q8_REUSE = os.environ.get("EXL3_MOE_Q8_REUSE", "1") != "0" and os.environ.get("BOLT_FQ_Q8Q8", "1") != "0"+_Q8_REUSE_SAID = [False]+++def _fq_gu_cat(mlp, s, x, params = None):+ """Gate + up of a foreign Q8_0 slice in ONE fq_gemv_q8_0 at 1 row: the row-stacked [gate; up] weights cached once, one q8+ quantization of x and one launch instead of two of each. Each output row is the same dot over the same quantized x, so g and u+ are bit-identical to the two separate calls. Returns (g, u) views or None (any other case keeps the two calls)."""+ if not _FQ_GU_CAT or not hasattr(ext, "fq_gemv_q8_0"):+ return None+ gm, um = mlp.gates[s], mlp.ups[s]+ if getattr(gm, "format", None) != "q8_0" or getattr(um, "format", None) != "q8_0":+ return None+ if gm.packed is None or um.packed is None or gm.in_features != um.in_features or gm.out_features != um.out_features:+ return None+ if x.dtype != torch.half or not x.is_contiguous() or x.shape[-1] != gm.in_features or x.device != gm.packed.device:+ return None+ if (gm.out_dtype or torch.half) != torch.half or (um.out_dtype or torch.half) != torch.half:+ return None+ N, K = gm.out_features, gm.in_features+ cache = mlp.__dict__.setdefault("_fq_gu_cat_w", {})+ w = cache.get(s)+ if w is None or w[0] != gm.packed.data_ptr():+ w = (gm.packed.data_ptr(), torch.cat([gm.packed.reshape(N, -1), um.packed.reshape(N, -1)], 0).contiguous())+ cache[s] = w+ out = torch.empty((1, 2 * N), dtype = torch.half, device = x.device)+ if _Q8_REUSE and params is not None and params.get("fq_q8_x") == x.data_ptr() and hasattr(ext, "fq_gemv_q8_0_q8"):+ # q8_1(x) already in the cached scratch (written by the routed MoE call on the same x): same bytes fq_gemv_q8_0 would make+ ext.fq_gemv_q8_0_q8(ext.fq_q8_scratch(x.device.index, 1, K), w[1].reshape(2 * N, -1, 34), out)+ if not _Q8_REUSE_SAID[0]:+ _Q8_REUSE_SAID[0] = True+ print(" -- MoE shared expert reuses the routed q8_1(x)", flush = True)+ else:+ ext.fq_gemv_q8_0(x.reshape(1, K), w[1].reshape(2 * N, -1, 34), out)+ shp = x.shape[:-1] + (N,)+ return out[:, :N].view(shp), out[:, N:].view(shp)++class GatedMLP(Module):def __init__(@@ -791,8 +833,12 @@ class GatedMLP(Module):self.bc.run_bszN(xv, d.view(xv.shape))elif self.multi_gu[s] is None or bsz * q_len > 32:- g = self.gates[s].forward(x, params)- u = self.ups[s].forward(x, params)+ gu = _fq_gu_cat(self, s, x, params) if bsz * q_len == 1 else None+ if gu is not None:+ g, u = gu+ else:+ g = self.gates[s].forward(x, params)+ u = self.ups[s].forward(x, params)# nc2 S1-rest (EXL3_NC2_SILU_PAD, default off): silu_mul writes its rows at the down projection's# padded pitch, so the down GEMM skips its pad_copy_in (same values, bit-exact)a_pitch = 0diff --git a/exllamav3/modules/moe_fused.py b/exllamav3/modules/moe_fused.pyindex ae997c5..4c801de 100644--- a/exllamav3/modules/moe_fused.py+++ b/exllamav3/modules/moe_fused.py@@ -112,6 +112,8 @@ class FusedMoEHalf:return "router bias / shared post norm"if len(mlp.gates) != mlp.num_experts or len(mlp.ups) != mlp.num_experts or len(mlp.downs) != mlp.num_experts:return "experts are not one linear each"+ if any(getattr(getattr(m, "inner", None), "K", None) is None for m in (mlp.gates[0], mlp.ups[0], mlp.downs[0])):+ return "experts are not EXL3 trellis linears (e.g. GGUF ForeignLinear experts)"return _k6s8_support_reason(mlp)def __init__(self, block):diff --git a/exllamav3/modules/ngram_embedding.py b/exllamav3/modules/ngram_embedding.pyindex 0f5fd08..e5601d8 100644--- a/exllamav3/modules/ngram_embedding.py+++ b/exllamav3/modules/ngram_embedding.py@@ -204,8 +204,45 @@ class NGramEmbedding(Module):stc.release_file(f)@override+ def _load_gguf(self, device) -> bool:+ """GGUF store: IQ4_NL table rows gathered from the GGUF file (mode iq4nl_disk), aux arrays from the metadata."""+ g = getattr(self.config, "gguf", None)+ if g is None:+ return False+ gname = g.name_map.get(f"{self.key}.weight")+ if gname is None or gname not in g.infos:+ return False+ ty, dims, off = g.infos[gname]+ assert ty == 20 and dims[0] == ROW_DIM, f"{gname}: expected IQ4_NL rows of {ROW_DIM}, got type {ty} dims {dims}"+ arch = g.meta["general.architecture"]+ meta = lambda k: torch.tensor([int(v) for v in g.meta[f"{arch}.ple.{k}"]], dtype = torch.int64)+ self.head_offsets = meta("head_offsets").contiguous()+ self.head_vocab_sizes = meta("head_vocab_sizes").contiguous()+ self.layer_multipliers = meta("layer_multipliers").contiguous()+ assert self.head_offsets.shape[0] == self.num_heads, (self.head_offsets.shape, self.num_heads)+ self.num_rows = dims[1]+ self.rows_per_shard = self.num_rows+ fi, o = off >> 48, off & ((1 << 48) - 1)+ self.handles = [DiskTensorHandle(key = self.key, filename = g.paths[fi], abs_offset = g.bases[fi] + o,+ shape = [self.num_rows, (ROW_DIM // 32) * 18], dtype = torch.uint8)]+ self.tables = None+ self.mode = "iq4nl_disk"+ self._row_dtype = torch.uint8+ print(f"[ngram] GGUF table {gname}: {self.num_rows} IQ4_NL rows of {ROW_DIM}, gathered from disk", flush = True)+ return True++ def _row_spec(self):+ """(words per staged row, staged dtype) for the current mode."""+ if self.mode.startswith("trellis"):+ return words_per_row(self.K), torch.int16+ if self.mode == "iq4nl_disk":+ return (ROW_DIM // 32) * 18, torch.uint8+ return ROW_DIM, self._row_dtype+def load(self, device: torch.device, **kwargs):self.device = device+ if self._load_gguf(device):+ returnstc = self.config.stcparent = self.key.rsplit(".", 1)[0]@@ -398,7 +435,10 @@ class NGramEmbedding(Module):Reference form of the row pipeline (torch codec); forward() runs the fast path."""uids_cpu = uids.to("cpu", torch.int64)raw = self._fetch_packed(uids_cpu).to(self.device)- if self.mode.startswith("trellis"):+ if self.mode == "iq4nl_disk":+ from ..foreign_quant.gap_formats import dequant as _gap_dequant+ rows = _gap_dequant("iq4_nl", raw).float()+ elif self.mode.startswith("trellis"):heads = (torch.searchsorted(self.head_offsets.to(self.device),uids.to(self.device, torch.int64),right = True) - 1).clamp(0, self.num_heads - 1)@@ -583,11 +623,8 @@ class NGramEmbedding(Module):history = history.to("cpu", torch.int64).contiguous().clone()if self._match(history) is not None:return- trellis = self.mode.startswith("trellis")- pin = self._acquire_pin(- bsz * out_len * self.num_heads,- words_per_row(self.K) if trellis else ROW_DIM,- torch.int16 if trellis else self._row_dtype)+ rw, rdt = self._row_spec()+ pin = self._acquire_pin(bsz * out_len * self.num_heads, rw, rdt)for h in self.handles or []:h._ensure_open() # lazy open isn't thread-safe; do it here, not on the workerif self._executor is None:@@ -605,8 +642,7 @@ class NGramEmbedding(Module):if pin is None:pin = self._warm_pin = _PinSet()n = (history.shape[1] - self.context_len) * self.num_heads- trellis = self.mode.startswith("trellis")- pin.grow(n, words_per_row(self.K) if trellis else ROW_DIM, torch.int16 if trellis else self._row_dtype)+ pin.grow(n, *self._row_spec())self._stage(history, pin)def warm(self, history: torch.Tensor):@@ -650,8 +686,7 @@ class NGramEmbedding(Module):H = self.num_headsn = bsz * out_len * Hdev = self.device- row_words = words_per_row(self.K) if trellis else ROW_DIM- row_dtype = torch.int16 if trellis else self._row_dtype+ row_words, row_dtype = self._row_spec()entry = self._match(ids)if entry is not None:@@ -670,6 +705,9 @@ class NGramEmbedding(Module):heads_d = pin.heads[:U].to(dev, non_blocking = True)rows = torch.empty((U, ROW_DIM), dtype = torch.half, device = dev)ext.ngram_dequant(packed_d, self.K, heads_d, self.head_bias, rows)+ elif self.mode == "iq4nl_disk":+ from ..foreign_quant.gap_formats import dequant as _gap_dequant+ rows = _gap_dequant("iq4_nl", packed_d).float()else:rows = packed_d.float()if rows.is_cuda:diff --git a/exllamav3/modules/quant/fp16.py b/exllamav3/modules/quant/fp16.pyindex 70963da..3f48e8f 100644--- a/exllamav3/modules/quant/fp16.py+++ b/exllamav3/modules/quant/fp16.py@@ -23,6 +23,11 @@ def _skinny_rows_ok(rows: int, n: int) -> bool:from ...util.tensor import to2from ...util import first_not_none+def _f16gemv_ok(R, K, N):+ from ...foreign_quant import triton_f16gemv+ return triton_f16gemv.supported(R, K, N)++class LinearFP16:quant_type: str = "fp16"@@ -108,7 +113,12 @@ class LinearFP16:from ...util.tensor import g_tensor_cacheweight = g_tensor_cache.get_bucketed(x.device, pinned.numel(), pinned.dtype, "fp16_pin_stage").view(pinned.shape)weight.copy_(pinned, non_blocking = True)- if (_hip and x.dtype == torch.half and dtype == torch.half and x.shape[0] >= 256+ if (_hip and x.dtype == torch.half and dtype == torch.half and pinned is None and weight.is_contiguous()+ and _f16gemv_ok(x.shape[0], x.shape[1], self.out_features)):+ # decode rows on ROCm: Triton GEMV instead of hipBLAS (small / medium N run far under the read roof there)+ from ...foreign_quant import triton_f16gemv+ triton_f16gemv.gemv(x.contiguous(), weight, y)+ elif (_hip and x.dtype == torch.half and dtype == torch.half and x.shape[0] >= 256and _os.environ.get("EXL3_DENSE_GEMM_TUNE", "1") != "0"and weight.is_contiguous() and x.is_contiguous()):# prefill: ext.hgemm's tuned rocBLAS path (see hgemm.cu dtune); torch's hipBLASLtdiff --git a/exllamav3/modules/quant/fp8.py b/exllamav3/modules/quant/fp8.pynew file mode 100644index 0000000..f55376d--- /dev/null+++ b/exllamav3/modules/quant/fp8.py@@ -0,0 +1,225 @@+"""FP8 (E4M3) linears served as stored: per-row / per-tensor scale (`weight_scale`) or the 2D block grid (`weight_scale_inv`,+DeepSeek / Qwen-FP8 / GLM / MiniMax layout). One byte per weight is read instead of the two of the fp16 dequant.++Decode GEMV (<= MAX_ROWS rows): one Triton kernel for ROCm and CUDA (no extension build). E4M3 -> fp16 is exact by bit placement:+half(bits = sign << 8 | (b & 0x7F) << 7) * 256 (normals and subnormals; the 0x7F NaN code is never stored by real checkpoints).+With the block grid, BN rows of a tile share one block row and each BK chunk one block column, so the block scale is one+scalar per (tile, chunk) applied to the chunk's partial sum. Wider batches: fp16 dequant of the matrix + matmul.+"""+from __future__ import annotations++import torch+import triton+import triton.language as tl++MAX_ROWS = 16+MOE_BN = 8 # grouped expert GEMV (moe_tiles.py 11/11, Qwen3-30B-A3B shapes, 8 slots): 79 / 185 GB/s vs 66 / 146 at BN 64+BN, BK = 64, 128 # Strix 27B shapes, 1 row (fp8_tiles.py 11/11): 170-190 GB/s vs 102-162 at BN 32+++def _gemv_fp8(x_ptr, q_ptr, s_ptr, y_ptr, R, K, N, S_COLS, GRID: tl.constexpr, BO: tl.constexpr, BI: tl.constexpr,+ BN: tl.constexpr, BK: tl.constexpr, RP: tl.constexpr):+ pid = tl.program_id(0)+ rn = pid * BN + tl.arange(0, BN)+ mn = rn < N+ rr = tl.arange(0, RP)+ mr = rr < R+ acc = tl.zeros((RP, BN), dtype=tl.float32)+ for k0 in range(0, K, BK):+ rk = k0 + tl.arange(0, BK)+ mk = rk < K+ b = tl.load(q_ptr + rn[:, None].to(tl.int64) * K + rk[None, :], mask=mn[:, None] & mk[None, :], other=0).to(tl.int16)+ h = (((b & 0x80) << 8) | ((b & 0x7F) << 7)).to(tl.float16, bitcast=True) * 256.0+ xv = tl.load(x_ptr + rr[:, None] * K + rk[None, :], mask=mr[:, None] & mk[None, :], other=0.0)+ part = tl.dot(xv, tl.trans(h), out_dtype=tl.float32)+ if GRID:+ part = part * tl.load(s_ptr + ((pid * BN) // BO) * S_COLS + k0 // BI)+ acc += part+ if not GRID:+ acc = acc * tl.load(s_ptr + rn, mask=mn, other=0.0)[None, :]+ tl.store(y_ptr + rr[:, None] * N + rn[None, :], acc, mask=mr[:, None] & mn[None, :])+++def _gemv_fp8_moe(x_ptr, qtab, stab, sel_ptr, y_ptr, K, N, S_COLS, XDIV, GRID: tl.constexpr, BO: tl.constexpr, BI: tl.constexpr,+ BN: tl.constexpr, BK: tl.constexpr):+ """Grouped decode GEMV over routed experts: program (tile, slot) computes y[slot, tile] = x[slot // XDIV] . W[sel[slot]]^T,+ the expert's bytes and scales found through pointer tables (qtab / stab int64 = data_ptr of each expert)."""+ pid = tl.program_id(0)+ slot = tl.program_id(1)+ e = tl.load(sel_ptr + slot).to(tl.int64)+ q_ptr = tl.load(qtab + e).to(tl.pointer_type(tl.uint8))+ s_ptr = tl.load(stab + e).to(tl.pointer_type(tl.float32))+ xr = x_ptr + (slot // XDIV).to(tl.int64) * K+ rn = pid * BN + tl.arange(0, BN)+ mn = rn < N+ acc = tl.zeros((BN,), dtype=tl.float32)+ for k0 in range(0, K, BK):+ rk = k0 + tl.arange(0, BK)+ mk = rk < K+ b = tl.load(q_ptr + rn[:, None].to(tl.int64) * K + rk[None, :], mask=mn[:, None] & mk[None, :], other=0).to(tl.int16)+ h = ((((b & 0x80) << 8) | ((b & 0x7F) << 7)).to(tl.float16, bitcast=True) * 256.0).to(tl.float32)+ xv = tl.load(xr + rk, mask=mk, other=0.0).to(tl.float32)+ part = tl.sum(h * xv[None, :], axis=1)+ if GRID:+ part = part * tl.load(s_ptr + ((pid * BN) // BO) * S_COLS + k0 // BI)+ acc += part+ if not GRID:+ acc = acc * tl.load(s_ptr + rn, mask=mn, other=0.0)+ tl.store(y_ptr + slot.to(tl.int64) * N + rn, acc, mask=mn)+++def moe_gemv(x, qtab, stab, sel, N, K, grid, block, xdiv, s_cols):+ """x half [rows, K]; sel int [slots] (expert of each slot); input row of slot = slot // xdiv -> float32 [slots, N]."""+ S = sel.numel()+ y = torch.empty((S, N), dtype=torch.float32, device=x.device)+ _gemv_fp8_moe[(triton.cdiv(N, MOE_BN), S)](x, qtab, stab, sel, y, K, N, s_cols, xdiv, GRID=grid, BO=block[0], BI=block[1],+ BN=MOE_BN, BK=BK, num_warps=2)+ return y+++def _fp8_moe_gu(x_ptr, gq, gs, uq, us, sel_ptr, y_ptr, K, N, S_COLS, XDIV, GRID: tl.constexpr, BO: tl.constexpr, BI: tl.constexpr,+ BN: tl.constexpr, BK: tl.constexpr):+ """gate and up of every routed slot in ONE launch: tiles [0, T) are gate, [T, 2T) up; y [slots, 2N] fp32 (gate | up)."""+ pid = tl.program_id(0)+ slot = tl.program_id(1)+ T = tl.cdiv(N, BN)+ is_up = pid >= T+ tile = pid - T * is_up.to(tl.int32)+ e = tl.load(sel_ptr + slot).to(tl.int64)+ q_ptr = tl.where(is_up, tl.load(uq + e), tl.load(gq + e)).to(tl.pointer_type(tl.uint8))+ s_ptr = tl.where(is_up, tl.load(us + e), tl.load(gs + e)).to(tl.pointer_type(tl.float32))+ xr = x_ptr + (slot // XDIV).to(tl.int64) * K+ rn = tile * BN + tl.arange(0, BN)+ mn = rn < N+ acc = tl.zeros((BN,), dtype=tl.float32)+ for k0 in range(0, K, BK):+ rk = k0 + tl.arange(0, BK)+ mk = rk < K+ b = tl.load(q_ptr + rn[:, None].to(tl.int64) * K + rk[None, :], mask=mn[:, None] & mk[None, :], other=0).to(tl.int16)+ h = ((((b & 0x80) << 8) | ((b & 0x7F) << 7)).to(tl.float16, bitcast=True) * 256.0).to(tl.float32)+ xv = tl.load(xr + rk, mask=mk, other=0.0).to(tl.float32)+ part = tl.sum(h * xv[None, :], axis=1)+ if GRID:+ part = part * tl.load(s_ptr + ((tile * BN) // BO) * S_COLS + k0 // BI)+ acc += part+ if not GRID:+ acc = acc * tl.load(s_ptr + rn, mask=mn, other=0.0)+ tl.store(y_ptr + slot.to(tl.int64) * (2 * N) + N * is_up.to(tl.int64) + rn, acc, mask=mn)+++def _fp8_moe_down(gu_ptr, dq, ds, sel_ptr, w_ptr, y_ptr, I, N, S_COLS, S, GRID: tl.constexpr, BO: tl.constexpr, BI: tl.constexpr,+ BN: tl.constexpr, BK: tl.constexpr):+ """down projection of the S slots of row r with silu(gate) * up staged on the fly and the routing-weighted fold: y [R, N] fp32."""+ pid = tl.program_id(0)+ r = tl.program_id(1)+ rn = pid * BN + tl.arange(0, BN)+ mn = rn < N+ out = tl.zeros((BN,), dtype=tl.float32)+ for j in range(0, S):+ slot = r * S + j+ e = tl.load(sel_ptr + slot).to(tl.int64)+ wt = tl.load(w_ptr + slot).to(tl.float32)+ q_ptr = tl.load(dq + e).to(tl.pointer_type(tl.uint8))+ s_ptr = tl.load(ds + e).to(tl.pointer_type(tl.float32))+ gr = gu_ptr + slot.to(tl.int64) * (2 * I)+ acc = tl.zeros((BN,), dtype=tl.float32)+ for k0 in range(0, I, BK):+ rk = k0 + tl.arange(0, BK)+ mk = rk < I+ g = tl.load(gr + rk, mask=mk, other=0.0)+ u = tl.load(gr + I + rk, mask=mk, other=0.0)+ a = (g / (1.0 + tl.exp(-g)) * u).to(tl.float16).to(tl.float32) # same fp16 rounding of the activation as the torch path+ b = tl.load(q_ptr + rn[:, None].to(tl.int64) * I + rk[None, :], mask=mn[:, None] & mk[None, :], other=0).to(tl.int16)+ h = ((((b & 0x80) << 8) | ((b & 0x7F) << 7)).to(tl.float16, bitcast=True) * 256.0).to(tl.float32)+ part = tl.sum(h * a[None, :], axis=1)+ if GRID:+ part = part * tl.load(s_ptr + ((pid * BN) // BO) * S_COLS + k0 // BI)+ acc += part+ if not GRID:+ acc = acc * tl.load(s_ptr + rn, mask=mn, other=0.0)+ out += wt * acc+ tl.store(y_ptr + r.to(tl.int64) * N + rn, out, mask=mn)+++def moe_fused(h, tabs, sel, wts, I, K, grid, block, S, sc_gu, sc_d):+ """Routed sum of a SwiGLU FP8 MoE layer in two launches: h half [R, K], sel / wts [R * S] -> float32 [R, K]."""+ gq, gs, uq, us, dq, ds = tabs+ R = h.shape[0]+ gu = torch.empty((R * S, 2 * I), dtype=torch.float32, device=h.device)+ _fp8_moe_gu[(2 * triton.cdiv(I, MOE_BN), R * S)](h, gq, gs, uq, us, sel, gu, K, I, sc_gu, S, GRID=grid, BO=block[0], BI=block[1],+ BN=MOE_BN, BK=BK, num_warps=2)+ y = torch.empty((R, K), dtype=torch.float32, device=h.device)+ _fp8_moe_down[(triton.cdiv(K, MOE_BN), R)](gu, dq, ds, sel, wts, y, I, K, sc_d, S, GRID=grid, BO=block[0], BI=block[1],+ BN=MOE_BN, BK=BK, num_warps=2)+ return y+++def gemv(x: torch.Tensor, q: torch.Tensor, s: torch.Tensor, grid: bool, block: tuple[int, int]) -> torch.Tensor:+ """x half [R, K] (R <= MAX_ROWS), q uint8 [N, K], s float32 [N] (per row) or [ceil(N/bo), ceil(K/bi)] (grid) -> float32 [R, N]."""+ R, K = x.shape+ N = q.shape[0]+ y = torch.empty((R, N), dtype=torch.float32, device=x.device)+ _gemv_fp8[(triton.cdiv(N, BN),)](x, q, s, y, R, K, N, s.shape[1] if grid else 1, GRID=grid, BO=block[0], BI=block[1],+ BN=BN, BK=BK, RP=16, num_warps=4)+ return y+++def ok(N: int, K: int, grid: bool, block: tuple[int, int]) -> bool:+ """The kernel's tiling fits this matrix: a tile's rows share one block row, a K chunk one block column."""+ return not grid or (block[0] % BN == 0 and block[1] % BK == 0)+++def dequant(q: torch.Tensor, s: torch.Tensor, grid: bool, block: tuple[int, int]) -> torch.Tensor:+ """fp16 [N, K] of the stored matrix (reference and the wide-batch path)."""+ w = q.view(torch.float8_e4m3fn).to(torch.float32)+ if grid:+ N, K = q.shape+ s = s.repeat_interleave(block[0], 0)[:N].repeat_interleave(block[1], 1)[:, :K]+ w = w * s+ else:+ w = w * s[:, None]+ return w.half()+++class LinearFP8:+ """Inner of a Linear (quant_type "fp8") over the stored E4M3 bytes, checkpoint orientation [out, in]."""++ def __init__(self, in_features, out_features, q, s, grid, block, bias, out_dtype, key=None):+ self.in_features, self.out_features = in_features, out_features+ self.q, self.s, self.grid, self.block = q.contiguous(), s.float().contiguous(), grid, tuple(block)+ self.bias, self.out_dtype, self.key = bias, out_dtype, key+ self.bc = None+ self._pinned_store = None+ self.swap_device = None++ def unload(self):+ pass++ def get_tensors(self, key: str):+ t = {f"{key}.weight": self.q, f"{key}.weight_scale{'_inv' if self.grid else ''}": self.s}+ if self.bias is not None:+ t[f"{key}.bias"] = self.bias+ return t++ def get_weight_tensor(self) -> torch.Tensor:+ return dequant(self.q, self.s, self.grid, self.block).T++ def get_bias_tensor(self):+ return self.bias++ def forward(self, x: torch.Tensor, params: dict, out_dtype: torch.dtype | None = None) -> torch.Tensor:+ out_shape = x.shape[:-1] + (self.out_features,)+ x = x.reshape(-1, x.shape[-1])+ dtype = out_dtype or self.out_dtype or torch.half+ xh = x if x.dtype == torch.half else x.half()+ if xh.shape[0] <= MAX_ROWS:+ y = gemv(xh.contiguous(), self.q, self.s, self.grid, self.block)+ else:+ y = torch.matmul(xh, dequant(self.q, self.s, self.grid, self.block).T)+ if self.bias is not None:+ y = y + self.bias+ return y.to(dtype).view(out_shape)diff --git a/exllamav3/version.py b/exllamav3/version.pyindex 15f0ae6..bae6b8a 100644--- a/exllamav3/version.py+++ b/exllamav3/version.py@@ -1 +1 @@-__version__ = "1.8.16"+__version__ = "1.8.17"diff --git a/tests/test_dense_iq_q8.py b/tests/test_dense_iq_q8.pynew file mode 100644index 0000000..97556c9--- /dev/null+++ b/tests/test_dense_iq_q8.py@@ -0,0 +1,43 @@+"""Single-row q8_1 dp4a GEMV for dense IQ3_XXS / IQ2_S / IQ3_S (fq_gemv_iq3_xxs_q8 / fq_gemv_iq2_s_q8 / fq_gemv_iq3_s_q8, ggml vecdotq ports)+vs the torch reference (gap_formats.dequant @ x in fp32) on real rows of a GGUF (default: the 8B UD-IQ3_XXS, first tensor of each type).+q8_1 activations -> relative error ~0.5 %; a wrong port gives errors of order 1. Usage: python tests/test_dense_iq_q8.py [GGUF]"""+import os, sys++import numpy as np+import torch++sys.path.insert(0, "tests")+from test_moe_iq_q8 import index # noqa: E402++import exllamav3_ext as ext # noqa: E402+from exllamav3.foreign_quant import gap_formats # noqa: E402++GGUF = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("DENSE_IQ_GGUF", "model.gguf")+TYPES = {18: ("iq3_xxs", 98, "fq_gemv_iq3_xxs_q8"), 22: ("iq2_s", 82, "fq_gemv_iq2_s_q8"), 21: ("iq3_s", 110, "fq_gemv_iq3_s_q8")}+++def test_dense_iq_q8_matches_reference():+ f, infos, base = index(GGUF)+ worst = 0.0+ for t, (fmt, bb, fn) in TYPES.items():+ name = next(n for n, v in infos.items() if v[1] == t and n.endswith(".weight") and len(v[0]) == 2)+ dims, _, off = infos[name]+ K, N = dims[0], dims[1]+ n = min(N, 1024)+ f.seek(base + off)+ w = torch.from_numpy(np.frombuffer(f.read(n * (K // 256) * bb), dtype=np.uint8).reshape(n, -1).copy()).cuda()+ x = (torch.randn(1, K, generator=torch.Generator().manual_seed(t)) * 0.5).half().cuda()+ ref = x.float() @ gap_formats.dequant(fmt, w).float().reshape(n, K).t()+ out = torch.empty((1, n), dtype=torch.half, device="cuda")+ qb = ext.fq_q8_scratch(torch.cuda.current_device(), 1, K)+ ext.fq_quant_q8_1_rows(x, qb)+ getattr(ext, fn)(qb, w, out)+ rel = float((out.float() - ref).norm() / ref.norm())+ print(f"{name} {fmt} [{n}, {K}] rel err {rel:.4f}")+ worst = max(worst, rel)+ assert worst < 0.02, f"relative error {worst:.4f}"+++if __name__ == "__main__":+ test_dense_iq_q8_matches_reference()+ print("PASS")diff --git a/tests/test_iq3xxs_q8.py b/tests/test_iq3xxs_q8.pynew file mode 100644index 0000000..16ddcc6--- /dev/null+++ b/tests/test_iq3xxs_q8.py@@ -0,0 +1,70 @@+"""IQ3_XXS q8_1 dp4a GEMV (fq_gemv_iq3_xxs_q8, port of ggml vec_dot_iq3_xxs_q8_1) vs the torch reference (gap_formats.dequant @ x in fp32)+on real IQ3_XXS rows of a GGUF (default: the 8B UD-IQ3_XXS ffn_gate of layer 0). The kernel quantizes x to q8_1 like llama.cpp, so it is+compared by relative error; the Triton decode (fp16 activations) is printed as the second reference. A wrong port (layout, signs, scale)+gives errors of order 1. Usage: python tests/test_iq3xxs_q8.py [GGUF]"""+import os, struct, sys++import numpy as np+import torch++import exllamav3_ext as ext+from exllamav3.foreign_quant import gap_formats, triton_iq++GGUF = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("IQ3XXS_GGUF", "model.gguf")+SZ = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}+++def tensor(path, want):+ f = open(path, "rb")+ u32 = lambda: struct.unpack("<I", f.read(4))[0]; u64 = lambda: struct.unpack("<Q", f.read(8))[0]+ def s(): return f.read(u64()).decode()+ def skip(t):+ if t == 8: f.seek(u64(), 1)+ elif t == 9:+ at, n = u32(), u64()+ if at in SZ: f.seek(SZ[at] * n, 1)+ else:+ for _ in range(n): skip(at)+ else: f.seek(SZ[t], 1)+ assert f.read(4) == b"GGUF"; u32(); nt = u64(); nkv = u64(); align = 32+ for _ in range(nkv):+ k = s(); t = u32()+ if k == "general.alignment": align = u32(); continue+ skip(t)+ infos = []+ for _ in range(nt):+ n = s(); nd = u32(); dims = [u64() for _ in range(nd)]; t = u32(); off = u64(); infos.append((n, dims, t, off))+ base = (f.tell() + align - 1) // align * align+ for n, dims, t, off in infos:+ if n == want:+ assert t == 18, f"{n}: type {t}, not IQ3_XXS"+ K, N = dims[0], dims[1]+ f.seek(base + off)+ return np.frombuffer(f.read(N * (K // 256) * 98), dtype=np.uint8).reshape(N, -1), K, N+ raise KeyError(want)+++def test_iq3xxs_q8_matches_reference():+ raw, K, N = tensor(GGUF, "blk.0.ffn_gate.weight")+ n = min(N, 1024)+ w = torch.from_numpy(raw[:n].copy()).cuda()+ g = torch.Generator(device="cpu").manual_seed(0)+ worst = 0.0+ for R in (1, 4, 8):+ x = (torch.randn(R, K, generator=g) * 0.5).half().cuda()+ ref = x.float() @ gap_formats.dequant("iq3_xxs", w).float().reshape(n, K).t()+ out = torch.empty((R, n), dtype=torch.half, device="cuda")+ qb = ext.fq_q8_scratch(torch.cuda.current_device(), R, K)+ ext.fq_quant_q8_1_rows(x, qb)+ ext.fq_gemv_iq3_xxs_q8(qb, w, out)+ rel = float((out.float() - ref).norm() / ref.norm())+ tri = triton_iq.gemv("iq3_xxs", x, w)+ rel_t = float((tri.float() - ref).norm() / ref.norm())+ print(f"R={R} rel err q8 kernel {rel:.4f} triton {rel_t:.4f}")+ worst = max(worst, rel)+ assert worst < 0.02, f"relative error {worst:.4f} (q8_1 activations alone give ~0.005)"+++if __name__ == "__main__":+ test_iq3xxs_q8_matches_reference()+ print("PASS")diff --git a/tests/test_kq_gemv_mrows.py b/tests/test_kq_gemv_mrows.pynew file mode 100644index 0000000..017f7f8--- /dev/null+++ b/tests/test_kq_gemv_mrows.py@@ -0,0 +1,130 @@+#!/usr/bin/env python3+"""Q4_K / Q6_K multi-row decode GEMV (x-rows 2..16): output row m must equal the one-row kernel's output for x-row m BIT FOR BIT,+for every row count R = 1..16, every launch shape (output rows per block, x-rows per pass), half and float output, row-slice views,+and the fallbacks (K not a multiple of 256 is not representable here; a base pointer off by one byte falls back to the v1 kernel).+Also checks that BOLT_FQ_KQ_MROWS=0 (old per-row launch) gives the same values, so batch composition never changes an output.+Mode "wmma" (gfx11 HIP): BOLT_FQ_KQ_WMMA=1 runs the WMMA kernel (fq_kq_wmma.cuh) for every eligible case (Q4_K, K >= 4096, aligned); every other case+falls back to the generic multi-row kernel inside the same launch, so all cases must still match the one-row kernel. Mode "auto" leaves the+variable unset (the default dispatch rule picks WMMA or the generic kernel per shape). The "mrows" mode pins BOLT_FQ_KQ_WMMA=0 so that it keeps+testing the generic kernel.+usage: python tests/test_kq_gemv_mrows.py (needs a CUDA / HIP GPU and the built extension)"""+import os, subprocess, sys++BB = {"q4_k": 144, "q6_k": 210}+# (fmt, N, K): odd N (N % WROWS != 0), small K (nt padded to 32), K = 12288 (3 chunks per lane), K = 4096, lm_head-like N+CASES = [("q4_k", 1, 256), ("q4_k", 3, 512), ("q4_k", 37, 1024), ("q4_k", 1000, 4096), ("q4_k", 4096, 12288), ("q4_k", 5, 2048),+ ("q4_k", 12288, 4096), ("q4_k", 1024, 4096),+ ("q6_k", 1, 256), ("q6_k", 3, 512), ("q6_k", 37, 1024), ("q6_k", 1000, 4096), ("q6_k", 4096, 12288), ("q6_k", 5, 2048),+ ("q6_k", 151936, 4096)]+# shapes of the 8B decode GEMVs and the WMMA edge cases (K = 6144: 1.5 windows per lane; N = 4096 x 4096 / 12288 x 4096 / 4096 x 12288; lm_head)+WMMA_CASES = [("q4_k", 4096, 4096), ("q4_k", 100, 6144), ("q4_k", 151936, 4096), ("q6_k", 4096, 4096), ("q6_k", 12288, 4096),+ ("q4_k", 33, 4096), ("q4_k", 1024, 4096), ("q4_k", 3000, 8192), ("q6_k", 100, 6144)]+CONFIGS = [(0, 0, 0), (1, 2, 1), (1, 4, 1), (1, 8, 1), (1, 16, 1), (2, 2, 1), (2, 4, 1), (2, 8, 1), (4, 2, 1), (4, 4, 1),+ (1, 2, 2), (1, 4, 2), (2, 2, 2), (2, 4, 2)] # (BOLT_FQ_KQ_MR_ROWS, BOLT_FQ_KQ_MR_RT, BOLT_FQ_KQ_MR_WT), 0 = default+RS = list(range(1, 17))+++def child(mode):+ import torch+ from exllamav3.ext import exllamav3_ext as ext+ if mode in ("wmma", "auto") and not torch.version.hip:+ print(f"child {mode}: skipped (not a HIP build)", flush=True); sys.exit(0)+ bad = [0]; n = [0]++ def gemv(fmt, w, x, dt):+ R = x.shape[0]+ qb = ext.fq_q8_scratch(0, R, x.shape[1])+ ext.fq_quant_q8_1_rows(x, qb)+ out = torch.empty((R, w.shape[0]), device="cuda", dtype=dt)+ getattr(ext, f"fq_gemv_{fmt}_q8")(qb, w, out)+ return out++ def check(name, got, ref):+ n[0] += 1+ if not torch.equal(got, ref):+ print("MISMATCH", name, flush=True); bad[0] += 1++ # the test is evidence only if the multi-row kernel really runs (every fallback gives the same values): look at the launched kernels+ from torch.profiler import profile, ProfilerActivity+ for fmt in ("q4_k", "q6_k"):+ w = torch.randint(0, 256, (256, 16 * BB[fmt]), dtype=torch.uint8, device="cuda")+ w.view(256, 16, BB[fmt])[:, :, 0:4 if fmt == "q4_k" else 0] = 0+ x = torch.randn((8, 4096), device="cuda").half()+ gemv(fmt, w, x, torch.half); torch.cuda.synchronize()+ with profile(activities=[ProfilerActivity.CUDA]) as prof:+ gemv(fmt, w, x, torch.half); torch.cuda.synchronize()+ names = [e.key for e in prof.key_averages()]+ ran = any("fq_gemv_kq_mrows_kernel" in k for k in names)+ ran_wmma = any("fq_gemv_kq_wmma" in k for k in names)+ if not names: # torch.profiler sees no kernel at all (ROCm): nothing to check here+ print(f"kernel check {fmt} mode {mode}: skipped, the profiler returned no kernel (check with rocprofv3 --kernel-trace)", flush=True)+ continue+ n[0] += 1+ if ran != (mode == "mrows") or (mode == "wmma" and not ran_wmma):+ print(f"MISMATCH kernel check {fmt} mode {mode}: multi-row kernel ran = {ran}, wmma ran = {ran_wmma}; kernels {names}", flush=True); bad[0] += 1+ else:+ print(f"kernel check {fmt} mode {mode}: multi-row kernel ran = {ran}, wmma ran = {ran_wmma}", flush=True)+ for fmt, N, K in (CASES + WMMA_CASES if mode in ("wmma", "auto") else CASES):+ nb = K // 256+ for variant in ("aligned", "slice", "odd"):+ if variant == "odd" and N > 5000:+ continue+ off = 3 if variant == "slice" else 0+ g = torch.Generator(device="cuda").manual_seed(N * 7919 + K + off)+ w = torch.randint(0, 256, (N + off, nb, BB[fmt]), dtype=torch.uint8, device="cuda", generator=g)+ h = (torch.rand((N + off, nb, 2), device="cuda", generator=g) * 0.002 + 0.0001).half().view(torch.uint8)+ if fmt == "q4_k":+ w[:, :, 0:4] = h+ else:+ w[:, :, 208:210] = h[:, :, 0:2]+ wp = w.reshape(N + off, nb * BB[fmt])[off:]+ if variant == "odd": # base pointer 1 byte off: every kernel falls back to v1 (same values)+ buf = torch.empty(wp.numel() + 1, dtype=torch.uint8, device="cuda")+ buf[1:] = wp.reshape(-1)+ wp = buf[1:].reshape(N, nb * BB[fmt])+ assert wp.data_ptr() % 2 == 1+ xs = (torch.randn((16, K), device="cuda", generator=g) * 3).half()+ xs[5] = 0 # all-zero row+ xs[9] *= 40 # large magnitudes+ xs[11, ::7] = 0+ for dt in (torch.half, torch.float):+ tag = f"{fmt}|N{N}|K{K}|{variant}|{dt}"+ ref = torch.cat([gemv(fmt, wp, xs[m:m + 1], dt) for m in range(16)]) # one x-row per call: the one-row kernel+ if dt == torch.float and not torch.isfinite(ref).all(): # half output may overflow to inf on the x40 row (equal bit for bit all the same)+ print("NONFINITE", tag); bad[0] += 1+ if mode in ("wmma", "auto"):+ for R in RS:+ check(f"{tag}|R{R}|{mode}", gemv(fmt, wp, xs[:R].contiguous(), dt), ref[:R])+ elif mode == "mrows":+ cfgs = CONFIGS if N <= 5000 else [(0, 0, 0), (1, 8, 1), (2, 4, 2)]+ for wr, rt, wt in cfgs:+ os.environ["BOLT_FQ_KQ_MR_ROWS"] = str(wr); os.environ["BOLT_FQ_KQ_MR_RT"] = str(rt); os.environ["BOLT_FQ_KQ_MR_WT"] = str(wt)+ for R in RS:+ check(f"{tag}|R{R}|wr{wr}|rt{rt}|wt{wt}", gemv(fmt, wp, xs[:R].contiguous(), dt), ref[:R])+ os.environ.pop("BOLT_FQ_KQ_MR_ROWS", None); os.environ.pop("BOLT_FQ_KQ_MR_RT", None); os.environ.pop("BOLT_FQ_KQ_MR_WT", None)+ else: # BOLT_FQ_KQ_MROWS=0: old launch, one block per (x-row, output row) for M >= 2+ for R in RS:+ check(f"{tag}|R{R}|off", gemv(fmt, wp, xs[:R].contiguous(), dt), ref[:R])+ print(f"child {mode}: {n[0]} comparisons, {bad[0]} bad", flush=True)+ sys.exit(1 if bad[0] else 0)+++def main():+ rc = 0+ for mode, extra in (("mrows", {"BOLT_FQ_KQ_WMMA": "0"}), ("wmma", {"BOLT_FQ_KQ_WMMA": "1"}), ("auto", {}), ("off", {"BOLT_FQ_KQ_MROWS": "0"})):+ env = dict(os.environ, **extra)+ env.pop("BOLT_FQ_KQ_ROWS", None)+ if mode == "auto":+ env.pop("BOLT_FQ_KQ_WMMA", None)+ if mode != "off":+ env.pop("BOLT_FQ_KQ_MROWS", None)+ rc |= subprocess.run([sys.executable, os.path.abspath(__file__), "child", mode], env=env).returncode+ print("test_kq_gemv_mrows:", "PASS (multi-row and WMMA == one-row bitwise, R 1..16, %d launch shapes, half/float out, slices, misaligned fallback, old path)" % len(CONFIGS) if rc == 0 else "FAIL")+ sys.exit(rc)+++if __name__ == "__main__":+ if len(sys.argv) > 2 and sys.argv[1] == "child":+ child(sys.argv[2])+ else:+ main()diff --git a/tests/test_kq_gemv_rows.py b/tests/test_kq_gemv_rows.pynew file mode 100644index 0000000..bd4d14a--- /dev/null+++ b/tests/test_kq_gemv_rows.py@@ -0,0 +1,64 @@+#!/usr/bin/env python3+"""Q4_K / Q6_K decode GEMV v2 ("rows" kernel) must equal the v1 kernel BIT FOR BIT (float summation order is kept).+Runs the same synthetic problems with BOLT_FQ_KQ_ROWS = 0 (v1), 1, 2, 4, 8 (v2) in child processes and compares the outputs with torch.equal.+usage: python tests/test_kq_gemv_rows.py (needs a CUDA / HIP GPU and the built extension)"""+import os, subprocess, sys, tempfile++BB = {"q4_k": 144, "q6_k": 210}+# (fmt, N, K): odd N (rows % ROWS != 0), small K (nt padded to 32), K = 12288 (3 chunks per lane), K = 4096, a row-slice view+CASES = [("q4_k", 1, 256), ("q4_k", 3, 512), ("q4_k", 37, 1024), ("q4_k", 1000, 4096), ("q4_k", 4096, 12288), ("q4_k", 5, 2048),+ ("q6_k", 1, 256), ("q6_k", 3, 512), ("q6_k", 37, 1024), ("q6_k", 1000, 4096), ("q6_k", 4096, 12288), ("q6_k", 5, 2048)]+++def child(out_path):+ import torch+ from exllamav3.ext import exllamav3_ext as ext+ res = {}+ for fmt, N, K in CASES:+ nb = K // 256+ for slice_off in (0, 3):+ g = torch.Generator(device="cuda").manual_seed(N * 7919 + K + slice_off)+ w = torch.randint(0, 256, (N + slice_off, nb, BB[fmt]), dtype=torch.uint8, device="cuda", generator=g)+ h = (torch.rand((N + slice_off, nb, 2), device="cuda", generator=g) * 0.002 + 0.0001).half().view(torch.uint8)+ if fmt == "q4_k":+ w[:, :, 0:4] = h+ else:+ w[:, :, 208:210] = h[:, :, 0:2]+ wp = w.reshape(N + slice_off, nb * BB[fmt])[slice_off:] # slice: base pointer at row `slice_off`+ for R in (1, 3):+ x = (torch.randn((R, K), device="cuda", generator=g) * 3).half()+ for dt in (torch.half, torch.float):+ qb = ext.fq_q8_scratch(0, R, K)+ ext.fq_quant_q8_1_rows(x, qb)+ out = torch.empty((R, N), device="cuda", dtype=dt)+ getattr(ext, f"fq_gemv_{fmt}_q8")(qb, wp, out)+ res[f"{fmt}|N{N}|K{K}|sl{slice_off}|R{R}|{dt}"] = out.cpu()+ torch.save(res, out_path)+++def main():+ import torch+ tmp = tempfile.mkdtemp()+ outs = {}+ for rows in (0, 1, 2, 4, 8, "default"):+ p = os.path.join(tmp, f"r{rows}.pt")+ env = dict(os.environ, BOLT_FQ_KQ_ROWS=str(rows), BOLT_FQ_KQ_MROWS="0") # R=3: v2 one-row vs v1 per x-row (multi-row has its own test)+ if rows == "default":+ env.pop("BOLT_FQ_KQ_ROWS")+ subprocess.run([sys.executable, os.path.abspath(__file__), "child", p], check=True, env=env)+ outs[rows] = torch.load(p)+ ref = outs[0]+ bad = 0+ for rows in (1, 2, 4, 8, "default"):+ for k, v in ref.items():+ if not torch.equal(v, outs[rows][k]) or not torch.isfinite(v.float()).all():+ print("MISMATCH rows", rows, k); bad += 1+ print("test_kq_gemv_rows:", "PASS (%d cases x 5 row settings, bitwise equal to v1)" % len(ref) if not bad else "FAIL %d" % bad)+ sys.exit(1 if bad else 0)+++if __name__ == "__main__":+ if len(sys.argv) > 2 and sys.argv[1] == "child":+ child(sys.argv[2])+ else:+ main()diff --git a/tests/test_linear_fp8.py b/tests/test_linear_fp8.pynew file mode 100644index 0000000..92cf013--- /dev/null+++ b/tests/test_linear_fp8.py@@ -0,0 +1,44 @@+"""LinearFP8 (FP8 served as stored on HIP / CUDA): Triton decode GEMV and the wide path equal dequant + matmul; per-row and block-grid scales."""+import pytest+import torch++pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="GPU")+++def _case(N, K, grid, seed):+ g = torch.Generator().manual_seed(seed)+ q = torch.randint(0, 256, (N, K), dtype=torch.uint8, generator=g)+ q[(q & 127) == 127] = 0x38 # no NaN codes+ if grid:+ s = torch.rand((-(-N // 128), -(-K // 128)), generator=g) * 2e-3 + 1e-3+ else:+ s = torch.rand(N, generator=g) * 2e-3 + 1e-3+ return q.cuda(), s.cuda()++[email protected]("grid", [False, True])[email protected]("N,K", [(256, 512), (300, 768), (5120, 17408), (1000, 1000)])[email protected]("R", [1, 3, 16, 40])+def test_linear_fp8_matches_dequant_matmul(grid, N, K, R):+ from exllamav3.modules.quant.fp8 import LinearFP8, dequant, ok+ q, s = _case(N, K, grid, N + K)+ if not ok(N, K, grid, (128, 128)):+ pytest.skip("tiling")+ lin = LinearFP8(K, N, q, s, grid, (128, 128), None, torch.half)+ x = torch.randn((R, K), device="cuda", dtype=torch.half)+ ref = x.float() @ dequant(q, s, grid, (128, 128)).float().T+ y = lin.forward(x, {}, torch.float).float()+ assert torch.isfinite(y).all()+ err = (y - ref).abs().max().item()+ assert err <= 2e-3 * ref.abs().max().item() + 1e-3, err+++def test_e4m3_decode_is_exact_on_every_code():+ from exllamav3.modules.quant.fp8 import gemv+ codes = torch.arange(256, dtype=torch.uint8)+ codes = codes[(codes & 127) != 127]+ n = codes.numel()+ q = torch.zeros((n, 128), dtype=torch.uint8); q[:, 0] = codes # row i holds code i at column 0+ x = torch.zeros((1, 128), dtype=torch.half); x[0, 0] = 1.0+ y = gemv(x.cuda(), q.cuda(), torch.ones(n, device="cuda"), False, (128, 128))[0].cpu()+ assert torch.equal(y, codes.view(torch.float8_e4m3fn).float())diff --git a/tests/test_moe_down32.py b/tests/test_moe_down32.pynew file mode 100644index 0000000..51e28e5--- /dev/null+++ b/tests/test_moe_down32.py@@ -0,0 +1,78 @@+"""Grouped MoE decode kernel with a 32-block down (ids 6 = q8_0, 7 = q5_1) vs an fp32 reference on the dequantized weights:+8 experts, K 2560, I 640, top-2, R 1 / 2, gate / up Q4_K. Tolerance covers the q8_1 activation quantization (same as the other+formats on this path). Also: q4_k down (id 0) at I 768 still works (regression guard). Run in the tree: python test_moe_down32.py"""+import numpy as np+import torch+import torch.nn.functional as F+from exllamav3.ext import exllamav3_ext as ext+from exllamav3.foreign_quant import gap_formats+from exllamav3.foreign_quant.k_quants import dequant_q4_K_bulk++rng = np.random.default_rng(0)+E, K, topk = 8, 2560, 2+++def f16bytes(a):+ return np.frombuffer(np.asarray(a, np.float16).tobytes(), np.uint8)+++def rand_q4k(N, Kc):+ nb = Kc // 256+ b = rng.integers(0, 256, (N, nb, 144), dtype=np.uint8)+ b[:, :, 0:2] = f16bytes(np.full(N * nb, 0.0004)).reshape(N, nb, 2)+ b[:, :, 2:4] = f16bytes(np.full(N * nb, 0.0002)).reshape(N, nb, 2)+ deq = dequant_q4_K_bulk(b.reshape(N * nb, 144)).reshape(N, Kc).astype(np.float32)+ return b.reshape(N, nb * 144), deq+++def rand_32(fmt, N, Kc):+ bb = {"q8_0": 34, "q5_1": 24}[fmt]+ nb = Kc // 32+ b = rng.integers(0, 256, (N, nb, bb), dtype=np.uint8)+ b[:, :, 0:2] = f16bytes(np.full(N * nb, 0.003)).reshape(N, nb, 2)+ if fmt == "q5_1":+ b[:, :, 2:4] = f16bytes(rng.standard_normal(N * nb) * 0.02).reshape(N, nb, 2)+ t = torch.from_numpy(b.reshape(N, nb * bb)).cuda()+ deq = gap_formats.dequant(fmt, t).float().cpu().numpy()+ return b.reshape(N, nb * bb), deq+++bad = 0+for fmt_d, fid, I in (("q8_0", 6, 640), ("q5_1", 7, 640), ("q4_k", 0, 768)):+ rng = np.random.default_rng(fid + 1) # fixed data per format (deterministic verdict)+ gates, ups, downs, Wg, Wu, Wd = [], [], [], [], [], []+ for e in range(E):+ g, gd = rand_q4k(I, K); u, ud = rand_q4k(I, K)+ d, dd = (rand_q4k(K, I) if fmt_d == "q4_k" else rand_32(fmt_d, K, I))+ gates.append(torch.from_numpy(g).cuda()); ups.append(torch.from_numpy(u).cuda()); downs.append(torch.from_numpy(d).cuda())+ Wg.append(gd); Wu.append(ud); Wd.append(dd)+ gp = torch.tensor([t.data_ptr() for t in gates], dtype=torch.int64, device="cuda")+ up = torch.tensor([t.data_ptr() for t in ups], dtype=torch.int64, device="cuda")+ dp = torch.tensor([t.data_ptr() for t in downs], dtype=torch.int64, device="cuda")+ gs = (K // 256) * 144+ ds = downs[0].shape[1]+ for R in (1, 2):+ h = (torch.randn(R, K) * 0.5).half().cuda()+ sel = torch.from_numpy(rng.choice(E, (R, topk), replace=False) if R == 1 else+ np.stack([rng.choice(E, topk, replace=False) for _ in range(R)])).long().cuda().reshape(-1)+ wts = torch.rand(R * topk).half().cuda()+ partial = torch.zeros(R * topk, K, dtype=torch.float, device="cuda")+ routed = torch.zeros(R, K, dtype=torch.float, device="cuda")+ ext.fq_moe_kq_grouped_mixed_q8(h, sel, wts, gp, up, dp, gs, gs, ds, 0, fid, partial, routed)+ torch.cuda.synchronize()+ hf = h.float().cpu().numpy()+ ref = np.zeros((R, K), np.float32)+ for r in range(R):+ for j in range(topk):+ e = int(sel[r * topk + j]); w = float(wts[r * topk + j])+ gg = hf[r] @ Wg[e].T; uu = hf[r] @ Wu[e].T+ a = (F.silu(torch.tensor(gg)) * torch.tensor(uu)).half().float().numpy()+ ref[r] += w * (a @ Wd[e].T)+ got = routed.cpu().numpy()+ amax = max(float(np.abs((F.silu(torch.tensor(hf[r] @ Wg[int(sel[r * topk + j])].T)) * torch.tensor(hf[r] @ Wu[int(sel[r * topk + j])].T)).numpy()).max()) for r in range(R) for j in range(topk))+ rel = float(np.abs(got - ref).max() / (np.abs(ref).max() + 1e-9))+ l2 = float(np.linalg.norm(got - ref) / (np.linalg.norm(ref) + 1e-9))+ ok = l2 < 3e-2 and rel < 5e-2 and np.isfinite(got).all()+ bad += not ok+ print(f"down {fmt_d} (id {fid}) I {I} R {R}: max rel err {rel:.2e} L2 rel {l2:.2e} (act max {amax:.1f}) {'ok' if ok else 'BAD'}")+print("PASS" if bad == 0 else f"FAIL ({bad})")diff --git a/tests/test_moe_iq_prefill.py b/tests/test_moe_iq_prefill.pynew file mode 100644index 0000000..37fd830--- /dev/null+++ b/tests/test_moe_iq_prefill.py@@ -0,0 +1,61 @@+"""Grouped IQ dequant of the prefill MoE (fq_moe_prefill_iq._dq_iq) vs the per-expert references (gap_formats.dequant for IQ2_S /+IQ3_XXS, ext.fq_dequant_iq4_xs for IQ4_XS) on real experts of an unsloth UD-IQ3_XXS MoE GGUF (default: Qwen3.6-35B-A3B). Same fp16+values expected (max abs diff ~0, both decode in fp32 then round). Usage: python tests/test_moe_iq_prefill.py [GGUF]"""+import sys++import torch+import triton++sys.path.insert(0, "tests")+from test_moe_iq_q8 import index, GGUF as G0 # noqa: E402++import exllamav3_ext as ext # noqa: E402+from exllamav3.foreign_quant import gap_formats # noqa: E402+from exllamav3.foreign_quant.triton_iq import _tabs # noqa: E402+from exllamav3.modules.fq_moe_prefill_iq import _dq_iq, _kv, FMT_ID # noqa: E402++import numpy as np # noqa: E402++GGUF = sys.argv[1] if len(sys.argv) > 1 else G0+TYPES = {18: ("iq3_xxs", 98), 22: ("iq2_s", 82), 23: ("iq4_xs", 136)}+++def check(f, infos, base, name, ne=4):+ dims, t, off = infos[name]+ fmt, bb = TYPES[t]+ Kin, N = dims[0], dims[1]+ per = N * (Kin // 256) * bb+ f.seek(base + off)+ raw = torch.from_numpy(np.frombuffer(f.read(per * ne), dtype=np.uint8).reshape(ne, N, -1).copy()).cuda()+ ptrs = torch.tensor([raw[e].data_ptr() for e in range(ne)], dtype=torch.int64, device="cuda")+ out = torch.empty(ne, N, Kin, dtype=torch.half, device="cuda")+ t3x, _, tks, _, t2s, _ = _tabs(raw.device)+ _dq_iq[(triton.cdiv(N, 32), Kin // 256, ne)](ptrs, out, 0, N, Kin, t3x, tks, t2s, _kv(raw.device), FMT=FMT_ID[fmt], BN=32, num_warps=4)+ worst = 0.0+ for e in range(ne):+ if fmt == "iq4_xs":+ ref = torch.empty(N, Kin, dtype=torch.half, device="cuda")+ ext.fq_dequant_iq4_xs(raw[e].contiguous(), ref)+ else:+ ref = gap_formats.dequant(fmt, raw[e]).reshape(N, Kin)+ worst = max(worst, float((out[e].float() - ref.float()).abs().max() / ref.float().abs().max()))+ print(f"{name} {fmt} [{ne}, {N}, {Kin}] max rel diff {worst:.2e}")+ return worst+++def test_moe_iq_prefill_dequant():+ f, infos, base = index(GGUF)+ names = []+ for want in (22, 18, 23):+ for kind in ("ffn_gate_exps", "ffn_down_exps"):+ n = next((f"blk.{i}.{kind}.weight" for i in range(200) if infos.get(f"blk.{i}.{kind}.weight", (0, -1))[1] == want), None)+ if n and n not in names:+ names.append(n)+ break+ worst = max(check(f, infos, base, n) for n in names)+ assert worst < 1e-3, f"dequant differs: {worst:.2e}"+++if __name__ == "__main__":+ test_moe_iq_prefill_dequant()+ print("PASS")diff --git a/tests/test_moe_iq_q8.py b/tests/test_moe_iq_q8.pynew file mode 100644index 0000000..3a46895--- /dev/null+++ b/tests/test_moe_iq_q8.py@@ -0,0 +1,94 @@+"""Grouped q8_1 decode MoE with IQ experts (fq_moe_kq_grouped_mixed_q8 FMT 5 IQ2_S gate/up + FMT 4 IQ3_XXS down, ggml vecdotq ports)+vs the torch reference (gap_formats.dequant, fp32 dots, torch-half SwiGLU like the per-expert path) on 8 real experts of an unsloth+UD-IQ3_XXS MoE GGUF (default: Qwen3.6-35B-A3B, first layer whose down experts are IQ3_XXS). q8_1 activations -> compared by relative+error (~0.5-1 % expected); a wrong port (layout, signs, scales, high index bits) gives errors of order 1.+Usage: python tests/test_moe_iq_q8.py [GGUF]"""+import os, struct, sys++import numpy as np+import torch++import exllamav3_ext as ext+from exllamav3.foreign_quant import gap_formats++GGUF = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("MOE_IQ_GGUF", "model.gguf")+SZ = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}+BLK = {18: ("iq3_xxs", 98), 22: ("iq2_s", 82)}+FID = {"iq3_xxs": 4, "iq2_s": 5}+++def index(path):+ f = open(path, "rb")+ u32 = lambda: struct.unpack("<I", f.read(4))[0]; u64 = lambda: struct.unpack("<Q", f.read(8))[0]+ def s(): return f.read(u64()).decode()+ def skip(t):+ if t == 8: f.seek(u64(), 1)+ elif t == 9:+ at, n = u32(), u64()+ if at in SZ: f.seek(SZ[at] * n, 1)+ else:+ for _ in range(n): skip(at)+ else: f.seek(SZ[t], 1)+ assert f.read(4) == b"GGUF"; u32(); nt = u64(); nkv = u64(); align = 32+ for _ in range(nkv):+ k = s(); t = u32()+ if k == "general.alignment": align = u32(); continue+ skip(t)+ infos = {}+ for _ in range(nt):+ n = s(); nd = u32(); dims = [u64() for _ in range(nd)]; t = u32(); off = u64(); infos[n] = (dims, t, off)+ return f, infos, (f.tell() + align - 1) // align * align+++def experts(f, infos, base, name, ne):+ dims, t, off = infos[name]+ fmt, bb = BLK[t]+ Kin, Nout = dims[0], dims[1]+ per = Nout * (Kin // 256) * bb+ f.seek(base + off)+ raw = np.frombuffer(f.read(per * ne), dtype=np.uint8).reshape(ne, Nout, -1)+ return fmt, torch.from_numpy(raw.copy()).cuda(), Kin, Nout+++def test_moe_iq_q8_matches_reference():+ f, infos, base = index(GGUF)+ layer = next(i for i in range(200) if infos.get(f"blk.{i}.ffn_down_exps.weight", (0, 0))[1] == 18+ and infos[f"blk.{i}.ffn_gate_exps.weight"][1] == 22)+ ne = 8+ fg, wg, K, I = experts(f, infos, base, f"blk.{layer}.ffn_gate_exps.weight", ne)+ fu, wu, _, _ = experts(f, infos, base, f"blk.{layer}.ffn_up_exps.weight", ne)+ fd, wd, I2, K2 = experts(f, infos, base, f"blk.{layer}.ffn_down_exps.weight", ne)+ assert (fg, fu, fd) == ("iq2_s", "iq2_s", "iq3_xxs") and (I2, K2) == (I, K), (fg, fu, fd, K, I, I2, K2)+ dq = lambda fmt, w, n, k: torch.stack([gap_formats.dequant(fmt, w[e]).float().reshape(n, k) for e in range(ne)])+ Gd, Ud, Dd = dq(fg, wg, I, K), dq(fu, wu, I, K), dq(fd, wd, K, I)+ ptrs = lambda w: torch.tensor([w[e].data_ptr() for e in range(ne)], dtype=torch.int64, device="cuda")+ gp, upp, dp = ptrs(wg), ptrs(wu), ptrs(wd)+ gs = wg[0].stride(0); ds = wd[0].stride(0)+ g = torch.Generator(device="cpu").manual_seed(0)+ worst = 0.0+ for R in (1, 4, 8):+ topk = 4+ x = (torch.randn(R, K, generator=g) * 0.5).half().cuda()+ sel = torch.stack([torch.randperm(ne, generator=g)[:topk] for _ in range(R)]).cuda()+ wts = torch.rand(R, topk, generator=g).half().cuda()+ ref = torch.zeros(R, K, device="cuda")+ for r in range(R):+ for j in range(topk):+ e = int(sel[r, j])+ gg = (x[r].float() @ Gd[e].t()).half().float(); uu = (x[r].float() @ Ud[e].t()).half().float()+ act = (torch.sigmoid(gg) * gg * uu).half().float()+ ref[r] += float(wts[r, j]) * (act @ Dd[e].t())+ partial = torch.empty(R * topk, K, dtype=torch.float, device="cuda")+ out = torch.empty(R, K, dtype=torch.float, device="cuda")+ ext.fq_moe_kq_grouped_mixed_q8(x, sel.reshape(-1).contiguous(), wts.reshape(-1).contiguous(), gp, upp, dp,+ gs, gs, ds, FID[fg], FID[fd], partial, out)+ torch.cuda.synchronize()+ rel = float((out - ref).norm() / ref.norm())+ print(f"layer {layer} R={R} rel err {rel:.4f}")+ worst = max(worst, rel)+ assert worst < 0.03, f"relative error {worst:.4f} (q8_1 activations alone give ~0.005-0.01)"+++if __name__ == "__main__":+ test_moe_iq_q8_matches_reference()+ print("PASS")diff --git a/tests/test_moe_v2.py b/tests/test_moe_v2.pynew file mode 100644index 0000000..5ce3249--- /dev/null+++ b/tests/test_moe_v2.py@@ -0,0 +1,106 @@+"""Grouped q8_1 decode MoE: v2 wide-load kernels (gate+up Q4_K, down Q4_K / Q5_K / Q6_K; BOLT_FQ_MOE_V2=1, default) vs the+v1 lane kernels (BOLT_FQ_MOE_V2=0) on real experts of a K-quant MoE GGUF (e.g. Qwen3.6-35B-A3B UD-Q4_K_XL: the first layer of+each (gate/up, down) format pair present):+outputs must be bit-identical (torch.equal), rows R = 1 / 4 / 8, 16-byte aligned expert rows and a misaligned copy (v1 fallback).+The flag is read once per process, so each arm runs in its own subprocess.+Usage: python tests/test_moe_v2.py [GGUF]"""+import os, struct, subprocess, sys, tempfile++import numpy as np+import torch++SZ = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}+BLK = {12: ("q4_k", 144, 0), 13: ("q5_k", 176, 1), 14: ("q6_k", 210, 2)}+GGUF = os.environ.get("MOE_V2_GGUF") or (sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("-") else "")+++def index(path):+ f = open(path, "rb")+ u32 = lambda: struct.unpack("<I", f.read(4))[0]; u64 = lambda: struct.unpack("<Q", f.read(8))[0]+ def s(): return f.read(u64()).decode()+ def skip(t):+ if t == 8: f.seek(u64(), 1)+ elif t == 9:+ at, n = u32(), u64()+ if at in SZ: f.seek(SZ[at] * n, 1)+ else:+ for _ in range(n): skip(at)+ else: f.seek(SZ[t], 1)+ assert f.read(4) == b"GGUF"; u32(); nt = u64(); nkv = u64(); align = 32+ for _ in range(nkv):+ k = s(); t = u32()+ if k == "general.alignment": align = u32(); continue+ skip(t)+ infos = {}+ for _ in range(nt):+ n = s(); nd = u32(); dims = [u64() for _ in range(nd)]; t = u32(); off = u64(); infos[n] = (dims, t, off)+ return f, infos, (f.tell() + align - 1) // align * align+++def experts(f, infos, base, name, ne, shift):+ dims, t, off = infos[name]+ fmt, bb, fid = BLK[t]+ Kin, Nout = dims[0], dims[1]+ per = Nout * (Kin // 256) * bb+ f.seek(base + off)+ raw = torch.from_numpy(np.frombuffer(f.read(per * ne), dtype=np.uint8).copy())+ buf = torch.zeros(per * ne + 64, dtype=torch.uint8, device="cuda")+ buf[shift:shift + per * ne] = raw.cuda()+ w = buf[shift:shift + per * ne].view(ne, Nout, -1)+ return fid, w, buf, Kin, Nout+++def arm(out_path):+ import exllamav3_ext as ext+ f, infos, base = index(GGUF)+ pairs = {}+ for i in range(200):+ if f"blk.{i}.ffn_down_exps.weight" not in infos: continue+ key = (infos[f"blk.{i}.ffn_gate_exps.weight"][1], infos[f"blk.{i}.ffn_down_exps.weight"][1])+ if all(t in BLK for t in key) and infos[f"blk.{i}.ffn_up_exps.weight"][1] == key[0]: pairs.setdefault(key, i)+ ne, topk = 16, 8+ res = {}+ for key, layer in sorted(pairs.items()):+ for shift in (0, 4):+ fg, wg, bg, K, I = experts(f, infos, base, f"blk.{layer}.ffn_gate_exps.weight", ne, shift)+ fu, wu, bu, _, _ = experts(f, infos, base, f"blk.{layer}.ffn_up_exps.weight", ne, shift)+ fd, wd, bd, I2, K2 = experts(f, infos, base, f"blk.{layer}.ffn_down_exps.weight", ne, shift)+ assert (I2, K2) == (I, K)+ ptrs = lambda w: torch.tensor([w[e].data_ptr() for e in range(ne)], dtype=torch.int64, device="cuda")+ g = torch.Generator(device="cpu").manual_seed(1)+ for R in (1, 4, 8):+ x = (torch.randn(R, K, generator=g) * 0.5).half().cuda()+ sel = torch.stack([torch.randperm(ne, generator=g)[:topk] for _ in range(R)]).cuda()+ wts = torch.rand(R, topk, generator=g).half().cuda()+ partial = torch.empty(R * topk, K, dtype=torch.float, device="cuda")+ out = torch.empty(R, K, dtype=torch.float, device="cuda")+ ext.fq_moe_kq_grouped_mixed_q8(x, sel.reshape(-1).contiguous(), wts.reshape(-1).contiguous(), ptrs(wg), ptrs(wu),+ ptrs(wd), wg[0].stride(0), wu[0].stride(0), wd[0].stride(0), fg, fd, partial, out)+ torch.cuda.synchronize()+ res[f"L{layer}_ug{fg}_d{fd}_shift{shift}_R{R}"] = out.cpu()+ layer = sorted(pairs.items())+ torch.save({"layer": layer, "res": res}, out_path)+++def test_moe_v2_bit_identical():+ assert GGUF, "set MOE_V2_GGUF or pass the GGUF path"+ d = tempfile.mkdtemp()+ outs = []+ for flag in ("0", "1"):+ p = os.path.join(d, f"arm{flag}.pt")+ env = dict(os.environ, BOLT_FQ_MOE_V2=flag, MOE_V2_GGUF=GGUF)+ subprocess.run([sys.executable, __file__, "--arm", p], env=env, check=True)+ outs.append(torch.load(p))+ a, b = outs[0]["res"], outs[1]["res"]+ for k in a:+ eq = torch.equal(a[k], b[k])+ print(f"{k}: equal={eq} max|d|={float((a[k] - b[k]).abs().max()):.3e}")+ assert eq, k+++if __name__ == "__main__":+ if len(sys.argv) > 2 and sys.argv[1] == "--arm":+ arm(sys.argv[2])+ else:+ test_moe_v2_bit_identical()+ print("PASS")diff --git a/tests/test_q51_triton.py b/tests/test_q51_triton.pynew file mode 100644index 0000000..be089bb--- /dev/null+++ b/tests/test_q51_triton.py@@ -0,0 +1,20 @@+"""Q5_1 dequant: Triton kernel vs the torch chain, bit-identical on random blocks (finite fp16 d / m, all qh / qs bit patterns)."""+import os, torch+os.environ["EXL3_Q51_TRITON"] = "1"+import exllamav3.foreign_quant.gap_formats as gf++torch.manual_seed(0)+bad = 0+for rows, nb in ((1, 1), (3, 5), (640, 80), (2560, 20), (7, 513)):+ raw = torch.randint(0, 256, (rows, nb, 24), dtype = torch.uint8)+ dm = (torch.randn(rows, nb, 2) * 0.01).half().view(torch.uint8).reshape(rows, nb, 4)+ raw[:, :, 0:4] = dm+ raw = raw.reshape(rows, nb * 24).cuda()+ gf._Q51_TRITON = True+ a = gf.dequant("q5_1", raw)+ gf._Q51_TRITON = False+ b = gf.dequant("q5_1", raw)+ same = torch.equal(a.view(torch.int16), b.view(torch.int16))+ bad += not same+ print(f"rows {rows} nb {nb}: {'equal' if same else 'DIFF max ' + str((a.float() - b.float()).abs().max().item())}")+print("PASS" if bad == 0 else f"FAIL ({bad})")diff --git a/tests/test_q5_1.py b/tests/test_q5_1.pynew file mode 100644index 0000000..5ffb351--- /dev/null+++ b/tests/test_q5_1.py@@ -0,0 +1,53 @@+"""Q5_1 checks: (1) torch dequant (gap_formats) == an independent numpy reference written from ggml's dequantize_row_q5_1 (exact);+(2) Triton fused decode GEMV (triton_gap, R 1 / 4) vs fp32 matmul over the dequantized weights (fp16-level tolerance, like the other+gap formats); (3) ForeignLinear("q5_1") forward runs. Run in the tree on the GPU: python test_q5_1.py"""+import numpy as np+import torch+from exllamav3.foreign_quant import gap_formats, triton_gap+++def ref_dequant(raw): # ggml dequantize_row_q5_1+ nb = raw.size // 24+ b = raw.reshape(nb, 24)+ d = b[:, 0:2].copy().view(np.float16).astype(np.float32)+ m = b[:, 2:4].copy().view(np.float16).astype(np.float32)+ qh = b[:, 4:8].copy().view(np.uint32)[:, 0]+ qs = b[:, 8:24]+ y = np.zeros((nb, 32), np.float32)+ for j in range(16):+ xh0 = ((qh >> j) << 4) & 0x10+ xh1 = (qh >> (j + 12)) & 0x10+ x0 = (qs[:, j] & 0x0F) | xh0+ x1 = (qs[:, j] >> 4) | xh1+ y[:, j] = x0 * d[:, 0] + m[:, 0]+ y[:, j + 16] = x1 * d[:, 0] + m[:, 0]+ return y.reshape(-1)+++rng = np.random.default_rng(0)+bad = 0+for N, K in ((64, 640), (2560, 640), (96, 2560)):+ nb = K // 32+ raw = rng.integers(0, 256, (N, nb, 24), dtype=np.uint8)+ raw[:, :, 0:2] = np.frombuffer(np.full(N * nb, 0.01, np.float16).tobytes(), np.uint8).reshape(N, nb, 2)+ raw[:, :, 2:4] = np.frombuffer((rng.standard_normal(N * nb) * 0.05).astype(np.float16).tobytes(), np.uint8).reshape(N, nb, 2)+ ref = ref_dequant(raw.reshape(-1)).reshape(N, K)+ t = torch.from_numpy(raw.reshape(N, nb * 24)).cuda()+ dq = gap_formats.dequant("q5_1", t) if hasattr(gap_formats, "dequant") else None+ if dq is None:+ import inspect+ fn = [f for n, f in inspect.getmembers(gap_formats, inspect.isfunction) if "dequant" in n][0]+ dq = fn("q5_1", t)+ ok1 = np.array_equal(dq.float().cpu().numpy(), ref.astype(np.float16).astype(np.float32))+ for R in (1, 4):+ x = torch.randn(R, K).half().cuda()+ if triton_gap.supported("q5_1", R, K, N):+ y = triton_gap.gemv("q5_1", x, t).float()+ want = x.float() @ dq.float().t()+ err = ((y - want).abs().max() / want.abs().max()).item()+ ok2 = err < 5e-3+ else:+ err, ok2 = None, True+ print(f"N {N} K {K} R {R}: dequant exact {ok1}, triton rel err {err}")+ bad += (not ok1) + (not ok2)+print("PASS" if bad == 0 else f"FAIL ({bad})")diff --git a/tests/test_q6k_bulk.py b/tests/test_q6k_bulk.pynew file mode 100644index 0000000..860ac4d--- /dev/null+++ b/tests/test_q6k_bulk.py@@ -0,0 +1,13 @@+import numpy as np++from exllamav3.foreign_quant.k_quants import dequant_q6_K_block, dequant_q6_K_bulk+++def test_q6_K_bulk_matches_block():+ rng = np.random.default_rng(0)+ raw = rng.integers(0, 256, size=(64, 210), dtype=np.uint8)+ raw[:, 208:210] = np.frombuffer(rng.uniform(-0.05, 0.05, 64).astype(np.float16).tobytes(), np.uint8).reshape(64, 2)+ ref = np.stack([dequant_q6_K_block(bytes(r)) for r in raw]).astype(np.float16)+ out = dequant_q6_K_bulk(raw)+ assert out.shape == (64, 256)+ np.testing.assert_array_equal(out, ref)diff --git a/tests/test_router_shapes_hip.py b/tests/test_router_shapes_hip.pynew file mode 100644index 0000000..dd3e329--- /dev/null+++ b/tests/test_router_shapes_hip.py@@ -0,0 +1,39 @@+"""Fused HIP decode router (routing_std_gfx12_bsz1) vs the torch routing path on the Qwen3.6-35B-A3B shape (2048 x 256, top-8):+same experts in the same order, same fp16 weights, rows 1..4, random inputs plus tied logits. Needs a gfx11.5 / gfx12 wave32 GPU.+Run: hiprun.sh python tests/test_router_shapes_hip.py (or pytest)."""+import types++import torch++from exllamav3.modules import block_sparse_mlp_routing as R+++def _cfg(gate):+ E = gate.shape[1]+ return types.SimpleNamespace(gate_tensor=gate, gate_tensor_t=None, num_experts=E, num_experts_per_tok=8, per_expert_scale=None,+ router_bias=None, router_logits_bsz1=torch.empty((1, E), dtype=torch.half, device="cuda"),+ selected_experts_bsz1=torch.empty((1, 8), dtype=torch.long, device="cuda"),+ routing_weights_bsz1=torch.empty((1, 8), dtype=torch.half, device="cuda"))+++def test_router_2048_256_top8_matches_torch():+ g = torch.Generator(device="cpu").manual_seed(0)+ bad = 0+ for trial in range(200):+ gate = (torch.randn(2048, 256, generator=g) * 0.02).half().cuda().contiguous()+ if trial % 4 == 0:+ gate[:, 1::2] = gate[:, 0::2] # tied logits: experts 2i and 2i+1 equal -> lowest index first+ for rows in (1, 2, 4):+ y = (torch.randn(rows, 2048, generator=g)).half().cuda().contiguous()+ cfg = _cfg(gate)+ assert R._hip_router_call_supported(rows, cfg, y, {}), "fused router not eligible"+ s1, w1 = R.routing_std(rows, cfg, y, {})+ s0, w0 = R._routing_std_torch(cfg, y, {})+ if not (torch.equal(s1.cpu(), s0.cpu()) and torch.equal(w1.cpu(), w0.cpu())):+ bad += 1+ assert bad == 0, f"{bad} of 600 calls differ from the torch routing"+++if __name__ == "__main__":+ test_router_2048_256_top8_matches_torch()+ print("PASS")diff --git a/tools/qwen/serve.py b/tools/qwen/serve.pyindex 066c2a4..f9a2315 100644--- a/tools/qwen/serve.py+++ b/tools/qwen/serve.py@@ -848,7 +848,14 @@ class QwenEngine:else:print(f"qserve: kv-mode tq: k{k_bits}v{v_bits} at head_dim {hd} has no TurboQuant codebook, keeping the quant cache", flush=True)# one recurrent (GDN) slot per session; the Generator caps its batch at the slot count- self.cache = Cache(self.model, max_num_tokens=ctx, max_history=max(3, ndt), max_batch_size=sessions, **qkw)+ # Recurrent (GDN) state history rows exist only for speculative verify rounds (draft_tokens is not None). Each row costs+ # sessions x 32 x 128 x 128 x 4 B = 0.5 MiB per session and layer: ndt 7 on the 35B-A3B (30 GDN layers, 8 sessions) is 3.75 GiB+ # of fp32 state, which is what made the UD-Q4_K_XL GGUF (20.3 GiB of weights on the GPU) miss a 24 GB card. Without a drafter+ # and without the plain lookup nothing writes history: keep the committed-state row only.+ hist = max(3, ndt) if (draft_policy != "off" or pl is not None) else 0+ if os.environ.get("KYO_GDN_HISTORY"): # A/B override+ hist = int(os.environ["KYO_GDN_HISTORY"])+ self.cache = Cache(self.model, max_num_tokens=ctx, max_history=hist, max_batch_size=sessions, **qkw)if qkw.get("layer_type") is not None and getattr(qkw["layer_type"], "tq", False):from exllamav3.cache.tq import cache_is_tqif not cache_is_tq(self.cache):