diff --git a/docs/development/ggml_extensions.md b/docs/development/ggml_extensions.md index c643237f56..fd5790e296 100644 --- a/docs/development/ggml_extensions.md +++ b/docs/development/ggml_extensions.md @@ -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 diff --git a/docs/dgl.md b/docs/dgl.md index 163824abc9..d7cb7f9f0d 100644 --- a/docs/dgl.md +++ b/docs/dgl.md @@ -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 diff --git a/docs/guides/int8_convrot.md b/docs/guides/int8_convrot.md index 54f36b6227..e7ad269a1c 100644 --- a/docs/guides/int8_convrot.md +++ b/docs/guides/int8_convrot.md @@ -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. diff --git a/docs/models/lora.md b/docs/models/lora.md index 6be0ba71b2..e1e75c3df6 100644 --- a/docs/models/lora.md +++ b/docs/models/lora.md @@ -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 diff --git a/src/api/generation_image.cpp b/src/api/generation_image.cpp index a5168ba8b4..f343c47ff1 100644 --- a/src/api/generation_image.cpp +++ b/src/api/generation_image.cpp @@ -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; diff --git a/src/core/cpu/int8.cpp b/src/core/cpu/int8.cpp index ec4be835bd..0f3612dbc8 100644 --- a/src/core/cpu/int8.cpp +++ b/src/core/cpu/int8.cpp @@ -5,24 +5,10 @@ #include #include #include +#include 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; @@ -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; @@ -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(data); + const int64_t k = e.op.weight->ne[0]; + const auto* base = static_cast(e.op.weight->data); + const auto* old = static_cast(e.op.scale->data); + const auto* diff = static_cast(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::infinity()); + } + e.stats[row] = {maximum, changed}; + } + } + static void quantize_lora_rows(ggml_tensor*, int ith, int nth, void* data) { + auto& e = *static_cast(data); + const int64_t k = e.op.weight->ne[0]; + const auto* base = static_cast(e.op.weight->data); + const auto* old = static_cast(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(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(ggml_backend_buffer_get_base(context->workspace)); + auto* packed = static_cast(dst->data); + auto* flags = reinterpret_cast(packed); + LoRAMergeExecution e{ + op, reinterpret_cast(scratch), reinterpret_cast(scratch + ggml_nbytes(op.diff)), + reinterpret_cast(packed + op.scale_offset()), reinterpret_cast(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; @@ -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)); } } diff --git a/src/core/cuda/CMakeLists.txt b/src/core/cuda/CMakeLists.txt index a1290e7372..4fc286f2b6 100644 --- a/src/core/cuda/CMakeLists.txt +++ b/src/core/cuda/CMakeLists.txt @@ -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) 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") @@ -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) @@ -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) diff --git a/src/core/cuda/i8_lora_merge.cu b/src/core/cuda/i8_lora_merge.cu new file mode 100644 index 0000000000..780554384b --- /dev/null +++ b/src/core/cuda/i8_lora_merge.cu @@ -0,0 +1,150 @@ +#include +#include + +#include "convrot_kernel.h" +#include "core/ggml_extensions.h" + +namespace SD_CUDA_NAMESPACE { + static constexpr int lora_threads = 256; + + static __global__ void combine_lora_weights(const int8_t* weight, const float* scale, const float* diff, float* merged, int64_t k, int64_t count, int group, bool scalar) { + __shared__ float values[lora_threads]; + const int tid = threadIdx.x; + const float normalization = group > 1 ? rsqrtf(float(group)) : 1.f; + for (int64_t base = int64_t(blockIdx.x) * blockDim.x; base < count; base += int64_t(gridDim.x) * blockDim.x) { + const int64_t i = base + tid; + float value = i < count ? diff[i] : 0.f; + if (group > 1) { + values[tid] = value * normalization; + __syncthreads(); + for (int stride = 1; stride < group; stride *= 4) { + const int j = tid / (4 * stride) * (4 * stride) + tid % stride; + value = sd_convrot::convrot_h4_cuda(values[j], values[j + stride], values[j + 2 * stride], values[j + 3 * stride], (tid / stride) % 4); + __syncthreads(); + values[tid] = value; + __syncthreads(); + } + } + if (i < count) + merged[i] = __fadd_rn(value, __fmul_rn(float(weight[i]), scale[scalar ? 0 : i / k])); + } + } + + static __device__ SDI8LoRARowStats reduce_lora_stats(float maximum, uint32_t flags) { + __shared__ SDI8LoRARowStats shared[lora_threads]; + const int tid = threadIdx.x; + shared[tid] = {maximum, flags}; + __syncthreads(); + for (int stride = lora_threads / 2; stride > 0; stride /= 2) { + if (tid < stride) { + shared[tid].maximum = fmaxf(shared[tid].maximum, shared[tid + stride].maximum); + shared[tid].changed |= shared[tid + stride].changed; + } + __syncthreads(); + } + const auto result = shared[0]; + __syncthreads(); + return result; + } + + static __global__ void lora_row_stats(const float* merged, const float* diff, SDI8LoRARowStats* stats, int64_t k, int64_t rows) { + for (int64_t row = blockIdx.x; row < rows; row += gridDim.x) { + float maximum = 0.f; + uint32_t changed = 0; + for (int64_t col = threadIdx.x; col < k; col += blockDim.x) { + const int64_t i = row * k + col; + maximum = fmaxf(maximum, isfinite(merged[i]) ? fabsf(merged[i]) : INFINITY); + changed |= diff[i] != 0.f; + } + const auto result = reduce_lora_stats(maximum, changed); + if (threadIdx.x == 0) + stats[row] = result; + } + } + + static __global__ void lora_merge_summary(const SDI8LoRARowStats* stats, uint32_t* flags, float* scales, int64_t rows, bool scalar) { + float maximum = 0.f; + uint32_t changed = 0; + for (int64_t row = threadIdx.x; row < rows; row += blockDim.x) { + const auto info = stats[row]; + if (scalar || info.changed) + maximum = fmaxf(maximum, info.maximum); + changed |= info.changed; + } + const auto result = reduce_lora_stats(maximum, changed); + if (threadIdx.x == 0) { + *flags = !result.changed ? 0 : SD_I8_LORA_CHANGED | (isfinite(result.maximum) ? 0 : SD_I8_LORA_NONFINITE); + if (scalar) + scales[0] = result.maximum / 127.f; + } + } + + static __global__ void quantize_lora_weights(const int8_t* weight, const float* old_scales, const float* merged, const SDI8LoRARowStats* stats, const uint32_t* flags, float* scales, int8_t* output, int64_t k, int64_t rows, bool scalar) { + const bool apply = *flags == SD_I8_LORA_CHANGED; + for (int64_t row = blockIdx.x; row < rows; row += gridDim.x) { + const bool changed = apply && (scalar || stats[row].changed); + const float scale = changed ? (scalar ? scales[0] : stats[row].maximum / 127.f) : old_scales[scalar ? 0 : row]; + if (threadIdx.x == 0 && (!scalar || (!apply && row == 0))) + scales[scalar ? 0 : row] = scale; + for (int64_t col = threadIdx.x; col < k; col += blockDim.x) { + const int64_t i = row * k + col; + if (changed) { + const int value = scale == 0.f ? 0 : __float2int_rn(merged[i] / scale); + output[i] = static_cast(max(-127, min(127, value))); + } else { + output[i] = weight[i]; + } + } + } + } + + void register_i8_lora_merge(ggml_backend_dev_t device) { + ggml_ext_kernel_desc desc = {}; + desc.abi_version = GGML_EXT_ABI_VERSION; + desc.name = "sd.i8_lora_merge." SD_CUDA_NAME ".v1"; + desc.op = GGML_OP_CUSTOM; + desc.custom_op = sd_ggml_i8_lora_merge_op(); + desc.priority = 100; + desc.supports = [](ggml_backend_dev_t, const ggml_tensor* node, void*) { + SDI8LoRAMerge op; + return sd_ggml_i8_lora_merge_describe(node, &op); + }; + desc.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; + }; + desc.execute = [](const ggml_ext_execution_context* e, ggml_tensor* const* nodes, int, void*, void*) { + SDI8LoRAMerge op; + ggml_ext_gpu_context gpu; + if (!cuda_context(e->backend, &gpu) || !sd_ggml_i8_lora_merge_describe(nodes[0], &op)) + return GGML_STATUS_FAILED; + auto stream = static_cast(gpu.stream); + auto* scratch = static_cast(ggml_backend_buffer_get_base(e->workspace)); + auto* packed = static_cast(nodes[0]->data); + auto* merged = reinterpret_cast(scratch); + auto* stats = reinterpret_cast(scratch + ggml_nbytes(op.diff)); + auto* flags = reinterpret_cast(packed); + auto* scales = reinterpret_cast(packed + op.scale_offset()); + auto* output = reinterpret_cast(packed + op.weight_offset()); + const auto* base = static_cast(op.weight->data); + const auto* old = static_cast(op.scale->data); + const auto* diff = static_cast(op.diff->data); + const auto k = op.weight->ne[0]; + const auto rows = op.weight->ne[1]; + const auto count = ggml_nelements(op.weight); + const auto scalar = op.scalar_scale(); + const unsigned row_blocks = unsigned(std::min(rows, 65535)); + const unsigned blocks = unsigned(std::min((count + lora_threads - 1) / lora_threads, 65535)); + combine_lora_weights<<>>(base, old, diff, merged, k, count, op.group, scalar); + lora_row_stats<<>>(merged, diff, stats, k, rows); + lora_merge_summary<<<1, lora_threads, 0, stream>>>(stats, flags, scales, rows, scalar); + quantize_lora_weights<<>>(base, old, merged, stats, flags, scales, output, k, rows, scalar); + return cuda_last_error() == cuda_success ? GGML_STATUS_SUCCESS : GGML_STATUS_FAILED; + }; + desc.destroy = [](void*, void*) {}; + GGML_ASSERT(ggml_ext_register_kernel_ex(device, &desc, GGML_EXT_KERNEL_CAPTURE_SAFE | GGML_EXT_KERNEL_REPLAY_REUSABLE)); + } +} diff --git a/src/core/cuda/registration.cu b/src/core/cuda/registration.cu index 2755264ea6..134424f7b8 100644 --- a/src/core/cuda/registration.cu +++ b/src/core/cuda/registration.cu @@ -10,6 +10,7 @@ void sd_ggml_register_cuda_window_attention(ggml_backend_dev_t device); namespace SD_CUDA_NAMESPACE { void register_rope(ggml_backend_dev_t device); void register_i8(ggml_backend_dev_t device); + void register_i8_lora_merge(ggml_backend_dev_t device); void register_w4(ggml_backend_dev_t device); void register_convrot(ggml_backend_dev_t device); void register_affine(ggml_backend_dev_t device); @@ -30,6 +31,7 @@ namespace SD_CUDA_NAMESPACE { register_affine(device); register_modulate(device); register_i8(device); + register_i8_lora_merge(device); register_w4(device); register_convrot(device); register_rope(device); diff --git a/src/core/ggml_extensions.cpp b/src/core/ggml_extensions.cpp index 1e20250634..56a72dceb4 100644 --- a/src/core/ggml_extensions.cpp +++ b/src/core/ggml_extensions.cpp @@ -1,11 +1,32 @@ #include "core/ggml_extensions.h" +#include + +void sd_ggml_rotate_convrot(float* values, int64_t width, int group) { + if (group <= 1) + return; + const float scale = 1.f / std::sqrt(static_cast(group)); + for (int64_t i = 0; i < width; ++i) + values[i] *= scale; + for (int stride = 1; stride < group; stride *= 4) { + for (int64_t base = 0; base < width; base += 4 * stride) { + for (int j = 0; j < stride; ++j) { + const int64_t 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; + } + } + } +} + #ifndef SD_USE_UPSTREAM_GGML #include "core/cpu/registration.h" #include "ggml-ext.h" #include -#include #include #include #include @@ -270,6 +291,54 @@ bool sd_ggml_convrot_describe(const ggml_tensor* node, int* group) { return convrot_infer(node->src, 1, group, &output) && output.type == node->type && !std::memcmp(output.ne, node->ne, sizeof(output.ne)); } +static bool i8_lora_merge_infer(ggml_tensor* const* inputs, int count, const void* attributes, ggml_ext_tensor_desc* output) { + if (count != 3) + return false; + int32_t group; + std::memcpy(&group, attributes, sizeof(group)); + const auto* weight = inputs[0]; + const auto* scale = inputs[1]; + const auto* diff = inputs[2]; + const int64_t k = weight->ne[0], rows = weight->ne[1]; + if (weight->type != GGML_TYPE_I8 || weight->ne[2] != 1 || weight->ne[3] != 1 || + k <= 0 || rows <= 0 || k > (i8_size_limit / rows - int64_t(sizeof(SDI8LoRARowStats))) / int64_t(sizeof(float)) || + diff->type != GGML_TYPE_F32 || !ggml_are_same_shape(weight, diff) || + scale->type != GGML_TYPE_F32 || (ggml_nelements(scale) != 1 && ggml_nelements(scale) != rows) || + !ggml_is_contiguous(weight) || !ggml_is_contiguous(diff) || !ggml_is_contiguous(scale) || + (group != 0 && (!sd_ggml_valid_convrot_group(group) || k % group != 0))) + return false; + + const SDI8LoRAMerge op = {weight, scale, diff, group}; + const size_t bytes = op.weight_offset() + ggml_nbytes(weight); + output->type = GGML_TYPE_I8; + output->ne[0] = GGML_PAD(bytes, sizeof(uint32_t)); + output->ne[1] = output->ne[2] = output->ne[3] = 1; + return true; +} + +ggml_ext_op_t sd_ggml_i8_lora_merge_op() { + static const auto op = [] { + const ggml_ext_op_desc desc = {GGML_EXT_ABI_VERSION, "sd.i8_lora_merge.v1", sizeof(int32_t), i8_lora_merge_infer}; + auto result = ggml_ext_register_op(&desc); + GGML_ASSERT(result); + return result; + }(); + return op; +} + +bool sd_ggml_i8_lora_merge_describe(const ggml_tensor* node, SDI8LoRAMerge* op) { + if (!node || ggml_ext_op_get(node) != sd_ggml_i8_lora_merge_op()) + return false; + const void* attributes = ggml_ext_op_attributes(node); + ggml_ext_tensor_desc output; + if (!i8_lora_merge_infer(node->src, 3, attributes, &output) || output.type != node->type || + std::memcmp(output.ne, node->ne, sizeof(output.ne)) != 0 || !ggml_is_contiguous(node)) + return false; + *op = {node->src[0], node->src[1], node->src[2], 0}; + std::memcpy(&op->group, attributes, sizeof(op->group)); + return true; +} + static bool w4_infer(ggml_tensor* const* inputs, int count, const void* attributes, ggml_ext_tensor_desc* out) { if (!attributes || count < 3) return false; diff --git a/src/core/ggml_extensions.h b/src/core/ggml_extensions.h index 3145c6fbb4..0b32dc5064 100644 --- a/src/core/ggml_extensions.h +++ b/src/core/ggml_extensions.h @@ -4,6 +4,7 @@ #include "ggml-backend.h" void sd_ggml_register_extensions(ggml_backend_t backend); +void sd_ggml_rotate_convrot(float* values, int64_t width, int group); #ifndef SD_USE_UPSTREAM_GGML #include "ggml-ext.h" @@ -48,6 +49,31 @@ bool sd_ggml_i8_describe(const ggml_tensor* node, SDI8Operation* operation); bool sd_ggml_convrot_describe(const ggml_tensor* node, int* group_size); +enum SDI8LoRAMergeFlags : uint32_t { + SD_I8_LORA_CHANGED = 1, + SD_I8_LORA_NONFINITE = 2, +}; + +struct SDI8LoRARowStats { + float maximum; + uint32_t changed; +}; + +struct SDI8LoRAMerge { + const ggml_tensor* weight; + const ggml_tensor* scale; + const ggml_tensor* diff; + int32_t group; + + bool scalar_scale() const { return ggml_nelements(scale) == 1; } + size_t scale_offset() const { return sizeof(uint32_t); } + size_t weight_offset() const { return scale_offset() + ggml_nbytes(scale); } + size_t workspace_size() const { return ggml_nbytes(diff) + ggml_nrows(weight) * sizeof(SDI8LoRARowStats); } +}; + +ggml_ext_op_t sd_ggml_i8_lora_merge_op(); +bool sd_ggml_i8_lora_merge_describe(const ggml_tensor* node, SDI8LoRAMerge* op); + enum class SDW4Kind : int32_t { W4A4 = 1, W4A8 = 2 }; diff --git a/src/core/metal/int8.metal b/src/core/metal/int8.metal index 41f4a32b2b..a2424fe3f7 100644 --- a/src/core/metal/int8.metal +++ b/src/core/metal/int8.metal @@ -72,6 +72,98 @@ kernel void sd_i8_quantize(device const float* input [[buffer(0)]], ((device float*)(output + p.scale_offset))[row] = scale; } +struct LoRAMergeParams { + uint k, rows, scalar; +}; + +struct LoRARowStats { + float maximum; + uint changed; +}; + +static void sd_i8_lora_reduce(threadgroup LoRARowStats* stats, uint tid, float maximum, uint changed) { + stats[tid].maximum = maximum; + stats[tid].changed = changed; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint stride = 128; stride > 0; stride /= 2) { + if (tid < stride) { + stats[tid].maximum = max(stats[tid].maximum, stats[tid + stride].maximum); + stats[tid].changed |= stats[tid + stride].changed; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} + +kernel void sd_i8_lora_stats(device const char* weight [[buffer(0)]], + device const float* scales [[buffer(1)]], + device const float* diff [[buffer(2)]], + device const float* rotated [[buffer(3)]], + device float* merged [[buffer(4)]], + device LoRARowStats* stats [[buffer(5)]], + constant LoRAMergeParams& p [[buffer(6)]], + uint row [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + threadgroup LoRARowStats reduction[256]; + const float scale = scales[p.scalar ? 0 : row]; + const ulong base = ulong(row) * p.k; + float maximum = 0.f; + uint changed = 0; + for (uint col = tid; col < p.k; col += 256) { + const ulong i = base + col; + const float value = rotated[i] + float(weight[i]) * scale; + merged[i] = value; + maximum = max(maximum, isnan(value) ? as_type(0x7f800000u) : abs(value)); + changed |= uint(diff[i] != 0.f); + } + sd_i8_lora_reduce(reduction, tid, maximum, changed); + if (tid == 0) { + stats[row].maximum = reduction[0].maximum; + stats[row].changed = reduction[0].changed; + } +} + +kernel void sd_i8_lora_summary(device const LoRARowStats* stats [[buffer(0)]], + device uint* packed [[buffer(1)]], + constant LoRAMergeParams& p [[buffer(2)]], + uint tid [[thread_index_in_threadgroup]]) { + threadgroup LoRARowStats reduction[256]; + float maximum = 0.f; + uint changed = 0; + for (uint row = tid; row < p.rows; row += 256) { + if (p.scalar || stats[row].changed) + maximum = max(maximum, stats[row].maximum); + changed |= stats[row].changed; + } + sd_i8_lora_reduce(reduction, tid, maximum, changed); + if (tid == 0) { + packed[0] = reduction[0].changed ? 1u | (isinf(reduction[0].maximum) ? 2u : 0u) : 0u; + if (p.scalar) + packed[1] = as_type(reduction[0].maximum / 127.f); + } +} + +kernel void sd_i8_lora_quantize(device const char* weight [[buffer(0)]], + device const float* old_scales [[buffer(1)]], + device const float* merged [[buffer(2)]], + device const LoRARowStats* stats [[buffer(3)]], + device uint* packed [[buffer(4)]], + constant LoRAMergeParams& p [[buffer(5)]], + uint row [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + const bool apply = packed[0] == 1; + auto scales = (device float*)(packed + 1); + auto output = (device char*)(packed + 1 + (p.scalar ? 1 : p.rows)); + const bool changed = apply && (p.scalar || stats[row].changed); + const float scale = changed ? (p.scalar ? scales[0] : stats[row].maximum / 127.f) : old_scales[p.scalar ? 0 : row]; + if (tid == 0 && (!p.scalar || (!apply && row == 0))) + scales[p.scalar ? 0 : row] = scale; + const ulong base = ulong(row) * p.k; + for (uint col = tid; col < p.k; col += 256) { + const ulong i = base + col; + output[i] = changed ? (scale == 0.f ? 0 : char(clamp(rint(merged[i] / scale), -127.f, 127.f))) : weight[i]; + } +} + struct MatParams { uint k; uint n; diff --git a/src/core/metal/int8.mm b/src/core/metal/int8.mm index 1fb2d568e4..f5c0dad4b0 100644 --- a/src/core/metal/int8.mm +++ b/src/core/metal/int8.mm @@ -6,6 +6,7 @@ #import #include +#include #include #include @@ -16,6 +17,9 @@ id quantize = nil; id multiply = nil; id multiply_mpp = nil; + id lora_stats = nil; + id lora_summary = nil; + id lora_quant = nil; ggml_ext_metal_buffer_fn buffer = nullptr; ggml_ext_metal_submit_fn submit = nullptr; @@ -24,6 +28,9 @@ [quantize release]; [multiply release]; [multiply_mpp release]; + [lora_stats release]; + [lora_summary release]; + [lora_quant release]; } }; @@ -229,6 +236,62 @@ static ggml_status execute(const ggml_ext_execution_context* context, ggml_tenso return e.kernels->submit(context->backend, encode, &e); } + struct LoRAMergeParams { + uint32_t k, rows, scalar; + }; + static bool lora_supports(ggml_backend_dev_t, const ggml_tensor* dst, void*) { + SDI8LoRAMerge op; + return sd_ggml_i8_lora_merge_describe(dst, &op) && dimensions(op.weight) && ggml_nelements(op.weight) <= UINT32_MAX; + } + 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 = aligned(ggml_nbytes(op.diff)) + ggml_nrows(op.weight) * sizeof(SDI8LoRARowStats); + return GGML_STATUS_SUCCESS; + } + static ggml_status lora_encode(void* command_buffer, void* user_data) { + auto& e = *static_cast(user_data); + SDI8LoRAMerge op; + if (!sd_ggml_i8_lora_merge_describe(e.node, &op)) + return GGML_STATUS_FAILED; + auto* kernels = e.kernels; + const LoRAMergeParams p = {uint32_t(op.weight->ne[0]), uint32_t(op.weight->ne[1]), op.scalar_scale()}; + ggml_ext_metal_buffer weight, scale, diff, packed, merged, stats; + const size_t diff_bytes = ggml_nbytes(op.diff); + if (!bind_tensor(kernels, op.weight, weight) || !bind_tensor(kernels, op.scale, scale) || + !bind_tensor(kernels, op.diff, diff) || !bind_tensor(kernels, e.node, packed) || + !kernels->buffer(e.context->workspace, 0, diff_bytes, &merged) || + !kernels->buffer(e.context->workspace, aligned(diff_bytes), p.rows * sizeof(SDI8LoRARowStats), &stats)) + return GGML_STATUS_FAILED; + id command = (id)command_buffer; + auto dispatch = [&](id pipeline, std::initializer_list buffers, + const void* params, size_t size, size_t blocks, size_t threads) { + id encoder = [command computeCommandEncoder]; + [encoder setComputePipelineState:pipeline]; + int index = 0; + for (const auto& buffer : buffers) + set_buffer(encoder, buffer, index++); + [encoder setBytes:params length:size atIndex:index]; + [encoder dispatchThreadgroups:MTLSizeMake(blocks, 1, 1) threadsPerThreadgroup:MTLSizeMake(threads, 1, 1)]; + [encoder endEncoding]; + }; + auto rotated = diff; + if (op.group > 1) { + const QuantParams rotation = {p.k, p.rows, uint32_t(op.group), 0, 0}; + dispatch(kernels->rotate, {diff, merged}, &rotation, sizeof(rotation), ggml_nelements(op.weight) / op.group, op.group); + rotated = merged; + } + dispatch(kernels->lora_stats, {weight, scale, diff, rotated, merged, stats}, &p, sizeof(p), p.rows, 256); + dispatch(kernels->lora_summary, {stats, packed}, &p, sizeof(p), 1, 256); + dispatch(kernels->lora_quant, {weight, scale, merged, stats, packed}, &p, sizeof(p), p.rows, 256); + return GGML_STATUS_SUCCESS; + } + static ggml_status lora_execute(const ggml_ext_execution_context* context, ggml_tensor* const* nodes, int, void*, void* user_data) { + Execution e = {context, nodes[0], static_cast(user_data)}; + return e.kernels->submit(context->backend, lora_encode, &e); + } + } void sd_ggml_register_metal_i8(ggml_backend_dev_t device) { @@ -261,9 +324,12 @@ void sd_ggml_register_metal_i8(ggml_backend_dev_t device) { [function release]; return result; }; - kernels->rotate = pipeline(@"sd_i8_rotate"); - kernels->quantize = pipeline(@"sd_i8_quantize"); - kernels->multiply = pipeline(@"sd_i8_multiply"); + kernels->rotate = pipeline(@"sd_i8_rotate"); + kernels->quantize = pipeline(@"sd_i8_quantize"); + kernels->multiply = pipeline(@"sd_i8_multiply"); + kernels->lora_stats = pipeline(@"sd_i8_lora_stats"); + kernels->lora_summary = pipeline(@"sd_i8_lora_summary"); + kernels->lora_quant = pipeline(@"sd_i8_lora_quantize"); [library release]; if (!kernels->rotate || !kernels->quantize || !kernels->multiply || kernels->quantize.threadExecutionWidth != 32 || kernels->multiply.threadExecutionWidth != 32 || @@ -292,6 +358,15 @@ void sd_ggml_register_metal_i8(ggml_backend_dev_t device) { desc.custom_op = sd_ggml_convrot_op(); desc.supports = supports_convrot; GGML_ASSERT(ggml_ext_register_kernel(device, &desc)); + if (kernels->lora_stats.maxTotalThreadsPerThreadgroup >= 256 && kernels->lora_summary.maxTotalThreadsPerThreadgroup >= 256 && + kernels->lora_quant.maxTotalThreadsPerThreadgroup >= 256) { + desc.name = "sd.i8_lora_merge.metal.v1"; + desc.custom_op = sd_ggml_i8_lora_merge_op(); + desc.supports = lora_supports; + desc.prepare = lora_prepare; + desc.execute = lora_execute; + GGML_ASSERT(ggml_ext_register_kernel(device, &desc)); + } static std::vector> registrations; registrations.push_back(std::move(kernels)); } diff --git a/src/core/vulkan/CMakeLists.txt b/src/core/vulkan/CMakeLists.txt index 19367d4340..974f435f95 100644 --- a/src/core/vulkan/CMakeLists.txt +++ b/src/core/vulkan/CMakeLists.txt @@ -54,6 +54,7 @@ sd_vulkan_shader(rms_rope_apply rms_rope_apply ON) sd_vulkan_shader(rms_rope_cast rms_rope_apply ON -DCAST_F16) sd_vulkan_shader(quantize_i8_convrot quantize_i8_convrot ${SD_VK_DOT} -O) sd_vulkan_shader(quantize_i8_convrot_h64 quantize_i8_convrot_h64 ${SD_VK_DOT} -O -DGROUP_SIZE=64) +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(mul_mat_w4a8_convrot mul_mat_w4a8_convrot ${SD_VK_DOT} -O) sd_vulkan_shader(mul_mat_w4a4_convrot_cm2 mul_mat_w4a4_convrot_cm2 ${SD_VK_CM2} -O) diff --git a/src/core/vulkan/int8.cpp b/src/core/vulkan/int8.cpp index 2bac51bb5a..23fc6cb724 100644 --- a/src/core/vulkan/int8.cpp +++ b/src/core/vulkan/int8.cpp @@ -6,6 +6,7 @@ #include #include "core/ggml_extensions.h" #include "ggml-ext-vulkan.h" +#include "i8_lora_merge.h" #include "modulate_convrot.h" #include "mul_mat_i8_residual_cm2.h" #include "mul_mat_i8_swiglu_split_cm2.h" @@ -860,6 +861,45 @@ namespace sd_vulkan_i8 { return multiply_w4(e, d, nodes[0]); return is_convrot(nodes[count - 1]) ? quantize(e, d, nodes, count) : multiply(e, d, nodes, count); } + + struct LoRAMergeParams { + uint32_t k, rows, count, group, scalar; + }; + static bool lora_supports(ggml_backend_dev_t dev, const ggml_tensor* dst, void*) { + Device d; + SDI8LoRAMerge op; + return sd_ggml_i8_lora_merge_describe(dst, &op) && device_info(dev, d) && + ggml_nelements(op.weight) % 4 == 0 && op.workspace_size() <= std::min(d.info.max_buffer_range, UINT32_MAX / 2) && + d.info.max_group_invocations >= 256 && d.info.max_group_size[0] >= 256 && d.compute.shared_memory >= 2048 && + bounded(d, dst) && bounded(d, op.weight) && bounded(d, op.scale) && bounded(d, op.diff); + } + 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* e, ggml_tensor* const* nodes, int, void*, void*) { + Device device; + SDI8LoRAMerge op; + if (!sd_ggml_i8_lora_merge_describe(nodes[0], &op) || !device_info(ggml_backend_get_device(e->backend), device)) + return GGML_STATUS_FAILED; + const LoRAMergeParams pc = {uint32_t(op.weight->ne[0]), uint32_t(op.weight->ne[1]), uint32_t(ggml_nelements(op.weight)), + uint32_t(op.group), op.scalar_scale()}; + const ggml_ext_vulkan_binding bindings[] = {{op.weight}, {op.scale}, {op.diff}, {nodes[0]}, {nullptr, e->workspace, 0, op.workspace_size()}}; + auto pipeline = SD_VK_PIPELINE(i8_lora_merge, 5, LoRAMergeParams); + const uint32_t workgroups[] = {(pc.count + 255) / 256, pc.rows, 1, (pc.count / 4 + 255) / 256}; + for (uint32_t stage = 0; stage < 4; ++stage) { + pipeline.constants = &stage; + pipeline.constant_count = 1; + const uint32_t groups[] = {std::min(workgroups[stage], device.info.max_group_count[0]), 1, 1}; + const auto status = device.api->dispatch(e->backend, &pipeline, bindings, &pc, groups); + if (status != GGML_STATUS_SUCCESS) + return status; + } + return GGML_STATUS_SUCCESS; + } #undef SD_VK_PIPELINE } @@ -871,13 +911,21 @@ void sd_ggml_register_vulkan_i8(ggml_backend_dev_t device) { ggml_ext_kernel_desc d = {}; d.abi_version = GGML_EXT_ABI_VERSION; d.priority = 100; - d.prepare = prepare; - d.destroy = destroy; - d.execute = execute; - d.name = "sd.quantize_i8_convrot.vulkan.v1"; d.op = GGML_OP_CUSTOM; - d.custom_op = sd_ggml_convrot_op(); - d.supports = quant_supports; + d.name = "sd.i8_lora_merge.vulkan.v1"; + d.custom_op = sd_ggml_i8_lora_merge_op(); + d.supports = lora_supports; + d.prepare = lora_prepare; + d.destroy = destroy; + d.execute = lora_execute; + GGML_ASSERT(ggml_ext_register_kernel(device, &d)); + d.prepare = prepare; + d.destroy = destroy; + d.execute = execute; + d.name = "sd.quantize_i8_convrot.vulkan.v1"; + d.op = GGML_OP_CUSTOM; + d.custom_op = sd_ggml_convrot_op(); + d.supports = quant_supports; GGML_ASSERT(ggml_ext_register_kernel(device, &d)); d.name = "sd.quantize_i8_convrot.h64.vulkan.v1"; d.supports = quant64_supports; diff --git a/src/core/vulkan/shaders/i8_lora_merge.comp b/src/core/vulkan/shaders/i8_lora_merge.comp new file mode 100644 index 0000000000..815c7393d3 --- /dev/null +++ b/src/core/vulkan/shaders/i8_lora_merge.comp @@ -0,0 +1,146 @@ +#version 450 + +layout(local_size_x = 256) in; +layout(constant_id = 0) const uint stage = 0; +layout(push_constant) uniform Params { + uint k; + uint rows; + uint count; + uint group_size; + uint scalar; +} +p; +layout(binding = 0, std430) readonly buffer Weight { + uint weight[]; +}; +layout(binding = 1, std430) readonly buffer OldScales { + float old_scales[]; +}; +layout(binding = 2, std430) readonly buffer Diff { + float diff[]; +}; +layout(binding = 3, std430) buffer Output { + uint packed[]; +}; +layout(binding = 4, std430) buffer Workspace { + uint scratch[]; +}; + +const uint CHANGED = 1; +const uint NONFINITE = 2; +shared float maxima[256]; +shared uint changed_rows[256]; + +int weight_at(uint i) { + return bitfieldExtract(int(weight[i / 4]), int(i % 4) * 8, 8); +} + +void combine_weights() { + const uint tid = gl_LocalInvocationID.x; + const float normalization = p.group_size > 1 ? inversesqrt(float(p.group_size)) : 1.0; + for (uint base = gl_WorkGroupID.x * 256; base < p.count; base += gl_NumWorkGroups.x * 256) { + const uint i = base + tid; + precise float value = i < p.count ? diff[i] : 0.0; + if (p.group_size > 1) { + maxima[tid] = value * normalization; + barrier(); + for (uint stride = 1; stride < p.group_size; stride *= 4) { + const uint j = tid / (4 * stride) * (4 * stride) + tid % stride; + const uint digit = (tid / stride) % 4; + const float a = maxima[j], b = maxima[j + stride], c = maxima[j + 2 * stride], d = maxima[j + 3 * stride]; + value = (digit == 3 ? -a : a) + (digit == 2 ? -b : b) + (digit == 1 ? -c : c) + (digit == 0 ? -d : d); + barrier(); + maxima[tid] = value; + barrier(); + } + } + if (i < p.count) { + value += float(weight_at(i)) * old_scales[p.scalar != 0 ? 0 : i / p.k]; + scratch[i] = floatBitsToUint(value); + } + } +} + +void reduce_stats(float maximum, uint changed) { + const uint tid = gl_LocalInvocationID.x; + maxima[tid] = maximum; + changed_rows[tid] = changed; + barrier(); + for (uint stride = 128; stride > 0; stride /= 2) { + if (tid < stride) { + maxima[tid] = max(maxima[tid], maxima[tid + stride]); + changed_rows[tid] |= changed_rows[tid + stride]; + } + barrier(); + } +} + +void row_stats() { + const uint tid = gl_LocalInvocationID.x; + for (uint row = gl_WorkGroupID.x; row < p.rows; row += gl_NumWorkGroups.x) { + float maximum = 0.0; + uint changed = 0; + for (uint col = tid; col < p.k; col += 256) { + const uint i = row * p.k + col; + const float value = uintBitsToFloat(scratch[i]); + maximum = max(maximum, isnan(value) ? uintBitsToFloat(0x7f800000u) : abs(value)); + changed |= uint(diff[i] != 0.0); + } + reduce_stats(maximum, changed); + if (tid == 0) { + scratch[p.count + 2 * row] = floatBitsToUint(maxima[0]); + scratch[p.count + 2 * row + 1] = changed_rows[0]; + } + barrier(); + } +} + +void summarize() { + const uint tid = gl_LocalInvocationID.x; + float maximum = 0.0; + uint changed = 0; + for (uint row = tid; row < p.rows; row += 256) { + const uint row_changed = scratch[p.count + 2 * row + 1]; + if (row_changed != 0 || p.scalar != 0) + maximum = max(maximum, uintBitsToFloat(scratch[p.count + 2 * row])); + changed |= row_changed; + } + reduce_stats(maximum, changed); + if (tid == 0) { + packed[0] = changed_rows[0] == 0 ? 0 : CHANGED | (isinf(maxima[0]) ? NONFINITE : 0); + if (p.scalar != 0) + packed[1] = floatBitsToUint(maxima[0] / 127.0); + } +} + +void quantize_weights() { + const bool apply = packed[0] == CHANGED; + const uint scale_count = p.scalar != 0 ? 1 : p.rows; + for (uint word = gl_GlobalInvocationID.x; word < p.count / 4; word += gl_NumWorkGroups.x * 256) { + uint result = 0; + for (uint lane = 0; lane < 4; ++lane) { + const uint i = 4 * word + lane; + const uint row = i / p.k; + const bool changed = apply && (p.scalar != 0 || scratch[p.count + 2 * row + 1] != 0); + const float scale = changed ? (p.scalar != 0 ? uintBitsToFloat(packed[1]) : uintBitsToFloat(scratch[p.count + 2 * row]) / 127.0) + : old_scales[p.scalar != 0 ? 0 : row]; + if (p.scalar != 0 ? (!apply && i == 0) : i % p.k == 0) + packed[1 + (p.scalar != 0 ? 0 : row)] = floatBitsToUint(scale); + const int q = changed ? (scale == 0.0 ? 0 : int(clamp(roundEven(uintBitsToFloat(scratch[i]) / scale), -127.0, 127.0))) : weight_at(i); + result |= (uint(q) & 255u) << (8 * lane); + } + packed[1 + scale_count + word] = result; + } +} + +void main() { + if (stage == 0) { + combine_weights(); + } else if (stage == 1) { + row_stats(); + } else if (stage == 2) { + summarize(); + } else { + quantize_weights(); + } +} diff --git a/src/dgl/bindings/predictor.cpp b/src/dgl/bindings/predictor.cpp index 5e20df0852..49cf20e2f7 100644 --- a/src/dgl/bindings/predictor.cpp +++ b/src/dgl/bindings/predictor.cpp @@ -139,10 +139,10 @@ namespace sd::dgl { const auto ref_rope_anchor = get_string(args, "ref_rope_anchor"); if (ref_rope_anchor != "default" && engine.version() != VERSION_MOSS_IMAGE) throw std::runtime_error("reference RoPE anchoring is not configurable for this model"); - output.options.ref_rope_anchor = ref_rope_anchor == "image_start" ? Rope::RefRoPEAnchor::IMAGE_START - : ref_rope_anchor == "text_start" ? Rope::RefRoPEAnchor::TEXT_START - : Rope::RefRoPEAnchor::MODEL_DEFAULT; - output.options.guidance = float(get_number(args, "guidance")); + output.options.ref_rope_anchor = ref_rope_anchor == "image_start" ? Rope::RefRoPEAnchor::IMAGE_START + : ref_rope_anchor == "text_start" ? Rope::RefRoPEAnchor::TEXT_START + : Rope::RefRoPEAnchor::MODEL_DEFAULT; + output.options.guidance = float(get_number(args, "guidance")); bind_predictor_options(output, args); const auto& condition = args.at("condition").fields; if (const auto controls = condition.find("controls"); controls != condition.end()) { diff --git a/src/dgl/models/diffusion_prediction.h b/src/dgl/models/diffusion_prediction.h index 94bc6d1e64..8535c9dd7d 100644 --- a/src/dgl/models/diffusion_prediction.h +++ b/src/dgl/models/diffusion_prediction.h @@ -34,15 +34,15 @@ namespace sd::dgl::models { struct DiffusionPredictionOptions { sd::Tensor vace_context, audio_embedding, video_positions; std::vector skip_layers; - float guidance = 3.5f; - float vace_strength = 1.f; - float fps = 24.f; - float video_sigma_shift = 12.f; - float audio_sigma_shift = 3.f; - int audio_length = 0; - Rope::RefIndexMode ref_index_mode = Rope::RefIndexMode::FIXED; + float guidance = 3.5f; + float vace_strength = 1.f; + float fps = 24.f; + float video_sigma_shift = 12.f; + float audio_sigma_shift = 3.f; + int audio_length = 0; + Rope::RefIndexMode ref_index_mode = Rope::RefIndexMode::FIXED; Rope::RefRoPEAnchor ref_rope_anchor = Rope::RefRoPEAnchor::MODEL_DEFAULT; - bool force_ref_timestep_zero = false; + bool force_ref_timestep_zero = false; std::function transform; }; diff --git a/src/dgl/models/lora.cpp b/src/dgl/models/lora.cpp index 5355095ce9..039244e35d 100644 --- a/src/dgl/models/lora.cpp +++ b/src/dgl/models/lora.cpp @@ -8,8 +8,7 @@ namespace sd::dgl::models { - lora_apply_mode_t resolve_lora_mode(lora_apply_mode_t mode, const ModelLoader& loader, - SDBackendManager& backends, SDBackendModule module, bool row_split) { + lora_apply_mode_t resolve_lora_mode(lora_apply_mode_t mode, const ModelLoader& loader, SDBackendManager& backends, SDBackendModule module, bool row_split) { if (mode != LORA_APPLY_AUTO) return mode; // Offloading can signal limited compute memory, so avoid merged copies in auto mode. @@ -20,9 +19,10 @@ namespace sd::dgl::models { const auto& tensors = loader.get_tensor_storage_map(); const bool quantized = std::any_of(tensors.begin(), tensors.end(), [](const auto& entry) { const auto& tensor = entry.second; - return tensor.is_int8_tensorwise || tensor.w4_convrot_kind || - ggml_is_quantized(tensor.type) || - (tensor.expected_type < GGML_TYPE_COUNT && ggml_is_quantized(tensor.expected_type)); + return tensor.w4_convrot_kind || + (!tensor.is_int8_tensorwise && + (ggml_is_quantized(tensor.type) || + (tensor.expected_type < GGML_TYPE_COUNT && ggml_is_quantized(tensor.expected_type)))); }); return quantized ? LORA_APPLY_AT_RUNTIME : LORA_APPLY_IMMEDIATELY; } diff --git a/src/dgl/models/lora.h b/src/dgl/models/lora.h index 40b5a86f4c..b4709c2132 100644 --- a/src/dgl/models/lora.h +++ b/src/dgl/models/lora.h @@ -29,8 +29,7 @@ namespace sd::dgl::models { lora_apply_mode_t mode = LORA_APPLY_AUTO; }; - lora_apply_mode_t resolve_lora_mode(lora_apply_mode_t mode, const ModelLoader& loader, - SDBackendManager& backends, SDBackendModule module, bool row_split = false); + lora_apply_mode_t resolve_lora_mode(lora_apply_mode_t mode, const ModelLoader& loader, SDBackendManager& backends, SDBackendModule module, bool row_split = false); class LoraExecution { std::vector> models_; diff --git a/src/dgl/models/model_runtime.cpp b/src/dgl/models/model_runtime.cpp index 177308546f..0dc6d3ade5 100644 --- a/src/dgl/models/model_runtime.cpp +++ b/src/dgl/models/model_runtime.cpp @@ -413,10 +413,10 @@ namespace sd::dgl::models { const auto& loader = model_.model_weights->loader(); const bool row_split = mode != LORA_APPLY_AT_RUNTIME && split_active(SDSplitMode::ROW); if (mode == LORA_APPLY_IMMEDIATELY) { - const auto& tensors = loader.get_tensor_storage_map(); + const auto& tensors = loader.get_tensor_storage_map(); apply_lora_immediately_ = !row_split && std::none_of(tensors.begin(), tensors.end(), [](const auto& entry) { - return entry.second.is_int8_tensorwise || entry.second.w4_convrot_kind; + return entry.second.w4_convrot_kind != 0; }); } else { apply_lora_immediately_ = resolve_lora_mode(mode, loader, backend_manager, module, row_split) == LORA_APPLY_IMMEDIATELY; diff --git a/src/dgl/ops/tensor.cpp b/src/dgl/ops/tensor.cpp index ff18e8f8fd..cbe9a12ec0 100644 --- a/src/dgl/ops/tensor.cpp +++ b/src/dgl/ops/tensor.cpp @@ -164,7 +164,7 @@ namespace sd::dgl::ops { } std::shared_ptr pool_tensor(const sd_tensor_t& source, const std::vector& axes, const std::vector& kernel, const std::vector& stride, const std::vector& before, const std::vector& after, std::optional pad_value, bool maximum) { - const auto* input = &source; + const auto* input = &source; const auto spatial = spatial_axes(source, axes); const auto x = spatial.first, y = spatial.second; if (kernel.size() != 2 || stride.size() != 2 || before.size() != 2 || after.size() != 2) diff --git a/src/model/adapter/lora.hpp b/src/model/adapter/lora.hpp index 2541f19dd3..aa61238e1b 100644 --- a/src/model/adapter/lora.hpp +++ b/src/model/adapter/lora.hpp @@ -23,6 +23,8 @@ struct LoraModel : public GGMLRunner { float metadata_alpha = -1.f; std::unordered_map lora_tensors; std::map original_tensor_to_final_tensor; + std::map int8_merged_weights; + std::map int8_merge_status; std::set applied_lora_tensors; std::set swapped_lora_up_tensors; std::set skipped_incompatible_lora_tensors; @@ -998,15 +1000,16 @@ struct LoraModel : public GGMLRunner { ggml_cgraph* build_lora_graph(const std::map& model_tensors, const std::set& model_tensor_names, - SDVersion version) { - size_t lora_graph_size = LORA_GRAPH_BASE_SIZE + lora_tensors.size() * 10; - ggml_cgraph* gf = ggml_new_graph_custom(compute_ctx, lora_graph_size, false); + const std::map& int8_weights) { + const size_t lora_graph_size = LORA_GRAPH_BASE_SIZE + lora_tensors.size() * 10 + int8_weights.size() * 12; + ggml_cgraph* gf = ggml_new_graph_custom(compute_ctx, lora_graph_size, false); auto runner_ctx = get_context(); preprocess_lora_tensors(model_tensor_names); original_tensor_to_final_tensor.clear(); - applied_lora_tensors.clear(); + int8_merged_weights.clear(); + int8_merge_status.clear(); for (auto it : model_tensors) { std::string model_tensor_name = it.first; @@ -1017,6 +1020,25 @@ struct LoraModel : public GGMLRunner { if (diff == nullptr) { continue; } + auto int8 = int8_weights.find(model_tensor); + if (int8 != int8_weights.end()) { + if (diff->type != GGML_TYPE_F32) + diff = ggml_ext_cast_f32(&runner_ctx, diff); + auto* merged = build_lora_int8_merge(compute_ctx, model_tensor, int8->second, diff); + if (!merged) { + LOG_ERROR("invalid INT8 LoRA merge layout for '%s'", model_tensor_name.c_str()); + return nullptr; + } + auto* status = append_lora_int8_writeback(compute_ctx, gf, runtime_backend, model_tensor, int8->second, merged); + if (status) { + int8_merge_status[model_tensor] = status; + } else { + ggml_set_output(merged); + ggml_build_forward_expand(gf, merged); + int8_merged_weights[model_tensor] = merged; + } + continue; + } ggml_tensor* original_tensor = model_tensor; if (!sd_backend_is_cpu(runtime_backend) && ggml_backend_buffer_is_host(original_tensor->buffer)) { @@ -1040,31 +1062,43 @@ struct LoraModel : public GGMLRunner { return gf; } - bool apply(std::map model_tensors, + bool apply(const std::map& model_tensors, const std::set& model_tensor_names, SDVersion version, int n_threads, - bool warn_unused = true) { - auto get_graph = [&]() -> ggml_cgraph* { - return build_lora_graph(model_tensors, model_tensor_names, version); + bool warn_unused = true, + const std::map& int8_weights = {}) { + applied_lora_tensors.clear(); + auto get_graph = [&]() { + return build_lora_graph(model_tensors, model_tensor_names, int8_weights); }; auto read_outputs = [&]() { + for (const auto& [weight, status] : int8_merge_status) { + if (!check_lora_int8_merge(weight, status)) + return false; + } + for (const auto& [weight, merged] : int8_merged_weights) { + if (!commit_lora_int8_merge(weight, int8_weights.at(weight), merged)) + return false; + } for (const auto& item : original_tensor_to_final_tensor) { ggml_backend_tensor_copy(item.second, item.first); } return true; }; - auto result = GGMLRunner::compute(get_graph, n_threads, false, true, read_outputs); - if (!result.has_value()) { + const bool success = GGMLRunner::compute(get_graph, n_threads, false, true, read_outputs).has_value(); + if (!success) { LOG_ERROR("LoRA graph execution failed"); } stat(!warn_unused); + int8_merged_weights.clear(); + int8_merge_status.clear(); original_tensor_to_final_tensor.clear(); runner_end(); - return result.has_value(); + return success; } - bool apply(std::map model_tensors, SDVersion version, int n_threads, bool warn_unused = true) { + bool apply(const std::map& model_tensors, SDVersion version, int n_threads, bool warn_unused = true) { return apply(model_tensors, tensor_names(model_tensors), version, n_threads, warn_unused); } diff --git a/src/model/adapter/lora_ops.cpp b/src/model/adapter/lora_ops.cpp index 9629c339db..27d243892c 100644 --- a/src/model/adapter/lora_ops.cpp +++ b/src/model/adapter/lora_ops.cpp @@ -4,7 +4,129 @@ #include "core/ggml_extend.h" #include "core/ggml_extend_backend.h" +#include "core/ggml_extensions.h" #include "core/ggml_runner.h" +#include "core/util.h" + +ggml_tensor* build_lora_int8_merge(ggml_context* ctx, ggml_tensor* weight, const LoraInt8Weight& layout, ggml_tensor* diff) { +#ifndef SD_USE_UPSTREAM_GGML + ggml_tensor* inputs[] = {weight, layout.scale, diff}; + const int32_t group = layout.convrot_group; + return ggml_ext_op_create(ctx, sd_ggml_i8_lora_merge_op(), inputs, 3, &group); +#else + GGML_UNUSED(ctx); + GGML_UNUSED(weight); + GGML_UNUSED(layout); + GGML_UNUSED(diff); + return nullptr; +#endif +} + +#ifndef SD_USE_UPSTREAM_GGML +static ggml_tensor* lora_storage_view(ggml_context* ctx, ggml_tensor* tensor, size_t bytes, size_t offset, ggml_type type) { + // Reinterpret the range as integers so CPY preserves weight and scale bits. + const size_t stride = ggml_type_size(type); + auto* view = ggml_view_1d(ctx, tensor, bytes / ggml_type_size(tensor->type), offset); + view->type = type; + view->ne[0] = bytes / stride; + view->nb[0] = stride; + view->nb[1] = view->nb[2] = view->nb[3] = bytes; + return view; +} + +static void copy_packed_lora_result(ggml_tensor* target, ggml_tensor* packed, size_t offset) { + ggml_tensor view = *target; + view.view_src = packed; + view.view_offs = offset; + view.buffer = packed->buffer; + view.data = static_cast(packed->data) + offset; + view.extra = packed->extra; + ggml_backend_tensor_copy(&view, target); +} + +static uint32_t lora_int8_merge_flags(const ggml_tensor* status) { + uint32_t flags; + ggml_backend_tensor_get(status, &flags, 0, sizeof(flags)); + return flags; +} + +static bool lora_int8_merge_valid(const ggml_tensor* weight, uint32_t flags) { + if (flags & SD_I8_LORA_NONFINITE) { + LOG_ERROR("non-finite INT8 LoRA merge for '%s'", ggml_get_name(weight)); + return false; + } + return true; +} +#endif + +ggml_tensor* append_lora_int8_writeback(ggml_context* ctx, ggml_cgraph* graph, ggml_backend_t backend, ggml_tensor* weight, const LoraInt8Weight& layout, ggml_tensor* packed) { +#ifndef SD_USE_UPSTREAM_GGML + SDI8LoRAMerge op; + if (!sd_ggml_i8_lora_merge_describe(packed, &op)) + return nullptr; + auto copy = [&](ggml_tensor* target, size_t offset) { + const auto bytes = ggml_nbytes(target); + const auto type = bytes % sizeof(uint32_t) == 0 && offset % sizeof(uint32_t) == 0 && + target->view_offs % sizeof(uint32_t) == 0 && uintptr_t(target->data) % sizeof(uint32_t) == 0 + ? GGML_TYPE_I32 + : GGML_TYPE_I8; + return ggml_cpy(ctx, lora_storage_view(ctx, packed, bytes, offset, type), + lora_storage_view(ctx, target, bytes, 0, type)); + }; + auto* status = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1); + auto* weights = copy(weight, op.weight_offset()); + auto* scales = copy(layout.scale, op.scale_offset()); + auto* flags = ggml_cpy(ctx, lora_storage_view(ctx, packed, sizeof(uint32_t), 0, GGML_TYPE_I32), status); + if (!ggml_backend_supports_op(backend, weights) || !ggml_backend_supports_op(backend, scales) || + !ggml_backend_supports_op(backend, flags)) + return nullptr; + + ggml_set_output(status); + ggml_build_forward_expand(graph, flags); + ggml_build_forward_expand(graph, scales); + ggml_build_forward_expand(graph, weights); + return status; +#else + GGML_UNUSED(ctx); + GGML_UNUSED(graph); + GGML_UNUSED(backend); + GGML_UNUSED(weight); + GGML_UNUSED(layout); + GGML_UNUSED(packed); + return nullptr; +#endif +} + +bool check_lora_int8_merge(const ggml_tensor* weight, const ggml_tensor* status) { +#ifndef SD_USE_UPSTREAM_GGML + return lora_int8_merge_valid(weight, lora_int8_merge_flags(status)); +#else + GGML_UNUSED(weight); + GGML_UNUSED(status); + return false; +#endif +} + +bool commit_lora_int8_merge(ggml_tensor* weight, const LoraInt8Weight& layout, ggml_tensor* packed) { +#ifndef SD_USE_UPSTREAM_GGML + SDI8LoRAMerge op; + if (!sd_ggml_i8_lora_merge_describe(packed, &op)) + return false; + const auto flags = lora_int8_merge_flags(packed); + if (!lora_int8_merge_valid(weight, flags)) + return false; + if (flags & SD_I8_LORA_CHANGED) { + copy_packed_lora_result(weight, packed, op.weight_offset()); + copy_packed_lora_result(layout.scale, packed, op.scale_offset()); + } + return true; +#else + GGML_UNUSED(weight); + GGML_UNUSED(layout); + GGML_UNUSED(packed); + return false; +#endif +} ggml_tensor* ggml_ext_mul_n_mode(GGMLRunnerContext* runner_ctx, ggml_tensor* a, ggml_tensor* b, int mode) { auto ctx = runner_ctx->ggml_ctx; diff --git a/src/model/adapter/lora_ops.h b/src/model/adapter/lora_ops.h index 309f513653..31acd4926e 100644 --- a/src/model/adapter/lora_ops.h +++ b/src/model/adapter/lora_ops.h @@ -3,6 +3,16 @@ #include "core/ggml_runner.h" +struct LoraInt8Weight { + ggml_tensor* scale; + int convrot_group; +}; + +ggml_tensor* build_lora_int8_merge(ggml_context* ctx, ggml_tensor* weight, const LoraInt8Weight& layout, ggml_tensor* diff); +ggml_tensor* append_lora_int8_writeback(ggml_context* ctx, ggml_cgraph* graph, ggml_backend_t backend, ggml_tensor* weight, const LoraInt8Weight& layout, ggml_tensor* packed); +bool check_lora_int8_merge(const ggml_tensor* weight, const ggml_tensor* status); +bool commit_lora_int8_merge(ggml_tensor* weight, const LoraInt8Weight& layout, ggml_tensor* packed); + // n-mode tensor-matrix product // example: 2-mode product // A: [ne03, k, ne01, ne00] diff --git a/src/model/diffusion/moss_image.hpp b/src/model/diffusion/moss_image.hpp index 3e87433394..c039f100dd 100644 --- a/src/model/diffusion/moss_image.hpp +++ b/src/model/diffusion/moss_image.hpp @@ -279,7 +279,7 @@ namespace MOSSImage { tokens += ref.shape()[1] * ref.shape()[0]; } } - auto pe = make_input(pe_cache_.get_or_create(pe_key, [&]() { + auto pe = make_input(pe_cache_.get_or_create(pe_key, [&]() { Rope::Embedding embedding; embedding.ids.reserve(tokens); auto append_image = [&](int64_t height, int64_t width, float ref_index, float text_position) { diff --git a/src/model_manager.cpp b/src/model_manager.cpp index 52bc14c636..3880fe8d8f 100644 --- a/src/model_manager.cpp +++ b/src/model_manager.cpp @@ -217,6 +217,7 @@ bool ModelManager::set_loras(Resource& resource, std::vector loras, SD resource.lora_targets_ = std::move(targets); resource.lora_version_ = version; resource.current_lora_epoch_++; + resolved_tensor_states_.clear(); reset_lora_applied_params(resource); return true; } @@ -310,6 +311,7 @@ bool ModelManager::register_param_tensors(Resource& resource, ModelComponent com state->source_file = source_file; state->source_version = source_version; state->sources = find_tensor_sources(*state, sources); + state->is_int8_weight = !state->sources.empty() && state->sources.front().is_int8_tensorwise; state->residency_mode = residency_mode; state->compute_backend = compute_backend; state->params_backend = params_backend; @@ -327,6 +329,21 @@ bool ModelManager::register_param_tensors(Resource& resource, ModelComponent com new_states.push_back(std::move(state)); } + std::map weight_scales; + for (const auto& state : new_states) { + if (ends_with(state->name, ".weight_scale")) + weight_scales.emplace(state->name, state.get()); + } + for (const auto& state : new_states) { + if (!state->is_int8_weight) + continue; + const auto scale = weight_scales.find(state->name + "_scale"); + if (scale != weight_scales.end()) { + state->lora_int8_partner = scale->second; + scale->second->lora_int8_partner = state.get(); + } + } + resolved_tensor_states_.clear(); for (auto& state : new_states) { TensorState* registered_state = state.get(); @@ -478,6 +495,12 @@ bool ModelManager::unregister_tensor_states(const std::unordered_setlora_int8_partner) { + state->lora_int8_partner->lora_int8_partner = nullptr; + state->lora_int8_partner = nullptr; + } + } for (auto it = tensor_states_by_tensor_.begin(); it != tensor_states_by_tensor_.end();) { if (target_states.count(it->second) > 0) { it = tensor_states_by_tensor_.erase(it); @@ -695,9 +718,15 @@ bool ModelManager::load_tensors_to_params_backend(const std::vectorlora_targets_.count(state.is_int8_weight ? state.name : state.lora_int8_partner->name) != 0; +} + bool ModelManager::needs_lora_staging(const TensorState& state) { - return !state.resource->shared_weights_key_.empty() && state.component != ModelComponent::LoRA && - state.resource->lora_targets_.count(state.name) != 0; + return state.component != ModelComponent::LoRA && + (has_lora_int8_pair(state) || (!state.resource->shared_weights_key_.empty() && + state.resource->lora_targets_.count(state.name) != 0)); } bool ModelManager::stage_tensors_to_compute_backend(const std::vector& states) { @@ -823,8 +852,16 @@ bool ModelManager::stage_tensors_to_compute_backend(const std::vector chunk; size_t chunk_size = 0; for (TensorState* state : target_states) { - const size_t tensor_size = GGML_PAD( + auto* partner = has_lora_int8_pair(*state) ? state->lora_int8_partner : nullptr; + if (partner && !state->is_int8_weight) + continue; + size_t tensor_size = GGML_PAD( ggml_backend_buft_get_alloc_size(staging_buft, state->tensor), alignment); + if (partner) { + // Evict and reload the merged weight and its scale together. + const size_t scale_size = GGML_PAD(ggml_backend_buft_get_alloc_size(staging_buft, partner->tensor), alignment); + tensor_size += std::min(scale_size, SIZE_MAX - tensor_size); + } if (!chunk.empty() && backend_limit > 0 && tensor_size > backend_limit - std::min(chunk_size, backend_limit)) { if (!stage_chunk(chunk, chunk_size)) { @@ -834,6 +871,8 @@ bool ModelManager::stage_tensors_to_compute_backend(const std::vector SIZE_MAX - chunk_size ? SIZE_MAX : chunk_size + tensor_size; } if (!stage_chunk(chunk, chunk_size)) { @@ -872,6 +911,7 @@ bool ModelManager::apply_resource_loras(Resource& resource, const std::vector model_tensors; + std::map int8_weights; std::vector states; }; @@ -882,11 +922,11 @@ bool ModelManager::apply_resource_loras(Resource& resource, const std::vectorsources.empty() && is_optional_missing_tensor(state->name))) { continue; } - if (!resource.shared_weights_key_.empty()) { - if (!needs_lora_staging(*state)) - continue; + if (needs_lora_staging(*state)) { if (!state->staged_to_compute_backend) return false; + } else if (!resource.shared_weights_key_.empty()) { + continue; } else if (state->component == ModelComponent::LatentUpsampler || resource.model_sources_.count(state->source_file) != 0) { continue; } @@ -912,7 +952,20 @@ bool ModelManager::apply_resource_loras(Resource& resource, const std::vectorname.c_str()); return false; } - LoraApplyGroup& group = groups[{state->compute_backend, state->params_backend, state->residency_mode}]; + LoraApplyGroup& group = groups[{state->compute_backend, state->params_backend, state->residency_mode}]; + if (state->is_int8_weight) { + if (resource.lora_targets_.count(state->name) == 0) + continue; + if (!state->lora_int8_partner || !state->lora_int8_partner->staged_to_compute_backend) { + LOG_ERROR("model manager INT8 LoRA target '%s' has no staged weight scale", state->name.c_str()); + return false; + } + const auto& storage = state->sources.front(); + group.int8_weights[state->tensor] = {state->lora_int8_partner->tensor, storage.int8_convrot ? storage.int8_convrot_group_size : 0}; + } else if (has_lora_int8_pair(*state)) { + group.states.push_back(state); + continue; + } group.model_tensors[state->name] = state->tensor; group.states.push_back(state); } @@ -966,7 +1019,7 @@ bool ModelManager::apply_resource_loras(Resource& resource, const std::vectormultiplier = lora_spec.multiplier; - if (!lora->apply(group.model_tensors, all_tensor_names, resource.lora_version_, resource.n_threads_, false)) + if (!lora->apply(group.model_tensors, all_tensor_names, resource.lora_version_, resource.n_threads_, false, group.int8_weights)) return false; if (temporary) lora->release_loaded_tensors(); @@ -1854,6 +1907,9 @@ bool ModelManager::resolve_required_tensor_states(const std::vectorlora_int8_partner).second) { + states.push_back(state->lora_int8_partner); + } } append_states(states); if (cacheable && !tensors.empty()) { @@ -1936,7 +1992,7 @@ size_t ModelManager::compute_backend_alloc_size(const std::vector& if (state == nullptr || state->tensor == nullptr) { continue; } - if (state->usage_op == GGML_OP_CUSTOM && !sd_backend_is_cpu(state->compute_backend)) { + if (state->usage_op == GGML_OP_CUSTOM && !sd_backend_is_cpu(state->compute_backend) && !needs_lora_staging(*state)) { continue; } const bool compute_resident = diff --git a/src/model_manager.h b/src/model_manager.h index 3007f40e99..08c37e6312 100644 --- a/src/model_manager.h +++ b/src/model_manager.h @@ -104,6 +104,8 @@ class ModelManager : public DeviceResidencyManager { bool params_follow_compute_backend = false; bool metadata_validated = false; enum ggml_op usage_op = GGML_OP_NONE; + TensorState* lora_int8_partner = nullptr; + bool is_int8_weight = false; int pin_count = 0; @@ -181,6 +183,7 @@ class ModelManager : public DeviceResidencyManager { bool load_tensors_to_params_backend(const std::vector& states); void reuse_shared_weights(std::vector& need_load); void detach_shared_weight(TensorState& state); + static bool has_lora_int8_pair(const TensorState& state); static bool needs_lora_staging(const TensorState& state); bool apply_loras_to_params(const std::vector& states); bool mmap_params(const std::vector& states, diff --git a/src/model_manager_prefetch.cpp b/src/model_manager_prefetch.cpp index 019b481deb..e1969ee24a 100644 --- a/src/model_manager_prefetch.cpp +++ b/src/model_manager_prefetch.cpp @@ -245,6 +245,11 @@ WeightPrefetchResult ModelManager::prepare_prefetch_params( is_optional_missing_tensor(state->name)) { continue; } + if (has_lora_int8_pair(*state)) { + // Synchronous staging keeps the merged weight and scale in the same block. + needs_synchronous_load = needs_synchronous_load || !state->staged_to_compute_backend; + continue; + } if (state->usage_op == GGML_OP_CUSTOM || state->compute_backend == state->params_backend) { needs_synchronous_load = needs_synchronous_load || !state->loaded_to_params_backend; @@ -310,6 +315,7 @@ bool ModelManager::activate_prefetched_params( [&](TensorState* state) { return state == nullptr || should_ignore(*state) || is_optional_missing_tensor(state->name) || + has_lora_int8_pair(*state) || state->usage_op == GGML_OP_CUSTOM || state->compute_backend == state->params_backend || state->staged_to_compute_backend;