Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions docs/guides/int8_convrot.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
214 changes: 186 additions & 28 deletions src/core/cuda/requantize.cu
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include <climits>
#include <type_traits>

#include "convrot_kernel.h"
#include "core/ggml_extensions.h"
Expand All @@ -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;
Expand All @@ -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);
Comment thread
leejet marked this conversation as resolved.
Resolved
} 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.
Expand All @@ -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)
Expand Down Expand Up @@ -113,32 +237,48 @@ 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);
}
}
}

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) {
Expand Down Expand Up @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion src/core/ggml_extend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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") ||
Expand Down
6 changes: 3 additions & 3 deletions src/core/ggml_extensions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
31 changes: 23 additions & 8 deletions src/core/ggml_extensions.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 {};
}
}

Expand Down
7 changes: 6 additions & 1 deletion src/core/vulkan/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading