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
Generic GGUF decode: bias in the fq_mmvq epilogue + one q8_1 quantize for q/k/v (EXL3_FQ_MMVQ_EPI)
YanissAmz34ab1d2e7845
diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cppindex 6209855..b32cf55 100644--- a/exllamav3/exllamav3_ext/bindings.cpp+++ b/exllamav3/exllamav3_ext/bindings.cpp@@ -619,6 +619,7 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)m.def("fq_mlp_shared_iq2xxs", &fq_mlp_shared_iq2xxs, "fq_mlp_shared_iq2xxs",py::arg("x"), py::arg("up_packed"), py::arg("h"));#endif+ m.def("fq_mmvq_epi_abi", &fq_mmvq_epi_abi, "fq_mmvq_epi_abi");m.def("fq_q8_scratch", &fq_q8_scratch, "fq_q8_scratch",py::arg("dev"), py::arg("M"), py::arg("K"));m.def("fq_quant_q8_1_rows", &fq_quant_q8_1_rows, "fq_quant_q8_1_rows",@@ -646,19 +647,19 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)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"));m.def("fq_mmvq_iq2_xxs", &fq_mmvq_iq2_xxs, "fq_mmvq_iq2_xxs",- py::arg("qb"), py::arg("packed"), py::arg("out"));+ py::arg("qb"), py::arg("packed"), py::arg("out"), py::arg("bias") = py::none());m.def("fq_mmvq_iq2_xs", &fq_mmvq_iq2_xs, "fq_mmvq_iq2_xs",- py::arg("qb"), py::arg("packed"), py::arg("out"));+ py::arg("qb"), py::arg("packed"), py::arg("out"), py::arg("bias") = py::none());m.def("fq_mmvq_iq2_s", &fq_mmvq_iq2_s, "fq_mmvq_iq2_s",- py::arg("qb"), py::arg("packed"), py::arg("out"));+ py::arg("qb"), py::arg("packed"), py::arg("out"), py::arg("bias") = py::none());m.def("fq_mmvq_iq3_xxs", &fq_mmvq_iq3_xxs, "fq_mmvq_iq3_xxs",- py::arg("qb"), py::arg("packed"), py::arg("out"));+ py::arg("qb"), py::arg("packed"), py::arg("out"), py::arg("bias") = py::none());m.def("fq_mmvq_iq3_s", &fq_mmvq_iq3_s, "fq_mmvq_iq3_s",- py::arg("qb"), py::arg("packed"), py::arg("out"));+ py::arg("qb"), py::arg("packed"), py::arg("out"), py::arg("bias") = py::none());m.def("fq_mmvq_iq4_nl", &fq_mmvq_iq4_nl, "fq_mmvq_iq4_nl",- py::arg("qb"), py::arg("packed"), py::arg("out"));+ py::arg("qb"), py::arg("packed"), py::arg("out"), py::arg("bias") = py::none());m.def("fq_mmvq_iq4_xs", &fq_mmvq_iq4_xs, "fq_mmvq_iq4_xs",- py::arg("qb"), py::arg("packed"), py::arg("out"));+ py::arg("qb"), py::arg("packed"), py::arg("out"), py::arg("bias") = py::none());m.def("fq_dequant_iq", &fq_dequant_iq, "fq_dequant_iq", py::arg("packed"), py::arg("out"), py::arg("fmt"));m.def("fq_moe_mmvq_grouped", &fq_moe_mmvq_grouped, "fq_moe_mmvq_grouped",py::arg("h"), py::arg("sel"), py::arg("wts"), py::arg("gate_ptrs"), py::arg("up_ptrs"), py::arg("down_ptrs"),@@ -670,21 +671,21 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)m.def("fq_mxfp4_moe_down", &fq_mxfp4_moe_down, "fq_mxfp4_moe_down",py::arg("qb"), py::arg("sel"), py::arg("down_ptrs"), py::arg("down_bias"), py::arg("out"), py::arg("N"), py::arg("K"));m.def("fq_mmvq_q5_k", &fq_mmvq_q5_k, "fq_mmvq_q5_k",- py::arg("qb"), py::arg("packed"), py::arg("out"));+ py::arg("qb"), py::arg("packed"), py::arg("out"), py::arg("bias") = py::none());m.def("fq_mmvq_q4_k", &fq_mmvq_q4_k, "fq_mmvq_q4_k",- py::arg("qb"), py::arg("packed"), py::arg("out"));+ py::arg("qb"), py::arg("packed"), py::arg("out"), py::arg("bias") = py::none());m.def("fq_mmvq_q6_k", &fq_mmvq_q6_k, "fq_mmvq_q6_k",- py::arg("qb"), py::arg("packed"), py::arg("out"));+ py::arg("qb"), py::arg("packed"), py::arg("out"), py::arg("bias") = py::none());m.def("fq_mmvq_q3_k", &fq_mmvq_q3_k, "fq_mmvq_q3_k",- py::arg("qb"), py::arg("packed"), py::arg("out"));+ py::arg("qb"), py::arg("packed"), py::arg("out"), py::arg("bias") = py::none());m.def("fq_mmvq_q4_0", &fq_mmvq_q4_0, "fq_mmvq_q4_0",- py::arg("qb"), py::arg("packed"), py::arg("out"));+ py::arg("qb"), py::arg("packed"), py::arg("out"), py::arg("bias") = py::none());m.def("fq_mmvq_q4_1", &fq_mmvq_q4_1, "fq_mmvq_q4_1",- py::arg("qb"), py::arg("packed"), py::arg("out"));+ py::arg("qb"), py::arg("packed"), py::arg("out"), py::arg("bias") = py::none());m.def("fq_mmvq_q5_0", &fq_mmvq_q5_0, "fq_mmvq_q5_0",- py::arg("qb"), py::arg("packed"), py::arg("out"));+ py::arg("qb"), py::arg("packed"), py::arg("out"), py::arg("bias") = py::none());m.def("fq_mmvq_q5_1", &fq_mmvq_q5_1, "fq_mmvq_q5_1",- py::arg("qb"), py::arg("packed"), py::arg("out"));+ py::arg("qb"), py::arg("packed"), py::arg("out"), py::arg("bias") = py::none());#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 bc98a6e..a46990c 100644--- a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu@@ -82,11 +82,26 @@ template <typename OUT> __device__ __forceinline__ void mq_store(OUT* p, float vtemplate <> __device__ __forceinline__ void mq_store<float>(float* p, float v) { *p = v; }template <> __device__ __forceinline__ void mq_store<__half>(__half* p, float v) { *p = __float2half_rn(v); }+// EXL3_FQ_MMVQ_EPI: optional bias in the store. half out: round the dot to half FIRST, then half(float(h) + float(b)) (torch's `y + bias` on half);+// float out: v + float(b). bias == nullptr is the plain store.+template <typename OUT> __device__ __forceinline__ void mq_store_b(OUT* p, float v, const __half* __restrict__ bias, int64_t n);+template <> __device__ __forceinline__ void mq_store_b<float>(float* p, float v, const __half* __restrict__ bias, int64_t n)+{+ *p = bias ? v + __half2float(bias[n]) : v;+}+template <> __device__ __forceinline__ void mq_store_b<__half>(__half* p, float v, const __half* __restrict__ bias, int64_t n)+{+ __half h = __float2half_rn(v);+ if (bias) h = __float2half_rn(__half2float(h) + __half2float(bias[n]));+ *p = h;+}+// One launch: out[j][row] = dot(weights row, activation column j), j < NC. Weight blocks of row r start at vx + r * row_bytes.template <int T, int NC, typename OUT>__global__ void __launch_bounds__(MQ_WARP * mq_nwarps(NC), 1)fq_mmvq_kernel(const uint8_t* __restrict__ vx, const block_q8_1* __restrict__ vy, OUT* __restrict__ dst,- int ncols_x, int nrows, int64_t row_blocks, int64_t y_col_blocks, int64_t dst_col_stride)+ int ncols_x, int nrows, int64_t row_blocks, int64_t y_col_blocks, int64_t dst_col_stride,+ const __half* __restrict__ bias){using Tr = MqTraits<T>;constexpr int NW = mq_nwarps(NC);@@ -151,40 +166,40 @@ fq_mmvq_kernel(const uint8_t* __restrict__ vx, const block_q8_1* __restrict__ vy}v = mq_warp_sum(v);if (threadIdx.x == 0 && row0 + i < nrows)- mq_store<OUT>(&dst[(int64_t)j * dst_col_stride + row0 + i], v);+ mq_store_b<OUT>(&dst[(int64_t)j * dst_col_stride + row0 + i], v, bias, row0 + i);}}}template <int T, int NC, typename OUT>-void mq_launch(const uint8_t* w, const uint8_t* qb, OUT* out, int K, int N, int64_t y_col_blocks, int64_t dst_col_stride, cudaStream_t stream)+void mq_launch(const uint8_t* w, const uint8_t* qb, OUT* out, int K, int N, int64_t y_col_blocks, int64_t dst_col_stride, const __half* bias, cudaStream_t stream){using Tr = MqTraits<T>;constexpr int NW = mq_nwarps(NC);constexpr int RPB = mq_rows(NC);dim3 grid((N + RPB - 1) / RPB, 1, 1), block(MQ_WARP, NW, 1);fq_mmvq_kernel<T, NC, OUT><<<grid, block, 0, stream>>>(w, reinterpret_cast<const block_q8_1*>(qb), out, K, N,- (int64_t)(K / Tr::qk), y_col_blocks, dst_col_stride);+ (int64_t)(K / Tr::qk), y_col_blocks, dst_col_stride, bias);}template <int T, typename OUT>-void mq_cols(int nc, const uint8_t* w, const uint8_t* qb, OUT* out, int K, int N, int64_t y_col_blocks, cudaStream_t stream)+void mq_cols(int nc, const uint8_t* w, const uint8_t* qb, OUT* out, int K, int N, int64_t y_col_blocks, const __half* bias, cudaStream_t stream){switch (nc){- case 1: mq_launch<T, 1, OUT>(w, qb, out, K, N, y_col_blocks, N, stream); break;- case 2: mq_launch<T, 2, OUT>(w, qb, out, K, N, y_col_blocks, N, stream); break;- case 3: mq_launch<T, 3, OUT>(w, qb, out, K, N, y_col_blocks, N, stream); break;- case 4: mq_launch<T, 4, OUT>(w, qb, out, K, N, y_col_blocks, N, stream); break;- case 5: mq_launch<T, 5, OUT>(w, qb, out, K, N, y_col_blocks, N, stream); break;- case 6: mq_launch<T, 6, OUT>(w, qb, out, K, N, y_col_blocks, N, stream); break;- case 7: mq_launch<T, 7, OUT>(w, qb, out, K, N, y_col_blocks, N, stream); break;- default: mq_launch<T, 8, OUT>(w, qb, out, K, N, y_col_blocks, N, stream); break;+ case 1: mq_launch<T, 1, OUT>(w, qb, out, K, N, y_col_blocks, N, bias, stream); break;+ case 2: mq_launch<T, 2, OUT>(w, qb, out, K, N, y_col_blocks, N, bias, stream); break;+ case 3: mq_launch<T, 3, OUT>(w, qb, out, K, N, y_col_blocks, N, bias, stream); break;+ case 4: mq_launch<T, 4, OUT>(w, qb, out, K, N, y_col_blocks, N, bias, stream); break;+ case 5: mq_launch<T, 5, OUT>(w, qb, out, K, N, y_col_blocks, N, bias, stream); break;+ case 6: mq_launch<T, 6, OUT>(w, qb, out, K, N, y_col_blocks, N, bias, stream); break;+ case 7: mq_launch<T, 7, OUT>(w, qb, out, K, N, y_col_blocks, N, bias, stream); break;+ default: mq_launch<T, 8, OUT>(w, qb, out, K, N, y_col_blocks, N, bias, stream); break;}}template <int T>-void mq_run(torch::Tensor qb, torch::Tensor packed, torch::Tensor out)+void mq_run(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, const std::optional<torch::Tensor>& bias_opt){using Tr = MqTraits<T>;TORCH_CHECK(qb.is_cuda() && packed.is_cuda() && out.is_cuda(), "tensors must be CUDA");@@ -202,6 +217,13 @@ void mq_run(torch::Tensor qb, torch::Tensor packed, torch::Tensor out)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");+ const __half* bias = nullptr;+ if (bias_opt.has_value() && bias_opt->defined())+ {+ TORCH_CHECK(bias_opt->is_cuda() && bias_opt->is_contiguous() && bias_opt->dtype() == torch::kHalf, "bias must be a contiguous CUDA half tensor");+ TORCH_CHECK(bias_opt->numel() == N, "bias must have N elements");+ bias = reinterpret_cast<const __half*>(bias_opt->data_ptr<at::Half>());+ }at::cuda::CUDAGuard guard(qb.device());auto stream = at::cuda::getCurrentCUDAStream().stream();const int64_t y_col_blocks = K / 32;@@ -212,9 +234,9 @@ void mq_run(torch::Tensor qb, torch::Tensor packed, torch::Tensor out)const int nc = std::min(MQ_MAX_COLS, M - m0);const uint8_t* qm = q + (int64_t)m0 * y_col_blocks * 36;if (out.dtype() == torch::kHalf)- mq_cols<T, __half>(nc, w, qm, reinterpret_cast<__half*>(out.data_ptr<at::Half>()) + (int64_t)m0 * N, K, N, y_col_blocks, stream);+ mq_cols<T, __half>(nc, w, qm, reinterpret_cast<__half*>(out.data_ptr<at::Half>()) + (int64_t)m0 * N, K, N, y_col_blocks, bias, stream);else- mq_cols<T, float>(nc, w, qm, out.data_ptr<float>() + (int64_t)m0 * N, K, N, y_col_blocks, stream);+ mq_cols<T, float>(nc, w, qm, out.data_ptr<float>() + (int64_t)m0 * N, K, N, y_col_blocks, bias, stream);}}@@ -579,21 +601,21 @@ template <int T> void mq_dequant_t(torch::Tensor packed, torch::Tensor out)} // namespace-void fq_mmvq_iq2_xxs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mq_run<MQ_IQ2_XXS>(qb, packed, out); }-void fq_mmvq_iq2_xs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mq_run<MQ_IQ2_XS>(qb, packed, out); }-void fq_mmvq_iq2_s(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mq_run<MQ_IQ2_S>(qb, packed, out); }-void fq_mmvq_iq3_xxs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mq_run<MQ_IQ3_XXS>(qb, packed, out); }-void fq_mmvq_iq3_s(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mq_run<MQ_IQ3_S>(qb, packed, out); }-void fq_mmvq_iq4_nl(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mq_run<MQ_IQ4_NL>(qb, packed, out); }-void fq_mmvq_iq4_xs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out) { mq_run<MQ_IQ4_XS>(qb, packed, 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); }-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); }+void fq_mmvq_iq2_xxs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias) { mq_run<MQ_IQ2_XXS>(qb, packed, out, bias); }+void fq_mmvq_iq2_xs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias) { mq_run<MQ_IQ2_XS>(qb, packed, out, bias); }+void fq_mmvq_iq2_s(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias) { mq_run<MQ_IQ2_S>(qb, packed, out, bias); }+void fq_mmvq_iq3_xxs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias) { mq_run<MQ_IQ3_XXS>(qb, packed, out, bias); }+void fq_mmvq_iq3_s(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias) { mq_run<MQ_IQ3_S>(qb, packed, out, bias); }+void fq_mmvq_iq4_nl(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias) { mq_run<MQ_IQ4_NL>(qb, packed, out, bias); }+void fq_mmvq_iq4_xs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias) { mq_run<MQ_IQ4_XS>(qb, packed, out, bias); }+void fq_mmvq_q5_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias) { mq_run<MQ_Q5_K>(qb, packed, out, bias); }+void fq_mmvq_q4_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias) { mq_run<MQ_Q4_K>(qb, packed, out, bias); }+void fq_mmvq_q6_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias) { mq_run<MQ_Q6_K>(qb, packed, out, bias); }+void fq_mmvq_q3_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias) { mq_run<MQ_Q3_K>(qb, packed, out, bias); }+void fq_mmvq_q4_0(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias) { mq_run<MQ_Q4_0>(qb, packed, out, bias); }+void fq_mmvq_q4_1(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias) { mq_run<MQ_Q4_1>(qb, packed, out, bias); }+void fq_mmvq_q5_0(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias) { mq_run<MQ_Q5_0>(qb, packed, out, bias); }+void fq_mmvq_q5_1(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias) { mq_run<MQ_Q5_1>(qb, packed, out, bias); }// 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 884f10e..272c545 100644--- a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h@@ -3,21 +3,21 @@#pragma once#include <torch/extension.h>-void fq_mmvq_iq2_xxs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);-void fq_mmvq_iq2_xs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);-void fq_mmvq_iq2_s(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);-void fq_mmvq_iq3_xxs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);-void fq_mmvq_iq3_s(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);-void fq_mmvq_iq4_nl(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);-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);-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);+void fq_mmvq_iq2_xxs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias = c10::nullopt);+void fq_mmvq_iq2_xs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias = c10::nullopt);+void fq_mmvq_iq2_s(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias = c10::nullopt);+void fq_mmvq_iq3_xxs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias = c10::nullopt);+void fq_mmvq_iq3_s(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias = c10::nullopt);+void fq_mmvq_iq4_nl(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias = c10::nullopt);+void fq_mmvq_iq4_xs(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias = c10::nullopt);+void fq_mmvq_q5_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias = c10::nullopt);+void fq_mmvq_q4_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias = c10::nullopt);+void fq_mmvq_q6_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias = c10::nullopt);+void fq_mmvq_q3_k(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias = c10::nullopt);+void fq_mmvq_q4_0(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias = c10::nullopt);+void fq_mmvq_q4_1(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias = c10::nullopt);+void fq_mmvq_q5_0(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias = c10::nullopt);+void fq_mmvq_q5_1(torch::Tensor qb, torch::Tensor packed, torch::Tensor out, std::optional<torch::Tensor> bias = c10::nullopt);// 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,@@ -36,3 +36,6 @@ void fq_dequant_iq(torch::Tensor packed, torch::Tensor out, int64_t fmt);// 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++// ABI marker: the fq_mmvq_* functions above take an optional half bias applied in the store (EXL3_FQ_MMVQ_EPI).+inline int fq_mmvq_epi_abi() { return 1; }diff --git a/exllamav3/modules/attn.py b/exllamav3/modules/attn.pyindex eeefbf7..d9fabcf 100644--- a/exllamav3/modules/attn.py+++ b/exllamav3/modules/attn.py@@ -908,6 +908,8 @@ class Attention(Module):return self.finish_qkv(q, k, v, g, bsz, q_len, params)qkv8 = self._qkv_q8cat(x, params, bsz, q_len)+ from .foreign_linear import q8_share_begin, q8_share_end+ q8_share_begin() # EXL3_FQ_MMVQ_EPI: q / k / v ForeignLinear gemvs share one q8_1 quantization of x (no-op when the flag is off)if self.multi_qg is None or bsz * q_len > 32:q = qkv8[0] if qkv8 is not None else self.q_proj.forward(x, params)if self.interleaved_gate:@@ -961,6 +963,7 @@ class Attention(Module):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 k+ q8_share_end()else:if x.shape[-1] < self.k_proj.in_features:@@ -992,6 +995,7 @@ class Attention(Module):k = kv[0].view(bsz, q_len, self.num_kv_heads * self.head_dim)v = kv[1].view(bsz, q_len, self.num_kv_heads * self.head_dim)+ q8_share_end()return self.finish_qkv(q, k, v, g, bsz, q_len, params)diff --git a/exllamav3/modules/foreign_linear.py b/exllamav3/modules/foreign_linear.pyindex 0167b18..c676d08 100644--- a/exllamav3/modules/foreign_linear.py+++ b/exllamav3/modules/foreign_linear.py@@ -106,6 +106,27 @@ _MMVQ_LEGACY = os.environ.get("EXL3_FQ_MMVQ_LEGACY", "0") == "1" and bool(torch.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})+# EXL3_FQ_MMVQ_EPI (default 0, CUDA only, read at call time): (A1) a ForeignLinear bias (_ForeignInner) is added inside the mmvq store (half out: round the dot to+# half, then half(float(h) + float(b)), torch's `y + bias` order; float out: v + float(b)) instead of a separate torch add; (A2) q, k and v of one attention+# layer read the same normed x: it is quantized to q8_1 once (attn.project_qkv brackets the three calls with q8_share_begin / q8_share_end; the key is+# x.data_ptr + x._version + R + K + device, valid only inside that bracket). Off = exactly the previous code.+def _epi_on() -> bool:+ return os.environ.get("EXL3_FQ_MMVQ_EPI", "0") == "1" and bool(torch.version.cuda) and not torch.version.hip+++_Q8S = {"on": False, "key": None}+++def q8_share_begin() -> None:+ _Q8S["on"] = _epi_on()+ _Q8S["key"] = None+++def q8_share_end() -> None:+ _Q8S["on"] = False+ _Q8S["key"] = None++_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)@@ -278,7 +299,10 @@ class ForeignLinear(Module):x: torch.Tensor,params: dict,out_dtype: torch.dtype | None = None,+ bias: Optional[torch.Tensor] = None,) -> torch.Tensor:+ # bias: only consumed by the mmvq epilogue under EXL3_FQ_MMVQ_EPI; self._bias_fused tells the caller whether it was added+ self._bias_fused = Falseshape = x.shapeK = self.in_featuresassert shape[-1] == K, f"{self.key}: width {shape[-1]} != {K}"@@ -311,8 +335,24 @@ class ForeignLinear(Module):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)- if ri and R > 4: # 5..8 columns launch 2 warps per row (other sum order than the one-row launch's 4): at most 4 columns per launch+ try:+ _ver = flat._version+ except RuntimeError: # inference tensor: no version counter (nothing writes x between q, k and v)+ _ver = -1+ _sk = (flat.data_ptr(), _ver, R, K, dev_idx)+ if _Q8S["on"] and _Q8S["key"] == _sk:+ pass # q8_1 of this exact x is already in the scratch (q / k / v of one layer)+ else:+ ext.fq_quant_q8_1_rows(flat, qb)+ _Q8S["key"] = _sk if _Q8S["on"] else None+ _bf = None+ if (bias is not None and R == 1 and out.dtype == dtype and bias.dtype == torch.half and bias.is_cuda and bias.is_contiguous()+ and bias.numel() == N and self.post_scale == 1.0 and self.softcap == 0.0 and _epi_on() and hasattr(ext, "fq_mmvq_epi_abi")):+ _bf = bias+ self._bias_fused = True+ if _bf is not None:+ getattr(ext, _MMVQ_FN[self.format])(qb, self.packed.reshape(N, -1), out, _bf)+ elif ri and R > 4: # 5..8 columns launch 2 warps per row (other sum order than the one-row launch's 4): at most 4 columns per launchfor a in range(0, R, 4):getattr(ext, _MMVQ_FN[self.format])(qb[a:a + 4], self.packed.reshape(N, -1), out[a:a + 4])else:@@ -338,6 +378,7 @@ class ForeignLinear(Module):dev_idx = dev.index if dev.index is not None else torch.cuda.current_device()qb = ext.fq_q8_scratch(dev_idx, R, K)ext.fq_quant_q8_1_rows(flat, qb)+ _Q8S["key"] = Nonegetattr(ext, _IQ_Q8_FN[self.format])(qb, self.packed.reshape(N, -1), out)if out.dtype != dtype:out = out.to(dtype)diff --git a/exllamav3/modules/linear.py b/exllamav3/modules/linear.pyindex 31ac6c3..8c88da3 100644--- a/exllamav3/modules/linear.py+++ b/exllamav3/modules/linear.py@@ -103,8 +103,11 @@ class _ForeignInner:return self.biasdef 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+ if self.bias is None:+ return self.fl.forward(x, params, out_dtype)+ self.fl._bias_fused = False+ y = self.fl.forward(x, params, out_dtype, bias = self.bias) # EXL3_FQ_MMVQ_EPI: the mmvq epilogue may add it (then _bias_fused)+ return y if self.fl._bias_fused else y + self.biasclass Linear(Module):diff --git a/tests/test_fq_mmvq_epi_cpu.py b/tests/test_fq_mmvq_epi_cpu.pynew file mode 100644index 0000000..3059527--- /dev/null+++ b/tests/test_fq_mmvq_epi_cpu.py@@ -0,0 +1,125 @@+"""CPU checks for EXL3_FQ_MMVQ_EPI: bias in the fq_mmvq epilogue (A1) + one q8_1 quantization for q / k / v (A2).+No GPU, no kernel launch: the extension is replaced by stubs. Needs the repo importable (exllamav3 package, built extension present so the+import does not start a build); skipped otherwise. Run: CUDA_VISIBLE_DEVICES= python -m pytest tests/test_fq_mmvq_epi_cpu.py -q"""+import glob+import os+import sys+import types++import numpy as np+import pytest++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+if not glob.glob(os.path.join(ROOT, "exllamav3_ext*.so")):+ pytest.skip("extension not built in " + ROOT + " (importing exllamav3 would start the build)", allow_module_level=True)+sys.path.insert(0, ROOT)+import torch++++def epi_half(v, b): # kernel: h = half(v); out = half(float(h) + float(b))+ h = v.astype(np.float16)+ return (h.astype(np.float32) + b.astype(np.float32)).astype(np.float16)++def epi_float(v, b):+ return v.astype(np.float32) + b.astype(np.float32)+++def test_bias_rounding():+ import torch+ rng = np.random.default_rng(1)+ v = (rng.standard_normal(4096) * 3).astype(np.float32)+ b = rng.standard_normal(4096).astype(np.float16)+ t = (torch.from_numpy(v).half() + torch.from_numpy(b)).numpy() # torch: y(half) + bias(half)+ assert np.array_equal(epi_half(v, b), t), "half epilogue != torch half add"+ tf = (torch.from_numpy(v) + torch.from_numpy(b)).numpy() # float y + half bias+ assert np.array_equal(epi_float(v, b), tf), "float epilogue != torch float add"+ # the wrong order (add in fp32 then round once) differs on some elements: the test is not vacuous+ wrong = (v + b.astype(np.float32)).astype(np.float16)+ ndiff = int((wrong != t).sum())+ print(f"bias epilogue: half order == torch (4096/4096), float == torch; single-rounding order would differ on {ndiff} elements")+ assert ndiff > 0+++def test_q8_reuse_numeric():+ import torch+ # q8_1 quantize emulation (ggml quantize_q8_1: d = amax / 127, q = round(x / d), s = d * sum q): deterministic, same input -> same bytes+ def q8(x):+ x = x.reshape(-1, 32).astype(np.float32)+ amax = np.abs(x).max(1, keepdims=True); d = amax / 127.0+ inv = np.where(d != 0, 1.0 / np.where(d == 0, 1, d), 0.0)+ q = np.rint(x * inv).astype(np.int8)+ return d.astype(np.float16), (d * q.sum(1, keepdims=True)).astype(np.float16), q+ rng = np.random.default_rng(2)+ x = rng.standard_normal(2880).astype(np.float16)+ a = q8(x); b = q8(x.copy()); c = q8(x)+ for i in range(3):+ assert np.array_equal(a[i], b[i]) and np.array_equal(a[i], c[i])+ W = [rng.standard_normal((16, 2880)).astype(np.float32) for _ in range(3)]+ dq = lambda t: (t[2].astype(np.float32) * t[0].astype(np.float32)).reshape(-1)+ y1 = [w @ dq(a) for w in W]; y2 = [w @ dq(q8(x)) for w in W] # 3 quantizations vs 1 shared+ assert all(np.array_equal(p, q) for p, q in zip(y1, y2))+ print("q8_1 reuse: quantize twice == once, the three gemv inputs bit-equal")+++class _FakeCudaBias:+ """Stand-in for a CUDA half bias on a CPU box."""+ is_cuda = True+ dtype = torch.half+ def __init__(self, n): self.n = n+ def is_contiguous(self): return True+ def numel(self): return self.n++[email protected](params=["0", "1"])+def flag(request, monkeypatch):+ monkeypatch.setattr(torch.version, "cuda", "13.0", raising=False)+ monkeypatch.setattr(torch.version, "hip", None, raising=False)+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)+ return request.param == "1"++def test_dispatch(flag, monkeypatch):+ from exllamav3.modules import foreign_linear as fl+ from exllamav3.modules import linear as lin+ monkeypatch.setenv("EXL3_FQ_MMVQ_EPI", "1" if flag else "0")+ log = []+ qcount = [0]+ 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: qcount.__setitem__(0, qcount[0] + 1),+ fq_mmvq_epi_abi=lambda: 1)+ ext.fq_mmvq_q5_0 = lambda qb, p, out, bias=None: (out.zero_(), log.append(("mmvq", bias is not None)))[1]+ monkeypatch.setattr(fl, "ext", ext)+ monkeypatch.setattr(fl, "_MMVQ_LEGACY", True)+ monkeypatch.setitem(fl._MMVQ_FN, "q5_0", "fq_mmvq_q5_0")+ monkeypatch.setitem(fl._MMVQ_QK, "q5_0", 32)+ FB = _FakeCudaBias(8)++ def mk():+ m = object.__new__(fl.ForeignLinear); m.format = "q5_0"; m.in_features = 64; m.out_features = 8; m.key = "t"+ m.packed = torch.zeros(8, 2 * 22, 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+ return m+ m = mk(); x = torch.zeros(1, 64, dtype=torch.half)+ # (A2) q / k / v of one layer: quantize count+ qcount[0] = 0+ fl.q8_share_begin()+ for _ in range(3): m.forward(x, {})+ fl.q8_share_end()+ assert qcount[0] == (1 if flag else 3), ("shared q8 quantizations", qcount[0])+ qcount[0] = 0+ for _ in range(3): m.forward(x, {}) # outside the bracket: always one quantization per call+ assert qcount[0] == 3, qcount[0]+ qcount[0] = 0+ fl.q8_share_begin(); m.forward(x, {}); x2 = torch.zeros(1, 64, dtype=torch.half); m.forward(x2, {}) # other tensor: re-quantize+ x.add_(1); m.forward(x, {}); fl.q8_share_end() # in-place write bumps the version: re-quantize+ assert qcount[0] == 3, qcount[0]+ # (A1) bias: kernel gets it only with the flag, R == 1 and a CUDA half contiguous bias+ log.clear(); m.forward(x, {}, None, bias=FB)+ assert log == [("mmvq", flag)], log+ assert m._bias_fused == flag+ log.clear(); m.forward(torch.zeros(1, 64, dtype=torch.half), {}, None, bias=torch.zeros(8, dtype=torch.half)) # CPU tensor bias: never fused+ assert log == [("mmvq", False)] and not m._bias_fused, log+ inner = lin._ForeignInner(m, torch.ones(8, dtype=torch.half))+ y = inner.forward(torch.zeros(1, 64, dtype=torch.half), {})+ assert torch.equal(y, torch.ones(1, 8, dtype=torch.half)), "bias must be added exactly once (CPU bias is never fused)"