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
8 changes: 8 additions & 0 deletions docs/development/ggml_extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,14 @@ CPU kernels and fusion rules live in `src/core/cpu/`, with registration collecte
in `cpu/registration.cpp`. CUDA-style and Vulkan implementations live in their
respective backend directories.

`sd.i8_lora_merge.v1` takes an INT8 weight, its F32 scale tensor, and an F32 LoRA
delta. It rotates the delta when the checkpoint uses convrot, adds it in the
stored weight's basis, and packs a status word, the new scales, and the INT8
weight into one tensor. Graph copy nodes use integer views to write both
ranges into the cached weight buffers and retain only the status word for
finalization. The views use I32 for aligned ranges and I8 for byte copies.
Layouts without native copy support write back during graph finalization.

`src/core/metal/int8.mm` registers Metal INT8 linear and ConvRot kernels. Their
Metal source is embedded at build time and compiled for the selected device
during registration. The public `ggml-ext-metal.h` services expose borrowed
Expand Down
5 changes: 3 additions & 2 deletions docs/dgl.md
Original file line number Diff line number Diff line change
Expand Up @@ -606,8 +606,9 @@ while they remain resident. Persistent contexts retain idle buffers subject
to RAM and VRAM pressure. Run-once contexts can release shared buffers after
their last use.
In both persistent and run-once contexts, `auto` selects `immediately` for
unquantized weights on the compute backend without row splitting. It selects
`at_runtime` for quantized, offloaded, or row-split weights.
unquantized and [INT8 tensorwise weights](guides/int8_convrot.md) on the compute
backend without row splitting. It selects `at_runtime` for other quantized
formats, offloaded weights, or row-split weights.

### Prompt encoding

Expand Down
13 changes: 12 additions & 1 deletion docs/guides/int8_convrot.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,18 @@ The packed runtime activation tensor contains the I8 activation rows and their f
- 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.

LoRA adapters are applied at runtime without modifying the INT8 weights. The INT8 convrot path computes the base linear output, while LoRA, LoHa, LoKr, and raw weight-difference adapters compute their output corrections from the original, unrotated activation and add them to the base output. `--lora-apply-mode auto` selects this path for models containing INT8 tensorwise weights. If `immediately` is requested, sd.cpp falls back to runtime application because merging an adapter would require dequantizing and rotating its weight update, then recalculating the per-row scales and requantizing the result.
`--lora-apply-mode auto` selects immediate merging for INT8 tensorwise models
on the compute backend without row splitting. Use `--lora-apply-mode at_runtime`
to compute each adapter's correction from the original activation and add it to
the INT8 linear output.

Immediate mode merges an adapter into INT8 tensorwise weights on first use.
For convrot weights, sd.cpp rotates the adapter update before adding it to the
dequantized weights. It then recalculates the weight
scales and requantizes the result to INT8. The merge runs on the selected
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.

Expand Down
9 changes: 6 additions & 3 deletions docs/models/lora.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,15 @@ The example loads `../models/loras/marblesh.safetensors` or

There are two ways to apply LoRA: **immediately** and **at_runtime**. You can specify it using the `--lora-apply-mode` parameter.

The default **auto** mode chooses **immediately** for unquantized weights on
the compute backend without row splitting. It chooses **at_runtime** for
quantized, offloaded, or row-split weights. For scripts, see
The default **auto** mode chooses **immediately** for unquantized and INT8
tensorwise weights on the compute backend without row splitting. It chooses
**at_runtime** for other quantized formats, offloaded weights, or row-split
weights. For scripts, see
[DGL LoRA combinations](../dgl.md#lora-combinations).

The **immediately** mode may have precision and compatibility issues with quantized parameters, but it usually offers faster inference speed and, in some cases, lower memory usage.
For INT8 tensorwise and convrot weights, **immediately** merges and requantizes
the affected weights. See the [INT8 convrot guide](../guides/int8_convrot.md).
In contrast, the **at_runtime** mode provides better compatibility and higher precision, but inference may be slower and memory usage may be higher in some cases.

## Notes and limitations
Expand Down
2 changes: 1 addition & 1 deletion src/api/generation_image.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ namespace sd::api {
request.fields["negative_prompt_options"] += ", media = [" + pixels + "]";
}
if (encode && !sd_version_is_unet_edit(version)) {
const bool increase = sd_version_is_flux2(version) || sd_version_is_flux3(version) ||
const bool increase = sd_version_is_flux2(version) || sd_version_is_flux3(version) ||
sd_version_is_qwen_image(version) || sd_version_is_minimax_h3_image(version) ||
version == VERSION_FIBO2 || sd_version_is_krea2(version) ||
version == VERSION_ANIMA || sd_version_is_mage_flow(version) || moss_edit;
Expand Down
117 changes: 101 additions & 16 deletions src/core/cpu/int8.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,10 @@
#include <algorithm>
#include <cmath>
#include <cstring>
#include <limits>

namespace sd_cpu {

static void transform(float* values, int group) {
const float scale = 1.f / std::sqrt(float(group));
for (int i = 0; i < group; ++i)
values[i] *= scale;
for (int stride = 1; stride < group; stride *= 4)
for (int base = 0; base < group; base += 4 * stride)
for (int j = 0; j < stride; ++j) {
const int i = base + j;
const float a = values[i], b = values[i + stride], c = values[i + 2 * stride], d = values[i + 3 * stride];
values[i] = a + b + c - d;
values[i + stride] = a + b - c + d;
values[i + 2 * stride] = a - b + c + d;
values[i + 3 * stride] = -a + b + c + d;
}
}
struct I8Execution {
SDI8Operation op;
int64_t rows;
Expand All @@ -40,7 +26,7 @@ namespace sd_cpu {
int8_t* dst = e.quant + row * k;
float amax = 0.f, values[256];
auto visit = [&](auto fn) { if (!group) { for (int64_t i = 0; i < k; ++i) fn(i, src[i]); }
else for (int64_t base = 0; base < k; base += group) { std::memcpy(values, src + base, group * sizeof(float)); transform(values, group); for (int j = 0; j < group; ++j) fn(base + j, values[j]); } };
else for (int64_t base = 0; base < k; base += group) { std::memcpy(values, src + base, group * sizeof(float)); sd_ggml_rotate_convrot(values, group, group); for (int j = 0; j < group; ++j) fn(base + j, values[j]); } };
visit([&](int64_t, float value) { amax = std::max(amax, std::fabs(value)); });
const float scale = amax / 127.f, inverse = scale == 0.f ? 0.f : 1.f / scale;
e.scales[row] = scale;
Expand Down Expand Up @@ -156,6 +142,96 @@ namespace sd_cpu {
}
return status;
}
struct LoRAMergeExecution {
SDI8LoRAMerge op;
float* merged;
SDI8LoRARowStats* stats;
float* scales;
int8_t* output;
};
static void merge_lora_rows(ggml_tensor*, int ith, int nth, void* data) {
auto& e = *static_cast<LoRAMergeExecution*>(data);
const int64_t k = e.op.weight->ne[0];
const auto* base = static_cast<const int8_t*>(e.op.weight->data);
const auto* old = static_cast<const float*>(e.op.scale->data);
const auto* diff = static_cast<const float*>(e.op.diff->data);
for (int64_t row = ith; row < e.op.weight->ne[1]; row += nth) {
const int64_t offset = row * k;
float* values = e.merged + offset;
std::memcpy(values, diff + offset, k * sizeof(float));
const bool changed = std::any_of(values, values + k, [](float value) { return value != 0.f; });
sd_ggml_rotate_convrot(values, k, e.op.group);
const float scale = old[e.op.scalar_scale() ? 0 : row];
float maximum = 0.f;
for (int64_t i = 0; i < k; ++i) {
const float value = values[i] + base[offset + i] * scale;
values[i] = value;
maximum = std::max(maximum, std::isfinite(value) ? std::fabs(value) : std::numeric_limits<float>::infinity());
}
e.stats[row] = {maximum, changed};
}
}
static void quantize_lora_rows(ggml_tensor*, int ith, int nth, void* data) {
auto& e = *static_cast<LoRAMergeExecution*>(data);
const int64_t k = e.op.weight->ne[0];
const auto* base = static_cast<const int8_t*>(e.op.weight->data);
const auto* old = static_cast<const float*>(e.op.scale->data);
for (int64_t row = ith; row < e.op.weight->ne[1]; row += nth) {
const int64_t offset = row * k;
if (!e.op.scalar_scale() && !e.stats[row].changed) {
e.scales[row] = old[row];
std::memcpy(e.output + offset, base + offset, k);
continue;
}
const float scale = e.op.scalar_scale() ? e.scales[0] : e.stats[row].maximum / 127.f;
if (!e.op.scalar_scale())
e.scales[row] = scale;
for (int64_t i = offset; i < offset + k; ++i)
e.output[i] = scale == 0.f ? 0 : static_cast<int8_t>(std::clamp(std::nearbyint(e.merged[i] / scale), -127.f, 127.f));
}
}
static ggml_status lora_prepare(ggml_backend_t, ggml_tensor* const* nodes, int, void**, size_t* bytes, void*) {
SDI8LoRAMerge op;
if (!sd_ggml_i8_lora_merge_describe(nodes[0], &op))
return GGML_STATUS_FAILED;
*bytes = op.workspace_size();
return GGML_STATUS_SUCCESS;
}
static ggml_status lora_execute(const ggml_ext_execution_context* context, ggml_tensor* const* nodes, int, void*, void*) {
auto* dst = nodes[0];
SDI8LoRAMerge op;
const auto run = parallel(context->backend);
if (!run || !sd_ggml_i8_lora_merge_describe(dst, &op))
return GGML_STATUS_FAILED;
auto* scratch = static_cast<char*>(ggml_backend_buffer_get_base(context->workspace));
auto* packed = static_cast<char*>(dst->data);
auto* flags = reinterpret_cast<uint32_t*>(packed);
LoRAMergeExecution e{
op, reinterpret_cast<float*>(scratch), reinterpret_cast<SDI8LoRARowStats*>(scratch + ggml_nbytes(op.diff)),
reinterpret_cast<float*>(packed + op.scale_offset()), reinterpret_cast<int8_t*>(packed + op.weight_offset())};
auto status = run(context->backend, dst, merge_lora_rows, &e);
if (status != GGML_STATUS_SUCCESS)
return status;
*flags = 0;
float maximum = 0.f;
for (int64_t row = 0; row < op.weight->ne[1]; ++row) {
const auto& stats = e.stats[row];
if (stats.changed)
*flags |= SD_I8_LORA_CHANGED;
if (stats.changed || op.scalar_scale())
maximum = std::max(maximum, stats.maximum);
}
if (*flags && !std::isfinite(maximum))
*flags |= SD_I8_LORA_NONFINITE;
if (*flags != SD_I8_LORA_CHANGED) {
std::memcpy(e.output, op.weight->data, ggml_nbytes(op.weight));
std::memcpy(e.scales, op.scale->data, ggml_nbytes(op.scale));
return GGML_STATUS_SUCCESS;
}
if (op.scalar_scale())
e.scales[0] = maximum / 127.f;
return run(context->backend, dst, quantize_lora_rows, &e);
}
void register_i8(ggml_backend_dev_t device) {
ggml_ext_kernel_desc d = {};
d.abi_version = GGML_EXT_ABI_VERSION;
Expand All @@ -175,6 +251,15 @@ namespace sd_cpu {
d.prepare = convrot_prepare;
d.execute = convrot_execute;
GGML_ASSERT(ggml_ext_register_kernel(device, &d));
d.name = "sd.i8_lora_merge.cpu.v1";
d.custom_op = sd_ggml_i8_lora_merge_op();
d.supports = [](ggml_backend_dev_t, const ggml_tensor* node, void*) {
SDI8LoRAMerge op;
return sd_ggml_i8_lora_merge_describe(node, &op);
};
d.prepare = lora_prepare;
d.execute = lora_execute;
GGML_ASSERT(ggml_ext_register_kernel(device, &d));
}

}
Expand Down
6 changes: 5 additions & 1 deletion src/core/cuda/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ cmake_policy(SET CMP0079 NEW)

function(sd_cuda_sources VENDOR LANGUAGE)
set(SOURCES)
foreach(OP rope int8 w4 convrot affine modulate bf16 rms_affine registration)
foreach(OP rope int8 i8_lora_merge w4 convrot affine modulate bf16 rms_affine registration)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
set(SOURCE "${CMAKE_CURRENT_BINARY_DIR}/${OP}_${VENDOR}.cu")
string(TOUPPER "${VENDOR}" UPPER_VENDOR)
file(GENERATE OUTPUT "${SOURCE}" CONTENT "#define SD_CUDA_VENDOR_${UPPER_VENDOR} 1\n#include \"core/cuda/${OP}.cu\"\n")
Expand Down Expand Up @@ -58,6 +58,8 @@ if(SD_HIPBLAS)
endif()
target_sources(${SD_CUDA_TARGET} PRIVATE hip_attention.cu)
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)
Expand Down Expand Up @@ -94,6 +96,8 @@ if(SD_MUSA)
list(APPEND FLAGS "--cuda-gpu-arch=mp_${ARCH}")
endforeach()
set_source_files_properties(${SD_CUDA_SOURCES} PROPERTIES COMPILE_OPTIONS "${FLAGS}")
list(REMOVE_ITEM FLAGS -ffast-math)
set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/i8_lora_merge_musa.cu" PROPERTIES COMPILE_OPTIONS "${FLAGS};-fno-fast-math")
if(GGML_STATIC)
target_link_libraries(${SD_CUDA_TARGET} PRIVATE MUSA::musart_static MUSA::mublas_static)
target_link_libraries(${SD_LIB} PRIVATE MUSA::musart_static MUSA::mublas_static)
Expand Down
Loading
Loading