Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

GGUF Q3_K on CUDA (mmvq, native dequant, few-row MMQ) + IQ4_XS few-row MMQ in decode graphs (#228)

Yaniss Amazouz06294c897807
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index b2b6ba3..0943079 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -26,9 +26,9 @@ llama.cpp (https://github.com/ggml-org/llama.cpp, commit 7182ef7):
- ggml_vecdotq_iq.cuh: the vec_dot_iq*_q8_1 functions and helpers from ggml/src/ggml-cuda/vecdotq.cuh (only ggml_cuda_dp4a renamed to __dp4a,
CUDA-only helpers).
- fq_mmvq.cu: kernel structure after ggml/src/ggml-cuda/mmvq.cu (mul_mat_vec_q, mul_mat_vec_q_moe).
-- ggml_vecdotq_k46.cuh: vec_dot_q4_K_q8_1 and vec_dot_q6_K_q8_1 (with their _impl helpers) and the block_q4_K / block_q6_K layouts,
- from llama.cpp commit 61dbf49 (only ggml_cuda_dp4a renamed to ggml_dp4a).
-- fq_mmq_few.cu: the few-row MMQ (mul_mat_q_few, its Q8_0 / Q4_K / Q5_K / Q6_K decoders and quantize_mmq_few_q8_1) of llama.cpp PR #31533
+- ggml_vecdotq_k46.cuh: vec_dot_q4_K_q8_1, vec_dot_q6_K_q8_1 and vec_dot_q3_K_q8_1 (with their _impl helpers) and the block_q4_K / block_q6_K /
+ block_q3_K layouts, from llama.cpp commit 61dbf49 (only ggml_cuda_dp4a renamed to ggml_dp4a, __vsubss4 wrapped for HIP).
+- fq_mmq_few.cu: the few-row MMQ (mul_mat_q_few, its Q8_0 / Q4_K / Q5_K / Q6_K decoders and quantize_mmq_few_q8_1; the Q3_K and IQ4_XS decoders are new, in the style of the Q6_K one) of llama.cpp PR #31533
(ggml/src/ggml-cuda/mmq-few.cu, quantize.cu; merge commit 0fb8f15770, release v1.0.0), with unpack_scales_q45_K (mmq-load-tiles.cuh) and
the int8 mma / cp.async PTX of mma.cuh / cp-async.cuh inlined. Renamed: ggml_type -> local MF_* ids, tile<16, 8, int> -> mf_c_tile;
one channel, half input, half or float output, no PDL / DGX Spark prefetch.
diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cpp
index 93b790e..efc7bd8 100644
--- a/exllamav3/exllamav3_ext/bindings.cpp
+++ b/exllamav3/exllamav3_ext/bindings.cpp
@@ -670,6 +670,8 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
py::arg("qb"), py::arg("packed"), py::arg("out"));
m.def("fq_mmvq_q6_k", &fq_mmvq_q6_k, "fq_mmvq_q6_k",
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"));
#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_mmq_few.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_mmq_few.cu
index e169cfd..4c7582b 100644
--- a/exllamav3/exllamav3_ext/foreign_quant/fq_mmq_few.cu
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_mmq_few.cu
@@ -1,10 +1,10 @@
-// Few-row MMQ (2..24 activation rows) for the dense GGUF Q8_0 / Q4_K / Q5_K / Q6_K linears: int8 MMA (m16n8k32 / m16n8k16) on raw
+// Few-row MMQ (2..24 activation rows) for the dense GGUF Q8_0 / Q4_K / Q5_K / Q6_K / Q3_K / IQ4_XS linears: int8 MMA (m16n8k32 / m16n8k16) on raw
// GGUF weight rows streamed through a per-warp cp.async ring, activations quantized to q8_1 in the MMA fragment layout.
//
// Ported from llama.cpp ggml/src/ggml-cuda/mmq-few.cu and quantize.cu (quantize_mmq_few_q8_1), PR #31533 "CUDA: few-row MMQ for
// BS 2-24" (https://github.com/ggml-org/llama.cpp, merge commit 0fb8f15770, release v1.0.0).
// MIT License, Copyright (c) 2023-2026 The ggml authors. See THIRD_PARTY_NOTICES.md at the repository root.
-// Changes: only the Q8_0 / Q4_K / Q5_K / Q6_K decoders; one channel and sample (no broadcast strides); half or float output; the
+// Changes: only the Q8_0 / Q4_K / Q5_K / Q6_K decoders (plus Q3_K and IQ4_XS decoders added here in the same style, not in llama.cpp); one channel and sample (no broadcast strides); half or float output; the
// tile / mma / cp.async helpers of mma.cuh / cp-async.cuh inlined as PTX (Ampere+ only); no PDL, no DGX Spark L2 prefetch;
// the src1 input is half (converted to float before the same quantization arithmetic). The decoder and kernel bodies are unchanged.
// NVIDIA only (sm_80+): this file is not built on ROCm (foreign_quant is excluded there, see build_config.py).
@@ -21,7 +21,7 @@ namespace {
using namespace ggml_iq;
-enum { MF_Q8_0 = 0, MF_Q4_K = 1, MF_Q5_K = 2, MF_Q6_K = 3 };
+enum { MF_Q8_0 = 0, MF_Q4_K = 1, MF_Q5_K = 2, MF_Q6_K = 3, MF_Q3_K = 4, MF_IQ4_XS = 5 };
struct block_q8_0_mf { half d; int8_t qs[32]; };
static_assert(sizeof(block_q8_0_mf) == 34, "ggml block layout");
@@ -36,7 +36,7 @@ constexpr int MF_QUANT_BLOCK = 128; // CUDA_QUANTIZE_BLOCK_SIZE_M
// src0 bytes per 256 values
constexpr __host__ __device__ int mmq_few_unit_size(const int type) {
- return type == MF_Q8_0 ? 8*34 : type == MF_Q4_K ? 144 : type == MF_Q5_K ? 176 : type == MF_Q6_K ? 210 : 0;
+ return type == MF_Q8_0 ? 8*34 : type == MF_Q4_K ? 144 : type == MF_Q5_K ? 176 : type == MF_Q6_K ? 210 : type == MF_Q3_K ? 110 : type == MF_IQ4_XS ? 136 : 0;
}
// Q4_K and Q5_K also need the src1 sums for their mins (DS4 layout: half2 (d, sum)), the others take float d (D4).
@@ -356,6 +356,98 @@ __device__ __forceinline__ void mmq_few_vec_dot_q6_K(const char * const (&x)[2],
mmq_few_add_scaled(sum, d, sum_d);
}
+// Q3_K (new, written for this file on the Q6_K decoder; the bit layout is ggml dequantize_row_q3_K / vec_dot_q3_K_q8_1): 3-bit values
+// (low 2 bits of qs, inverted high bit of hmask: 0 -> subtract 4) with a 6-bit scale per 16 values -> one k=16 MMA per half of a sub-block.
+template <int ncg>
+__device__ __forceinline__ void mmq_few_vec_dot_q3_K(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) {
+ const int t = threadIdx.x % 4;
+
+ float d[2];
+ int scw[2][3];
+ int hm[2][2];
+#pragma unroll
+ for (int r = 0; r < 2; ++r) {
+ const block_q3_K * bx = (const block_q3_K *) x[r];
+ d[r] = __half2float(bx->d);
+#pragma unroll
+ for (int w = 0; w < 3; ++w) {
+ scw[r][w] = get_int_b2(bx->scales, w);
+ }
+ hm[r][0] = ~get_int_b2(bx->hmask, t);
+ hm[r][1] = ~get_int_b2(bx->hmask + 16, t);
+ }
+
+ float sum_d[ncg][4] = {{0.0f}};
+#pragma unroll
+ for (int n = 0; n < 2; ++n) {
+ int qs[2][2];
+#pragma unroll
+ for (int r = 0; r < 2; ++r) {
+ const block_q3_K * bx = (const block_q3_K *) x[r];
+ qs[r][0] = get_int_b2(bx->qs + 32*n, t);
+ qs[r][1] = get_int_b2(bx->qs + 32*n + 16, t);
+ }
+#pragma unroll
+ for (int j = 0; j < 4; ++j) {
+ const int s = 4*n + j;
+ int lo[2];
+ int hi[2];
+ int sc_s[2];
+#pragma unroll
+ for (int r = 0; r < 2; ++r) {
+ lo[r] = ggml_vsubss4((qs[r][0] >> (2*j)) & 0x03030303, ((hm[r][0] >> s) << 2) & 0x04040404);
+ hi[r] = ggml_vsubss4((qs[r][1] >> (2*j)) & 0x03030303, ((hm[r][1] >> s) << 2) & 0x04040404);
+ int sv[2];
+#pragma unroll
+ for (int h = 0; h < 2; ++h) {
+ const int is = 2*s + h;
+ const int low = (scw[r][(is % 8)/4] >> (8*(is % 4) + 4*(is/8))) & 0xF;
+ const int high = ((scw[r][2] >> (8*(is % 4) + 2*(is/4))) & 3) << 4;
+ sv[h] = (low | high) - 32;
+ }
+ sc_s[r] = (sv[0] & 0xFF) | ((sv[1] & 0xFF) << 8);
+ }
+ mmq_few_mma_k16_add<MF_Q3_K>(lo, hi, sc_s, yf, s, sum_d);
+ }
+ }
+ mmq_few_add_scaled(sum, d, sum_d);
+}
+
+// IQ4_XS: 4-bit non-linear values (kvalues_iq4nl) with a 6-bit scale per 32 values, low nibbles = values [0, 16), high nibbles = [16, 32).
+template <int ncg>
+__device__ __forceinline__ void mmq_few_vec_dot_iq4_xs(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) {
+ const int t = threadIdx.x % 4;
+
+ float d[2];
+ int scl[2];
+ int sch[2];
+#pragma unroll
+ for (int r = 0; r < 2; ++r) {
+ const block_iq4_xs * bx = (const block_iq4_xs *) x[r];
+ d[r] = __half2float(bx->d);
+ scl[r] = get_int_b2(bx->scales_l, 0);
+ sch[r] = bx->scales_h;
+ }
+
+ float sum_d[ncg][4] = {{0.0f}};
+#pragma unroll
+ for (int s = 0; s < 8; ++s) {
+ int lo[2];
+ int hi[2];
+ int ls[2];
+#pragma unroll
+ for (int r = 0; r < 2; ++r) {
+ const block_iq4_xs * bx = (const block_iq4_xs *) x[r];
+ const int2 v = get_int_from_table_16(get_int_b2(bx->qs + 16*s, t), kvalues_iq4nl);
+ lo[r] = v.x;
+ hi[r] = v.y;
+ ls[r] = (((scl[r] >> (4*s)) & 0xF) | (((sch[r] >> (2*s)) & 3) << 4)) - 32;
+ }
+ mmq_few_mma_add<MF_IQ4_XS>(lo, hi, ls, yf, s, sum_d);
+ }
+ mmq_few_add_scaled(sum, d, sum_d);
+}
+
template <int ncg>
__device__ __forceinline__ void mmq_few_vec_dot_q8_0(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) {
const int t = threadIdx.x % 4;
@@ -382,6 +474,10 @@ __device__ __forceinline__ void mmq_few_vec_dot(const char * const (&x)[2], cons
mmq_few_vec_dot_q8_0<ncg>(x, yf, sum);
} else if constexpr (type == MF_Q4_K || type == MF_Q5_K) {
mmq_few_vec_dot_q45_K<type, ncg>(x, yf, sum);
+ } else if constexpr (type == MF_Q3_K) {
+ mmq_few_vec_dot_q3_K<ncg>(x, yf, sum);
+ } else if constexpr (type == MF_IQ4_XS) {
+ mmq_few_vec_dot_iq4_xs<ncg>(x, yf, sum);
} else {
mmq_few_vec_dot_q6_K<ncg>(x, yf, sum);
}
@@ -649,14 +745,14 @@ void launch_switch_ncg(const uint8_t * x, const int4 * y, OUT * dst, int nunits,
} // namespace
-// out[R, N] = x[R, K] @ W^T for raw GGUF rows packed [N, K/256 * unit bytes] (fmt 0 Q8_0, 1 Q4_K, 2 Q5_K, 3 Q6_K), 1 <= R <= 24.
+// out[R, N] = x[R, K] @ W^T for raw GGUF rows packed [N, K/256 * unit bytes] (fmt 0 Q8_0, 1 Q4_K, 2 Q5_K, 3 Q6_K, 4 Q3_K, 5 IQ4_XS), 1 <= R <= 24.
// scratch: uint8 CUDA tensor of at least ceil(R/8) * K * 9 bytes (fq_q8_scratch(dev, 8*ceil(R/8), K) has exactly that size).
// Returns false (nothing launched) when the case is not served: GPU older than sm_80, K not a whole number of ring stages, short
// rows (K < 2048: the warps idle), misaligned weights.
bool fq_mmq_few(torch::Tensor x, torch::Tensor scratch, torch::Tensor packed, torch::Tensor out, int fmt)
{
TORCH_CHECK(x.is_cuda() && x.dtype() == torch::kHalf && x.is_contiguous() && x.dim() == 2, "x must be contiguous CUDA half [R, K]");
- TORCH_CHECK(fmt >= 0 && fmt <= 3, "fmt must be 0..3");
+ TORCH_CHECK(fmt >= 0 && fmt <= 5, "fmt must be 0..5");
const int R = (int) x.size(0), K = (int) x.size(1), N = (int) packed.size(0);
TORCH_CHECK(R >= 1 && R <= MMQ_FEW_MAX_NCG*MMQ_FEW_NCOLS, "R must be 1..24");
TORCH_CHECK(out.is_contiguous() && out.size(0) == R && out.size(1) == N, "out must be contiguous [R, N]");
@@ -694,6 +790,8 @@ bool fq_mmq_few(torch::Tensor x, torch::Tensor scratch, torch::Tensor packed, to
case MF_Q8_0: launch_switch_ncg<MF_Q8_0, OUT>(w, y, dst, nunits, N, R, row_bytes, ncg, nmt, stream); break;
case MF_Q4_K: launch_switch_ncg<MF_Q4_K, OUT>(w, y, dst, nunits, N, R, row_bytes, ncg, nmt, stream); break;
case MF_Q5_K: launch_switch_ncg<MF_Q5_K, OUT>(w, y, dst, nunits, N, R, row_bytes, ncg, nmt, stream); break;
+ case MF_Q3_K: launch_switch_ncg<MF_Q3_K, OUT>(w, y, dst, nunits, N, R, row_bytes, ncg, nmt, stream); break;
+ case MF_IQ4_XS: launch_switch_ncg<MF_IQ4_XS, OUT>(w, y, dst, nunits, N, R, row_bytes, ncg, nmt, stream); break;
default: launch_switch_ncg<MF_Q6_K, OUT>(w, y, dst, nunits, N, R, row_bytes, ncg, nmt, stream); break;
}
};
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu
index 76c9a0e..abc3899 100644
--- a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu
@@ -32,7 +32,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_NTYPES = 10 };
+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 };
// qk = weight elements per block, qi = ints per block (ggml QI*), vdr = ints per lane per call, bb = block bytes
template <int T> struct MqTraits;
@@ -52,6 +52,7 @@ MQ_TRAITS(MQ_IQ4_XS, 256, 32, VDR_IQ4_XS_Q8_1_MMVQ, 136, vec_dot_iq4_xs_q8_1);
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);
#undef MQ_TRAITS
constexpr int MQ_WARP = 32;
@@ -448,6 +449,23 @@ template <int T> __global__ void fq_deq_iq_kernel(const uint8_t* __restrict__ pa
y[j + 16] = __float2half_rn(d * kvalues_iq4nl[q4[j] >> 4]);
}
}
+ else if constexpr (T == MQ_Q3_K)
+ {
+ // ggml convert.cu dequantize_block_q3_K: thread = 8 values of one 16-value scale group
+ const block_q3_K* x = (const block_q3_K*)base + bi;
+ const int n = tid / 16, j = (tid / 4) % 4, half_ = (tid / 2) % 2, l8 = (tid % 2) * 8;
+ const int is = 8 * n + 2 * j + half_;
+ const int sc = (((x->scales[is % 8] >> (4 * (is / 8))) & 0xF) | (((x->scales[8 + is % 4] >> (2 * (is / 4))) & 3) << 4)) - 32;
+ const float dl = __half2float(x->d) * sc;
+ const int l = 16 * half_ + l8;
+ __half* y = y0 + 128 * n + 32 * j + l;
+ for (int e = 0; e < 8; ++e)
+ {
+ const int q = (x->qs[32 * n + l + e] >> (2 * j)) & 3;
+ const int hb = (x->hmask[l + e] >> (4 * n + j)) & 1;
+ y[e] = __float2half_rn(dl * (float)(q - (hb ? 0 : 4)));
+ }
+ }
else // MQ_IQ4_XS
{
const block_iq4_xs* x = (const block_iq4_xs*)base + bi;
@@ -491,6 +509,7 @@ void fq_mmvq_iq4_xs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) {
void fq_mmvq_q5_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mq_run<MQ_Q5_K>(qb, packed, out); }
void 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); }
// 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:
@@ -500,9 +519,9 @@ void fq_moe_mmvq_grouped(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
torch::Tensor down_ptrs, int64_t gate_stride, int64_t up_stride, int64_t down_stride, int64_t type_ug, int64_t type_down,
torch::Tensor partial, torch::Tensor out)
{
- static const int kQk[MQ_NTYPES] = {256, 256, 256, 256, 256, 32, 256, 256};
- static const int kBb[MQ_NTYPES] = {66, 74, 82, 98, 110, 18, 136, 176};
- TORCH_CHECK(type_ug >= 0 && type_ug < MQ_NTYPES && type_down >= 0 && type_down < MQ_NTYPES, "fq_moe_mmvq_grouped: bad format id");
+ static const int kQk[8] = {256, 256, 256, 256, 256, 32, 256, 256};
+ static const int kBb[8] = {66, 74, 82, 98, 110, 18, 136, 176};
+ TORCH_CHECK(type_ug >= 0 && type_ug < 8 && type_down >= 0 && type_down < 8, "fq_moe_mmvq_grouped: bad format id");
const int K = (int)h.size(1), R = (int)h.size(0), S = (int)sel.numel();
TORCH_CHECK(S % R == 0 && R >= 1, "sel must be R x topk");
TORCH_CHECK(h.dtype() == torch::kHalf && h.is_cuda() && h.is_contiguous(), "h must be contiguous half CUDA");
@@ -561,6 +580,7 @@ void fq_dequant_iq(torch::Tensor packed, torch::Tensor out, int64_t fmt)
case MQ_IQ3_S: mq_dequant_t<MQ_IQ3_S>(packed, out); break;
case MQ_IQ4_NL: mq_dequant_t<MQ_IQ4_NL>(packed, out); break;
case MQ_IQ4_XS: mq_dequant_t<MQ_IQ4_XS>(packed, out); break;
+ case MQ_Q3_K: mq_dequant_t<MQ_Q3_K>(packed, out); break;
default: TORCH_CHECK(false, "fq_dequant_iq: bad format id ", fmt);
}
}
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h
index 7fc3b1d..af5bad6 100644
--- a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h
@@ -13,15 +13,16 @@ void fq_mmvq_iq4_xs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);
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);
// 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,
torch::Tensor down_ptrs, int64_t gate_stride, int64_t up_stride, int64_t down_stride, int64_t type_ug, int64_t type_down,
torch::Tensor partial, torch::Tensor out);
-// Dequantize IQ blocks to fp16 [N, K] (K % 256 == 0); fmt = MQ type id as above (0..6). Port of ggml convert.cu dequantize_block_iq*.
+// Dequantize IQ blocks to fp16 [N, K] (K % 256 == 0); fmt = MQ type id as above (0..6, 10 q3_k). Port of ggml convert.cu dequantize_block_iq*.
void fq_dequant_iq(torch::Tensor packed, torch::Tensor out, int64_t fmt);
#if !defined(USE_ROCM)
// Few-row MMQ (fq_mmq_few.cu, CUDA sm_80+, port of llama.cpp PR #31533): out[R, N] = x[R, K] (half) @ W^T, R 1..24, raw GGUF rows
-// packed [N, K/256 * unit bytes], fmt 0 Q8_0, 1 Q4_K, 2 Q5_K, 3 Q6_K; scratch >= ceil(R/8)*K*9 bytes. False = not served (nothing launched).
+// packed [N, K/256 * unit bytes], fmt 0 Q8_0, 1 Q4_K, 2 Q5_K, 3 Q6_K, 4 Q3_K, 5 IQ4_XS; scratch >= ceil(R/8)*K*9 bytes. False = not served (nothing launched).
bool fq_mmq_few(torch::Tensor x, torch::Tensor scratch, torch::Tensor packed, torch::Tensor out, int fmt);
#endif
diff --git a/exllamav3/exllamav3_ext/foreign_quant/ggml_mmvq/ggml_vecdotq_k46.cuh b/exllamav3/exllamav3_ext/foreign_quant/ggml_mmvq/ggml_vecdotq_k46.cuh
index df606a2..295a43b 100644
--- a/exllamav3/exllamav3_ext/foreign_quant/ggml_mmvq/ggml_vecdotq_k46.cuh
+++ b/exllamav3/exllamav3_ext/foreign_quant/ggml_mmvq/ggml_vecdotq_k46.cuh
@@ -1,4 +1,4 @@
-// Q4_K and Q6_K vec-dots (q8_1 activations, integer dp4a dots) ported from llama.cpp ggml/src/ggml-cuda/vecdotq.cuh
+// Q4_K, Q6_K and Q3_K vec-dots (q8_1 activations, integer dp4a dots) ported from llama.cpp ggml/src/ggml-cuda/vecdotq.cuh
// (https://github.com/ggml-org/llama.cpp, commit 61dbf49) and block_q4_K / block_q6_K of ggml/src/ggml-common.h.
// MIT License, Copyright (c) 2023-2026 The ggml authors. See THIRD_PARTY_NOTICES.md at the repository root.
// Changes: ggml_cuda_dp4a -> ggml_dp4a, namespace ggml_iq, plain half2 / half block fields. The dot-product bodies are unchanged.
@@ -164,4 +164,93 @@ static __device__ __forceinline__ float vec_dot_q6_K_q8_1(
return vec_dot_q6_K_q8_1_impl_mmvq(vl, vh, u, scales, __half2float(bq6_K->d), d8);
}
+// ---- Q3_K (llama.cpp vecdotq.cuh vec_dot_q3_K_q8_1, same commit) ----
+#define QR3_K 4
+#define QI3_K (QK_K / (4*QR3_K))
+#define VDR_Q3_K_Q8_1_MMVQ 1
+
+struct block_q3_K {
+ uint8_t hmask[QK_K / 8]; // high bit, inverted (0 = subtract 4)
+ uint8_t qs[QK_K / 4]; // low 2 bits
+ uint8_t scales[12]; // 16 x 6-bit scales
+ half d;
+};
+static_assert(sizeof(block_q3_K) == 110, "ggml block layout");
+
+// saturating per-byte signed subtract (CUDA __vsubss4; HIP has none, llama.cpp vendors/hip.h computes it per byte)
+static __device__ __forceinline__ int ggml_vsubss4(const int a, const int b) {
+#if !defined(USE_ROCM)
+ return __vsubss4(a, b);
+#else
+ const int8_t * a8 = reinterpret_cast<const int8_t *>(&a);
+ const int8_t * b8 = reinterpret_cast<const int8_t *>(&b);
+ int8_t r[4];
+#pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ const int v = (int) a8[i] - (int) b8[i];
+ r[i] = (int8_t) (v > 127 ? 127 : (v < -128 ? -128 : v));
+ }
+ return *reinterpret_cast<const int *>(r);
+#endif
+}
+
+static __device__ __forceinline__ float vec_dot_q3_K_q8_1_impl_mmvq(
+ const int & vl, const int & vh, const int * __restrict__ u, const uint8_t * __restrict__ scales,
+ const int & scale_offset, const float & d3, const float * __restrict__ d8) {
+
+ float sumf = 0.0f;
+
+#pragma unroll
+ for (int i = 0; i < QR3_K; ++i) {
+ const int isc = scale_offset + 2*i;
+
+ const int isc_low = isc % (QK_K/32);
+ const int sc_shift_low = 4 * (isc / (QK_K/32));
+ const int sc_low = (scales[isc_low] >> sc_shift_low) & 0xF;
+
+ const int isc_high = isc % (QK_K/64);
+ const int sc_shift_high = 2 * (isc / (QK_K/64));
+ const int sc_high = ((scales[(QK_K/32) + isc_high] >> sc_shift_high) & 3) << 4;
+
+ const int sc = (sc_low | sc_high) - 32;
+
+ const int vil = (vl >> (2*i)) & 0x03030303;
+
+ const int vih = ((vh >> i) << 2) & 0x04040404;
+
+ const int vi = ggml_vsubss4(vil, vih);
+
+ sumf += d8[i] * (ggml_dp4a(vi, u[i], 0) * sc); // SIMD dot product
+ }
+
+ return d3 * sumf;
+}
+
+static __device__ __forceinline__ float vec_dot_q3_K_q8_1(
+ const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & kbx, const int & iqs) {
+
+ const block_q3_K * bq3_K = (const block_q3_K *) vbq + kbx;
+
+ const int bq8_offset = QR3_K * (iqs / (QI3_K/2));
+ const int scale_offset = iqs - iqs % QI8_1 + (iqs % QI8_1) / (QI8_1/2);
+
+ const float d = __half2float(bq3_K->d);
+
+ const int vl = get_int_b2(bq3_K->qs, iqs);
+
+ // invert the mask with ~ so that a 0/1 results in 4/0 being subtracted
+ const int vh = ~get_int_b2(bq3_K->hmask, iqs % (QI3_K/2)) >> bq8_offset;
+
+ int u[QR3_K];
+ float d8[QR3_K];
+
+#pragma unroll
+ for (int i = 0; i < QR3_K; ++i) {
+ u[i] = get_int_b4(bq8_1[bq8_offset + i].qs, iqs % QI8_1);
+ d8[i] = __low2float(bq8_1[bq8_offset + i].ds);
+ }
+
+ return vec_dot_q3_K_q8_1_impl_mmvq(vl, vh, u, bq3_K->scales, scale_offset, d, d8);
+}
+
} // namespace ggml_iq
diff --git a/exllamav3/modules/foreign_linear.py b/exllamav3/modules/foreign_linear.py
index 3f985f9..ad0433a 100644
--- a/exllamav3/modules/foreign_linear.py
+++ b/exllamav3/modules/foreign_linear.py
@@ -82,15 +82,21 @@ _MMVQ_FN = {"iq2_xxs": "fq_mmvq_iq2_xxs", "iq2_xs": "fq_mmvq_iq2_xs", "iq2_s": "
# BOLT_FQ_MMVQ_KQ: Q4_K / Q6_K decode rows (1..15) also through the mmvq kernel (llama.cpp vec_dot_q4_K / q6_K_q8_1). Default on for
# CUDA (RTX 3090, 8B Q4_K_M served: N8 +28 %, N4 +11 %, N1 +4 %), off on ROCm until measured there; 0 / 1 forces.
if os.environ.get("BOLT_FQ_MMVQ_KQ", "1" if (torch.version.cuda and not torch.version.hip) else "0") == "1":
- _MMVQ_FN.update({"q4_k": "fq_mmvq_q4_k", "q6_k": "fq_mmvq_q6_k"})
+ _MMVQ_FN.update({"q4_k": "fq_mmvq_q4_k", "q6_k": "fq_mmvq_q6_k", "q3_k": "fq_mmvq_q3_k"})
# BOLT_FQ_MMQ_FEW: Q8_0 / Q4_K / Q5_K / Q6_K rows from a per-format minimum up to 24 through the few-row int8-MMA kernel (fq_mmq_few.cu,
# llama.cpp PR #31533 port, thresholds tuned there on an RTX 5090). CUDA only (sm_80+), off on ROCm; 0 / 1 forces. RTX 3090 served, 8 sessions:
# 8B Q4_K_M N4 +15 %, N8 +54 % (different prompts) / +77 % (same prompt), N1 and 8K prefill unchanged; 35B-A3B GGUF N8 +21 % / +26 %.
_MMQ_FEW = os.environ.get("BOLT_FQ_MMQ_FEW", "1" if (torch.version.cuda and not torch.version.hip) else "0") == "1"
-_MMQ_FEW_FMT = {"q8_0": 0, "q4_k": 1, "q5_k": 2, "q6_k": 3}
-_MMQ_FEW_MINR = {"q5_k": 3, "q4_k": 4, "q6_k": 4, "q8_0": 5}
+_MMQ_FEW_FMT = {"q8_0": 0, "q4_k": 1, "q5_k": 2, "q6_k": 3, "q3_k": 4, "iq4_xs": 5}
+_MMQ_FEW_MINR = {"q5_k": 3, "q4_k": 4, "q6_k": 4, "q8_0": 5, "q3_k": 4, "iq4_xs": 4}
+# IQ4_XS few-row MMQ only inside CUDA-graph capture (the batched decode steps). Eager calls with 4..24 rows are prompt-chunk tails: there the
+# int8 activations would change the prompt KV (single-session output and decode path differ from the 1-row mmvq route) for no speed gain.
+# 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}
-_DEQ_IQ_ID = {"iq2_xs": 1, "iq2_s": 2, "iq3_xxs": 3, "iq3_s": 4, "iq4_nl": 5} # fq_dequant_iq format ids (the others have native dequants already)
+_DEQ_IQ_ID = {"iq2_xs": 1, "iq2_s": 2, "iq3_xxs": 3, "iq3_s": 4, "iq4_nl": 5}
+if torch.version.cuda and not torch.version.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)
# rows served by the mmvq kernel (8 columns per launch, so R/8 passes over the weights): the old IQ path above 16 rows dequantized the whole weight in torch
# on every call (1.7 s for the 8B at ANY prompt length). Past ~64 rows the dequant + GEMM path is the better one again.
_MMVQ_MAXR = int(os.environ.get("BOLT_FQ_MMVQ_MAXR", "64"))
@@ -274,7 +280,8 @@ class ForeignLinear(Module):
flat = flat.contiguous()
out: Optional[torch.Tensor] = None
if (_MMQ_FEW and self.format in _MMQ_FEW_FMT and _MMQ_FEW_MINR[self.format] <= R <= 24 and flat.dtype == torch.half
- and K % 256 == 0 and K >= 2048 and hasattr(ext, "fq_mmq_few")):
+ and K % 256 == 0 and K >= 2048 and hasattr(ext, "fq_mmq_few")
+ and (self.format not in _MMQ_FEW_CAPTURE_ONLY or torch.cuda.is_current_stream_capturing())):
N = self.out_features
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()
@@ -285,7 +292,7 @@ class ForeignLinear(Module):
out = None
if 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") 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 <= (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
and hasattr(ext, _MMVQ_FN[self.format])):
N = self.out_features
out = torch.empty((R, N), dtype=dtype if dtype in (torch.half, torch.float) else torch.half, device=dev)
diff --git a/tests/test_mmvq_iq.py b/tests/test_mmvq_iq.py
index 95d1560..506e923 100644
--- a/tests/test_mmvq_iq.py
+++ b/tests/test_mmvq_iq.py
@@ -15,9 +15,9 @@ FMTS = { # name: (block bytes, elements per block, mmvq id)
"iq3_s": (110, 256, 4), "iq4_nl": (18, 32, 5), "iq4_xs": (136, 256, 6), "q5_k": (176, 256, 7),
}
# dense-only K-quant entries (llama.cpp vec_dot_q4_K / q6_K_q8_1 in fq_mmvq.cu; no grouped MoE id)
-KQ_DENSE = {"q4_k": (144, 256, 8), "q6_k": (210, 256, 9)}
+KQ_DENSE = {"q4_k": (144, 256, 8), "q6_k": (210, 256, 9), "q3_k": (110, 256, 10)}
# few-row MMQ formats (fq_mmq_few.cu, llama.cpp PR #31533 port): name -> (block bytes, elements per block, fq_mmq_few fmt id)
-MMQ_FEW = {"q8_0": (34, 32, 0), "q4_k": (144, 256, 1), "q5_k": (176, 256, 2), "q6_k": (210, 256, 3)}
+MMQ_FEW = {"q8_0": (34, 32, 0), "q4_k": (144, 256, 1), "q5_k": (176, 256, 2), "q6_k": (210, 256, 3), "q3_k": (110, 256, 4), "iq4_xs": (136, 256, 5)}
def make_weights(fmt, n, k, seed, dscale=1.0):
@@ -25,8 +25,8 @@ def make_weights(fmt, n, k, seed, dscale=1.0):
g = torch.Generator().manual_seed(seed)
w = torch.randint(0, 256, (n, k // qk, bb), generator=g, dtype=torch.uint8)
d = ((torch.rand(n, k // qk, generator=g) * 0.02 + 0.001) * dscale).half().view(torch.uint8).reshape(n, k // qk, 2)
- if fmt == "q6_k": # d is the last field of block_q6_K
- w[:, :, 208:210] = d
+ if fmt in ("q6_k", "q3_k"): # d is the last field of block_q6_K / block_q3_K
+ w[:, :, bb - 2:bb] = d
else:
w[:, :, 0:2] = d
if fmt in ("q5_k", "q4_k"): # half2 (d, dmin)
@@ -48,7 +48,7 @@ def dequant(fmt, w, n, k):
out = torch.empty((n, k), dtype=torch.half, device="cuda")
getattr(ext, f"fq_dequant_{fmt}")(w, out)
return out.float()
- return gap_formats.dequant(fmt, w).float().reshape(n, k)
+ return gap_formats.dequant(fmt, w).float().reshape(n, k) # q3_k: the torch gap reference
def q8_dequant(qb, m, k):
@@ -91,6 +91,19 @@ def test_dense():
d = float((out - o).norm() / o.norm())
assert d < 2e-5, f"{fmt} [{n}x{k}] m={m}: differs from {old} by {d:.2e}"
worst_old[0] = max(worst_old[0], d)
+ if fmt == "q3_k": # vs the Triton gap kernel (fp16 activations, so the q8_1 quantization error shows: ~1e-2 relative)
+ from exllamav3.foreign_quant import triton_iq
+ n, k, m = 1024, 4096, 4
+ w = make_weights(fmt, n, k, 7)
+ x = (torch.randn(m, k, generator=torch.Generator().manual_seed(m)) * 0.5).half().cuda()
+ qb = ext.fq_q8_scratch(torch.cuda.current_device(), m, k)
+ ext.fq_quant_q8_1_rows(x, qb)
+ o = torch.empty((m, n), dtype=torch.float, device="cuda")
+ ext.fq_mmvq_q3_k(qb, w, o)
+ t = triton_iq.gemv("q3_k", x, w.reshape(n, -1)).float()
+ d = float((o - t).norm() / t.norm())
+ print(f"dense q3_k vs the Triton gap kernel: {d:.2e}")
+ assert d < 1e-2, f"q3_k differs from the Triton gap kernel by {d}"
print(f"dense {fmt}: ok")
print(f"dense worst fp32-out rel err vs dequant reference {worst:.2e}, vs previous q8 kernels {worst_old[0]:.2e}")
@@ -108,6 +121,15 @@ def test_dequant():
bad = int((out.view(torch.int16) != ref.view(torch.int16)).sum())
print(f"dequant {fmt}: {bad} of {n * k} fp16 values differ from the reference")
assert bad == 0, f"{fmt}: fq_dequant_iq differs from the reference"
+ n, k = 96, 1024
+ w = make_weights("q3_k", n, k, 11)
+ ref = gap_formats.dequant("q3_k", w).half().reshape(n, k)
+ out = torch.empty((n, k), dtype=torch.half, device="cuda")
+ ext.fq_dequant_iq(w, out, 10)
+ torch.cuda.synchronize()
+ bad = int((out.view(torch.int16) != ref.view(torch.int16)).sum())
+ print(f"dequant q3_k: {bad} of {n * k} fp16 values differ from the torch gap reference")
+ assert bad == 0, "q3_k: fq_dequant_iq differs from the reference"
def moe_case(fug, fd, K, I, E, R, topk, seed):