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
18 changes: 8 additions & 10 deletions docs/development/ggml_extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,15 +109,13 @@ and backend `graph_plan_*` interfaces do not dispatch these extensions.

## Backend services

Packed ComfyUI INT4 linear layers use `sd.linear_w4_convrot.v1`, built by
`ggml_ext_mul_mat_w4_convrot`. The operator consumes byte-packed I8 weights and the
explicit output of `sd.quantize_i8_convrot.v1`; F32 callers get a quantization
node during graph construction. Logical output dimensions are stored in the
operator attributes, so backend copies of the packed activation do not need to
retain the producer's op marker. W4A4 uses row scales; W4A8 additionally exposes
the codebook, channel scales, and FP8 relative scales as tensor dependencies.
CPU, CUDA/HIP/MUSA, and Vulkan register kernels through the same extension API
as INT8. No ggml submodule changes are required.
ComfyUI W4A4 linear layers use `sd.linear_w4_convrot.v1`. W4A8 uses the same
`sd.linear_i8.v1` node as W8A8 with packed weights, a codebook, and FP8 relative
scales. The backend decodes that projection's weights into scheduler workspace
before running the shared INT8 GEMM with its channel scales. Both formats consume the explicit output of
`sd.quantize_i8_convrot.v1`. Logical output dimensions are stored in the linear
operator attributes so backend copies of the packed activation can be used
directly.

Services are discovered through `ggml_backend_reg_get_proc_address`:

Expand Down Expand Up @@ -286,7 +284,7 @@ backend paths have been removed. CPU, CUDA/HIP/MUSA, and Vulkan register kernels
and fusion rules through the extension interfaces.

For already quantized activations, `ggml_ext_mul_mat_i8_tensorwise` accepts ordinary
I8 weight and activation tensors. Its optional final `input_scale` parameter is a
I8 weight and activation tensors. Its optional `input_scale` parameter is a
separate F32 tensor with one value per activation row. Weight scales have one
value per output channel; weight scales and bias can be null. Existing calls
omit `input_scale` and retain their original argument order. It computes `float(int32_dot(W, X)) * X_scale * W_scale + bias`, in that
Expand Down
71 changes: 28 additions & 43 deletions docs/guides/int8_convrot.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,9 @@ The packed runtime activation tensor contains the I8 activation rows and their f

- CPU provides the portable regular Hadamard, activation quantization, INT8 matrix multiplication, and scale restoration implementations.
- Metal supports INT8 tensorwise and convrot on Apple silicon (Apple GPU family 7 or newer). It keeps weights in INT8 and rotates and quantizes activations on the GPU. On macOS/iOS 26 or newer, it probes Metal TensorOps `matmul2d` with INT8 inputs and INT32 cooperative results. It combines 1024-product partial sums using wrapping integer addition to preserve exact accumulation on older GPUs, then applies scales and bias in registers. Older systems or unavailable TensorOps pipelines use SIMD-group matrix multiplication: INT8 tiles are converted to FP16, and FP32 partial sums cover at most 256 products before being combined as integers, preserving the I32 accumulation contract. Convrot groups 1, 4, 16, 64, and 256 are supported. These kernels require the patched GGML Metal extension services and are enabled by `SD_METAL=ON`.
- NVIDIA CUDA devices with compute capability 7.5 or newer use the native accelerated path. For H256, CUDA fuses the rotation, row-wise maximum reduction, and activation quantization. Eligible shapes use the CUTLASS INT8 implementation when enabled. For linear layers, it restores scales and adds any aligned bias before writing the result; other supported shapes use cuBLAS for I8 x I8 to I32 GEMM and a CUDA kernel for scale restoration and bias addition.
- AMD HIP devices in the CDNA, RDNA3 (including RDNA3.5), and RDNA4 families use the same INT8/H256 kernels with hipBLAS for I8 x I8 to I32 GEMM. Other AMD architectures fall back to CPU for INT8 matrix multiplication.
- MUSA shares the CUDA-style H256 activation kernels. INT8 GEMM falls back to CPU because the MUSA backend does not advertise INT8 BLAS support.
- Vulkan provides H256 activation quantization and INT8 matrix multiplication when the build and device support accelerated packed INT8 dot products. Unsupported configurations and GPU backends without these kernels use the backend scheduler to fall back to CPU.
- CUDA uses CUTLASS for eligible shapes when enabled, and cuBLAS for other eligible shapes on Turing and newer. HIP uses hipBLAS or hipBLASLt on supported targets, including RDNA2, RDNA3, RDNA3.5, RDNA4 (`gfx120x`), and CDNA.
- CUDA, HIP, and MUSA share a tiled INT8 dot-product fallback. It handles devices without INT8 BLAS and projections whose output width is not divisible by four. It uses packed byte-dot instructions where available.
- Vulkan supports H64 and H256 activation quantization and packed-activation INT8 matrix multiplication with input widths divisible by 64. It requires integer dot product support and uses cooperative matrices when available. Unsupported configurations use the scheduler's CPU fallback.

`--lora-apply-mode auto` selects immediate merging for INT8 tensorwise models
on the compute backend without row splitting. Use `--lora-apply-mode at_runtime`
Expand All @@ -116,7 +115,7 @@ backend when it supports the operation, with ggml's usual CPU fallback. The
additional quantization step can change the output compared with runtime
application.

The shared CUDA/HIP/MUSA convrot activation paths support H64 and H256. Vulkan also supports H64 activation quantization; its INT8 matrix multiplication path currently requires H256.
The shared CUDA/HIP/MUSA convrot activation paths support H64 and H256.

## Packed INT4 convrot

Expand All @@ -130,49 +129,35 @@ converted to GGUF Q4 blocks at load time.
the format name does not select a native INT4 activation kernel.
- `asym_w4a8_int8`: 4-bit indices into `weight_codebook` (16 F32 values), F32
`weight_s_channel`, and F8_E4M3 `weight_s_rel` per 16 input features. The
metadata must specify `group_size: 16`. CPU evaluates the floating-point
codebook; GPU kernels requantize it to INT8 with `amax / 127`, introducing a
small additional rounding error.
weight group size must be 16 and defaults to 16 when omitted.

Both formats imply convrot rotation even without a `convrot` flag; missing
`convrot_groupsize` defaults to 256.

Both formats reuse the convrot activation cache when the input scale is `1` and
produce F32 outputs with optional bias. CPU provides a portable implementation.
CUDA/HIP/MUSA use shared packed-weight kernels without requiring INT8 BLAS.
With CUTLASS enabled, NVIDIA
SM80 and newer devices use mixed-input S8 x S4 GEMM for eligible W4A4 shapes,
reusing the INT8 scale epilogue without expanding the full weight tensor. W4A8
uses CUTLASS integer MMA per 16-value group with FP32 scale restoration.
Other CUDA shapes and builds retain the packed byte-dot path. Set
`GGML_CUDA_W4_FORCE_DP4A=1` to compare against that path. Supported AMD targets
use packed byte-dot instructions, with portable byte arithmetic for other targets.
Vulkan requires integer dot product support and at least 13312 bytes of shared
memory for W4A4 or 16452 bytes for W4A8. GPU W4 kernels require the logical input
width to be divisible by 64; H64 and H256 are supported. When supported by the
compiler and device, Vulkan uses NV cooperative matrix integer GEMM. W4A4
decodes packed weights directly into cooperative matrices for aligned input
and output widths. Complete activation tiles and the final partial tile use
separate shader specializations. Other W4A4 shapes use double-buffered weight
and activation tiles (20480 bytes of shared memory, or 30720 for larger tiles).
W4A8 stages both weights and activations in shared memory in K=64 tiles,
reusing them for each 16-value group's integer
MMA and FP32 scale restoration. FP8 scales use a shared lookup table, and
expanding projections visit activation tiles in groups of weight panels for
cache reuse. Adjacent groups share a K=32 activation fragment, with
complementary zero padding in the weights to preserve each group's scale.
This path uses 17476 bytes of shared memory, or 22596 for larger tiles.
Both paths use 256-thread workgroups and keep the model's
weights packed; neither expands a full layer in device memory. Other Vulkan
devices retain the packed dot-product path; set `GGML_VK_W4_FORCE_DP4A=1` to compare
against it. FP32 accumulation order can differ between these paths.
Other shapes use CPU fallback. HIP W4A8 selects wave64 WMMA by the active
compilation target's intrinsic support, preferring the GFX12 fragment layout
over the GFX11 layout.
There is no GPU architecture allowlist: newer targets supporting either
intrinsic automatically use its matching layout. Selection happens per device
image, including multi-architecture builds; targets supporting neither intrinsic
retain the integer-dot fallback. W4A4 retains integer dot products on HIP.
produce F32 outputs with optional bias.

W4A8 multiplies the codebook value by the group's relative scale, rounds to nearest even,
and clamps to `[-127, 127]`. The linear operation decodes weights into temporary workspace,
then runs the same INT8 GEMM as W8A8 with `weight_s_channel` as the per-output
scale. Eligible large CUDA projections decode slices and write GEMM results
directly into the corresponding output columns. CPU, CUDA/HIP/MUSA, Vulkan,
and Metal provide weight decoders. The checkpoint's packed weights stay in
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
their original layout.

If the decoded W4A8 weights exceed the Vulkan device's `maxStorageBufferRange`,
the linear operation decodes slices of output channels into shared workspace
and writes each GEMM result directly to the corresponding output columns. An
`8192 × 24576` projection needs 192 MiB after decoding and can run on a device
with a 128 MiB storage-buffer range. The packed weights, activations, scales,
and FP32 output must still fit their respective bindings. Projections that
exceed those limits fall back to CPU.

W4A4 uses packed-weight kernels. Eligible CUDA SM80+ shapes can use CUTLASS mixed
S8 x S4 GEMM. Vulkan uses cooperative matrices where supported and requires a
logical input width divisible by 64. Use `GGML_CUDA_W4_FORCE_DP4A=1` or
`GGML_VK_W4_FORCE_DP4A=1` to select packed byte dots for W4A4 on the corresponding
backend.

LoRA application remains at runtime, using the original unrotated activations
and logical weight dimensions. Packed weights and their codebook/scale tensors
Expand Down
32 changes: 29 additions & 3 deletions src/core/cpu/int8.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ namespace sd_cpu {
SDI8Operation op;
int64_t rows;
int8_t* quant;
int8_t* decoded;
float* scales;
float* output;
};
Expand All @@ -36,11 +37,30 @@ namespace sd_cpu {
visit([&](int64_t i, float value) { dst[i] = static_cast<int8_t>(std::max(-127L, std::min(127L, std::lrintf(value * inverse)))); });
}
}
static void decode_w4a8(ggml_tensor*, int ith, int nth, void* data) {
const auto& e = *static_cast<I8Execution*>(data);
const auto* packed = static_cast<const uint8_t*>(e.op.weight->data);
const auto* codebook = static_cast<const float*>(e.op.codebook->data);
const auto* scales = static_cast<const uint8_t*>(e.op.relative_scale->data);
auto* decoded = e.decoded;
const auto to_float = ggml_get_type_traits(GGML_TYPE_F8_E4M3)->to_float;
const int64_t groups = ggml_nelements(e.op.relative_scale);
for (int64_t g = ith; g < groups; g += nth) {
float relative;
to_float(scales + g, &relative, 1);
for (int i = 0; i < 16; ++i) {
const int code = (packed[g * 8 + i / 2] >> (4 * (i % 2))) & 15;
const float value = codebook[code] * relative;
decoded[g * 16 + i] = std::isnan(value) ? 0 : int8_t(std::clamp(std::nearbyint(value), -127.f, 127.f));
}
}
}

static void multiply(ggml_tensor*, int ith, int nth, void* data) {
auto& e = *static_cast<I8Execution*>(data);
const auto& op = e.op;
const int64_t k = op.weight->ne[0], n = op.weight->ne[1];
const auto* w = static_cast<const int8_t*>(op.weight->data);
const int64_t k = op.k(), n = op.weight->ne[1];
const auto* w = e.decoded ? e.decoded : static_cast<const int8_t*>(op.weight->data);
const auto* ws = op.weight_scale ? static_cast<const float*>(op.weight_scale->data) : nullptr;
const auto* bias = op.bias ? static_cast<const float*>(op.bias->data) : nullptr;
for (int64_t index = ith; index < e.rows * n; index += nth) {
Expand Down Expand Up @@ -79,7 +99,7 @@ namespace sd_cpu {
SDI8Operation op;
if (!sd_ggml_i8_describe(nodes[0], &op))
return GGML_STATUS_FAILED;
*bytes = quant_workspace(nodes[0], op) + ggml_nbytes(nodes[0]);
*bytes = quant_workspace(nodes[0], op) + ggml_nbytes(nodes[0]) + op.decoded_weight_bytes();
return GGML_STATUS_SUCCESS;
}
static ggml_status convrot_prepare(ggml_backend_t, ggml_tensor* const* nodes, int, void**, size_t* bytes, void*) {
Expand Down Expand Up @@ -111,6 +131,12 @@ namespace sd_cpu {
e.quant = static_cast<int8_t*>(e.op.input->data);
e.scales = e.op.packed ? reinterpret_cast<float*>(e.quant + e.op.input->ne[0] * ((e.rows + 3) / 4 * 4)) : static_cast<float*>(e.op.input_scale->data);
}
if (e.op.codebook) {
e.decoded = reinterpret_cast<int8_t*>(scratch + quant_size + ggml_nbytes(dst));
auto status = run(context->backend, dst, decode_w4a8, &e);
if (status != GGML_STATUS_SUCCESS)
return status;
}
bool alias = false;
for (auto* input : dst->src)
alias |= overlaps(dst, input);
Expand Down
45 changes: 13 additions & 32 deletions src/core/cpu/w4.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,42 +15,23 @@ namespace sd_cpu {
auto& e = *static_cast<W4Execution*>(data);
const auto& op = e.op;
const int64_t k = op.input->ne[0], n = op.weight->ne[1];
const auto* w = static_cast<const uint8_t*>(op.weight->data);
const auto* x = static_cast<const int8_t*>(op.input->data);
const auto* xs = reinterpret_cast<const float*>(x + k * ((e.rows + 3) / 4 * 4));
const auto* ws = static_cast<const float*>(op.weight_scale->data);
const auto* bias = op.bias ? static_cast<const float*>(op.bias->data) : nullptr;
const auto* sc = op.s_channel ? static_cast<const float*>(op.s_channel->data) : nullptr;
const auto* sr = op.s_rel ? static_cast<const uint8_t*>(op.s_rel->data) : nullptr;
const auto to_float = ggml_get_type_traits(GGML_TYPE_F8_E4M3)->to_float;
const auto* w = static_cast<const uint8_t*>(op.weight->data);
const auto* x = static_cast<const int8_t*>(op.input->data);
const auto* xs = reinterpret_cast<const float*>(x + k * ((e.rows + 3) / 4 * 4));
const auto* ws = static_cast<const float*>(op.weight_scale->data);
const auto* bias = op.bias ? static_cast<const float*>(op.bias->data) : nullptr;
for (int64_t index = ith; index < n * e.rows; index += nth) {
const int64_t row = index / n, col = index % n;
const auto* packed = w + col * (k / 2);
float value;
if (op.kind == SDW4Kind::W4A4) {
uint32_t sum = 0;
for (int64_t i = 0; i < k; ++i) {
const int nibble = (packed[i / 2] >> (4 * (i % 2))) & 15;
sum += uint32_t(((nibble ^ 8) - 8) * int32_t(x[row * k + i]));
}
int32_t signed_sum;
std::memcpy(&signed_sum, &sum, sizeof(sum));
value = float(signed_sum) * xs[row] * ws[col];
} else {
float sum = 0.f;
for (int64_t g = 0; g < k / 16; ++g) {
float relative;
to_float(sr + col * (k / 16) + g, &relative, 1);
const float scale = sc[col] * relative;
for (int j = 0; j < 16; ++j) {
const int64_t i = g * 16 + j;
const int code = (packed[i / 2] >> (4 * (i % 2))) & 15;
sum += (ws[code] * scale) * float(x[row * k + i]);
}
}
value = sum * xs[row];
uint32_t sum = 0;
for (int64_t i = 0; i < k; ++i) {
const int nibble = (packed[i / 2] >> (4 * (i % 2))) & 15;
sum += uint32_t(((nibble ^ 8) - 8) * int32_t(x[row * k + i]));
}
e.output[index] = value + (bias ? bias[col] : 0.f);
int32_t signed_sum;
std::memcpy(&signed_sum, &sum, sizeof(sum));
const float value = float(signed_sum) * xs[row] * ws[col];
e.output[index] = value + (bias ? bias[col] : 0.f);
}
}

Expand Down
2 changes: 0 additions & 2 deletions src/core/cuda/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,6 @@ if(SD_HIPBLAS)
set_source_files_properties(${SD_CUDA_SOURCES} PROPERTIES COMPILE_OPTIONS "-ffast-math")
# LoRA merging must detect NaNs and infinities before requantization.
set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/i8_lora_merge_hip.cu" PROPERTIES COMPILE_OPTIONS "-fno-fast-math")
# W4A8 WMMA uses the wave64 fragment layout on both GFX11 and GFX12.
set_property(SOURCE "${CMAKE_CURRENT_BINARY_DIR}/w4_hip.cu" APPEND PROPERTY COMPILE_OPTIONS "-mwavefrontsize64")
target_link_libraries(${SD_CUDA_TARGET} PRIVATE hip::host roc::hipblas)
target_link_libraries(${SD_LIB} PRIVATE hip::host roc::hipblas)
find_package(hipblaslt CONFIG QUIET)
Expand Down
4 changes: 2 additions & 2 deletions src/core/cuda/i8_gated_residual.cu
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ namespace sd_i8_gated {
const bool scaled = producer->op == GGML_OP_SCALE;
const auto* mat = scaled ? producer->src[0] : producer;
SDI8Operation op;
if (!sd_ggml_i8_describe(mat, &op) || op.input->type != GGML_TYPE_I8 || !op.weight_scale || op.bias)
if (!sd_ggml_i8_describe(mat, &op) || op.codebook || op.input->type != GGML_TYPE_I8 || !op.weight_scale || op.bias)
continue;
int scale_index = -1;
for (int j = i - 1; j >= 0 && j >= i - 64; --j) {
Expand Down Expand Up @@ -362,7 +362,7 @@ namespace sd_i8_gated {
for (int i = 0; i < std::min(available, 5); ++i)
nodes[i] = ggml_graph_node(const_cast<ggml_cgraph*>(graph), first + i);
SDI8Operation mat;
if (!sd_ggml_i8_describe(nodes[0], &mat) || mat.input->type != GGML_TYPE_I8 || !mat.weight_scale || mat.bias)
if (!sd_ggml_i8_describe(nodes[0], &mat) || mat.codebook || mat.input->type != GGML_TYPE_I8 || !mat.weight_scale || mat.bias)
return 0;
const int64_t rows = ggml_nrows(nodes[0]), n = nodes[0]->ne[0], k = mat.weight->ne[0];
if (rows < (small_rows_enabled(rows, n, k) ? 1 : 128) || rows > INT_MAX || n > INT_MAX || k > INT_MAX || n % 128 || k % 64 ||
Expand Down
Loading
Loading