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
Foreign 1-row gemv: Q4_0 / Q4_1 / Q5_0 / Q5_1 in fq_mmvq (EXL3_FQ_MMVQ_LEGACY)
YanissAmzc6290d573a8f
diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cppindex efc7bd8..430e91e 100644--- a/exllamav3/exllamav3_ext/bindings.cpp+++ b/exllamav3/exllamav3_ext/bindings.cpp@@ -672,6 +672,14 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)py::arg("qb"), py::arg("packed"), py::arg("out"));m.def("fq_mmvq_q3_k", &fq_mmvq_q3_k, "fq_mmvq_q3_k",py::arg("qb"), py::arg("packed"), py::arg("out"));+ m.def("fq_mmvq_q4_0", &fq_mmvq_q4_0, "fq_mmvq_q4_0",+ py::arg("qb"), py::arg("packed"), py::arg("out"));+ m.def("fq_mmvq_q4_1", &fq_mmvq_q4_1, "fq_mmvq_q4_1",+ py::arg("qb"), py::arg("packed"), py::arg("out"));+ m.def("fq_mmvq_q5_0", &fq_mmvq_q5_0, "fq_mmvq_q5_0",+ py::arg("qb"), py::arg("packed"), py::arg("out"));+ m.def("fq_mmvq_q5_1", &fq_mmvq_q5_1, "fq_mmvq_q5_1",+ py::arg("qb"), py::arg("packed"), py::arg("out"));#if !defined(USE_ROCM)m.def("fq_mmq_few", &fq_mmq_few, "fq_mmq_few",py::arg("x"), py::arg("scratch"), py::arg("packed"), py::arg("out"), py::arg("fmt"));diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cuindex abc3899..12eb741 100644--- a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu@@ -22,6 +22,7 @@#include "fq_api.h"#include "ggml_mmvq/ggml_vecdotq_iq.cuh"#include "ggml_mmvq/ggml_vecdotq_k46.cuh"+#include "ggml_mmvq/ggml_vecdotq_legacy.cuh"#if defined(USE_ROCM)// HIP: maskless shuffles (RDNA runs these kernels as wave32, MQ_WARP = 32)@@ -32,7 +33,7 @@ namespace {using namespace ggml_iq;-enum { MQ_IQ2_XXS = 0, MQ_IQ2_XS = 1, MQ_IQ2_S = 2, MQ_IQ3_XXS = 3, MQ_IQ3_S = 4, MQ_IQ4_NL = 5, MQ_IQ4_XS = 6, MQ_Q5_K = 7, MQ_Q4_K = 8, MQ_Q6_K = 9, MQ_Q3_K = 10, MQ_NTYPES = 11 };+enum { MQ_IQ2_XXS = 0, MQ_IQ2_XS = 1, MQ_IQ2_S = 2, MQ_IQ3_XXS = 3, MQ_IQ3_S = 4, MQ_IQ4_NL = 5, MQ_IQ4_XS = 6, MQ_Q5_K = 7, MQ_Q4_K = 8, MQ_Q6_K = 9, MQ_Q3_K = 10, MQ_Q4_0 = 11, MQ_Q4_1 = 12, MQ_Q5_0 = 13, MQ_Q5_1 = 14, MQ_NTYPES = 15 };// qk = weight elements per block, qi = ints per block (ggml QI*), vdr = ints per lane per call, bb = block bytestemplate <int T> struct MqTraits;@@ -53,6 +54,11 @@ MQ_TRAITS(MQ_Q5_K, 256, 32, VDR_Q5_K_Q8_1_MMVQ, 176, vec_dot_q5_K_q8_1);MQ_TRAITS(MQ_Q4_K, 256, 32, VDR_Q4_K_Q8_1_MMVQ, 144, vec_dot_q4_K_q8_1);MQ_TRAITS(MQ_Q6_K, 256, 32, VDR_Q6_K_Q8_1_MMVQ, 210, vec_dot_q6_K_q8_1);MQ_TRAITS(MQ_Q3_K, 256, 16, VDR_Q3_K_Q8_1_MMVQ, 110, vec_dot_q3_K_q8_1);+// legacy 32-element GGUF blocks (EXL3_FQ_MMVQ_LEGACY in foreign_linear.py): qi = QI4_0 = QI5_0 = 4 ints per block+MQ_TRAITS(MQ_Q4_0, 32, 4, VDR_Q4_0_Q8_1_MMVQ, 18, vec_dot_q4_0_q8_1);+MQ_TRAITS(MQ_Q4_1, 32, 4, VDR_Q4_1_Q8_1_MMVQ, 20, vec_dot_q4_1_q8_1);+MQ_TRAITS(MQ_Q5_0, 32, 4, VDR_Q5_0_Q8_1_MMVQ, 22, vec_dot_q5_0_q8_1);+MQ_TRAITS(MQ_Q5_1, 32, 4, VDR_Q5_1_Q8_1_MMVQ, 24, vec_dot_q5_1_q8_1);#undef MQ_TRAITSconstexpr int MQ_WARP = 32;@@ -192,6 +198,7 @@ void mq_run(torch::Tensor qb, torch::Tensor packed, torch::Tensor out)TORCH_CHECK(K % Tr::qk == 0, "K must be a multiple of the format block size");TORCH_CHECK(packed.size(1) == (int64_t)(K / Tr::qk) * Tr::bb, "packed width must match K");TORCH_CHECK((uintptr_t)packed.data_ptr() % 4 == 0 && ((int64_t)(K / Tr::qk) * Tr::bb) % 2 == 0, "weights must be 2-byte aligned (4 for IQ4_XS)");+ TORCH_CHECK(Tr::bb % 4 == 2 || ((int64_t)(K / Tr::qk) * Tr::bb) % 4 == 0, "this format needs 4-byte aligned weight rows");TORCH_CHECK((uintptr_t)qb.data_ptr() % 4 == 0, "qb must be 4-byte aligned");at::cuda::CUDAGuard guard(qb.device());auto stream = at::cuda::getCurrentCUDAStream().stream();@@ -510,6 +517,10 @@ void fq_mmvq_q5_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mvoid fq_mmvq_q4_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mq_run<MQ_Q4_K>(qb, packed, out); }void fq_mmvq_q6_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mq_run<MQ_Q6_K>(qb, packed, out); }void fq_mmvq_q3_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mq_run<MQ_Q3_K>(qb, packed, out); }+void fq_mmvq_q4_0(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mq_run<MQ_Q4_0>(qb, packed, out); }+void fq_mmvq_q4_1(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mq_run<MQ_Q4_1>(qb, packed, out); }+void fq_mmvq_q5_0(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mq_run<MQ_Q5_0>(qb, packed, out); }+void fq_mmvq_q5_1(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mq_run<MQ_Q5_1>(qb, packed, out); }// Standalone grouped decode MoE for IQ experts (any of the 7 IQ formats for gate/up and for down; type ids = MQ_* order:// 0 iq2_xxs, 1 iq2_xs, 2 iq2_s, 3 iq3_xxs, 4 iq3_s, 5 iq4_nl, 6 iq4_xs). Same arguments and results as fq_moe_kq_grouped_mixed_q8:diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.hindex af5bad6..43d2583 100644--- a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h@@ -14,6 +14,10 @@ void fq_mmvq_q5_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);void fq_mmvq_q4_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);void fq_mmvq_q6_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);void fq_mmvq_q3_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);+void fq_mmvq_q4_0(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);+void fq_mmvq_q4_1(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);+void fq_mmvq_q5_0(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);+void fq_mmvq_q5_1(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);// Grouped decode MoE for IQ experts: format ids 0 iq2_xxs, 1 iq2_xs, 2 iq2_s, 3 iq3_xxs, 4 iq3_s, 5 iq4_nl, 6 iq4_xs, 7 q5_k (gate/up and down independent).// Arguments and results as fq_moe_kq_grouped_mixed_q8 (fq_api.h).void fq_moe_mmvq_grouped(torch::Tensor h, torch::Tensor sel, torch::Tensor wts, torch::Tensor gate_ptrs, torch::Tensor up_ptrs,diff --git a/exllamav3/exllamav3_ext/foreign_quant/ggml_mmvq/ggml_vecdotq_legacy.cuh b/exllamav3/exllamav3_ext/foreign_quant/ggml_mmvq/ggml_vecdotq_legacy.cuhnew file mode 100644index 0000000..bb517c0--- /dev/null+++ b/exllamav3/exllamav3_ext/foreign_quant/ggml_mmvq/ggml_vecdotq_legacy.cuh@@ -0,0 +1,172 @@+// Legacy GGUF block vec-dots Q4_0, Q4_1, Q5_0, Q5_1 (q8_1 activations, integer dp4a dots), MMVQ variants (VDR = 2), ported from llama.cpp+// ggml/src/ggml-cuda/vecdotq.cuh (vec_dot_q{4_0,4_1,5_0,5_1}_q8_1 and their _impl) and the block structs of ggml/src/ggml-common.h+// (https://github.com/ggml-org/llama.cpp). MIT License, Copyright (c) 2023-2026 The ggml authors. See THIRD_PARTY_NOTICES.md.+// Changes: ggml_cuda_dp4a -> ggml_dp4a, namespace ggml_iq, plain half / half2 block fields, the FAST_FP16_AVAILABLE half2 multiply+// replaced by its float branch (identical to ggml's non-fp16 path). The dot-product bodies are unchanged.+#pragma once++#include "ggml_vecdotq_iq.cuh"++namespace ggml_iq {++#define QK4_0 32+#define QR4_0 2+#define QI4_0 (QK4_0 / (4 * QR4_0))+#define QK4_1 32+#define QR4_1 2+#define QI4_1 (QK4_1 / (4 * QR4_1))+#define QK5_0 32+#define QR5_0 2+#define QI5_0 (QK5_0 / (4 * QR5_0))+#define QK5_1 32+#define QR5_1 2+#define QI5_1 (QK5_1 / (4 * QR5_1))+#define QI8_1 8++struct block_q4_0 { half d; uint8_t qs[QK4_0 / 2]; };+struct block_q4_1 { half2 dm; uint8_t qs[QK4_1 / 2]; };+struct block_q5_0 { half d; uint8_t qh[4]; uint8_t qs[QK5_0 / 2]; };+struct block_q5_1 { half2 dm; uint32_t qh; uint8_t qs[QK5_1 / 2]; };+static_assert(sizeof(block_q4_0) == 18 && sizeof(block_q4_1) == 20 && sizeof(block_q5_0) == 22 && sizeof(block_q5_1) == 24, "ggml block layout");++#ifndef VDR_Q4_0_Q8_1_MMVQ+#define VDR_Q4_0_Q8_1_MMVQ 2+#endif+#define VDR_Q4_1_Q8_1_MMVQ 2+#define VDR_Q5_0_Q8_1_MMVQ 2+#define VDR_Q5_1_Q8_1_MMVQ 2++template <int vdr> static __device__ __forceinline__ float vec_dot_q4_0_q8_1_impl(+ const int * v, const int * u, const float & d4, const half2 & ds8) {+ int sumi = 0;+#pragma unroll+ for (int i = 0; i < vdr; ++i) {+ const int vi0 = (v[i] >> 0) & 0x0F0F0F0F;+ const int vi1 = (v[i] >> 4) & 0x0F0F0F0F;+ sumi = ggml_dp4a(vi0, u[2*i+0], sumi);+ sumi = ggml_dp4a(vi1, u[2*i+1], sumi);+ }+ const float2 ds8f = __half22float2(ds8);+ // second part effectively subtracts 8 from each quant value+ return d4 * (sumi * ds8f.x - (8*vdr/QI4_0) * ds8f.y);+}++template <int vdr> static __device__ __forceinline__ float vec_dot_q4_1_q8_1_impl(+ const int * v, const int * u, const half2 & dm4, const half2 & ds8) {+ int sumi = 0;+#pragma unroll+ for (int i = 0; i < vdr; ++i) {+ const int vi0 = (v[i] >> 0) & 0x0F0F0F0F;+ const int vi1 = (v[i] >> 4) & 0x0F0F0F0F;+ sumi = ggml_dp4a(vi0, u[2*i+0], sumi);+ sumi = ggml_dp4a(vi1, u[2*i+1], sumi);+ }+ const float2 dm4f = __half22float2(dm4);+ const float2 ds8f = __half22float2(ds8);+ const float d4d8 = dm4f.x * ds8f.x;+ const float m4s8 = dm4f.y * ds8f.y;+ // scale second part of sum by QI8_1/(vdr * QR4_1) to compensate for multiple threads adding it+ return sumi * d4d8 + m4s8 / (QI8_1 / (vdr * QR4_1));+}++// the 5th bit of the 8 quants held in vl[i] (low nibbles: bits 0..3 of vh, high nibbles: bits 16..19 of vh)+#define GGML_LEGACY_Q5_SUMI(vl_i, vh_i, u0, u1, sumi) \+ { \+ int vi0 = ((vl_i) >> 0) & 0x0F0F0F0F; \+ vi0 |= ((vh_i) << 4) & 0x00000010; \+ vi0 |= ((vh_i) << 11) & 0x00001000; \+ vi0 |= ((vh_i) << 18) & 0x00100000; \+ vi0 |= ((vh_i) << 25) & 0x10000000; \+ sumi = ggml_dp4a(vi0, (u0), sumi); \+ int vi1 = ((vl_i) >> 4) & 0x0F0F0F0F; \+ vi1 |= ((vh_i) >> 12) & 0x00000010; \+ vi1 |= ((vh_i) >> 5) & 0x00001000; \+ vi1 |= ((vh_i) << 2) & 0x00100000; \+ vi1 |= ((vh_i) << 9) & 0x10000000; \+ sumi = ggml_dp4a(vi1, (u1), sumi); \+ }++template <int vdr> static __device__ __forceinline__ float vec_dot_q5_0_q8_1_impl(+ const int * vl, const int * vh, const int * u, const float & d5, const half2 & ds8) {+ int sumi = 0;+#pragma unroll+ for (int i = 0; i < vdr; ++i) GGML_LEGACY_Q5_SUMI(vl[i], vh[i], u[2*i+0], u[2*i+1], sumi)+ const float2 ds8f = __half22float2(ds8);+ // second part effectively subtracts 16 from each quant value+ return d5 * (sumi * ds8f.x - (16*vdr/QI5_0) * ds8f.y);+}++template <int vdr> static __device__ __forceinline__ float vec_dot_q5_1_q8_1_impl(+ const int * vl, const int * vh, const int * u, const half2 & dm5, const half2 & ds8) {+ int sumi = 0;+#pragma unroll+ for (int i = 0; i < vdr; ++i) GGML_LEGACY_Q5_SUMI(vl[i], vh[i], u[2*i+0], u[2*i+1], sumi)+ const float2 dm5f = __half22float2(dm5);+ const float2 ds8f = __half22float2(ds8);+ const float d5d8 = dm5f.x * ds8f.x;+ const float m5s8 = dm5f.y * ds8f.y;+ // scale second part of sum by QI5_1 / vdr to compensate for multiple threads adding it+ return sumi * d5d8 + m5s8 / (QI5_1 / vdr);+}++static __device__ __forceinline__ float vec_dot_q4_0_q8_1(+ const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & kbx, const int & iqs) {+ const block_q4_0 * bq4_0 = (const block_q4_0 *) vbq + kbx;+ int v[VDR_Q4_0_Q8_1_MMVQ];+ int u[2*VDR_Q4_0_Q8_1_MMVQ];+#pragma unroll+ for (int i = 0; i < VDR_Q4_0_Q8_1_MMVQ; ++i) {+ v[i] = get_int_b2(bq4_0->qs, iqs + i);+ u[2*i+0] = get_int_b4(bq8_1->qs, iqs + i);+ u[2*i+1] = get_int_b4(bq8_1->qs, iqs + i + QI4_0);+ }+ return vec_dot_q4_0_q8_1_impl<VDR_Q4_0_Q8_1_MMVQ>(v, u, __half2float(bq4_0->d), bq8_1->ds);+}++static __device__ __forceinline__ float vec_dot_q4_1_q8_1(+ const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & kbx, const int & iqs) {+ const block_q4_1 * bq4_1 = (const block_q4_1 *) vbq + kbx;+ int v[VDR_Q4_1_Q8_1_MMVQ];+ int u[2*VDR_Q4_1_Q8_1_MMVQ];+#pragma unroll+ for (int i = 0; i < VDR_Q4_1_Q8_1_MMVQ; ++i) {+ v[i] = get_int_b4(bq4_1->qs, iqs + i);+ u[2*i+0] = get_int_b4(bq8_1->qs, iqs + i);+ u[2*i+1] = get_int_b4(bq8_1->qs, iqs + i + QI4_1);+ }+ return vec_dot_q4_1_q8_1_impl<VDR_Q4_1_Q8_1_MMVQ>(v, u, bq4_1->dm, bq8_1->ds);+}++static __device__ __forceinline__ float vec_dot_q5_0_q8_1(+ const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & kbx, const int & iqs) {+ const block_q5_0 * bq5_0 = (const block_q5_0 *) vbq + kbx;+ int vl[VDR_Q5_0_Q8_1_MMVQ];+ int vh[VDR_Q5_0_Q8_1_MMVQ];+ int u[2*VDR_Q5_0_Q8_1_MMVQ];+#pragma unroll+ for (int i = 0; i < VDR_Q5_0_Q8_1_MMVQ; ++i) {+ vl[i] = get_int_b2(bq5_0->qs, iqs + i);+ vh[i] = get_int_b2(bq5_0->qh, 0) >> (4 * (iqs + i));+ u[2*i+0] = get_int_b4(bq8_1->qs, iqs + i);+ u[2*i+1] = get_int_b4(bq8_1->qs, iqs + i + QI5_0);+ }+ return vec_dot_q5_0_q8_1_impl<VDR_Q5_0_Q8_1_MMVQ>(vl, vh, u, __half2float(bq5_0->d), bq8_1->ds);+}++static __device__ __forceinline__ float vec_dot_q5_1_q8_1(+ const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & kbx, const int & iqs) {+ const block_q5_1 * bq5_1 = (const block_q5_1 *) vbq + kbx;+ int vl[VDR_Q5_1_Q8_1_MMVQ];+ int vh[VDR_Q5_1_Q8_1_MMVQ];+ int u[2*VDR_Q5_1_Q8_1_MMVQ];+#pragma unroll+ for (int i = 0; i < VDR_Q5_1_Q8_1_MMVQ; ++i) {+ vl[i] = get_int_b4(bq5_1->qs, iqs + i);+ vh[i] = get_int_b4(&bq5_1->qh, 0) >> (4 * (iqs + i));+ u[2*i+0] = get_int_b4(bq8_1->qs, iqs + i);+ u[2*i+1] = get_int_b4(bq8_1->qs, iqs + i + QI5_1);+ }+ return vec_dot_q5_1_q8_1_impl<VDR_Q5_1_Q8_1_MMVQ>(vl, vh, u, bq5_1->dm, bq8_1->ds);+}++} // namespace ggml_iqdiff --git a/exllamav3/modules/foreign_linear.py b/exllamav3/modules/foreign_linear.pyindex f04b58c..0167b18 100644--- a/exllamav3/modules/foreign_linear.py+++ b/exllamav3/modules/foreign_linear.py@@ -99,6 +99,13 @@ _MMQ_FEW_MINR = {"q5_k": 3, "q4_k": 4, "q6_k": 4, "q8_0": 5, "q3_k": 4, "iq4_xs"# BOLT_FQ_MMQ_FEW_IQ4XS_ANY=1 serves every 4..24-row call. The other formats keep the unconditional gate._MMQ_FEW_CAPTURE_ONLY = () if os.environ.get("BOLT_FQ_MMQ_FEW_IQ4XS_ANY", "0") == "1" else ("iq4_xs",)_MMVQ_QK = {"iq4_nl": 32}+# EXL3_FQ_MMVQ_LEGACY (default 0): Q4_0 / Q4_1 / Q5_0 / Q5_1 single decode row through the mmvq kernel (ggml vec_dot_q*_q8_1 port, q8_1 activations) instead+# of the Triton triton_gap.gemv (~37 GB/s on gpt-oss-20b UD-Q4_K_XL attention q/k/v). Off = unchanged. 2+ rows stay on the Triton path.+_LEGACY_FMTS = ("q4_0", "q4_1", "q5_0", "q5_1")+_MMVQ_LEGACY = os.environ.get("EXL3_FQ_MMVQ_LEGACY", "0") == "1" and bool(torch.version.cuda) and not torch.version.hip+if _MMVQ_LEGACY:+ _MMVQ_FN.update({f: "fq_mmvq_" + f for f in _LEGACY_FMTS})+ _MMVQ_QK.update({f: 32 for f in _LEGACY_FMTS})_DEQ_IQ_ID = {"iq2_xs": 1, "iq2_s": 2, "iq3_xxs": 3, "iq3_s": 4, "iq4_nl": 5}if os.environ.get("BOLT_FQ_DEQ_Q3K", "1") != "0": # CUDA and HIP_DEQ_IQ_ID["q3_k"] = 10 # native Q3_K dequant (prefill dequant + GEMM; the torch gap_dequant is ~2.5x slower at 8K) # fq_dequant_iq format ids (the others have native dequants already)@@ -298,7 +305,7 @@ class ForeignLinear(Module):out = Noneif out is not None:pass- elif (_MMVQ_ON and self.format in _MMVQ_FN and flat.dtype == torch.half and R <= (min(_MMVQ_MAXR, FUSED_ROWS_MAX - 1) if self.format in ("q5_k", "q4_k", "q6_k", "q3_k") else _MMVQ_MAXR) and K % _MMVQ_QK.get(self.format, 256) == 0+ elif (_MMVQ_ON and self.format in _MMVQ_FN and flat.dtype == torch.half and (R == 1 or self.format not in _LEGACY_FMTS) and R <= (min(_MMVQ_MAXR, FUSED_ROWS_MAX - 1) if self.format in ("q5_k", "q4_k", "q6_k", "q3_k") else _MMVQ_MAXR) and K % _MMVQ_QK.get(self.format, 256) == 0and hasattr(ext, _MMVQ_FN[self.format])):N = self.out_featuresout = torch.empty((R, N), dtype=dtype if dtype in (torch.half, torch.float) else torch.half, device=dev)diff --git a/tests/test_fq_legacy_cpu.py b/tests/test_fq_legacy_cpu.pynew file mode 100644index 0000000..3659f5d--- /dev/null+++ b/tests/test_fq_legacy_cpu.py@@ -0,0 +1,147 @@+"""CPU tests for EXL3_FQ_MMVQ_LEGACY: (a) numpy ggml dequant == engine dequant for Q4_0/Q4_1/Q5_0/Q5_1 bytes,+(b) numpy emulation of the ported vec_dot (q8_1 activations, lane/iqs walk) ~= dequant(W) @ x, (c) forward() dispatch flag off/on.+(c) runs in a subprocess per flag value (the flag is read at import)."""+import os, sys, subprocess+import pytest+os.environ.setdefault("CUDA_VISIBLE_DEVICES", "")+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+import numpy as np++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+++def _xl():+ """Import the exllamav3 sub-packages under the name `xl` WITHOUT running exllamav3/__init__ (it would build/load the CUDA+ extension): bare package shells, a stub `xl.ext` and a stub Module base class."""+ import types+ if "xl" in sys.modules:+ return+ root = os.path.join(ROOT, "exllamav3")+ for name, sub in (("xl", ""), ("xl.modules", "modules"), ("xl.util", "util")):+ m = types.ModuleType(name); m.__path__ = [os.path.join(root, sub)]; sys.modules[name] = m+ ext = types.ModuleType("xl.ext"); ext.exllamav3_ext = types.SimpleNamespace(); sys.modules["xl.ext"] = ext+ mod = types.ModuleType("xl.modules.module"); mod.Module = type("Module", (), {"__init__": lambda self, *a, **k: None})+ sys.modules["xl.modules.module"] = mod+++BB = {"q4_0": 18, "q4_1": 20, "q5_0": 22, "q5_1": 24}++def rand_blocks(fmt, n, nb, rng):+ raw = rng.integers(0, 256, size=(n, nb, BB[fmt]), dtype=np.uint8)+ def f16(lo, hi, shape):+ return rng.uniform(lo, hi, shape).astype(np.float16).view(np.uint8).reshape(*shape, 2)+ raw[:, :, 0:2] = f16(0.01, 0.1, (n, nb))+ if fmt in ("q4_1", "q5_1"):+ raw[:, :, 2:4] = f16(-1, 1, (n, nb))+ return raw.reshape(n, nb * BB[fmt])++def f16at(b, o):+ return np.ascontiguousarray(b[..., o:o + 2]).view(np.float16)[..., 0].astype(np.float32)++def deq_np(fmt, raw): # ggml dequantize_row_q*: low nibbles = elements 0..15, high = 16..31+ n = raw.shape[0]; b = raw.reshape(n, -1, BB[fmt]); d = f16at(b, 0)[..., None]+ if fmt == "q4_0":+ qs = b[..., 2:18]; lo, hi = (qs & 15).astype(np.float32) - 8, (qs >> 4).astype(np.float32) - 8+ return (d * np.concatenate([lo, hi], -1)).reshape(n, -1)+ if fmt == "q4_1":+ m = f16at(b, 2)[..., None]; qs = b[..., 4:20]+ return (d * np.concatenate([(qs & 15), (qs >> 4)], -1).astype(np.float32) + m).reshape(n, -1)+ if fmt == "q5_0":+ qh = np.ascontiguousarray(b[..., 2:6]).view(np.uint32)[..., 0]; qs = b[..., 6:22]; j = np.arange(16)+ lo = (qs & 15) | (((qh[..., None] >> j) & 1) << 4); hi = (qs >> 4) | (((qh[..., None] >> (j + 16)) & 1) << 4)+ return (d * (np.concatenate([lo, hi], -1).astype(np.float32) - 16)).reshape(n, -1)+ m = f16at(b, 2)[..., None]; qh = np.ascontiguousarray(b[..., 4:8]).view(np.uint32)[..., 0]; qs = b[..., 8:24]; j = np.arange(16)+ lo = (qs & 15) | (((qh[..., None] >> j) & 1) << 4); hi = (qs >> 4) | (((qh[..., None] >> (j + 16)) & 1) << 4)+ return (d * np.concatenate([lo, hi], -1).astype(np.float32) + m).reshape(n, -1)++def q8_1(x): # block_q8_1: d = amax/127, q = round(x/d), s = d * sum(q) (as fq_quant_q8_1_rows)+ xb = x.reshape(-1, 32).astype(np.float32); amax = np.abs(xb).max(1, keepdims=True)+ d = amax / 127.0; q = np.where(d > 0, np.rint(xb / np.where(d > 0, d, 1)), 0).astype(np.int32)+ d16 = d.astype(np.float16).astype(np.float32); s16 = (d * q.sum(1, keepdims=True)).astype(np.float16).astype(np.float32)+ return q, d16[:, 0], s16[:, 0]++def u32(a): return np.ascontiguousarray(a).view(np.uint32).astype(np.uint32)++def dp4a(a, b): # a: 4 unsigned bytes (packed), b: 4 signed int8 (packed) -> int+ a8 = np.frombuffer(np.uint32(a).tobytes(), np.uint8).astype(np.int32); b8 = np.frombuffer(np.uint32(b).tobytes(), np.int8).astype(np.int32)+ return int((a8 * b8).sum())++def emulate_vecdot(fmt, raw, x): # port of the CUDA vec_dot_*_q8_1 with vdr=2, qi=4: 2 lanes (iqs 0, 2) per block, summed+ n = raw.shape[0]; K = x.shape[0]; nb = K // 32; qa, d8, s8 = q8_1(x)+ out = np.zeros(n, np.float32)+ for r in range(n):+ for kb in range(nb):+ blk = raw[r, kb * BB[fmt]:(kb + 1) * BB[fmt]]; u = [int(v) for v in u32(qa[kb].astype(np.int8).view(np.uint8))]+ for iqs in (0, 2):+ sumi = 0+ if fmt in ("q4_0", "q4_1"):+ off = 2 if fmt == "q4_0" else 4; qs = u32(blk[off:off + 16])+ for i in range(2):+ v = int(qs[iqs + i]); sumi += dp4a(v & 0x0F0F0F0F, u[iqs + i]) + dp4a((v >> 4) & 0x0F0F0F0F, u[iqs + i + 4])+ else:+ ho, qo = (2, 6) if fmt == "q5_0" else (4, 8); qh = int(u32(blk[ho:ho + 4])[0]); qs = u32(blk[qo:qo + 16])+ for i in range(2):+ vl = int(qs[iqs + i]); vh = qh >> (4 * (iqs + i)); M = 0xFFFFFFFF+ vi0 = (vl & 0x0F0F0F0F) | ((vh << 4) & 0x10) | ((vh << 11) & 0x1000) | ((vh << 18) & 0x100000) | ((vh << 25) & 0x10000000)+ vi1 = ((vl >> 4) & 0x0F0F0F0F) | ((vh >> 12) & 0x10) | ((vh >> 5) & 0x1000) | ((vh << 2) & 0x100000) | ((vh << 9) & 0x10000000)+ sumi += dp4a(vi0 & M, u[iqs + i]) + dp4a(vi1 & M, u[iqs + i + 4])+ d, ds, ss = f16at(blk, 0), d8[kb], s8[kb]+ if fmt == "q4_0": out[r] += d * (sumi * ds - 4 * ss)+ elif fmt == "q5_0": out[r] += d * (sumi * ds - 8 * ss)+ else:+ m = f16at(blk, 2); out[r] += sumi * d * ds + m * ss / 2+ return out++def test_numeric():+ import torch+ _xl()+ from xl.foreign_quant.gap_formats import dequant+ rng = np.random.default_rng(0)+ for fmt in BB:+ raw = rand_blocks(fmt, 6, 8, rng) # 6 rows x K=256+ ref = deq_np(fmt, raw)+ # q4_1 is not an engine format yet (not in BLOCKS / _FORMATS): numpy reference only+ e1 = np.abs(ref - dequant(fmt, torch.from_numpy(raw)).float().numpy()).max() if fmt != "q4_1" else 0.0+ x = rng.standard_normal(256).astype(np.float32)+ y = emulate_vecdot(fmt, raw, x); yref = ref.astype(np.float64) @ x+ e2 = np.abs(y - yref).max() / np.abs(yref).max()+ print(f"{fmt}: numpy-vs-engine dequant max abs {e1:.2e} (fp16 rounding); vec_dot emulation vs W@x rel {e2:.2e}")+ assert e1 < 2e-3 * max(1, np.abs(ref).max()) and e2 < 2e-2, fmt++def child():+ import types, torch+ _xl()+ import xl.modules.foreign_linear as fl+ flag = fl._MMVQ_LEGACY; calls = []+ ext = types.SimpleNamespace(fq_q8_scratch=lambda dev, R, K: torch.zeros(R, K // 32 * 36, dtype=torch.uint8),+ fq_quant_q8_1_rows=lambda x, qb: None)+ for f in ("q4_0", "q4_1", "q5_0", "q5_1", "iq4_nl", "q4_k"):+ setattr(ext, "fq_mmvq_" + f, (lambda f: lambda qb, p, out: calls.append(("mmvq", f)))(f))+ fl.ext = ext; torch.cuda.current_device = lambda: 0+ fl.triton_gap.gemv = lambda fmt, x, p: (calls.append(("triton", fmt)), torch.zeros(x.shape[0], p.shape[0], dtype=torch.half))[1]+ fl.triton_gap.supported = lambda *a, **k: True+ res = {}+ for fmt in ("q4_0", "q5_0", "q5_1"): # q4_1 cannot be a ForeignLinear (not in _FORMATS)+ for R in (1, 2):+ m = object.__new__(fl.ForeignLinear); m.format = fmt; m.in_features = 64; m.out_features = 4; m.key = "t"+ m.packed = torch.zeros(4, 2 * BB[fmt], dtype=torch.uint8); m.scales = None; m.global_scale = None+ m.out_dtype = torch.half; m.post_scale = 1.0; m.softcap = 0.0; m.pre_scale = 1.0+ calls.clear()+ try: m.forward(torch.zeros(R, 64, dtype=torch.half), {})+ except Exception as e: calls.append(("exc", type(e).__name__ + str(e)[:80]))+ res[(fmt, R)] = calls[0] if calls else None+ print("flag", int(flag), res)+ for (fmt, R), c in res.items():+ want = ("mmvq", fmt) if (flag and R == 1) else ("triton", fmt)+ assert c == want, (fmt, R, c, want)+ print("dispatch OK flag", int(flag))+[email protected]("flag", ["0", "1"])+def test_dispatch(flag):+ r = subprocess.run([sys.executable, __file__, "child"], env={**os.environ, "EXL3_FQ_MMVQ_LEGACY": flag},+ capture_output=True, text=True, timeout=100)+ assert r.returncode == 0, r.stdout[-900:] + r.stderr[-1500:]+++if __name__ == "__main__" and len(sys.argv) > 1 and sys.argv[1] == "child":+ child()diff --git a/tests/test_fq_mmvq_legacy_gpu.py b/tests/test_fq_mmvq_legacy_gpu.pynew file mode 100644index 0000000..3cbd390--- /dev/null+++ b/tests/test_fq_mmvq_legacy_gpu.py@@ -0,0 +1,38 @@+"""GPU check for the legacy-block fq_mmvq kernels (Q4_0 / Q4_1 / Q5_0 / Q5_1, 1 row): y = fq_mmvq(q8_1(x)) vs dequant(W) @ x.+The tolerance covers the q8_1 activation noise (llama.cpp quantizes the activations the same way)."""+import os+import sys++import numpy as np+import pytest+import torch++pytestmark = pytest.mark.skipif(not torch.cuda.is_available() or bool(torch.version.hip), reason="needs CUDA")+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_fq_legacy_cpu import BB, deq_np, rand_blocks # noqa: E402++SHAPES = [(64, 256), (96, 1024), (256, 512)] # (N out, K in)++[email protected]("fmt", ["q4_0", "q4_1", "q5_0", "q5_1"])[email protected]("N,K", SHAPES)+def test_mmvq_legacy_vs_dequant(fmt, N, K):+ from exllamav3.ext import exllamav3_ext as ext+ fn = getattr(ext, "fq_mmvq_" + fmt, None)+ if fn is None:+ pytest.skip("extension built without the legacy mmvq kernels")+ dev = torch.device("cuda:0")+ rng = np.random.default_rng(1)+ raw = rand_blocks(fmt, N, K // 32, rng)+ packed = torch.from_numpy(raw).to(dev)+ W = torch.from_numpy(deq_np(fmt, raw)).to(dev) # fp32 reference dequant (ggml dequantize_row_q*)+ x = torch.randn(1, K, device=dev, dtype=torch.half)+ ref = (W.double() @ x.double().t()).t().float() # [1, N]+ qb = ext.fq_q8_scratch(0, 1, K)+ out = torch.empty(1, N, dtype=torch.half, device=dev)+ ext.fq_quant_q8_1_rows(x, qb)+ fn(qb, packed, out)+ torch.cuda.synchronize()+ assert torch.isfinite(out).all()+ rel = (out.float() - ref).abs().max().item() / ref.abs().max().item()+ assert rel < 3e-2, (fmt, N, K, rel)