Commit 97d6af1 for stable-diffusion.cpp

commit 97d6af1b0d9b6ac2cc96cb31f7749d79ada10fd8
Author: kwilkins-82 <83912856+kwilkins-82@users.noreply.github.com>
Date:   Fri Dec 4 16:23:28 2026 +0000

    perf(hip): run W4A4 convrot through the shared INT8 linear path (#2516)

diff --git a/src/core/cuda/int8.cu b/src/core/cuda/int8.cu
index ebfa339..fc11eb3 100644
--- a/src/core/cuda/int8.cu
+++ b/src/core/cuda/int8.cu
@@ -505,6 +505,28 @@ namespace SD_CUDA_NAMESPACE {
             return cuda_last_error();
         }

+        // Signed-nibble W4A4 weights decode exactly like the int8 model's
+        // weight bytes; the column scale stays separate, as for W4A8.
+        static __global__ void decode_w4a4(const uint32_t* __restrict__ packed, uint64_t* __restrict__ decoded, int64_t quads) {
+            const int64_t i = int64_t(blockIdx.x) * blockDim.x + threadIdx.x;
+            if (i >= quads) {
+                return;
+            }
+            auto pair = [](uint32_t byte) {
+                const uint32_t lo = byte & 15, hi = (byte >> 4) & 15;
+                return uint64_t(uint8_t(int((lo ^ 8) - 8))) | (uint64_t(uint8_t(int((hi ^ 8) - 8))) << 8);
+            };
+            const uint32_t b = packed[i];
+            decoded[i]       = pair(b) | (pair(b >> 8) << 16) | (pair(b >> 16) << 32) | (pair(b >> 24) << 48);
+        }
+
+        static CUDAError decode_w4a4_weights(const SDI8Operation& op, int8_t* decoded, CUDAStream stream) {
+            const int64_t quads = op.k() * op.weight->ne[1] / 8;
+            decode_w4a4<<<unsigned((quads + 255) / 256), 256, 0, stream>>>(
+                reinterpret_cast<const uint32_t*>(op.weight->data), reinterpret_cast<uint64_t*>(decoded), quads);
+            return cuda_last_error();
+        }
+
         static bool supports(ggml_backend_dev_t device, const ggml_tensor* node, void*) {
             SDI8Operation op;
             if (!sd_ggml_i8_describe(node, &op) || !aligned(node))
@@ -743,10 +765,13 @@ namespace SD_CUDA_NAMESPACE {
             total += (bytes + 255) / 256 * 256;
             return offset;
         }
-        static ggml_status prepare(ggml_backend_t backend, ggml_tensor* const* nodes, int count, void** state, size_t* workspace, void*) {
+        static ggml_status prepare_impl(ggml_backend_t backend, ggml_tensor* const* nodes, int count, void** state, size_t* workspace, void*,
+                                        const SDI8Operation* w4op) {
             const auto* dst = nodes[count - 1];
-            SDI8Operation op;
-            const bool mat = sd_ggml_i8_describe(nodes[0], &op);
+            SDI8Operation op = {};
+            const bool mat   = w4op ? true : sd_ggml_i8_describe(nodes[0], &op);
+            if (w4op)
+                op = *w4op;
             auto* p        = new Plan{};
             *state         = p;
             auto device    = ggml_backend_get_device(backend);
@@ -1031,7 +1056,8 @@ namespace SD_CUDA_NAMESPACE {
                 up, stride, stride, xs, ws, nullptr, 0.f, 1.f, 0.f, nullptr, nullptr);
             return cuda_last_error();
         }
-        static ggml_status execute(const ggml_ext_execution_context* execution, ggml_tensor* const* nodes, int count, void* state, void*) {
+        static ggml_status execute_impl(const ggml_ext_execution_context* execution, ggml_tensor* const* nodes, int count, void* state, void*,
+                                        const SDI8Operation* w4op) {
             const auto& p = *static_cast<const Plan*>(state);
             ggml_ext_gpu_context context;
             if (!cuda_context(execution->backend, &context) || context.device != p.device.device)
@@ -1040,8 +1066,10 @@ namespace SD_CUDA_NAMESPACE {
             auto* scratch   = execution->workspace ? static_cast<char*>(ggml_backend_buffer_get_base(execution->workspace)) : nullptr;
             auto scratch_at = [scratch](size_t offset) { return scratch ? scratch + offset : nullptr; };
             auto* dst       = nodes[count - 1];
-            SDI8Operation op;
-            const bool mat       = sd_ggml_i8_describe(nodes[0], &op);
+            SDI8Operation op     = {};
+            const bool mat       = w4op ? true : sd_ggml_i8_describe(nodes[0], &op);
+            if (w4op)
+                op = *w4op;
             const auto* residual = p.kind == GATED_RESIDUAL ? residual_input(nodes[1], dst) : nullptr;
             bool alias           = false;
             for (int i = 0; i < count; ++i)
@@ -1091,7 +1119,12 @@ namespace SD_CUDA_NAMESPACE {
                 if (error != cuda_success || cuda_last_error() != cuda_success)
                     return GGML_STATUS_FAILED;
                 const auto* weight = static_cast<const int8_t*>(op.weight->data);
-                if (op.codebook && !p.chunk_cols) {
+                if (op.w4a4 && !p.chunk_cols) {
+                    auto* decoded = reinterpret_cast<int8_t*>(scratch_at(p.decoded_weight));
+                    if (decode_w4a4_weights(op, decoded, stream) != cuda_success)
+                        return GGML_STATUS_FAILED;
+                    weight = decoded;
+                } else if (op.codebook && !p.chunk_cols) {
                     auto* decoded = reinterpret_cast<int8_t*>(scratch_at(p.decoded_weight));
                     if (decode_w4a8_weights(op, decoded, 0, p.n, stream) != cuda_success)
                         return GGML_STATUS_FAILED;
@@ -1103,6 +1136,13 @@ namespace SD_CUDA_NAMESPACE {
                 auto* gemm_output       = reinterpret_cast<float*>(static_cast<char*>(output) + prefix);
                 auto* accum             = reinterpret_cast<int32_t*>(scratch_at(p.accum));
                 const bool intermediate = p.kind == SWIGLU_QUANTIZE || (p.kind == GATED && !p.fused_activation);
+                auto run_dot = [&]() {
+                    const dim3 grid(unsigned(std::min<int64_t>((p.n + 31) / 32, 65535)), unsigned(std::min<int64_t>((p.rows + 31) / 32, 65535)));
+                    mul_mat_i8_dot<<<grid, dim3(16, 16), 0, stream>>>(reinterpret_cast<const int*>(weight),
+                                                                      reinterpret_cast<const int*>(quant), accum, p.k / 4, p.n, p.rows);
+                    return cuda_last_error() == cuda_success;
+                };
+                bool gemm_done = false;
 #ifdef SD_CUDA_I8_CUTLASS
                 if (p.chunk_cols) {
                     auto* decoded = reinterpret_cast<int8_t*>(scratch_at(p.decoded_weight));
@@ -1117,44 +1157,50 @@ namespace SD_CUDA_NAMESPACE {
                         if (status != GGML_STATUS_SUCCESS)
                             return status;
                     }
+                    gemm_done = true;
                 } else if (p.gemm) {
                     auto status = sd_cuda_i8_gemm_execute(p.gemm, quant, weight, scales, ws,
                                                           intermediate ? reinterpret_cast<float*>(accum) : gemm_output, scratch_at(p.gemm_offset), stream, bias);
                     if (status != GGML_STATUS_SUCCESS)
                         return status;
-                } else
+                    gemm_done = true;
+                }
 #endif
-                    if (!p.use_blas) {
-                    const dim3 grid(unsigned(std::min<int64_t>((p.n + 31) / 32, 65535)), unsigned(std::min<int64_t>((p.rows + 31) / 32, 65535)));
-                    mul_mat_i8_dot<<<grid, dim3(16, 16), 0, stream>>>(reinterpret_cast<const int*>(weight),
-                                                                      reinterpret_cast<const int*>(quant), accum, p.k / 4, p.n, p.rows);
-                    if (cuda_last_error() != cuda_success)
+                if (!gemm_done && !p.use_blas) {
+                    if (!run_dot())
                         return GGML_STATUS_FAILED;
+                    gemm_done = true;
                 }
 #if !defined(SD_CUDA_VENDOR_MUSA)
-                else {
+                if (!gemm_done) {
                     auto reg        = ggml_backend_dev_backend_reg(ggml_backend_get_device(execution->backend));
                     auto blas_query = reinterpret_cast<ggml_ext_gpu_blas_fn>(ggml_backend_reg_get_proc_address(reg, "ggml_ext_gpu_blas_v1"));
                     auto handle     = blas_query ? blas_query(execution->backend) : nullptr;
-                    if (!handle)
-                        return GGML_STATUS_FAILED;
+                    bool blas_ok    = handle != nullptr;
 #if defined(SD_CUDA_VENDOR_HIP)
-                    const HipI8Gemm gemm{int(p.n), int(p.padded), int(p.k), weight, quant, accum,
-                                         static_cast<hipblasHandle_t>(handle), stream};
+                    if (blas_ok) {
+                        const HipI8Gemm gemm{int(p.n), int(p.padded), int(p.k), weight, quant, accum,
+                                             static_cast<hipblasHandle_t>(handle), stream};
 #ifdef SD_HIP_I8_LT
-                    if (!hip_i8_gemm_lt(context.device, gemm) && gemm.run_hipblas() != HIPBLAS_STATUS_SUCCESS)
+                        blas_ok = hip_i8_gemm_lt(context.device, gemm) || gemm.run_hipblas() == HIPBLAS_STATUS_SUCCESS;
 #else
-                    if (gemm.run_hipblas() != HIPBLAS_STATUS_SUCCESS)
+                        blas_ok = gemm.run_hipblas() == HIPBLAS_STATUS_SUCCESS;
 #endif
+                    }
 #else
-                    const int32_t alpha = 1, beta = 0;
-                    const auto status = cublasGemmEx(static_cast<cublasHandle_t>(handle), CUBLAS_OP_T, CUBLAS_OP_N,
-                                                     int(p.n), int(p.padded), int(p.k), &alpha,
-                                                     weight, CUDA_R_8I, int(p.k), quant, CUDA_R_8I, int(p.k),
-                                                     &beta, accum, CUDA_R_32I, int(p.n), CUBLAS_COMPUTE_32I, CUBLAS_GEMM_DEFAULT_TENSOR_OP);
-                    if (status != CUBLAS_STATUS_SUCCESS)
+                    if (blas_ok) {
+                        const int32_t alpha = 1, beta = 0;
+                        blas_ok = cublasGemmEx(static_cast<cublasHandle_t>(handle), CUBLAS_OP_T, CUBLAS_OP_N,
+                                               int(p.n), int(p.padded), int(p.k), &alpha,
+                                               weight, CUDA_R_8I, int(p.k), quant, CUDA_R_8I, int(p.k),
+                                               &beta, accum, CUDA_R_32I, int(p.n), CUBLAS_COMPUTE_32I, CUBLAS_GEMM_DEFAULT_TENSOR_OP) == CUBLAS_STATUS_SUCCESS;
+                    }
 #endif
-                        return GGML_STATUS_FAILED;
+                    if (!blas_ok) {
+                        (void)cuda_last_error();
+                        if (!run_dot())
+                            return GGML_STATUS_FAILED;
+                    }
                 }
 #endif
                 const auto* values = reinterpret_cast<const float*>(accum);
@@ -1202,6 +1248,52 @@ namespace SD_CUDA_NAMESPACE {
             return error == cuda_success ? GGML_STATUS_SUCCESS : GGML_STATUS_FAILED;
         }

+        static ggml_status prepare(ggml_backend_t backend, ggml_tensor* const* nodes, int count, void** state, size_t* workspace, void* user_data) {
+            return prepare_impl(backend, nodes, count, state, workspace, user_data, nullptr);
+        }
+        static ggml_status execute(const ggml_ext_execution_context* execution, ggml_tensor* const* nodes, int count, void* state, void* user_data) {
+            return execute_impl(execution, nodes, count, state, user_data, nullptr);
+        }
+#if defined(SD_CUDA_VENDOR_HIP)
+        static bool w4a4_forced() {
+            static const bool forced = [] { const char* v = std::getenv("GGML_CUDA_W4_FORCE_DP4A"); return v && std::atoi(v); }();
+            return forced;
+        }
+        static bool describe_w4a4(const ggml_tensor* node, SDI8Operation* op) {
+            SDW4Operation w4;
+            if (!sd_ggml_w4_describe(node, &w4) || w4.input->type != GGML_TYPE_I8)
+                return false;
+            *op = {w4.weight, w4.input, nullptr, w4.weight_scale, w4.bias, 0, true, nullptr, nullptr, true};
+            return true;
+        }
+        static bool w4a4_supports(ggml_backend_dev_t device, const ggml_tensor* node, void*) {
+            SDI8Operation op;
+            if (w4a4_forced() || !describe_w4a4(node, &op) || !aligned(node) || !aligned(op.weight, 8) || !aligned(op.input, 8))
+                return false;
+            const int64_t k = op.k(), n = node->ne[0], rows = ggml_nrows(node);
+            const auto info = cuda_device_info(device);
+            // Without BLAS the whole matrix would be expanded only to feed the
+            // generic INT8 dot kernel; the packed DP4A kernel is faster there.
+            // Bound the decode buffer so large shapes stay on that path too.
+            constexpr size_t max_decode_bytes = 96 * 1024 * 1024;
+            return k % 64 == 0 && k <= INT_MAX && n <= INT_MAX && rows <= INT_MAX - 3 &&
+                   size_t(k) * size_t(n) <= max_decode_bytes && info.device >= 0 &&
+                   blas_supported(device, info, n);
+        }
+        static ggml_status w4a4_prepare(ggml_backend_t backend, ggml_tensor* const* nodes, int count, void** state, size_t* workspace, void* user_data) {
+            SDI8Operation op;
+            if (!describe_w4a4(nodes[0], &op))
+                return GGML_STATUS_FAILED;
+            return prepare_impl(backend, nodes, count, state, workspace, user_data, &op);
+        }
+        static ggml_status w4a4_execute(const ggml_ext_execution_context* execution, ggml_tensor* const* nodes, int count, void* state, void* user_data) {
+            SDI8Operation op;
+            if (!describe_w4a4(nodes[0], &op))
+                return GGML_STATUS_FAILED;
+            return execute_impl(execution, nodes, count, state, user_data, &op);
+        }
+#endif
+
 #if defined(SD_CUDA_VENDOR_HIP)
         struct SplitConvrotPlan {
             int64_t k, n, rows, padded;
@@ -1356,6 +1448,19 @@ namespace SD_CUDA_NAMESPACE {
         desc.execute   = sd_i8_cuda::split_convrot_execute;
         desc.destroy   = sd_i8_cuda::split_convrot_destroy;
         GGML_ASSERT(ggml_ext_register_kernel_ex(device, &desc, GGML_EXT_KERNEL_CAPTURE_SAFE | GGML_EXT_KERNEL_REPLAY_REUSABLE));
+#endif
+#if defined(SD_CUDA_VENDOR_HIP)
+        desc.name      = "sd.linear_w4a4." SD_CUDA_NAME ".v1";
+        desc.custom_op = sd_ggml_w4_op();
+        desc.priority  = 200;
+        desc.supports  = sd_i8_cuda::w4a4_supports;
+        desc.preferred = nullptr;
+        desc.match     = nullptr;
+        desc.optimize  = nullptr;
+        desc.prepare   = sd_i8_cuda::w4a4_prepare;
+        desc.execute   = sd_i8_cuda::w4a4_execute;
+        desc.destroy   = sd_i8_cuda::destroy;
+        GGML_ASSERT(ggml_ext_register_kernel_ex(device, &desc, GGML_EXT_KERNEL_CAPTURE_SAFE | GGML_EXT_KERNEL_REPLAY_REUSABLE));
 #endif
     }

diff --git a/src/core/ggml_extensions.cpp b/src/core/ggml_extensions.cpp
index 0aa0f8a..05d50ba 100644
--- a/src/core/ggml_extensions.cpp
+++ b/src/core/ggml_extensions.cpp
@@ -328,7 +328,7 @@ static constexpr int i8_flags = SD_I8_PACKED | SD_I8_INPUT_SCALE | SD_I8_WEIGHT_
 static bool i8_operands(ggml_tensor* const* inputs, int count, const SDI8Attributes& attr, SDI8Operation* op) {
     if (count < 2 || (attr.flags & ~i8_flags))
         return false;
-    *op       = {inputs[0], inputs[1], nullptr, nullptr, nullptr, attr.group_size, (attr.flags & SD_I8_PACKED) != 0, nullptr, nullptr};
+    *op       = {inputs[0], inputs[1], nullptr, nullptr, nullptr, attr.group_size, (attr.flags & SD_I8_PACKED) != 0, nullptr, nullptr, false};
     int index = 2;
     for (auto entry : {std::make_pair(SD_I8_INPUT_SCALE, &op->input_scale), std::make_pair(SD_I8_WEIGHT_SCALE, &op->weight_scale), std::make_pair(SD_I8_BIAS, &op->bias)}) {
         if (attr.flags & entry.first) {
diff --git a/src/core/ggml_extensions.h b/src/core/ggml_extensions.h
index 1da179e..c9cba7e 100644
--- a/src/core/ggml_extensions.h
+++ b/src/core/ggml_extensions.h
@@ -62,9 +62,10 @@ struct SDI8Operation {
     bool packed;
     const ggml_tensor* codebook;
     const ggml_tensor* relative_scale;
+    bool w4a4;

     int64_t k() const { return input->ne[0]; }
-    size_t decoded_weight_bytes() const { return codebook ? size_t(k()) * weight->ne[1] : 0; }
+    size_t decoded_weight_bytes() const { return w4a4 || codebook ? size_t(k()) * weight->ne[1] : 0; }
 };

 bool sd_ggml_valid_convrot_group(int group);