Skip to content

Commit d68f288

Browse files
authored
feat: support Q4 and Q5 weights in INT8 linear layers (#2452)
1 parent 3771ef2 commit d68f288

8 files changed

Lines changed: 205 additions & 86 deletions

File tree

‎docs/guides/int8_convrot.md‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -166,12 +166,14 @@ these formats because they require the application extension API.
166166

167167
## Runtime requantization to INT8
168168

169-
Use `--linear-type i8` to run eligible Q8_0 linear layers through INT8 GEMM on
170-
CUDA, HIP, MUSA, and Vulkan. A bare mode applies to all models in the context,
171-
including diffusion models and text encoders loaded with `--llm`. The default
172-
is `auto`, which currently behaves like `raw`. With `--linear-type raw`, each
173-
layer uses its original execution path. Native INT8 weights use their INT8
174-
path in all three modes.
169+
Use `--linear-type i8` to run eligible Q4_0, Q4_1, Q5_0, Q5_1, and Q8_0 linear
170+
layers through INT8 GEMM on CUDA, HIP, MUSA, and Vulkan. A bare mode applies to
171+
all models in the context, including diffusion models and text encoders loaded
172+
with `--llm`. The default is `auto`, which currently behaves like `raw`. With
173+
`--linear-type raw`, each layer uses its original execution path. Native INT8
174+
weights use their INT8 path in all three modes. For floating-point checkpoints,
175+
use `--type q4_0` (or another supported weight type) to quantize eligible weights
176+
at load time.
175177

176178
Use module assignments to apply a mode selectively. For example,
177179
`--linear-type dit=i8` selects runtime conversion for the diffusion module.
@@ -189,14 +191,14 @@ dot products and compatible storage buffer sizes and alignment. The C API option
189191
use `sd_dgl_ctx_set(ctx, "linear_type", "dit=i8")` or pass
190192
`--linear-type dit=i8` when running the script from the CLI.
191193

192-
At runtime, sd.cpp dequantizes the Q8_0 blocks, rotates the weights, and
194+
At runtime, sd.cpp dequantizes the weight blocks, rotates the weights, and
193195
requantizes them to INT8 with one scale per output channel. It applies the
194196
same rotation to the activations before quantizing each input row. The
195197
converted matrix uses temporary GPU memory and feeds the standard INT8 kernels
196198
and their fusions. The checkpoint file stays in its original format.
197199
Requantization changes numerical results, and conversion overhead depends on
198-
matrix shape. Row-split models and unsupported layers use the standard Q8_0
199-
path.
200+
matrix shape. Row-split models and unsupported layers use their original
201+
execution paths.
200202

201203
## Example
202204

‎src/core/cuda/requantize.cu‎

Lines changed: 85 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -10,40 +10,58 @@ namespace SD_CUDA_NAMESPACE {
1010
using i8::blas_supported;
1111
using i8::warp_reduce_max;
1212

13-
// Match the GGML Q8_0 block layout checked by requantize_q8_supports().
14-
struct Q8Block {
15-
static constexpr int size = 32;
16-
static constexpr int pairs = size / 2;
17-
half scale;
18-
uint16_t values[pairs];
13+
constexpr int block_size = SD_REQUANTIZE_I8_BLOCK_SIZE;
14+
15+
// GGML stores FP16 parameters, then the Q5 high bits, then the quants.
16+
template <ggml_type type>
17+
struct QuantBlock {
18+
static constexpr int bits = type == GGML_TYPE_Q8_0 ? 8 : (type == GGML_TYPE_Q5_0 || type == GGML_TYPE_Q5_1 ? 5 : 4);
19+
static constexpr bool affine = type == GGML_TYPE_Q4_1 || type == GGML_TYPE_Q5_1;
20+
static constexpr int high_words = bits == 5 ? 2 : 0;
21+
half params[affine ? 2 : 1];
22+
uint16_t payload[(bits == 8 ? block_size / 2 : block_size / 4) + high_words];
23+
24+
__device__ __forceinline__ float decode(int lane) const {
25+
const float scale = __half2float(params[0]);
26+
if constexpr (bits == 8) {
27+
const int8_t value = int8_t(payload[lane / 2] >> (8 * (lane % 2)));
28+
return float(value) * scale;
29+
} else {
30+
const int low_lane = lane % 16;
31+
const uint16_t packed = payload[high_words + low_lane / 2];
32+
int value = (packed >> (8 * (low_lane % 2) + 4 * (lane / 16))) & 15;
33+
if constexpr (bits == 5)
34+
value |= ((payload[lane / 16] >> low_lane) & 1) << 4;
35+
if constexpr (affine)
36+
return float(value) * scale + __half2float(params[1]);
37+
return float(value - (1 << (bits - 1))) * scale;
38+
}
39+
}
1940
};
20-
static_assert(sizeof(Q8Block) == 34);
2141

22-
static __device__ __forceinline__ int8_t requantize_q8_value(float value) {
42+
static __device__ __forceinline__ int8_t requantize_i8_value(float value) {
2343
return int8_t(__float2int_rn(fminf(127.f, fmaxf(-127.f, value))));
2444
}
2545

26-
static __device__ __forceinline__ void load_rotated_group(const Q8Block* blocks, int lane, float (&values)[8]) {
46+
template <ggml_type type>
47+
static __device__ __forceinline__ void load_rotated_group(const QuantBlock<type>* blocks, int lane, float (&values)[8]) {
2748
#pragma unroll
28-
for (int j = 0; j < 8; ++j) {
29-
const auto& block = blocks[j];
30-
const int8_t value = int8_t(block.values[lane / 2] >> (8 * (lane % 2)));
31-
values[j] = (float(value) * __half2float(block.scale)) * (1.0f / 16.0f);
32-
}
49+
for (int j = 0; j < 8; ++j)
50+
values[j] = blocks[j].decode(lane) * (1.0f / 16.0f);
3351
sd_convrot::rotate_h256(values, lane);
3452
}
3553

3654
constexpr int requantize_warps = 8;
37-
constexpr int blocks_per_group = 256 / Q8Block::size;
55+
constexpr int blocks_per_group = 256 / block_size;
3856
constexpr int blocks_per_round = requantize_warps * blocks_per_group;
39-
constexpr int weights_per_round = blocks_per_round * Q8Block::size;
57+
constexpr int weights_per_round = blocks_per_round * block_size;
4058

41-
template <int cached_groups>
42-
static __global__ void requantize_q8_weights(const Q8Block* weights, int8_t* decoded, float* scales, int64_t blocks_per_channel) {
59+
template <ggml_type type, int cached_groups>
60+
static __global__ void requantize_i8_weights(const QuantBlock<type>* weights, int8_t* decoded, float* scales, int64_t blocks_per_channel) {
4361
const int lane = threadIdx.x;
4462
const int warp = threadIdx.y;
4563
const auto* blocks = weights + int64_t(blockIdx.x) * blocks_per_channel;
46-
auto* output = decoded + int64_t(blockIdx.x) * blocks_per_channel * Q8Block::size;
64+
auto* output = decoded + int64_t(blockIdx.x) * blocks_per_channel * block_size;
4765

4866
__shared__ float maxima[requantize_warps];
4967
// Keep a bounded number of rotated groups in registers across the scale reduction.
@@ -98,46 +116,66 @@ namespace SD_CUDA_NAMESPACE {
98116
load_rotated_group(blocks + block, lane, values);
99117
#pragma unroll
100118
for (int j = 0; j < 8; ++j) {
101-
const float value = cached_groups > 0 ? retained[slot][j] : values[j];
102-
output[(block + j) * Q8Block::size + lane] = requantize_q8_value(value * inverse);
119+
const float value = cached_groups > 0 ? retained[slot][j] : values[j];
120+
output[(block + j) * block_size + lane] = requantize_i8_value(value * inverse);
103121
}
104122
}
105123
}
106124

107-
template <int cached_groups>
108-
static void launch_requantize(const Q8Block* weights, int8_t* values, float* scales, int64_t k, int64_t n, CUDAStream stream) {
109-
requantize_q8_weights<cached_groups><<<unsigned(n), dim3(Q8Block::size, requantize_warps), 0, stream>>>(
110-
weights, values, scales, k / Q8Block::size);
111-
}
112-
113-
static bool requantize_q8_supports(ggml_backend_dev_t device, const ggml_tensor* node, void*) {
125+
static bool requantize_i8_supports(ggml_backend_dev_t device, const ggml_tensor* node, void*) {
114126
const auto* weight = node->src[0];
115127
const int64_t k = weight->ne[0], n = weight->ne[1];
116128
const auto info = cuda_device_info(device);
117-
return info.device >= 0 && k <= INT_MAX / 16384 && n <= INT_MAX && aligned(weight, alignof(Q8Block)) &&
118-
ggml_blck_size(GGML_TYPE_Q8_0) == Q8Block::size && ggml_type_size(GGML_TYPE_Q8_0) == sizeof(Q8Block) &&
129+
return info.device >= 0 && k <= INT_MAX / 16384 && n <= INT_MAX && aligned(weight, alignof(uint16_t)) &&
119130
(cuda_kind != GGML_EXT_GPU_CUDA || blas_supported(device, info, n));
120131
}
121132

122-
static ggml_status requantize_q8_execute(const ggml_ext_execution_context* execution, ggml_tensor* const* nodes, int, void*, void*) {
123-
ggml_ext_gpu_context context;
124-
if (!cuda_context(execution->backend, &context))
125-
return GGML_STATUS_FAILED;
126-
auto* dst = nodes[0];
127-
const auto* weight = dst->src[0];
133+
template <ggml_type type>
134+
static void launch_requantize(const ggml_tensor* weight, int8_t* values, CUDAStream stream) {
135+
using Block = QuantBlock<type>;
136+
static_assert(sizeof(Block) == sd_ggml_requantize_i8_block_bytes(type) && alignof(Block) == alignof(uint16_t));
128137
const int64_t k = weight->ne[0], n = weight->ne[1];
129-
auto* values = static_cast<int8_t*>(dst->data);
130138
auto* scales = reinterpret_cast<float*>(values + k * n);
131-
const auto* weights = static_cast<const Q8Block*>(weight->data);
132-
const auto stream = static_cast<CUDAStream>(context.stream);
139+
const auto* weights = static_cast<const Block*>(weight->data);
140+
const dim3 threads(block_size, requantize_warps);
141+
const int64_t blocks_per_channel = k / block_size;
133142
if (cuda_kind == GGML_EXT_GPU_CUDA && k <= 2 * weights_per_round) {
134-
launch_requantize<2>(weights, values, scales, k, n, stream);
143+
requantize_i8_weights<type, 2><<<unsigned(n), threads, 0, stream>>>(weights, values, scales, blocks_per_channel);
135144
} else if (cuda_kind == GGML_EXT_GPU_CUDA && k <= 4 * weights_per_round) {
136-
launch_requantize<4>(weights, values, scales, k, n, stream);
145+
requantize_i8_weights<type, 4><<<unsigned(n), threads, 0, stream>>>(weights, values, scales, blocks_per_channel);
137146
} else if (cuda_kind == GGML_EXT_GPU_CUDA && k <= 8 * weights_per_round) {
138-
launch_requantize<8>(weights, values, scales, k, n, stream);
147+
requantize_i8_weights<type, 8><<<unsigned(n), threads, 0, stream>>>(weights, values, scales, blocks_per_channel);
139148
} else {
140-
launch_requantize<0>(weights, values, scales, k, n, stream);
149+
requantize_i8_weights<type, 0><<<unsigned(n), threads, 0, stream>>>(weights, values, scales, blocks_per_channel);
150+
}
151+
}
152+
153+
static ggml_status requantize_i8_execute(const ggml_ext_execution_context* execution, ggml_tensor* const* nodes, int, void*, void*) {
154+
ggml_ext_gpu_context context;
155+
if (!cuda_context(execution->backend, &context))
156+
return GGML_STATUS_FAILED;
157+
auto* dst = nodes[0];
158+
const auto* weight = dst->src[0];
159+
auto* values = static_cast<int8_t*>(dst->data);
160+
const auto stream = static_cast<CUDAStream>(context.stream);
161+
switch (weight->type) {
162+
case GGML_TYPE_Q4_0:
163+
launch_requantize<GGML_TYPE_Q4_0>(weight, values, stream);
164+
break;
165+
case GGML_TYPE_Q4_1:
166+
launch_requantize<GGML_TYPE_Q4_1>(weight, values, stream);
167+
break;
168+
case GGML_TYPE_Q5_0:
169+
launch_requantize<GGML_TYPE_Q5_0>(weight, values, stream);
170+
break;
171+
case GGML_TYPE_Q5_1:
172+
launch_requantize<GGML_TYPE_Q5_1>(weight, values, stream);
173+
break;
174+
case GGML_TYPE_Q8_0:
175+
launch_requantize<GGML_TYPE_Q8_0>(weight, values, stream);
176+
break;
177+
default:
178+
return GGML_STATUS_FAILED;
141179
}
142180
return cuda_last_error() == cuda_success ? GGML_STATUS_SUCCESS : GGML_STATUS_FAILED;
143181
}
@@ -147,10 +185,10 @@ namespace SD_CUDA_NAMESPACE {
147185
ggml_ext_kernel_desc desc = {};
148186
desc.abi_version = GGML_EXT_ABI_VERSION;
149187
desc.op = GGML_OP_CUSTOM;
150-
desc.name = "sd.requantize_q8." SD_CUDA_NAME ".v1";
151-
desc.custom_op = sd_ggml_requantize_q8_op();
152-
desc.supports = requantize_q8_supports;
153-
desc.execute = requantize_q8_execute;
188+
desc.name = "sd.requantize_i8." SD_CUDA_NAME ".v1";
189+
desc.custom_op = sd_ggml_requantize_i8_op();
190+
desc.supports = requantize_i8_supports;
191+
desc.execute = requantize_i8_execute;
154192
GGML_ASSERT(ggml_ext_register_kernel_ex(device, &desc, GGML_EXT_KERNEL_CAPTURE_SAFE | GGML_EXT_KERNEL_REPLAY_REUSABLE));
155193
}
156194
}

‎src/core/ggml_extend.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ ggml_tensor* ggml_ext_linear(GGMLRunnerContext* runner_ctx,
217217
const auto mul_mat = [&](ggml_tensor* input) {
218218
#ifndef SD_USE_UPSTREAM_GGML
219219
// The INT8 path accumulates in INT32 and rescales in FP32.
220-
if (runner_ctx->requantize_to_i8 && w->type == GGML_TYPE_Q8_0 && input->type == GGML_TYPE_F32 &&
220+
if (runner_ctx->requantize_to_i8 && sd_ggml_requantize_i8_block_bytes(w->type) && input->type == GGML_TYPE_F32 &&
221221
(sd_backend_is(runner_ctx->backend, "CUDA") ||
222222
sd_backend_is(runner_ctx->backend, "ROCm") ||
223223
sd_backend_is(runner_ctx->backend, "MUSA") ||
@@ -227,7 +227,7 @@ ggml_tensor* ggml_ext_linear(GGMLRunnerContext* runner_ctx,
227227
if (quantized && ggml_backend_supports_op(runner_ctx->backend, quantized)) {
228228
// Make the conversion depend on the activation so decoded weights only live near their GEMM.
229229
ggml_tensor* inputs[] = {w, quantized};
230-
auto* converted = ggml_ext_op_create(ctx, sd_ggml_requantize_q8_op(), inputs, 2, nullptr);
230+
auto* converted = ggml_ext_op_create(ctx, sd_ggml_requantize_i8_op(), inputs, 2, nullptr);
231231
if (converted && ggml_backend_supports_op(runner_ctx->backend, converted)) {
232232
const int64_t k = w->ne[0], n = w->ne[1];
233233
auto* weight = ggml_view_2d(ctx, converted, k, n, k, 0);

‎src/core/ggml_extensions.cpp‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -252,10 +252,13 @@ static bool i8_infer(ggml_tensor* const* inputs, int count, const void* attribut
252252
return true;
253253
}
254254

255-
static bool requantize_q8_infer(ggml_tensor* const* inputs, int count, const void*, ggml_ext_tensor_desc* output) {
256-
if (count != 2 || !inputs[0] || !inputs[1] || inputs[0]->type != GGML_TYPE_Q8_0 || inputs[1]->type != GGML_TYPE_I8)
255+
static bool requantize_i8_infer(ggml_tensor* const* inputs, int count, const void*, ggml_ext_tensor_desc* output) {
256+
if (count != 2 || !inputs[0] || !inputs[1] || inputs[1]->type != GGML_TYPE_I8)
257+
return false;
258+
const auto* weight = inputs[0];
259+
const size_t block_bytes = sd_ggml_requantize_i8_block_bytes(weight->type);
260+
if (!block_bytes || ggml_blck_size(weight->type) != SD_REQUANTIZE_I8_BLOCK_SIZE || ggml_type_size(weight->type) != block_bytes)
257261
return false;
258-
const auto* weight = inputs[0];
259262
const int64_t k = weight->ne[0], n = weight->ne[1];
260263
constexpr int64_t scale_bytes = sizeof(float);
261264
int group;
@@ -290,9 +293,9 @@ ggml_ext_op_t sd_ggml_i8_op() {
290293
return op;
291294
}
292295

293-
ggml_ext_op_t sd_ggml_requantize_q8_op() {
296+
ggml_ext_op_t sd_ggml_requantize_i8_op() {
294297
static const auto op = [] {
295-
const ggml_ext_op_desc desc = {GGML_EXT_ABI_VERSION, "sd.requantize_q8.v1", 0, requantize_q8_infer};
298+
const ggml_ext_op_desc desc = {GGML_EXT_ABI_VERSION, "sd.requantize_i8.v1", 0, requantize_i8_infer};
296299
const auto result = ggml_ext_register_op(&desc);
297300
GGML_ASSERT(result);
298301
return result;

‎src/core/ggml_extensions.h‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,26 @@ struct SDI8Operation {
4848
bool sd_ggml_valid_convrot_group(int group);
4949

5050
ggml_ext_op_t sd_ggml_i8_op();
51-
ggml_ext_op_t sd_ggml_requantize_q8_op();
51+
ggml_ext_op_t sd_ggml_requantize_i8_op();
52+
53+
constexpr int SD_REQUANTIZE_I8_BLOCK_SIZE = 32;
54+
55+
constexpr size_t sd_ggml_requantize_i8_block_bytes(ggml_type type) {
56+
switch (type) {
57+
case GGML_TYPE_Q4_0:
58+
return 18;
59+
case GGML_TYPE_Q4_1:
60+
return 20;
61+
case GGML_TYPE_Q5_0:
62+
return 22;
63+
case GGML_TYPE_Q5_1:
64+
return 24;
65+
case GGML_TYPE_Q8_0:
66+
return 34;
67+
default:
68+
return 0;
69+
}
70+
}
5271

5372
ggml_ext_op_t sd_ggml_convrot_op();
5473

‎src/core/vulkan/CMakeLists.txt‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,10 @@ sd_vulkan_shader(rms_rope_cast rms_rope_apply ON -DCAST_F16)
5555
sd_vulkan_shader(quantize_i8_convrot quantize_i8_convrot ${SD_VK_DOT} -O)
5656
sd_vulkan_shader(quantize_i8_convrot_h64 quantize_i8_convrot_h64 ${SD_VK_DOT} -O -DGROUP_SIZE=64)
5757
sd_vulkan_shader(quantize_i8_rowwise pack_i8_rows ${SD_VK_DOT} -O)
58+
sd_vulkan_shader(requantize_q4_0 pack_i8_rows ${SD_VK_DOT} -O -DQUANT_BITS=4 -DQUANT_AFFINE=0)
59+
sd_vulkan_shader(requantize_q4_1 pack_i8_rows ${SD_VK_DOT} -O -DQUANT_BITS=4 -DQUANT_AFFINE=1)
60+
sd_vulkan_shader(requantize_q5_0 pack_i8_rows ${SD_VK_DOT} -O -DQUANT_BITS=5 -DQUANT_AFFINE=0)
61+
sd_vulkan_shader(requantize_q5_1 pack_i8_rows ${SD_VK_DOT} -O -DQUANT_BITS=5 -DQUANT_AFFINE=1)
5862
sd_vulkan_shader(requantize_q8 pack_i8_rows ${SD_VK_DOT} -O -DQ8_0=1)
5963
sd_vulkan_shader(quantize_i8_rowwise_subgroup pack_i8_rows ${SD_VK_DOT} -O -DSUBGROUP_MAX=1)
6064
sd_vulkan_shader(requantize_q8_subgroup pack_i8_rows ${SD_VK_DOT} -O -DQ8_0=1 -DQ8_HALFWORDS=1 -DSUBGROUP_MAX=1)

0 commit comments

Comments
 (0)