Commit 51866c1 for stable-diffusion.cpp

commit 51866c1a31f5f6630aff2bbd173585bc7f8ded96
Author: leejet <leejet714@gmail.com>
Date:   Sat Nov 28 22:00:21 2026 +0800

    feat: support K-quant weights in INT8 linear layers (#2454)

diff --git a/docs/guides/int8_convrot.md b/docs/guides/int8_convrot.md
index 75ddc00..07ee5de 100644
--- a/docs/guides/int8_convrot.md
+++ b/docs/guides/int8_convrot.md
@@ -166,10 +166,11 @@ these formats because they require the application extension API.

 ## Runtime requantization to INT8

-Use `--linear-type i8` to run eligible Q4_0, Q4_1, Q5_0, Q5_1, and Q8_0 linear
-layers through INT8 GEMM on CUDA, HIP, MUSA, and Vulkan. A bare mode applies to
-all models in the context, including diffusion models and text encoders loaded
-with `--llm`. The default is `auto`, which currently behaves like `raw`. With
+Use `--linear-type i8` to run eligible Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q2_K, Q3_K,
+Q4_K, Q5_K, Q6_K, and Q8_K linear layers through INT8 GEMM on CUDA, HIP, MUSA,
+and Vulkan. A bare mode applies to all models in the context, including
+diffusion models and text encoders loaded with `--llm`. The default is `auto`,
+which currently behaves like `raw`. With
 `--linear-type raw`, each layer uses its original execution path. Native INT8
 weights use their INT8 path in all three modes. For floating-point checkpoints,
 use `--type q4_0` (or another supported weight type) to quantize eligible weights
diff --git a/src/core/cuda/requantize.cu b/src/core/cuda/requantize.cu
index 8659b9d..82a0d40 100644
--- a/src/core/cuda/requantize.cu
+++ b/src/core/cuda/requantize.cu
@@ -1,4 +1,5 @@
 #include <climits>
+#include <type_traits>

 #include "convrot_kernel.h"
 #include "core/ggml_extensions.h"
@@ -10,11 +11,10 @@ namespace SD_CUDA_NAMESPACE {
         using i8::blas_supported;
         using i8::warp_reduce_max;

-        constexpr int block_size = SD_REQUANTIZE_I8_BLOCK_SIZE;
-
         // GGML stores FP16 parameters, then the Q5 high bits, then the quants.
         template <ggml_type type>
         struct QuantBlock {
+            static constexpr int block_size = 32;
             static constexpr int bits       = type == GGML_TYPE_Q8_0 ? 8 : (type == GGML_TYPE_Q5_0 || type == GGML_TYPE_Q5_1 ? 5 : 4);
             static constexpr bool affine    = type == GGML_TYPE_Q4_1 || type == GGML_TYPE_Q5_1;
             static constexpr int high_words = bits == 5 ? 2 : 0;
@@ -39,29 +39,153 @@ namespace SD_CUDA_NAMESPACE {
             }
         };

+        template <ggml_type type>
+        struct QuantKBlock {
+            static_assert(type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K);
+            static constexpr int high_bytes = type == GGML_TYPE_Q5_K ? 32 : 0;
+            half d, dmin;
+            uint8_t scales[12];
+            uint8_t quants[high_bytes + 128];
+
+            __device__ __forceinline__ float decode(int i) const {
+                const int group = i / 32;
+                const int scale = group < 4 ? scales[group] & 63 : (scales[group + 4] & 15) | ((scales[group - 4] >> 6) << 4);
+                const int min   = group < 4 ? scales[group + 4] & 63 : (scales[group + 4] >> 4) | ((scales[group] >> 6) << 4);
+                int value       = (quants[high_bytes + i / 64 * 32 + i % 32] >> (4 * (group % 2))) & 15;
+                if constexpr (high_bytes != 0)
+                    value |= ((quants[i % 32] >> group) & 1) << 4;
+                return (__half2float(d) * scale) * value - __half2float(dmin) * min;
+            }
+        };
+
+        template <>
+        struct QuantKBlock<GGML_TYPE_Q2_K> {
+            uint8_t scales[16];
+            uint8_t quants[64];
+            half d, dmin;
+
+            __device__ __forceinline__ float decode(int i) const {
+                const int scale = scales[i / 16];
+                const int value = (quants[i / 128 * 32 + i % 32] >> (2 * (i / 32 % 4))) & 3;
+                return (__half2float(d) * (scale & 15)) * value - __half2float(dmin) * (scale >> 4);
+            }
+        };
+
+        template <>
+        struct QuantKBlock<GGML_TYPE_Q3_K> {
+            uint8_t high[32];
+            uint8_t quants[64];
+            uint8_t scales[12];
+            half d;
+
+            __device__ __forceinline__ float decode(int i) const {
+                const int group      = i / 16;
+                const int scale_low  = (scales[group % 8] >> (4 * (group / 8))) & 15;
+                const int scale_high = (scales[8 + group % 4] >> (2 * (group / 4))) & 3;
+                const int scale      = (scale_low | (scale_high << 4)) - 32;
+                const int low        = (quants[i / 128 * 32 + i % 32] >> (2 * (i / 32 % 4))) & 3;
+                const int value      = low - ((high[i % 32] >> (i / 32)) & 1 ? 0 : 4);
+                return (__half2float(d) * scale) * value;
+            }
+        };
+
+        template <>
+        struct QuantKBlock<GGML_TYPE_Q6_K> {
+            uint8_t low[128];
+            uint8_t high[64];
+            int8_t scales[16];
+            half d;
+
+            __device__ __forceinline__ float decode(int i) const {
+                const int low_bits  = (low[i / 128 * 64 + i % 64] >> (4 * (i / 64 % 2))) & 15;
+                const int high_bits = (high[i / 128 * 32 + i % 32] >> (2 * (i / 32 % 4))) & 3;
+                const int value     = (low_bits | (high_bits << 4)) - 32;
+                return (__half2float(d) * scales[i / 16]) * value;
+            }
+        };
+
+        template <>
+        struct QuantKBlock<GGML_TYPE_Q8_K> {
+            float d;
+            int8_t quants[256];
+            int16_t sums[16];
+
+            __device__ __forceinline__ float decode(int i) const {
+                return d * quants[i];
+            }
+        };
+
+        constexpr int lanes             = 32;
+        constexpr int requantize_warps  = 8;
+        constexpr int group_size        = 256;
+        constexpr int weights_per_round = requantize_warps * group_size;
+
+        template <ggml_type type>
+        using WeightBlock = std::conditional_t<sd_ggml_requantize_i8_block(type).size == group_size, QuantKBlock<type>, QuantBlock<type>>;
+
         static __device__ __forceinline__ int8_t requantize_i8_value(float value) {
             return int8_t(__float2int_rn(fminf(127.f, fmaxf(-127.f, value))));
         }

-        template <ggml_type type>
-        static __device__ __forceinline__ void load_rotated_group(const QuantBlock<type>* blocks, int lane, float (&values)[8]) {
+        static __device__ __forceinline__ float h256_signed(float value, int i) {
+            return (__popc(i & (i >> 1) & 0x55) & 1) ? -value : value;
+        }
+
+        static __device__ __forceinline__ void rotate_k_group(float (&values)[8], int lane) {
+            // H4 is a Walsh-Hadamard transform with sign changes on index 3 and
+            // a swap of the two index bits. Each lane owns eight adjacent weights
+            // so the first three stages are local and the result can be stored as a pair of words.
+#pragma unroll
+            for (int stride = 1; stride < 8; stride *= 2) {
+#pragma unroll
+                for (int j = 0; j < 8; ++j) {
+                    if ((j & stride) == 0) {
+                        const float a      = values[j];
+                        const float b      = values[j + stride];
+                        values[j]          = a + b;
+                        values[j + stride] = a - b;
+                    }
+                }
+            }
+#pragma unroll
+            for (int stride = 1; stride < lanes; stride *= 2) {
 #pragma unroll
-            for (int j = 0; j < 8; ++j)
-                values[j] = blocks[j].decode(lane) * (1.0f / 16.0f);
-            sd_convrot::rotate_h256(values, lane);
+                for (int j = 0; j < 8; ++j) {
+                    const float value = values[j];
+                    const float other = cuda_shuffle_xor(value, stride, lanes);
+                    values[j]         = (lane & stride ? -value : value) + other;
+                }
+            }
         }

-        constexpr int requantize_warps  = 8;
-        constexpr int blocks_per_group  = 256 / block_size;
-        constexpr int blocks_per_round  = requantize_warps * blocks_per_group;
-        constexpr int weights_per_round = blocks_per_round * block_size;
+        template <ggml_type type, int block_size = sd_ggml_requantize_i8_block(type).size>
+        static __device__ __forceinline__ void load_rotated_group(const WeightBlock<type>* blocks, int lane, float (&values)[8]) {
+#pragma unroll
+            for (int j = 0; j < 8; ++j) {
+                if constexpr (cuda_kind == GGML_EXT_GPU_CUDA && block_size == group_size) {
+                    const int i      = lane * 8 + j;
+                    const int source = ((i & 0x55) << 1) | ((i & 0xAA) >> 1);
+                    values[j]        = h256_signed(blocks[0].decode(source) * (1.0f / 16.0f), i);
+                } else {
+                    const int i = j * lanes + lane;
+                    values[j] = blocks[i / block_size].decode(i % block_size) * (1.0f / 16.0f);
+                }
+            }
+            if constexpr (cuda_kind == GGML_EXT_GPU_CUDA && block_size == group_size) {
+                rotate_k_group(values, lane);
+            } else {
+                sd_convrot::rotate_h256(values, lane);
+            }
+        }

-        template <ggml_type type, int cached_groups>
-        static __global__ void requantize_i8_weights(const QuantBlock<type>* weights, int8_t* decoded, float* scales, int64_t blocks_per_channel) {
-            const int lane     = threadIdx.x;
-            const int warp     = threadIdx.y;
-            const auto* blocks = weights + int64_t(blockIdx.x) * blocks_per_channel;
-            auto* output       = decoded + int64_t(blockIdx.x) * blocks_per_channel * block_size;
+        template <ggml_type type, int cached_groups, int block_size = sd_ggml_requantize_i8_block(type).size>
+        static __global__ void requantize_i8_weights(const WeightBlock<type>* weights, int8_t* decoded, float* scales, int64_t blocks_per_channel) {
+            constexpr int blocks_per_group = group_size / block_size;
+            constexpr int blocks_per_round = requantize_warps * blocks_per_group;
+            const int lane                 = threadIdx.x;
+            const int warp                 = threadIdx.y;
+            const auto* blocks             = weights + int64_t(blockIdx.x) * blocks_per_channel;
+            auto* output                   = decoded + int64_t(blockIdx.x) * blocks_per_channel * block_size;

             __shared__ float maxima[requantize_warps];
             // Keep a bounded number of rotated groups in registers across the scale reduction.
@@ -76,7 +200,7 @@ namespace SD_CUDA_NAMESPACE {
                         break;
                 }
                 float values[8];
-                load_rotated_group(blocks + block, lane, values);
+                load_rotated_group<type>(blocks + block, lane, values);
 #pragma unroll
                 for (int j = 0; j < 8; ++j) {
                     if constexpr (cached_groups > 0)
@@ -113,11 +237,22 @@ namespace SD_CUDA_NAMESPACE {
                 }
                 float values[8];
                 if constexpr (cached_groups == 0)
-                    load_rotated_group(blocks + block, lane, values);
+                    load_rotated_group<type>(blocks + block, lane, values);
+                const float* rotated = cached_groups > 0 ? retained[slot] : values;
+                if constexpr (cuda_kind == GGML_EXT_GPU_CUDA && block_size == group_size) {
+                    uint2 packed = {};
 #pragma unroll
-                for (int j = 0; j < 8; ++j) {
-                    const float value                       = cached_groups > 0 ? retained[slot][j] : values[j];
-                    output[(block + j) * block_size + lane] = requantize_i8_value(value * inverse);
+                    for (int j = 0; j < 4; ++j) {
+                        const auto lower = requantize_i8_value(h256_signed(rotated[j], lane * 8 + j) * inverse);
+                        const auto upper = requantize_i8_value(h256_signed(rotated[j + 4], lane * 8 + j + 4) * inverse);
+                        packed.x |= uint32_t(uint8_t(lower)) << (8 * j);
+                        packed.y |= uint32_t(uint8_t(upper)) << (8 * j);
+                    }
+                    reinterpret_cast<uint2*>(output + block * block_size)[lane] = packed;
+                } else {
+#pragma unroll
+                    for (int j = 0; j < 8; ++j)
+                        output[block * block_size + j * lanes + lane] = requantize_i8_value(rotated[j] * inverse);
                 }
             }
         }
@@ -125,20 +260,25 @@ namespace SD_CUDA_NAMESPACE {
         static bool requantize_i8_supports(ggml_backend_dev_t device, const ggml_tensor* node, void*) {
             const auto* weight = node->src[0];
             const int64_t k = weight->ne[0], n = weight->ne[1];
-            const auto info = cuda_device_info(device);
-            return info.device >= 0 && k <= INT_MAX / 16384 && n <= INT_MAX && aligned(weight, alignof(uint16_t)) &&
+            const auto info        = cuda_device_info(device);
+            const size_t alignment = weight->type == GGML_TYPE_Q8_K ? alignof(float) : alignof(uint16_t);
+            const bool packed      = cuda_kind == GGML_EXT_GPU_CUDA && sd_ggml_requantize_i8_block(weight->type).size == group_size;
+            return info.device >= 0 && k <= INT_MAX / 16384 && n <= INT_MAX && aligned(weight, alignment) &&
+                   (!packed || aligned(node, alignof(uint2))) &&
                    (cuda_kind != GGML_EXT_GPU_CUDA || blas_supported(device, info, n));
         }

         template <ggml_type type>
         static void launch_requantize(const ggml_tensor* weight, int8_t* values, CUDAStream stream) {
-            using Block = QuantBlock<type>;
-            static_assert(sizeof(Block) == sd_ggml_requantize_i8_block_bytes(type) && alignof(Block) == alignof(uint16_t));
+            using Block          = WeightBlock<type>;
+            constexpr auto block = sd_ggml_requantize_i8_block(type);
+            static_assert(sizeof(Block) == block.bytes);
+            static_assert(alignof(Block) == (type == GGML_TYPE_Q8_K ? alignof(float) : alignof(uint16_t)));
             const int64_t k = weight->ne[0], n = weight->ne[1];
             auto* scales        = reinterpret_cast<float*>(values + k * n);
             const auto* weights = static_cast<const Block*>(weight->data);
-            const dim3 threads(block_size, requantize_warps);
-            const int64_t blocks_per_channel = k / block_size;
+            const dim3 threads(lanes, requantize_warps);
+            const int64_t blocks_per_channel = k / block.size;
             if (cuda_kind == GGML_EXT_GPU_CUDA && k <= 2 * weights_per_round) {
                 requantize_i8_weights<type, 2><<<unsigned(n), threads, 0, stream>>>(weights, values, scales, blocks_per_channel);
             } else if (cuda_kind == GGML_EXT_GPU_CUDA && k <= 4 * weights_per_round) {
@@ -174,6 +314,24 @@ namespace SD_CUDA_NAMESPACE {
                 case GGML_TYPE_Q8_0:
                     launch_requantize<GGML_TYPE_Q8_0>(weight, values, stream);
                     break;
+                case GGML_TYPE_Q2_K:
+                    launch_requantize<GGML_TYPE_Q2_K>(weight, values, stream);
+                    break;
+                case GGML_TYPE_Q3_K:
+                    launch_requantize<GGML_TYPE_Q3_K>(weight, values, stream);
+                    break;
+                case GGML_TYPE_Q4_K:
+                    launch_requantize<GGML_TYPE_Q4_K>(weight, values, stream);
+                    break;
+                case GGML_TYPE_Q5_K:
+                    launch_requantize<GGML_TYPE_Q5_K>(weight, values, stream);
+                    break;
+                case GGML_TYPE_Q6_K:
+                    launch_requantize<GGML_TYPE_Q6_K>(weight, values, stream);
+                    break;
+                case GGML_TYPE_Q8_K:
+                    launch_requantize<GGML_TYPE_Q8_K>(weight, values, stream);
+                    break;
                 default:
                     return GGML_STATUS_FAILED;
             }
diff --git a/src/core/ggml_extend.cpp b/src/core/ggml_extend.cpp
index f840d76..834ba9a 100644
--- a/src/core/ggml_extend.cpp
+++ b/src/core/ggml_extend.cpp
@@ -217,7 +217,7 @@ ggml_tensor* ggml_ext_linear(GGMLRunnerContext* runner_ctx,
     const auto mul_mat = [&](ggml_tensor* input) {
 #ifndef SD_USE_UPSTREAM_GGML
         // The INT8 path accumulates in INT32 and rescales in FP32.
-        if (runner_ctx->requantize_to_i8 && sd_ggml_requantize_i8_block_bytes(w->type) && input->type == GGML_TYPE_F32 &&
+        if (runner_ctx->requantize_to_i8 && sd_ggml_requantize_i8_block(w->type).bytes && input->type == GGML_TYPE_F32 &&
             (sd_backend_is(runner_ctx->backend, "CUDA") ||
              sd_backend_is(runner_ctx->backend, "ROCm") ||
              sd_backend_is(runner_ctx->backend, "MUSA") ||
diff --git a/src/core/ggml_extensions.cpp b/src/core/ggml_extensions.cpp
index cf9ef8f..5d52748 100644
--- a/src/core/ggml_extensions.cpp
+++ b/src/core/ggml_extensions.cpp
@@ -255,9 +255,9 @@ static bool i8_infer(ggml_tensor* const* inputs, int count, const void* attribut
 static bool requantize_i8_infer(ggml_tensor* const* inputs, int count, const void*, ggml_ext_tensor_desc* output) {
     if (count != 2 || !inputs[0] || !inputs[1] || inputs[1]->type != GGML_TYPE_I8)
         return false;
-    const auto* weight       = inputs[0];
-    const size_t block_bytes = sd_ggml_requantize_i8_block_bytes(weight->type);
-    if (!block_bytes || ggml_blck_size(weight->type) != SD_REQUANTIZE_I8_BLOCK_SIZE || ggml_type_size(weight->type) != block_bytes)
+    const auto* weight = inputs[0];
+    const auto block   = sd_ggml_requantize_i8_block(weight->type);
+    if (!block.bytes || ggml_blck_size(weight->type) != block.size || ggml_type_size(weight->type) != block.bytes)
         return false;
     const int64_t k = weight->ne[0], n = weight->ne[1];
     constexpr int64_t scale_bytes = sizeof(float);
diff --git a/src/core/ggml_extensions.h b/src/core/ggml_extensions.h
index e8aee75..4d1ebbb 100644
--- a/src/core/ggml_extensions.h
+++ b/src/core/ggml_extensions.h
@@ -50,22 +50,37 @@ bool sd_ggml_valid_convrot_group(int group);
 ggml_ext_op_t sd_ggml_i8_op();
 ggml_ext_op_t sd_ggml_requantize_i8_op();

-constexpr int SD_REQUANTIZE_I8_BLOCK_SIZE = 32;
+struct SDI8QuantBlock {
+    int size;
+    size_t bytes;
+};

-constexpr size_t sd_ggml_requantize_i8_block_bytes(ggml_type type) {
+constexpr SDI8QuantBlock sd_ggml_requantize_i8_block(ggml_type type) {
     switch (type) {
         case GGML_TYPE_Q4_0:
-            return 18;
+            return {32, 18};
         case GGML_TYPE_Q4_1:
-            return 20;
+            return {32, 20};
         case GGML_TYPE_Q5_0:
-            return 22;
+            return {32, 22};
         case GGML_TYPE_Q5_1:
-            return 24;
+            return {32, 24};
         case GGML_TYPE_Q8_0:
-            return 34;
+            return {32, 34};
+        case GGML_TYPE_Q2_K:
+            return {256, 84};
+        case GGML_TYPE_Q3_K:
+            return {256, 110};
+        case GGML_TYPE_Q4_K:
+            return {256, 144};
+        case GGML_TYPE_Q5_K:
+            return {256, 176};
+        case GGML_TYPE_Q6_K:
+            return {256, 210};
+        case GGML_TYPE_Q8_K:
+            return {256, 292};
         default:
-            return 0;
+            return {};
     }
 }

diff --git a/src/core/vulkan/CMakeLists.txt b/src/core/vulkan/CMakeLists.txt
index 3c10523..8a26fec 100644
--- a/src/core/vulkan/CMakeLists.txt
+++ b/src/core/vulkan/CMakeLists.txt
@@ -60,9 +60,14 @@ sd_vulkan_shader(requantize_q4_1 pack_i8_rows ${SD_VK_DOT} -O -DQUANT_BITS=4 -DQ
 sd_vulkan_shader(requantize_q5_0 pack_i8_rows ${SD_VK_DOT} -O -DQUANT_BITS=5 -DQUANT_AFFINE=0)
 sd_vulkan_shader(requantize_q5_1 pack_i8_rows ${SD_VK_DOT} -O -DQUANT_BITS=5 -DQUANT_AFFINE=1)
 sd_vulkan_shader(requantize_q8 pack_i8_rows ${SD_VK_DOT} -O -DQ8_0=1)
+foreach(BITS 2 3 4 5 6)
+    sd_vulkan_shader(requantize_q${BITS}_k pack_i8_rows ${SD_VK_DOT} -O -DQUANT_K_BITS=${BITS})
+    sd_vulkan_shader(requantize_q${BITS}_k_subgroup pack_i8_rows ${SD_VK_DOT} -O -DQUANT_K_BITS=${BITS} -DSUBGROUP_MAX=1 -DSUBGROUP_ROTATION=1)
+endforeach()
+sd_vulkan_shader(requantize_q8_k pack_i8_rows ${SD_VK_DOT} -O -DQUANT_K_BITS=8)
 sd_vulkan_shader(quantize_i8_rowwise_subgroup pack_i8_rows ${SD_VK_DOT} -O -DSUBGROUP_MAX=1)
 sd_vulkan_shader(requantize_q8_subgroup pack_i8_rows ${SD_VK_DOT} -O -DQ8_0=1 -DQ8_HALFWORDS=1 -DSUBGROUP_MAX=1)
-sd_vulkan_shader(requantize_q8_register pack_i8_rows ${SD_VK_DOT} -O -DQ8_0=1 -DQ8_HALFWORDS=1 -DSUBGROUP_MAX=1 -DQ8_RETAIN=1)
+sd_vulkan_shader(requantize_q8_register pack_i8_rows ${SD_VK_DOT} -O -DQ8_0=1 -DQ8_HALFWORDS=1 -DSUBGROUP_MAX=1 -DRETAIN_ROTATION=1)
 sd_vulkan_shader(i8_lora_merge i8_lora_merge ON -O)
 sd_vulkan_shader(mul_mat_w4a4_convrot mul_mat_w4a4_convrot ${SD_VK_DOT} -O)
 sd_vulkan_shader(decode_w4a8 decode_w4a8 ON -O)
diff --git a/src/core/vulkan/int8.cpp b/src/core/vulkan/int8.cpp
index cbf4b40..117f338 100644
--- a/src/core/vulkan/int8.cpp
+++ b/src/core/vulkan/int8.cpp
@@ -23,11 +23,22 @@
 #include "quantize_i8_convrot_subgroup.h"
 #include "quantize_i8_rowwise.h"
 #include "quantize_i8_rowwise_subgroup.h"
+#include "requantize_q2_k.h"
+#include "requantize_q2_k_subgroup.h"
+#include "requantize_q3_k.h"
+#include "requantize_q3_k_subgroup.h"
 #include "requantize_q4_0.h"
 #include "requantize_q4_1.h"
+#include "requantize_q4_k.h"
+#include "requantize_q4_k_subgroup.h"
 #include "requantize_q5_0.h"
 #include "requantize_q5_1.h"
+#include "requantize_q5_k.h"
+#include "requantize_q5_k_subgroup.h"
+#include "requantize_q6_k.h"
+#include "requantize_q6_k_subgroup.h"
 #include "requantize_q8.h"
+#include "requantize_q8_k.h"
 #include "requantize_q8_register.h"
 #include "requantize_q8_subgroup.h"
 #include "rms_modulate_convrot.h"
@@ -564,6 +575,15 @@ namespace sd_vulkan_i8 {
             return GGML_STATUS_FAILED;
         const ggml_ext_vulkan_binding bindings[] = {{input}, dst};
         const uint32_t groups[]                  = {std::min(rows, d.info.max_group_count[0]), 1, 1};
+        constexpr uint32_t words_per_round       = 8 * 64;
+        constexpr uint32_t max_cached_groups     = 8;
+        const bool subgroup_rotation             = d.subgroup && d.info.max_group_size[0] >= 256;
+        const bool q8_subgroup                   = q8 && d.info.float16;
+        const bool k_subgroup                    = subgroup_rotation && words >= words_per_round && input->type != GGML_TYPE_Q8_K &&
+                                                   sd_ggml_requantize_i8_block(input->type).size == 256;
+        const uint32_t cached_groups             = words <= 2 * words_per_round ? 2 : words <= 4 * words_per_round ? 4
+                                                                                                                   : max_cached_groups;
+        const bool retain                        = subgroup_rotation && q8_subgroup && words <= max_cached_groups * words_per_round;
         auto pipeline                            = SD_VK_PIPELINE(quantize_i8_rowwise, 2, PackParameters);
         switch (input->type) {
             case GGML_TYPE_Q4_0:
@@ -579,22 +599,36 @@ namespace sd_vulkan_i8 {
                 pipeline = SD_VK_PIPELINE(requantize_q5_1, 2, PackParameters);
                 break;
             case GGML_TYPE_Q8_0:
-                pipeline = SD_VK_PIPELINE(requantize_q8, 2, PackParameters);
+                pipeline = retain ? SD_VK_PIPELINE(requantize_q8_register, 2, PackParameters) : SD_VK_PIPELINE(requantize_q8, 2, PackParameters);
+                break;
+            case GGML_TYPE_Q2_K:
+                pipeline = k_subgroup ? SD_VK_PIPELINE(requantize_q2_k_subgroup, 2, PackParameters) : SD_VK_PIPELINE(requantize_q2_k, 2, PackParameters);
+                break;
+            case GGML_TYPE_Q3_K:
+                pipeline = k_subgroup ? SD_VK_PIPELINE(requantize_q3_k_subgroup, 2, PackParameters) : SD_VK_PIPELINE(requantize_q3_k, 2, PackParameters);
+                break;
+            case GGML_TYPE_Q4_K:
+                pipeline = k_subgroup ? SD_VK_PIPELINE(requantize_q4_k_subgroup, 2, PackParameters) : SD_VK_PIPELINE(requantize_q4_k, 2, PackParameters);
+                break;
+            case GGML_TYPE_Q5_K:
+                pipeline = k_subgroup ? SD_VK_PIPELINE(requantize_q5_k_subgroup, 2, PackParameters) : SD_VK_PIPELINE(requantize_q5_k, 2, PackParameters);
+                break;
+            case GGML_TYPE_Q6_K:
+                pipeline = k_subgroup ? SD_VK_PIPELINE(requantize_q6_k_subgroup, 2, PackParameters) : SD_VK_PIPELINE(requantize_q6_k, 2, PackParameters);
+                break;
+            case GGML_TYPE_Q8_K:
+                pipeline = SD_VK_PIPELINE(requantize_q8_k, 2, PackParameters);
                 break;
             case GGML_TYPE_F32:
                 break;
             default:
                 return GGML_STATUS_FAILED;
         }
-        constexpr uint32_t words_per_round = 8 * 64;
-        const uint32_t cached_groups       = words <= 2 * words_per_round ? 2 : words <= 4 * words_per_round ? 4
-                                                                                                             : 8;
-        if (d.subgroup && (!requantize || (q8 && d.info.float16))) {
-            if (q8 && words <= cached_groups * words_per_round && d.info.max_group_size[0] >= 256) {
-                pipeline                = SD_VK_PIPELINE(requantize_q8_register, 2, PackParameters);
+        if (d.subgroup && (k_subgroup || !requantize || q8_subgroup)) {
+            if (retain) {
                 pipeline.constants      = &cached_groups;
                 pipeline.constant_count = 1;
-            } else {
+            } else if (!k_subgroup) {
                 pipeline = q8 ? SD_VK_PIPELINE(requantize_q8_subgroup, 2, PackParameters) : SD_VK_PIPELINE(quantize_i8_rowwise_subgroup, 2, PackParameters);
             }
             pipeline.full_subgroups         = d.info.full_subgroups;
diff --git a/src/core/vulkan/shaders/pack_i8_rows.comp b/src/core/vulkan/shaders/pack_i8_rows.comp
index 7caf4f9..ea637ee 100644
--- a/src/core/vulkan/shaders/pack_i8_rows.comp
+++ b/src/core/vulkan/shaders/pack_i8_rows.comp
@@ -4,15 +4,18 @@
 #extension GL_KHR_shader_subgroup_basic : require
 #extension GL_KHR_shader_subgroup_arithmetic : require
 #endif
-#ifdef Q8_HALFWORDS
+#if defined(Q8_HALFWORDS) || (defined(QUANT_K_BITS) && (QUANT_K_BITS == 3 || QUANT_K_BITS == 6))
 #extension GL_EXT_shader_16bit_storage : require
+#define SOURCE_HALFWORDS
 #endif

-#ifdef Q8_RETAIN
+#if defined(RETAIN_ROTATION) || defined(SUBGROUP_ROTATION)
 #extension GL_KHR_shader_subgroup_shuffle : require
 #extension GL_EXT_control_flow_attributes : require
 layout(local_size_x = 256) in;
+#ifdef RETAIN_ROTATION
 layout(constant_id = 0) const uint cached_groups = 4;
+#endif
 #else
 layout(local_size_x = 128) in;
 #endif
@@ -24,13 +27,13 @@ layout(push_constant) uniform Parameters {
 }
 p;

-#if defined(Q8_0) || defined(QUANT_BITS)
+#if defined(Q8_0) || defined(QUANT_BITS) || defined(QUANT_K_BITS)
 #define ROTATE_WEIGHTS
 #endif

 #ifdef ROTATE_WEIGHTS
 layout(binding = 0, std430) readonly buffer Source {
-#ifdef Q8_HALFWORDS
+#ifdef SOURCE_HALFWORDS
     uint16_t source_halfwords[];
 #else
     uint source_words[];
@@ -52,11 +55,16 @@ shared float maxima[gl_WorkGroupSize.x / 32];
 shared float maxima[gl_WorkGroupSize.x];
 #endif

-#if defined(ROTATE_WEIGHTS) && !defined(Q8_HALFWORDS)
+#ifdef ROTATE_WEIGHTS
 uint load_u32(uint byte_offset) {
+#ifdef SOURCE_HALFWORDS
+    const uint index = byte_offset / 2;
+    return uint(source_halfwords[index]) | (uint(source_halfwords[index + 1]) << 16);
+#else
     const uint index = byte_offset / 4;
     const uint word  = source_words[index];
     return (byte_offset & 2) == 0 ? word : (word >> 16) | (source_words[index + 1] << 16);
+#endif
 }
 #endif

@@ -81,11 +89,83 @@ ivec4 load_q8(const uint row, const uint word, out float scale) {
 }
 #endif

+#ifdef QUANT_K_BITS
+uint load_byte(uint offset) {
+#ifdef SOURCE_HALFWORDS
+    return (uint(source_halfwords[offset / 2]) >> (8 * (offset % 2))) & 255u;
+#else
+    return (source_words[offset / 4] >> (8 * (offset % 4))) & 255u;
+#endif
+}
+
+#ifdef SOURCE_HALFWORDS
+float load_half(uint offset) {
+    // Q3_K and Q6_K can end on a halfword boundary with no padding in the binding.
+    return unpackHalf2x16(uint(source_halfwords[offset / 2])).x;
+}
+#endif
+
+uvec4 load_bytes(uint offset) {
+    return (uvec4(load_u32(offset)) >> uvec4(0, 8, 16, 24)) & 255u;
+}
+
+vec4 load_k_values(uint block_index, uint i) {
+    // A K block contains one H256 group. Each invocation decodes four adjacent weights.
+#if QUANT_K_BITS == 2
+    const uint block   = block_index * 84;
+    const vec2 dm      = unpackHalf2x16(source_words[(block + 80) / 4]);
+    const uint scale   = load_byte(block + i / 16);
+    const uvec4 values = (load_bytes(block + 16 + i / 128 * 32 + i % 32) >> (2 * (i / 32 % 4))) & 3u;
+    return (dm.x * float(scale & 15u)) * vec4(values) - dm.y * float(scale >> 4);
+#elif QUANT_K_BITS == 3
+    const uint block      = block_index * 110;
+    const float d         = load_half(block + 108);
+    const uint group      = i / 16;
+    const uint scale_low  = (load_byte(block + 96 + group % 8) >> (4 * (group / 8))) & 15u;
+    const uint scale_high = (load_byte(block + 104 + group % 4) >> (2 * (group / 4))) & 3u;
+    const int scale       = int(scale_low | (scale_high << 4)) - 32;
+    const uvec4 low       = (load_bytes(block + 32 + i / 128 * 32 + i % 32) >> (2 * (i / 32 % 4))) & 3u;
+    const uvec4 high      = (load_bytes(block + i % 32) >> (i / 32)) & 1u;
+    return (d * float(scale)) * vec4(ivec4(low | (high << 2)) - 4);
+#elif QUANT_K_BITS == 4 || QUANT_K_BITS == 5
+    const uint high_bytes = QUANT_K_BITS == 5 ? 32u : 0u;
+    const uint block      = block_index * (144 + high_bytes);
+    const vec2 dm         = unpackHalf2x16(source_words[block / 4]);
+    const uint scales     = block + 4;
+    const uint group      = i / 32;
+    const uint scale      = group < 4 ? load_byte(scales + group) & 63u
+                                      : (load_byte(scales + group + 4) & 15u) | ((load_byte(scales + group - 4) >> 6) << 4);
+    const uint minimum    = group < 4 ? load_byte(scales + group + 4) & 63u
+                                      : (load_byte(scales + group + 4) >> 4) | ((load_byte(scales + group) >> 6) << 4);
+    uvec4 values          = (load_bytes(block + 16 + high_bytes + i / 64 * 32 + i % 32) >> (4 * (group % 2))) & 15u;
+#if QUANT_K_BITS == 5
+    values |= ((load_bytes(block + 16 + i % 32) >> group) & 1u) << 4;
+#endif
+    return (dm.x * float(scale)) * vec4(values) - dm.y * float(minimum);
+#elif QUANT_K_BITS == 6
+    const uint block = block_index * 210;
+    const float d    = load_half(block + 208);
+    const int scale  = bitfieldExtract(int(load_byte(block + 192 + i / 16)), 0, 8);
+    const uvec4 low  = (load_bytes(block + i / 128 * 64 + i % 64) >> (4 * (i / 64 % 2))) & 15u;
+    const uvec4 high = (load_bytes(block + 128 + i / 128 * 32 + i % 32) >> (2 * (i / 32 % 4))) & 3u;
+    return (d * float(scale)) * vec4(ivec4(low | (high << 4)) - 32);
+#elif QUANT_K_BITS == 8
+    const uint block = block_index * 292;
+    const float d    = uintBitsToFloat(source_words[block / 4]);
+    const int values = int(source_words[(block + 4 + i) / 4]);
+    return d * vec4(bitfieldExtract(values, 0, 8), bitfieldExtract(values, 8, 8),
+                    bitfieldExtract(values, 16, 8), bitfieldExtract(values, 24, 8));
+#endif
+}
+#endif
+
 vec4 load_values(const uint row, const uint word) {
 #ifdef Q8_0
     float scale;
     const ivec4 values = load_q8(row, word, scale);
     return scale * vec4(values);
+#elif defined(QUANT_K_BITS)
+    return load_k_values(row * (p.words_per_row / 64) + word / 64, (word % 64) * 4);
 #elif defined(QUANT_BITS)
     const uint param_bytes = QUANT_AFFINE == 1 ? 4u : 2u;
     const uint high_bytes  = QUANT_BITS == 5 ? 4u : 0u;
@@ -130,7 +210,7 @@ vec4 rotate_four(vec4 a, vec4 b, vec4 c, vec4 d, uint i) {
 }
 #endif

-#ifdef Q8_RETAIN
+#if defined(RETAIN_ROTATION) || defined(SUBGROUP_ROTATION)
 vec4 rotate_lanes(vec4 value, uint lane, uint stride) {
     const uint first = lane & ~(3u * stride);
     return rotate_four(subgroupShuffle(value, first), subgroupShuffle(value, first + stride),
@@ -139,7 +219,26 @@ vec4 rotate_lanes(vec4 value, uint lane, uint stride) {
 }

 void rotate_subgroup(uint row, uint word, out vec4 lower, out vec4 upper) {
-    const uint lane  = gl_SubgroupInvocationID;
+    const uint lane = gl_SubgroupInvocationID;
+#ifdef QUANT_K_BITS
+    // The three H4 stages across words are a Walsh-Hadamard transform with
+    // swapped bits in each input pair and sign changes on digit 3.
+    const uint block_index = row * (p.words_per_row / 64) + word / 64;
+    const uint source      = ((lane & 0x15u) << 1) | ((lane & 0x2Au) >> 1);
+    const float lower_sign = (bitCount(lane & (lane >> 1) & 0x15u) & 1) != 0 ? -1.0 : 1.0;
+    const float upper_sign = (lane & 16u) != 0 ? -lower_sign : lower_sign;
+    lower                  = rotate_word(load_k_values(block_index, source * 4) * (lower_sign / 16.0));
+    upper                  = rotate_word(load_k_values(block_index, (source + 16) * 4) * (upper_sign / 16.0));
+    [[unroll]] for (uint stride = 1; stride < 32; stride *= 2) {
+        const vec4 other_lower = subgroupShuffle(lower, lane ^ stride);
+        const vec4 other_upper = subgroupShuffle(upper, lane ^ stride);
+        lower                  = ((lane & stride) == 0 ? lower : -lower) + other_lower;
+        upper                  = ((lane & stride) == 0 ? upper : -upper) + other_upper;
+    }
+    const vec4 lower_sum = lower + upper;
+    upper                = (lower - upper) * upper_sign;
+    lower                = lower_sum * lower_sign;
+#else
     lower            = rotate_word(load_values(row, word) * (1.0 / 16.0));
     upper            = rotate_word(load_values(row, word + 32) * (1.0 / 16.0));
     lower            = rotate_lanes(rotate_lanes(lower, lane, 1), lane, 4);
@@ -151,6 +250,7 @@ void rotate_subgroup(uint row, uint word, out vec4 lower, out vec4 upper) {
     const vec4 d     = subgroupShuffle(upper, first + 16);
     lower            = rotate_four(a, b, c, d, lane / 16);
     upper            = rotate_four(a, b, c, d, 2 + lane / 16);
+#endif
 }
 #elif defined(ROTATE_WEIGHTS)
 shared vec4 rotation[2][gl_WorkGroupSize.x];
@@ -183,7 +283,7 @@ void pack_word(uint row, uint word, vec4 values, float inverse) {
 void pack_row(const uint row) {
     const uint tid = gl_LocalInvocationID.x;
     float maximum  = 0.0;
-#ifdef Q8_RETAIN
+#ifdef RETAIN_ROTATION
     // One 32-lane subgroup owns an H256 group, with two vec4 values per lane.
     const uint subgroups = gl_WorkGroupSize.x / 32;
     const uint groups    = p.words_per_row / 64;
@@ -196,6 +296,13 @@ void pack_row(const uint row) {
         const vec4 peak = max(abs(lower[slot]), abs(upper[slot]));
         maximum         = max(maximum, max(max(peak.x, peak.y), max(peak.z, peak.w)));
     }
+#elif defined(SUBGROUP_ROTATION)
+    for (uint group = gl_SubgroupID; group < p.words_per_row / 64; group += gl_WorkGroupSize.x / 32) {
+        vec4 lower, upper;
+        rotate_subgroup(row, group * 64 + gl_SubgroupInvocationID, lower, upper);
+        const vec4 peak = max(abs(lower), abs(upper));
+        maximum         = max(maximum, max(max(peak.x, peak.y), max(peak.z, peak.w)));
+    }
 #elif defined(ROTATE_WEIGHTS)
     for (uint first = 0; first < p.words_per_row; first += gl_WorkGroupSize.x) {
         const vec4 values = abs(rotate_group(row, first + tid));
@@ -241,7 +348,7 @@ void pack_row(const uint row) {
     const float inverse = scale == 0.0 ? 0.0 : 1.0 / scale;
 #endif

-#ifdef Q8_RETAIN
+#ifdef RETAIN_ROTATION
     [[unroll]] for (uint slot = 0; slot < cached_groups; ++slot) {
         const uint group = gl_SubgroupID + slot * subgroups;
         if (group >= groups)
@@ -250,6 +357,14 @@ void pack_row(const uint row) {
         pack_word(row, word, lower[slot], inverse);
         pack_word(row, word + 32, upper[slot], inverse);
     }
+#elif defined(SUBGROUP_ROTATION)
+    for (uint group = gl_SubgroupID; group < p.words_per_row / 64; group += gl_WorkGroupSize.x / 32) {
+        const uint word = group * 64 + gl_SubgroupInvocationID;
+        vec4 lower, upper;
+        rotate_subgroup(row, word, lower, upper);
+        pack_word(row, word, lower, inverse);
+        pack_word(row, word + 32, upper, inverse);
+    }
 #else
 #ifdef ROTATE_WEIGHTS
     for (uint first = 0; first < p.words_per_row; first += gl_WorkGroupSize.x) {